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/ASTLambda.h" 19 #include "clang/AST/ASTMutationListener.h" 20 #include "clang/AST/CXXInheritance.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/ExprObjC.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/LiteralSupport.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/AnalysisBasedWarnings.h" 35 #include "clang/Sema/DeclSpec.h" 36 #include "clang/Sema/DelayedDiagnostic.h" 37 #include "clang/Sema/Designator.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaFixItUtils.h" 44 #include "clang/Sema/Template.h" 45 #include "llvm/Support/ConvertUTF.h" 46 using namespace clang; 47 using namespace sema; 48 49 /// \brief Determine whether the use of this declaration is valid, without 50 /// emitting diagnostics. 51 bool Sema::CanUseDecl(NamedDecl *D) { 52 // See if this is an auto-typed variable whose initializer we are parsing. 53 if (ParsingInitForAutoVars.count(D)) 54 return false; 55 56 // See if this is a deleted function. 57 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 58 if (FD->isDeleted()) 59 return false; 60 61 // If the function has a deduced return type, and we can't deduce it, 62 // then we can't use it either. 63 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 64 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 65 return false; 66 } 67 68 // See if this function is unavailable. 69 if (D->getAvailability() == AR_Unavailable && 70 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 71 return false; 72 73 return true; 74 } 75 76 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 77 // Warn if this is used but marked unused. 78 if (D->hasAttr<UnusedAttr>()) { 79 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext()); 80 if (!DC->hasAttr<UnusedAttr>()) 81 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 82 } 83 } 84 85 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S, 86 NamedDecl *D, SourceLocation Loc, 87 const ObjCInterfaceDecl *UnknownObjCClass, 88 bool ObjCPropertyAccess) { 89 // See if this declaration is unavailable or deprecated. 90 std::string Message; 91 92 // Forward class declarations get their attributes from their definition. 93 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) { 94 if (IDecl->getDefinition()) 95 D = IDecl->getDefinition(); 96 } 97 AvailabilityResult Result = D->getAvailability(&Message); 98 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 99 if (Result == AR_Available) { 100 const DeclContext *DC = ECD->getDeclContext(); 101 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 102 Result = TheEnumDecl->getAvailability(&Message); 103 } 104 105 const ObjCPropertyDecl *ObjCPDecl = nullptr; 106 if (Result == AR_Deprecated || Result == AR_Unavailable) { 107 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 108 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 109 AvailabilityResult PDeclResult = PD->getAvailability(nullptr); 110 if (PDeclResult == Result) 111 ObjCPDecl = PD; 112 } 113 } 114 } 115 116 switch (Result) { 117 case AR_Available: 118 case AR_NotYetIntroduced: 119 break; 120 121 case AR_Deprecated: 122 if (S.getCurContextAvailability() != AR_Deprecated) 123 S.EmitAvailabilityWarning(Sema::AD_Deprecation, 124 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 125 ObjCPropertyAccess); 126 break; 127 128 case AR_Unavailable: 129 if (S.getCurContextAvailability() != AR_Unavailable) 130 S.EmitAvailabilityWarning(Sema::AD_Unavailable, 131 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 132 ObjCPropertyAccess); 133 break; 134 135 } 136 return Result; 137 } 138 139 /// \brief Emit a note explaining that this function is deleted. 140 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 141 assert(Decl->isDeleted()); 142 143 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 144 145 if (Method && Method->isDeleted() && Method->isDefaulted()) { 146 // If the method was explicitly defaulted, point at that declaration. 147 if (!Method->isImplicit()) 148 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 149 150 // Try to diagnose why this special member function was implicitly 151 // deleted. This might fail, if that reason no longer applies. 152 CXXSpecialMember CSM = getSpecialMember(Method); 153 if (CSM != CXXInvalid) 154 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 155 156 return; 157 } 158 159 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) { 160 if (CXXConstructorDecl *BaseCD = 161 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) { 162 Diag(Decl->getLocation(), diag::note_inherited_deleted_here); 163 if (BaseCD->isDeleted()) { 164 NoteDeletedFunction(BaseCD); 165 } else { 166 // FIXME: An explanation of why exactly it can't be inherited 167 // would be nice. 168 Diag(BaseCD->getLocation(), diag::note_cannot_inherit); 169 } 170 return; 171 } 172 } 173 174 Diag(Decl->getLocation(), diag::note_availability_specified_here) 175 << Decl << true; 176 } 177 178 /// \brief Determine whether a FunctionDecl was ever declared with an 179 /// explicit storage class. 180 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 181 for (auto I : D->redecls()) { 182 if (I->getStorageClass() != SC_None) 183 return true; 184 } 185 return false; 186 } 187 188 /// \brief Check whether we're in an extern inline function and referring to a 189 /// variable or function with internal linkage (C11 6.7.4p3). 190 /// 191 /// This is only a warning because we used to silently accept this code, but 192 /// in many cases it will not behave correctly. This is not enabled in C++ mode 193 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 194 /// and so while there may still be user mistakes, most of the time we can't 195 /// prove that there are errors. 196 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 197 const NamedDecl *D, 198 SourceLocation Loc) { 199 // This is disabled under C++; there are too many ways for this to fire in 200 // contexts where the warning is a false positive, or where it is technically 201 // correct but benign. 202 if (S.getLangOpts().CPlusPlus) 203 return; 204 205 // Check if this is an inlined function or method. 206 FunctionDecl *Current = S.getCurFunctionDecl(); 207 if (!Current) 208 return; 209 if (!Current->isInlined()) 210 return; 211 if (!Current->isExternallyVisible()) 212 return; 213 214 // Check if the decl has internal linkage. 215 if (D->getFormalLinkage() != InternalLinkage) 216 return; 217 218 // Downgrade from ExtWarn to Extension if 219 // (1) the supposedly external inline function is in the main file, 220 // and probably won't be included anywhere else. 221 // (2) the thing we're referencing is a pure function. 222 // (3) the thing we're referencing is another inline function. 223 // This last can give us false negatives, but it's better than warning on 224 // wrappers for simple C library functions. 225 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 226 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 227 if (!DowngradeWarning && UsedFn) 228 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 229 230 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 231 : diag::ext_internal_in_extern_inline) 232 << /*IsVar=*/!UsedFn << D; 233 234 S.MaybeSuggestAddingStaticToDecl(Current); 235 236 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 237 << D; 238 } 239 240 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 241 const FunctionDecl *First = Cur->getFirstDecl(); 242 243 // Suggest "static" on the function, if possible. 244 if (!hasAnyExplicitStorageClass(First)) { 245 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 246 Diag(DeclBegin, diag::note_convert_inline_to_static) 247 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 248 } 249 } 250 251 /// \brief Determine whether the use of this declaration is valid, and 252 /// emit any corresponding diagnostics. 253 /// 254 /// This routine diagnoses various problems with referencing 255 /// declarations that can occur when using a declaration. For example, 256 /// it might warn if a deprecated or unavailable declaration is being 257 /// used, or produce an error (and return true) if a C++0x deleted 258 /// function is being used. 259 /// 260 /// \returns true if there was an error (this declaration cannot be 261 /// referenced), false otherwise. 262 /// 263 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 264 const ObjCInterfaceDecl *UnknownObjCClass, 265 bool ObjCPropertyAccess) { 266 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 267 // If there were any diagnostics suppressed by template argument deduction, 268 // emit them now. 269 SuppressedDiagnosticsMap::iterator 270 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 271 if (Pos != SuppressedDiagnostics.end()) { 272 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 273 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 274 Diag(Suppressed[I].first, Suppressed[I].second); 275 276 // Clear out the list of suppressed diagnostics, so that we don't emit 277 // them again for this specialization. However, we don't obsolete this 278 // entry from the table, because we want to avoid ever emitting these 279 // diagnostics again. 280 Suppressed.clear(); 281 } 282 283 // C++ [basic.start.main]p3: 284 // The function 'main' shall not be used within a program. 285 if (cast<FunctionDecl>(D)->isMain()) 286 Diag(Loc, diag::ext_main_used); 287 } 288 289 // See if this is an auto-typed variable whose initializer we are parsing. 290 if (ParsingInitForAutoVars.count(D)) { 291 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 292 << D->getDeclName(); 293 return true; 294 } 295 296 // See if this is a deleted function. 297 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 298 if (FD->isDeleted()) { 299 Diag(Loc, diag::err_deleted_function_use); 300 NoteDeletedFunction(FD); 301 return true; 302 } 303 304 // If the function has a deduced return type, and we can't deduce it, 305 // then we can't use it either. 306 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 307 DeduceReturnType(FD, Loc)) 308 return true; 309 } 310 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, ObjCPropertyAccess); 311 312 DiagnoseUnusedOfDecl(*this, D, Loc); 313 314 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 315 316 return false; 317 } 318 319 /// \brief Retrieve the message suffix that should be added to a 320 /// diagnostic complaining about the given function being deleted or 321 /// unavailable. 322 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 323 std::string Message; 324 if (FD->getAvailability(&Message)) 325 return ": " + Message; 326 327 return std::string(); 328 } 329 330 /// DiagnoseSentinelCalls - This routine checks whether a call or 331 /// message-send is to a declaration with the sentinel attribute, and 332 /// if so, it checks that the requirements of the sentinel are 333 /// satisfied. 334 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 335 ArrayRef<Expr *> Args) { 336 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 337 if (!attr) 338 return; 339 340 // The number of formal parameters of the declaration. 341 unsigned numFormalParams; 342 343 // The kind of declaration. This is also an index into a %select in 344 // the diagnostic. 345 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 346 347 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 348 numFormalParams = MD->param_size(); 349 calleeType = CT_Method; 350 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 351 numFormalParams = FD->param_size(); 352 calleeType = CT_Function; 353 } else if (isa<VarDecl>(D)) { 354 QualType type = cast<ValueDecl>(D)->getType(); 355 const FunctionType *fn = nullptr; 356 if (const PointerType *ptr = type->getAs<PointerType>()) { 357 fn = ptr->getPointeeType()->getAs<FunctionType>(); 358 if (!fn) return; 359 calleeType = CT_Function; 360 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 361 fn = ptr->getPointeeType()->castAs<FunctionType>(); 362 calleeType = CT_Block; 363 } else { 364 return; 365 } 366 367 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 368 numFormalParams = proto->getNumParams(); 369 } else { 370 numFormalParams = 0; 371 } 372 } else { 373 return; 374 } 375 376 // "nullPos" is the number of formal parameters at the end which 377 // effectively count as part of the variadic arguments. This is 378 // useful if you would prefer to not have *any* formal parameters, 379 // but the language forces you to have at least one. 380 unsigned nullPos = attr->getNullPos(); 381 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 382 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 383 384 // The number of arguments which should follow the sentinel. 385 unsigned numArgsAfterSentinel = attr->getSentinel(); 386 387 // If there aren't enough arguments for all the formal parameters, 388 // the sentinel, and the args after the sentinel, complain. 389 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 390 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 391 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 392 return; 393 } 394 395 // Otherwise, find the sentinel expression. 396 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 397 if (!sentinelExpr) return; 398 if (sentinelExpr->isValueDependent()) return; 399 if (Context.isSentinelNullExpr(sentinelExpr)) return; 400 401 // Pick a reasonable string to insert. Optimistically use 'nil' or 402 // 'NULL' if those are actually defined in the context. Only use 403 // 'nil' for ObjC methods, where it's much more likely that the 404 // variadic arguments form a list of object pointers. 405 SourceLocation MissingNilLoc 406 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 407 std::string NullValue; 408 if (calleeType == CT_Method && 409 PP.getIdentifierInfo("nil")->hasMacroDefinition()) 410 NullValue = "nil"; 411 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition()) 412 NullValue = "NULL"; 413 else 414 NullValue = "(void*) 0"; 415 416 if (MissingNilLoc.isInvalid()) 417 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 418 else 419 Diag(MissingNilLoc, diag::warn_missing_sentinel) 420 << int(calleeType) 421 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 422 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 423 } 424 425 SourceRange Sema::getExprRange(Expr *E) const { 426 return E ? E->getSourceRange() : SourceRange(); 427 } 428 429 //===----------------------------------------------------------------------===// 430 // Standard Promotions and Conversions 431 //===----------------------------------------------------------------------===// 432 433 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 434 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 435 // Handle any placeholder expressions which made it here. 436 if (E->getType()->isPlaceholderType()) { 437 ExprResult result = CheckPlaceholderExpr(E); 438 if (result.isInvalid()) return ExprError(); 439 E = result.get(); 440 } 441 442 QualType Ty = E->getType(); 443 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 444 445 if (Ty->isFunctionType()) { 446 // If we are here, we are not calling a function but taking 447 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 448 if (getLangOpts().OpenCL) { 449 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 450 return ExprError(); 451 } 452 E = ImpCastExprToType(E, Context.getPointerType(Ty), 453 CK_FunctionToPointerDecay).get(); 454 } else if (Ty->isArrayType()) { 455 // In C90 mode, arrays only promote to pointers if the array expression is 456 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 457 // type 'array of type' is converted to an expression that has type 'pointer 458 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 459 // that has type 'array of type' ...". The relevant change is "an lvalue" 460 // (C90) to "an expression" (C99). 461 // 462 // C++ 4.2p1: 463 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 464 // T" can be converted to an rvalue of type "pointer to T". 465 // 466 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 467 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 468 CK_ArrayToPointerDecay).get(); 469 } 470 return E; 471 } 472 473 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 474 // Check to see if we are dereferencing a null pointer. If so, 475 // and if not volatile-qualified, this is undefined behavior that the 476 // optimizer will delete, so warn about it. People sometimes try to use this 477 // to get a deterministic trap and are surprised by clang's behavior. This 478 // only handles the pattern "*null", which is a very syntactic check. 479 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 480 if (UO->getOpcode() == UO_Deref && 481 UO->getSubExpr()->IgnoreParenCasts()-> 482 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 483 !UO->getType().isVolatileQualified()) { 484 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 485 S.PDiag(diag::warn_indirection_through_null) 486 << UO->getSubExpr()->getSourceRange()); 487 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 488 S.PDiag(diag::note_indirection_through_null)); 489 } 490 } 491 492 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 493 SourceLocation AssignLoc, 494 const Expr* RHS) { 495 const ObjCIvarDecl *IV = OIRE->getDecl(); 496 if (!IV) 497 return; 498 499 DeclarationName MemberName = IV->getDeclName(); 500 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 501 if (!Member || !Member->isStr("isa")) 502 return; 503 504 const Expr *Base = OIRE->getBase(); 505 QualType BaseType = Base->getType(); 506 if (OIRE->isArrow()) 507 BaseType = BaseType->getPointeeType(); 508 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 509 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 510 ObjCInterfaceDecl *ClassDeclared = nullptr; 511 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 512 if (!ClassDeclared->getSuperClass() 513 && (*ClassDeclared->ivar_begin()) == IV) { 514 if (RHS) { 515 NamedDecl *ObjectSetClass = 516 S.LookupSingleName(S.TUScope, 517 &S.Context.Idents.get("object_setClass"), 518 SourceLocation(), S.LookupOrdinaryName); 519 if (ObjectSetClass) { 520 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd()); 521 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 522 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 523 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 524 AssignLoc), ",") << 525 FixItHint::CreateInsertion(RHSLocEnd, ")"); 526 } 527 else 528 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 529 } else { 530 NamedDecl *ObjectGetClass = 531 S.LookupSingleName(S.TUScope, 532 &S.Context.Idents.get("object_getClass"), 533 SourceLocation(), S.LookupOrdinaryName); 534 if (ObjectGetClass) 535 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 536 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 537 FixItHint::CreateReplacement( 538 SourceRange(OIRE->getOpLoc(), 539 OIRE->getLocEnd()), ")"); 540 else 541 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 542 } 543 S.Diag(IV->getLocation(), diag::note_ivar_decl); 544 } 545 } 546 } 547 548 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 549 // Handle any placeholder expressions which made it here. 550 if (E->getType()->isPlaceholderType()) { 551 ExprResult result = CheckPlaceholderExpr(E); 552 if (result.isInvalid()) return ExprError(); 553 E = result.get(); 554 } 555 556 // C++ [conv.lval]p1: 557 // A glvalue of a non-function, non-array type T can be 558 // converted to a prvalue. 559 if (!E->isGLValue()) return E; 560 561 QualType T = E->getType(); 562 assert(!T.isNull() && "r-value conversion on typeless expression?"); 563 564 // We don't want to throw lvalue-to-rvalue casts on top of 565 // expressions of certain types in C++. 566 if (getLangOpts().CPlusPlus && 567 (E->getType() == Context.OverloadTy || 568 T->isDependentType() || 569 T->isRecordType())) 570 return E; 571 572 // The C standard is actually really unclear on this point, and 573 // DR106 tells us what the result should be but not why. It's 574 // generally best to say that void types just doesn't undergo 575 // lvalue-to-rvalue at all. Note that expressions of unqualified 576 // 'void' type are never l-values, but qualified void can be. 577 if (T->isVoidType()) 578 return E; 579 580 // OpenCL usually rejects direct accesses to values of 'half' type. 581 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 582 T->isHalfType()) { 583 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 584 << 0 << T; 585 return ExprError(); 586 } 587 588 CheckForNullPointerDereference(*this, E); 589 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 590 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 591 &Context.Idents.get("object_getClass"), 592 SourceLocation(), LookupOrdinaryName); 593 if (ObjectGetClass) 594 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 595 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 596 FixItHint::CreateReplacement( 597 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 598 else 599 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 600 } 601 else if (const ObjCIvarRefExpr *OIRE = 602 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 603 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 604 605 // C++ [conv.lval]p1: 606 // [...] If T is a non-class type, the type of the prvalue is the 607 // cv-unqualified version of T. Otherwise, the type of the 608 // rvalue is T. 609 // 610 // C99 6.3.2.1p2: 611 // If the lvalue has qualified type, the value has the unqualified 612 // version of the type of the lvalue; otherwise, the value has the 613 // type of the lvalue. 614 if (T.hasQualifiers()) 615 T = T.getUnqualifiedType(); 616 617 UpdateMarkingForLValueToRValue(E); 618 619 // Loading a __weak object implicitly retains the value, so we need a cleanup to 620 // balance that. 621 if (getLangOpts().ObjCAutoRefCount && 622 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 623 ExprNeedsCleanups = true; 624 625 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 626 nullptr, VK_RValue); 627 628 // C11 6.3.2.1p2: 629 // ... if the lvalue has atomic type, the value has the non-atomic version 630 // of the type of the lvalue ... 631 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 632 T = Atomic->getValueType().getUnqualifiedType(); 633 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 634 nullptr, VK_RValue); 635 } 636 637 return Res; 638 } 639 640 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 641 ExprResult Res = DefaultFunctionArrayConversion(E); 642 if (Res.isInvalid()) 643 return ExprError(); 644 Res = DefaultLvalueConversion(Res.get()); 645 if (Res.isInvalid()) 646 return ExprError(); 647 return Res; 648 } 649 650 /// CallExprUnaryConversions - a special case of an unary conversion 651 /// performed on a function designator of a call expression. 652 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 653 QualType Ty = E->getType(); 654 ExprResult Res = E; 655 // Only do implicit cast for a function type, but not for a pointer 656 // to function type. 657 if (Ty->isFunctionType()) { 658 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 659 CK_FunctionToPointerDecay).get(); 660 if (Res.isInvalid()) 661 return ExprError(); 662 } 663 Res = DefaultLvalueConversion(Res.get()); 664 if (Res.isInvalid()) 665 return ExprError(); 666 return Res.get(); 667 } 668 669 /// UsualUnaryConversions - Performs various conversions that are common to most 670 /// operators (C99 6.3). The conversions of array and function types are 671 /// sometimes suppressed. For example, the array->pointer conversion doesn't 672 /// apply if the array is an argument to the sizeof or address (&) operators. 673 /// In these instances, this routine should *not* be called. 674 ExprResult Sema::UsualUnaryConversions(Expr *E) { 675 // First, convert to an r-value. 676 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 677 if (Res.isInvalid()) 678 return ExprError(); 679 E = Res.get(); 680 681 QualType Ty = E->getType(); 682 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 683 684 // Half FP have to be promoted to float unless it is natively supported 685 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 686 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 687 688 // Try to perform integral promotions if the object has a theoretically 689 // promotable type. 690 if (Ty->isIntegralOrUnscopedEnumerationType()) { 691 // C99 6.3.1.1p2: 692 // 693 // The following may be used in an expression wherever an int or 694 // unsigned int may be used: 695 // - an object or expression with an integer type whose integer 696 // conversion rank is less than or equal to the rank of int 697 // and unsigned int. 698 // - A bit-field of type _Bool, int, signed int, or unsigned int. 699 // 700 // If an int can represent all values of the original type, the 701 // value is converted to an int; otherwise, it is converted to an 702 // unsigned int. These are called the integer promotions. All 703 // other types are unchanged by the integer promotions. 704 705 QualType PTy = Context.isPromotableBitField(E); 706 if (!PTy.isNull()) { 707 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 708 return E; 709 } 710 if (Ty->isPromotableIntegerType()) { 711 QualType PT = Context.getPromotedIntegerType(Ty); 712 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 713 return E; 714 } 715 } 716 return E; 717 } 718 719 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 720 /// do not have a prototype. Arguments that have type float or __fp16 721 /// are promoted to double. All other argument types are converted by 722 /// UsualUnaryConversions(). 723 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 724 QualType Ty = E->getType(); 725 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 726 727 ExprResult Res = UsualUnaryConversions(E); 728 if (Res.isInvalid()) 729 return ExprError(); 730 E = Res.get(); 731 732 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 733 // double. 734 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 735 if (BTy && (BTy->getKind() == BuiltinType::Half || 736 BTy->getKind() == BuiltinType::Float)) 737 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 738 739 // C++ performs lvalue-to-rvalue conversion as a default argument 740 // promotion, even on class types, but note: 741 // C++11 [conv.lval]p2: 742 // When an lvalue-to-rvalue conversion occurs in an unevaluated 743 // operand or a subexpression thereof the value contained in the 744 // referenced object is not accessed. Otherwise, if the glvalue 745 // has a class type, the conversion copy-initializes a temporary 746 // of type T from the glvalue and the result of the conversion 747 // is a prvalue for the temporary. 748 // FIXME: add some way to gate this entire thing for correctness in 749 // potentially potentially evaluated contexts. 750 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 751 ExprResult Temp = PerformCopyInitialization( 752 InitializedEntity::InitializeTemporary(E->getType()), 753 E->getExprLoc(), E); 754 if (Temp.isInvalid()) 755 return ExprError(); 756 E = Temp.get(); 757 } 758 759 return E; 760 } 761 762 /// Determine the degree of POD-ness for an expression. 763 /// Incomplete types are considered POD, since this check can be performed 764 /// when we're in an unevaluated context. 765 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 766 if (Ty->isIncompleteType()) { 767 // C++11 [expr.call]p7: 768 // After these conversions, if the argument does not have arithmetic, 769 // enumeration, pointer, pointer to member, or class type, the program 770 // is ill-formed. 771 // 772 // Since we've already performed array-to-pointer and function-to-pointer 773 // decay, the only such type in C++ is cv void. This also handles 774 // initializer lists as variadic arguments. 775 if (Ty->isVoidType()) 776 return VAK_Invalid; 777 778 if (Ty->isObjCObjectType()) 779 return VAK_Invalid; 780 return VAK_Valid; 781 } 782 783 if (Ty.isCXX98PODType(Context)) 784 return VAK_Valid; 785 786 // C++11 [expr.call]p7: 787 // Passing a potentially-evaluated argument of class type (Clause 9) 788 // having a non-trivial copy constructor, a non-trivial move constructor, 789 // or a non-trivial destructor, with no corresponding parameter, 790 // is conditionally-supported with implementation-defined semantics. 791 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 792 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 793 if (!Record->hasNonTrivialCopyConstructor() && 794 !Record->hasNonTrivialMoveConstructor() && 795 !Record->hasNonTrivialDestructor()) 796 return VAK_ValidInCXX11; 797 798 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 799 return VAK_Valid; 800 801 if (Ty->isObjCObjectType()) 802 return VAK_Invalid; 803 804 if (getLangOpts().MSVCCompat) 805 return VAK_MSVCUndefined; 806 807 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 808 // permitted to reject them. We should consider doing so. 809 return VAK_Undefined; 810 } 811 812 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 813 // Don't allow one to pass an Objective-C interface to a vararg. 814 const QualType &Ty = E->getType(); 815 VarArgKind VAK = isValidVarArgType(Ty); 816 817 // Complain about passing non-POD types through varargs. 818 switch (VAK) { 819 case VAK_ValidInCXX11: 820 DiagRuntimeBehavior( 821 E->getLocStart(), nullptr, 822 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 823 << Ty << CT); 824 // Fall through. 825 case VAK_Valid: 826 if (Ty->isRecordType()) { 827 // This is unlikely to be what the user intended. If the class has a 828 // 'c_str' member function, the user probably meant to call that. 829 DiagRuntimeBehavior(E->getLocStart(), nullptr, 830 PDiag(diag::warn_pass_class_arg_to_vararg) 831 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 832 } 833 break; 834 835 case VAK_Undefined: 836 case VAK_MSVCUndefined: 837 DiagRuntimeBehavior( 838 E->getLocStart(), nullptr, 839 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 840 << getLangOpts().CPlusPlus11 << Ty << CT); 841 break; 842 843 case VAK_Invalid: 844 if (Ty->isObjCObjectType()) 845 DiagRuntimeBehavior( 846 E->getLocStart(), nullptr, 847 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 848 << Ty << CT); 849 else 850 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 851 << isa<InitListExpr>(E) << Ty << CT; 852 break; 853 } 854 } 855 856 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 857 /// will create a trap if the resulting type is not a POD type. 858 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 859 FunctionDecl *FDecl) { 860 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 861 // Strip the unbridged-cast placeholder expression off, if applicable. 862 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 863 (CT == VariadicMethod || 864 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 865 E = stripARCUnbridgedCast(E); 866 867 // Otherwise, do normal placeholder checking. 868 } else { 869 ExprResult ExprRes = CheckPlaceholderExpr(E); 870 if (ExprRes.isInvalid()) 871 return ExprError(); 872 E = ExprRes.get(); 873 } 874 } 875 876 ExprResult ExprRes = DefaultArgumentPromotion(E); 877 if (ExprRes.isInvalid()) 878 return ExprError(); 879 E = ExprRes.get(); 880 881 // Diagnostics regarding non-POD argument types are 882 // emitted along with format string checking in Sema::CheckFunctionCall(). 883 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 884 // Turn this into a trap. 885 CXXScopeSpec SS; 886 SourceLocation TemplateKWLoc; 887 UnqualifiedId Name; 888 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 889 E->getLocStart()); 890 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 891 Name, true, false); 892 if (TrapFn.isInvalid()) 893 return ExprError(); 894 895 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 896 E->getLocStart(), None, 897 E->getLocEnd()); 898 if (Call.isInvalid()) 899 return ExprError(); 900 901 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 902 Call.get(), E); 903 if (Comma.isInvalid()) 904 return ExprError(); 905 return Comma.get(); 906 } 907 908 if (!getLangOpts().CPlusPlus && 909 RequireCompleteType(E->getExprLoc(), E->getType(), 910 diag::err_call_incomplete_argument)) 911 return ExprError(); 912 913 return E; 914 } 915 916 /// \brief Converts an integer to complex float type. Helper function of 917 /// UsualArithmeticConversions() 918 /// 919 /// \return false if the integer expression is an integer type and is 920 /// successfully converted to the complex type. 921 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 922 ExprResult &ComplexExpr, 923 QualType IntTy, 924 QualType ComplexTy, 925 bool SkipCast) { 926 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 927 if (SkipCast) return false; 928 if (IntTy->isIntegerType()) { 929 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 930 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 931 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 932 CK_FloatingRealToComplex); 933 } else { 934 assert(IntTy->isComplexIntegerType()); 935 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 936 CK_IntegralComplexToFloatingComplex); 937 } 938 return false; 939 } 940 941 /// \brief Handle arithmetic conversion with complex types. Helper function of 942 /// UsualArithmeticConversions() 943 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 944 ExprResult &RHS, QualType LHSType, 945 QualType RHSType, 946 bool IsCompAssign) { 947 // if we have an integer operand, the result is the complex type. 948 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 949 /*skipCast*/false)) 950 return LHSType; 951 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 952 /*skipCast*/IsCompAssign)) 953 return RHSType; 954 955 // This handles complex/complex, complex/float, or float/complex. 956 // When both operands are complex, the shorter operand is converted to the 957 // type of the longer, and that is the type of the result. This corresponds 958 // to what is done when combining two real floating-point operands. 959 // The fun begins when size promotion occur across type domains. 960 // From H&S 6.3.4: When one operand is complex and the other is a real 961 // floating-point type, the less precise type is converted, within it's 962 // real or complex domain, to the precision of the other type. For example, 963 // when combining a "long double" with a "double _Complex", the 964 // "double _Complex" is promoted to "long double _Complex". 965 966 // Compute the rank of the two types, regardless of whether they are complex. 967 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 968 969 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 970 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 971 QualType LHSElementType = 972 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 973 QualType RHSElementType = 974 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 975 976 QualType ResultType = S.Context.getComplexType(LHSElementType); 977 if (Order < 0) { 978 // Promote the precision of the LHS if not an assignment. 979 ResultType = S.Context.getComplexType(RHSElementType); 980 if (!IsCompAssign) { 981 if (LHSComplexType) 982 LHS = 983 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 984 else 985 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 986 } 987 } else if (Order > 0) { 988 // Promote the precision of the RHS. 989 if (RHSComplexType) 990 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 991 else 992 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 993 } 994 return ResultType; 995 } 996 997 /// \brief Hande arithmetic conversion from integer to float. Helper function 998 /// of UsualArithmeticConversions() 999 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1000 ExprResult &IntExpr, 1001 QualType FloatTy, QualType IntTy, 1002 bool ConvertFloat, bool ConvertInt) { 1003 if (IntTy->isIntegerType()) { 1004 if (ConvertInt) 1005 // Convert intExpr to the lhs floating point type. 1006 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1007 CK_IntegralToFloating); 1008 return FloatTy; 1009 } 1010 1011 // Convert both sides to the appropriate complex float. 1012 assert(IntTy->isComplexIntegerType()); 1013 QualType result = S.Context.getComplexType(FloatTy); 1014 1015 // _Complex int -> _Complex float 1016 if (ConvertInt) 1017 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1018 CK_IntegralComplexToFloatingComplex); 1019 1020 // float -> _Complex float 1021 if (ConvertFloat) 1022 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1023 CK_FloatingRealToComplex); 1024 1025 return result; 1026 } 1027 1028 /// \brief Handle arithmethic conversion with floating point types. Helper 1029 /// function of UsualArithmeticConversions() 1030 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1031 ExprResult &RHS, QualType LHSType, 1032 QualType RHSType, bool IsCompAssign) { 1033 bool LHSFloat = LHSType->isRealFloatingType(); 1034 bool RHSFloat = RHSType->isRealFloatingType(); 1035 1036 // If we have two real floating types, convert the smaller operand 1037 // to the bigger result. 1038 if (LHSFloat && RHSFloat) { 1039 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1040 if (order > 0) { 1041 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1042 return LHSType; 1043 } 1044 1045 assert(order < 0 && "illegal float comparison"); 1046 if (!IsCompAssign) 1047 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1048 return RHSType; 1049 } 1050 1051 if (LHSFloat) 1052 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1053 /*convertFloat=*/!IsCompAssign, 1054 /*convertInt=*/ true); 1055 assert(RHSFloat); 1056 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1057 /*convertInt=*/ true, 1058 /*convertFloat=*/!IsCompAssign); 1059 } 1060 1061 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1062 1063 namespace { 1064 /// These helper callbacks are placed in an anonymous namespace to 1065 /// permit their use as function template parameters. 1066 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1067 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1068 } 1069 1070 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1071 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1072 CK_IntegralComplexCast); 1073 } 1074 } 1075 1076 /// \brief Handle integer arithmetic conversions. Helper function of 1077 /// UsualArithmeticConversions() 1078 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1079 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1080 ExprResult &RHS, QualType LHSType, 1081 QualType RHSType, bool IsCompAssign) { 1082 // The rules for this case are in C99 6.3.1.8 1083 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1084 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1085 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1086 if (LHSSigned == RHSSigned) { 1087 // Same signedness; use the higher-ranked type 1088 if (order >= 0) { 1089 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1090 return LHSType; 1091 } else if (!IsCompAssign) 1092 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1093 return RHSType; 1094 } else if (order != (LHSSigned ? 1 : -1)) { 1095 // The unsigned type has greater than or equal rank to the 1096 // signed type, so use the unsigned type 1097 if (RHSSigned) { 1098 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1099 return LHSType; 1100 } else if (!IsCompAssign) 1101 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1102 return RHSType; 1103 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1104 // The two types are different widths; if we are here, that 1105 // means the signed type is larger than the unsigned type, so 1106 // use the signed type. 1107 if (LHSSigned) { 1108 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1109 return LHSType; 1110 } else if (!IsCompAssign) 1111 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1112 return RHSType; 1113 } else { 1114 // The signed type is higher-ranked than the unsigned type, 1115 // but isn't actually any bigger (like unsigned int and long 1116 // on most 32-bit systems). Use the unsigned type corresponding 1117 // to the signed type. 1118 QualType result = 1119 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1120 RHS = (*doRHSCast)(S, RHS.get(), result); 1121 if (!IsCompAssign) 1122 LHS = (*doLHSCast)(S, LHS.get(), result); 1123 return result; 1124 } 1125 } 1126 1127 /// \brief Handle conversions with GCC complex int extension. Helper function 1128 /// of UsualArithmeticConversions() 1129 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1130 ExprResult &RHS, QualType LHSType, 1131 QualType RHSType, 1132 bool IsCompAssign) { 1133 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1134 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1135 1136 if (LHSComplexInt && RHSComplexInt) { 1137 QualType LHSEltType = LHSComplexInt->getElementType(); 1138 QualType RHSEltType = RHSComplexInt->getElementType(); 1139 QualType ScalarType = 1140 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1141 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1142 1143 return S.Context.getComplexType(ScalarType); 1144 } 1145 1146 if (LHSComplexInt) { 1147 QualType LHSEltType = LHSComplexInt->getElementType(); 1148 QualType ScalarType = 1149 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1150 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1151 QualType ComplexType = S.Context.getComplexType(ScalarType); 1152 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1153 CK_IntegralRealToComplex); 1154 1155 return ComplexType; 1156 } 1157 1158 assert(RHSComplexInt); 1159 1160 QualType RHSEltType = RHSComplexInt->getElementType(); 1161 QualType ScalarType = 1162 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1163 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1164 QualType ComplexType = S.Context.getComplexType(ScalarType); 1165 1166 if (!IsCompAssign) 1167 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1168 CK_IntegralRealToComplex); 1169 return ComplexType; 1170 } 1171 1172 /// UsualArithmeticConversions - Performs various conversions that are common to 1173 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1174 /// routine returns the first non-arithmetic type found. The client is 1175 /// responsible for emitting appropriate error diagnostics. 1176 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1177 bool IsCompAssign) { 1178 if (!IsCompAssign) { 1179 LHS = UsualUnaryConversions(LHS.get()); 1180 if (LHS.isInvalid()) 1181 return QualType(); 1182 } 1183 1184 RHS = UsualUnaryConversions(RHS.get()); 1185 if (RHS.isInvalid()) 1186 return QualType(); 1187 1188 // For conversion purposes, we ignore any qualifiers. 1189 // For example, "const float" and "float" are equivalent. 1190 QualType LHSType = 1191 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1192 QualType RHSType = 1193 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1194 1195 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1196 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1197 LHSType = AtomicLHS->getValueType(); 1198 1199 // If both types are identical, no conversion is needed. 1200 if (LHSType == RHSType) 1201 return LHSType; 1202 1203 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1204 // The caller can deal with this (e.g. pointer + int). 1205 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1206 return QualType(); 1207 1208 // Apply unary and bitfield promotions to the LHS's type. 1209 QualType LHSUnpromotedType = LHSType; 1210 if (LHSType->isPromotableIntegerType()) 1211 LHSType = Context.getPromotedIntegerType(LHSType); 1212 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1213 if (!LHSBitfieldPromoteTy.isNull()) 1214 LHSType = LHSBitfieldPromoteTy; 1215 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1216 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1217 1218 // If both types are identical, no conversion is needed. 1219 if (LHSType == RHSType) 1220 return LHSType; 1221 1222 // At this point, we have two different arithmetic types. 1223 1224 // Handle complex types first (C99 6.3.1.8p1). 1225 if (LHSType->isComplexType() || RHSType->isComplexType()) 1226 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1227 IsCompAssign); 1228 1229 // Now handle "real" floating types (i.e. float, double, long double). 1230 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1231 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1232 IsCompAssign); 1233 1234 // Handle GCC complex int extension. 1235 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1236 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1237 IsCompAssign); 1238 1239 // Finally, we have two differing integer types. 1240 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1241 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1242 } 1243 1244 1245 //===----------------------------------------------------------------------===// 1246 // Semantic Analysis for various Expression Types 1247 //===----------------------------------------------------------------------===// 1248 1249 1250 ExprResult 1251 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1252 SourceLocation DefaultLoc, 1253 SourceLocation RParenLoc, 1254 Expr *ControllingExpr, 1255 ArrayRef<ParsedType> ArgTypes, 1256 ArrayRef<Expr *> ArgExprs) { 1257 unsigned NumAssocs = ArgTypes.size(); 1258 assert(NumAssocs == ArgExprs.size()); 1259 1260 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1261 for (unsigned i = 0; i < NumAssocs; ++i) { 1262 if (ArgTypes[i]) 1263 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1264 else 1265 Types[i] = nullptr; 1266 } 1267 1268 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1269 ControllingExpr, 1270 llvm::makeArrayRef(Types, NumAssocs), 1271 ArgExprs); 1272 delete [] Types; 1273 return ER; 1274 } 1275 1276 ExprResult 1277 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1278 SourceLocation DefaultLoc, 1279 SourceLocation RParenLoc, 1280 Expr *ControllingExpr, 1281 ArrayRef<TypeSourceInfo *> Types, 1282 ArrayRef<Expr *> Exprs) { 1283 unsigned NumAssocs = Types.size(); 1284 assert(NumAssocs == Exprs.size()); 1285 if (ControllingExpr->getType()->isPlaceholderType()) { 1286 ExprResult result = CheckPlaceholderExpr(ControllingExpr); 1287 if (result.isInvalid()) return ExprError(); 1288 ControllingExpr = result.get(); 1289 } 1290 1291 bool TypeErrorFound = false, 1292 IsResultDependent = ControllingExpr->isTypeDependent(), 1293 ContainsUnexpandedParameterPack 1294 = ControllingExpr->containsUnexpandedParameterPack(); 1295 1296 for (unsigned i = 0; i < NumAssocs; ++i) { 1297 if (Exprs[i]->containsUnexpandedParameterPack()) 1298 ContainsUnexpandedParameterPack = true; 1299 1300 if (Types[i]) { 1301 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1302 ContainsUnexpandedParameterPack = true; 1303 1304 if (Types[i]->getType()->isDependentType()) { 1305 IsResultDependent = true; 1306 } else { 1307 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1308 // complete object type other than a variably modified type." 1309 unsigned D = 0; 1310 if (Types[i]->getType()->isIncompleteType()) 1311 D = diag::err_assoc_type_incomplete; 1312 else if (!Types[i]->getType()->isObjectType()) 1313 D = diag::err_assoc_type_nonobject; 1314 else if (Types[i]->getType()->isVariablyModifiedType()) 1315 D = diag::err_assoc_type_variably_modified; 1316 1317 if (D != 0) { 1318 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1319 << Types[i]->getTypeLoc().getSourceRange() 1320 << Types[i]->getType(); 1321 TypeErrorFound = true; 1322 } 1323 1324 // C11 6.5.1.1p2 "No two generic associations in the same generic 1325 // selection shall specify compatible types." 1326 for (unsigned j = i+1; j < NumAssocs; ++j) 1327 if (Types[j] && !Types[j]->getType()->isDependentType() && 1328 Context.typesAreCompatible(Types[i]->getType(), 1329 Types[j]->getType())) { 1330 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1331 diag::err_assoc_compatible_types) 1332 << Types[j]->getTypeLoc().getSourceRange() 1333 << Types[j]->getType() 1334 << Types[i]->getType(); 1335 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1336 diag::note_compat_assoc) 1337 << Types[i]->getTypeLoc().getSourceRange() 1338 << Types[i]->getType(); 1339 TypeErrorFound = true; 1340 } 1341 } 1342 } 1343 } 1344 if (TypeErrorFound) 1345 return ExprError(); 1346 1347 // If we determined that the generic selection is result-dependent, don't 1348 // try to compute the result expression. 1349 if (IsResultDependent) 1350 return new (Context) GenericSelectionExpr( 1351 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1352 ContainsUnexpandedParameterPack); 1353 1354 SmallVector<unsigned, 1> CompatIndices; 1355 unsigned DefaultIndex = -1U; 1356 for (unsigned i = 0; i < NumAssocs; ++i) { 1357 if (!Types[i]) 1358 DefaultIndex = i; 1359 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1360 Types[i]->getType())) 1361 CompatIndices.push_back(i); 1362 } 1363 1364 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1365 // type compatible with at most one of the types named in its generic 1366 // association list." 1367 if (CompatIndices.size() > 1) { 1368 // We strip parens here because the controlling expression is typically 1369 // parenthesized in macro definitions. 1370 ControllingExpr = ControllingExpr->IgnoreParens(); 1371 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1372 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1373 << (unsigned) CompatIndices.size(); 1374 for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(), 1375 E = CompatIndices.end(); I != E; ++I) { 1376 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1377 diag::note_compat_assoc) 1378 << Types[*I]->getTypeLoc().getSourceRange() 1379 << Types[*I]->getType(); 1380 } 1381 return ExprError(); 1382 } 1383 1384 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1385 // its controlling expression shall have type compatible with exactly one of 1386 // the types named in its generic association list." 1387 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1388 // We strip parens here because the controlling expression is typically 1389 // parenthesized in macro definitions. 1390 ControllingExpr = ControllingExpr->IgnoreParens(); 1391 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1392 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1393 return ExprError(); 1394 } 1395 1396 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1397 // type name that is compatible with the type of the controlling expression, 1398 // then the result expression of the generic selection is the expression 1399 // in that generic association. Otherwise, the result expression of the 1400 // generic selection is the expression in the default generic association." 1401 unsigned ResultIndex = 1402 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1403 1404 return new (Context) GenericSelectionExpr( 1405 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1406 ContainsUnexpandedParameterPack, ResultIndex); 1407 } 1408 1409 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1410 /// location of the token and the offset of the ud-suffix within it. 1411 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1412 unsigned Offset) { 1413 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1414 S.getLangOpts()); 1415 } 1416 1417 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1418 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1419 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1420 IdentifierInfo *UDSuffix, 1421 SourceLocation UDSuffixLoc, 1422 ArrayRef<Expr*> Args, 1423 SourceLocation LitEndLoc) { 1424 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1425 1426 QualType ArgTy[2]; 1427 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1428 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1429 if (ArgTy[ArgIdx]->isArrayType()) 1430 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1431 } 1432 1433 DeclarationName OpName = 1434 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1435 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1436 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1437 1438 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1439 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1440 /*AllowRaw*/false, /*AllowTemplate*/false, 1441 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1442 return ExprError(); 1443 1444 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1445 } 1446 1447 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1448 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1449 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1450 /// multiple tokens. However, the common case is that StringToks points to one 1451 /// string. 1452 /// 1453 ExprResult 1454 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1455 assert(!StringToks.empty() && "Must have at least one string!"); 1456 1457 StringLiteralParser Literal(StringToks, PP); 1458 if (Literal.hadError) 1459 return ExprError(); 1460 1461 SmallVector<SourceLocation, 4> StringTokLocs; 1462 for (unsigned i = 0; i != StringToks.size(); ++i) 1463 StringTokLocs.push_back(StringToks[i].getLocation()); 1464 1465 QualType CharTy = Context.CharTy; 1466 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1467 if (Literal.isWide()) { 1468 CharTy = Context.getWideCharType(); 1469 Kind = StringLiteral::Wide; 1470 } else if (Literal.isUTF8()) { 1471 Kind = StringLiteral::UTF8; 1472 } else if (Literal.isUTF16()) { 1473 CharTy = Context.Char16Ty; 1474 Kind = StringLiteral::UTF16; 1475 } else if (Literal.isUTF32()) { 1476 CharTy = Context.Char32Ty; 1477 Kind = StringLiteral::UTF32; 1478 } else if (Literal.isPascal()) { 1479 CharTy = Context.UnsignedCharTy; 1480 } 1481 1482 QualType CharTyConst = CharTy; 1483 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1484 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1485 CharTyConst.addConst(); 1486 1487 // Get an array type for the string, according to C99 6.4.5. This includes 1488 // the nul terminator character as well as the string length for pascal 1489 // strings. 1490 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1491 llvm::APInt(32, Literal.GetNumStringChars()+1), 1492 ArrayType::Normal, 0); 1493 1494 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1495 if (getLangOpts().OpenCL) { 1496 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1497 } 1498 1499 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1500 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1501 Kind, Literal.Pascal, StrTy, 1502 &StringTokLocs[0], 1503 StringTokLocs.size()); 1504 if (Literal.getUDSuffix().empty()) 1505 return Lit; 1506 1507 // We're building a user-defined literal. 1508 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1509 SourceLocation UDSuffixLoc = 1510 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1511 Literal.getUDSuffixOffset()); 1512 1513 // Make sure we're allowed user-defined literals here. 1514 if (!UDLScope) 1515 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1516 1517 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1518 // operator "" X (str, len) 1519 QualType SizeType = Context.getSizeType(); 1520 1521 DeclarationName OpName = 1522 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1523 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1524 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1525 1526 QualType ArgTy[] = { 1527 Context.getArrayDecayedType(StrTy), SizeType 1528 }; 1529 1530 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1531 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1532 /*AllowRaw*/false, /*AllowTemplate*/false, 1533 /*AllowStringTemplate*/true)) { 1534 1535 case LOLR_Cooked: { 1536 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1537 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1538 StringTokLocs[0]); 1539 Expr *Args[] = { Lit, LenArg }; 1540 1541 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1542 } 1543 1544 case LOLR_StringTemplate: { 1545 TemplateArgumentListInfo ExplicitArgs; 1546 1547 unsigned CharBits = Context.getIntWidth(CharTy); 1548 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1549 llvm::APSInt Value(CharBits, CharIsUnsigned); 1550 1551 TemplateArgument TypeArg(CharTy); 1552 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1553 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1554 1555 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1556 Value = Lit->getCodeUnit(I); 1557 TemplateArgument Arg(Context, Value, CharTy); 1558 TemplateArgumentLocInfo ArgInfo; 1559 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1560 } 1561 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1562 &ExplicitArgs); 1563 } 1564 case LOLR_Raw: 1565 case LOLR_Template: 1566 llvm_unreachable("unexpected literal operator lookup result"); 1567 case LOLR_Error: 1568 return ExprError(); 1569 } 1570 llvm_unreachable("unexpected literal operator lookup result"); 1571 } 1572 1573 ExprResult 1574 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1575 SourceLocation Loc, 1576 const CXXScopeSpec *SS) { 1577 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1578 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1579 } 1580 1581 /// BuildDeclRefExpr - Build an expression that references a 1582 /// declaration that does not require a closure capture. 1583 ExprResult 1584 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1585 const DeclarationNameInfo &NameInfo, 1586 const CXXScopeSpec *SS, NamedDecl *FoundD, 1587 const TemplateArgumentListInfo *TemplateArgs) { 1588 if (getLangOpts().CUDA) 1589 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1590 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1591 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller), 1592 CalleeTarget = IdentifyCUDATarget(Callee); 1593 if (CheckCUDATarget(CallerTarget, CalleeTarget)) { 1594 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1595 << CalleeTarget << D->getIdentifier() << CallerTarget; 1596 Diag(D->getLocation(), diag::note_previous_decl) 1597 << D->getIdentifier(); 1598 return ExprError(); 1599 } 1600 } 1601 1602 bool refersToEnclosingScope = 1603 (CurContext != D->getDeclContext() && 1604 D->getDeclContext()->isFunctionOrMethod()) || 1605 (isa<VarDecl>(D) && 1606 cast<VarDecl>(D)->isInitCapture()); 1607 1608 DeclRefExpr *E; 1609 if (isa<VarTemplateSpecializationDecl>(D)) { 1610 VarTemplateSpecializationDecl *VarSpec = 1611 cast<VarTemplateSpecializationDecl>(D); 1612 1613 E = DeclRefExpr::Create( 1614 Context, 1615 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1616 VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope, 1617 NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs); 1618 } else { 1619 assert(!TemplateArgs && "No template arguments for non-variable" 1620 " template specialization references"); 1621 E = DeclRefExpr::Create( 1622 Context, 1623 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1624 SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD); 1625 } 1626 1627 MarkDeclRefReferenced(E); 1628 1629 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) && 1630 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1631 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1632 recordUseOfEvaluatedWeak(E); 1633 1634 // Just in case we're building an illegal pointer-to-member. 1635 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1636 if (FD && FD->isBitField()) 1637 E->setObjectKind(OK_BitField); 1638 1639 return E; 1640 } 1641 1642 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1643 /// possibly a list of template arguments. 1644 /// 1645 /// If this produces template arguments, it is permitted to call 1646 /// DecomposeTemplateName. 1647 /// 1648 /// This actually loses a lot of source location information for 1649 /// non-standard name kinds; we should consider preserving that in 1650 /// some way. 1651 void 1652 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1653 TemplateArgumentListInfo &Buffer, 1654 DeclarationNameInfo &NameInfo, 1655 const TemplateArgumentListInfo *&TemplateArgs) { 1656 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1657 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1658 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1659 1660 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1661 Id.TemplateId->NumArgs); 1662 translateTemplateArguments(TemplateArgsPtr, Buffer); 1663 1664 TemplateName TName = Id.TemplateId->Template.get(); 1665 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1666 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1667 TemplateArgs = &Buffer; 1668 } else { 1669 NameInfo = GetNameFromUnqualifiedId(Id); 1670 TemplateArgs = nullptr; 1671 } 1672 } 1673 1674 /// Diagnose an empty lookup. 1675 /// 1676 /// \return false if new lookup candidates were found 1677 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1678 CorrectionCandidateCallback &CCC, 1679 TemplateArgumentListInfo *ExplicitTemplateArgs, 1680 ArrayRef<Expr *> Args) { 1681 DeclarationName Name = R.getLookupName(); 1682 1683 unsigned diagnostic = diag::err_undeclared_var_use; 1684 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1685 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1686 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1687 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1688 diagnostic = diag::err_undeclared_use; 1689 diagnostic_suggest = diag::err_undeclared_use_suggest; 1690 } 1691 1692 // If the original lookup was an unqualified lookup, fake an 1693 // unqualified lookup. This is useful when (for example) the 1694 // original lookup would not have found something because it was a 1695 // dependent name. 1696 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty()) 1697 ? CurContext : nullptr; 1698 while (DC) { 1699 if (isa<CXXRecordDecl>(DC)) { 1700 LookupQualifiedName(R, DC); 1701 1702 if (!R.empty()) { 1703 // Don't give errors about ambiguities in this lookup. 1704 R.suppressDiagnostics(); 1705 1706 // During a default argument instantiation the CurContext points 1707 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1708 // function parameter list, hence add an explicit check. 1709 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1710 ActiveTemplateInstantiations.back().Kind == 1711 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1712 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1713 bool isInstance = CurMethod && 1714 CurMethod->isInstance() && 1715 DC == CurMethod->getParent() && !isDefaultArgument; 1716 1717 1718 // Give a code modification hint to insert 'this->'. 1719 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1720 // Actually quite difficult! 1721 if (getLangOpts().MSVCCompat) 1722 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1723 if (isInstance) { 1724 Diag(R.getNameLoc(), diagnostic) << Name 1725 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1726 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1727 CallsUndergoingInstantiation.back()->getCallee()); 1728 1729 CXXMethodDecl *DepMethod; 1730 if (CurMethod->isDependentContext()) 1731 DepMethod = CurMethod; 1732 else if (CurMethod->getTemplatedKind() == 1733 FunctionDecl::TK_FunctionTemplateSpecialization) 1734 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()-> 1735 getInstantiatedFromMemberTemplate()->getTemplatedDecl()); 1736 else 1737 DepMethod = cast<CXXMethodDecl>( 1738 CurMethod->getInstantiatedFromMemberFunction()); 1739 assert(DepMethod && "No template pattern found"); 1740 1741 QualType DepThisType = DepMethod->getThisType(Context); 1742 CheckCXXThisCapture(R.getNameLoc()); 1743 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1744 R.getNameLoc(), DepThisType, false); 1745 TemplateArgumentListInfo TList; 1746 if (ULE->hasExplicitTemplateArgs()) 1747 ULE->copyTemplateArgumentsInto(TList); 1748 1749 CXXScopeSpec SS; 1750 SS.Adopt(ULE->getQualifierLoc()); 1751 CXXDependentScopeMemberExpr *DepExpr = 1752 CXXDependentScopeMemberExpr::Create( 1753 Context, DepThis, DepThisType, true, SourceLocation(), 1754 SS.getWithLocInContext(Context), 1755 ULE->getTemplateKeywordLoc(), nullptr, 1756 R.getLookupNameInfo(), 1757 ULE->hasExplicitTemplateArgs() ? &TList : nullptr); 1758 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1759 } else { 1760 Diag(R.getNameLoc(), diagnostic) << Name; 1761 } 1762 1763 // Do we really want to note all of these? 1764 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1765 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1766 1767 // Return true if we are inside a default argument instantiation 1768 // and the found name refers to an instance member function, otherwise 1769 // the function calling DiagnoseEmptyLookup will try to create an 1770 // implicit member call and this is wrong for default argument. 1771 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1772 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1773 return true; 1774 } 1775 1776 // Tell the callee to try to recover. 1777 return false; 1778 } 1779 1780 R.clear(); 1781 } 1782 1783 // In Microsoft mode, if we are performing lookup from within a friend 1784 // function definition declared at class scope then we must set 1785 // DC to the lexical parent to be able to search into the parent 1786 // class. 1787 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1788 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1789 DC->getLexicalParent()->isRecord()) 1790 DC = DC->getLexicalParent(); 1791 else 1792 DC = DC->getParent(); 1793 } 1794 1795 // We didn't find anything, so try to correct for a typo. 1796 TypoCorrection Corrected; 1797 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), 1798 S, &SS, CCC, CTK_ErrorRecovery))) { 1799 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1800 bool DroppedSpecifier = 1801 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1802 R.setLookupName(Corrected.getCorrection()); 1803 1804 bool AcceptableWithRecovery = false; 1805 bool AcceptableWithoutRecovery = false; 1806 NamedDecl *ND = Corrected.getCorrectionDecl(); 1807 if (ND) { 1808 if (Corrected.isOverloaded()) { 1809 OverloadCandidateSet OCS(R.getNameLoc(), 1810 OverloadCandidateSet::CSK_Normal); 1811 OverloadCandidateSet::iterator Best; 1812 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1813 CDEnd = Corrected.end(); 1814 CD != CDEnd; ++CD) { 1815 if (FunctionTemplateDecl *FTD = 1816 dyn_cast<FunctionTemplateDecl>(*CD)) 1817 AddTemplateOverloadCandidate( 1818 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1819 Args, OCS); 1820 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1821 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1822 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1823 Args, OCS); 1824 } 1825 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1826 case OR_Success: 1827 ND = Best->Function; 1828 Corrected.setCorrectionDecl(ND); 1829 break; 1830 default: 1831 // FIXME: Arbitrarily pick the first declaration for the note. 1832 Corrected.setCorrectionDecl(ND); 1833 break; 1834 } 1835 } 1836 R.addDecl(ND); 1837 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1838 CXXRecordDecl *Record = nullptr; 1839 if (Corrected.getCorrectionSpecifier()) { 1840 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1841 Record = Ty->getAsCXXRecordDecl(); 1842 } 1843 if (!Record) 1844 Record = cast<CXXRecordDecl>( 1845 ND->getDeclContext()->getRedeclContext()); 1846 R.setNamingClass(Record); 1847 } 1848 1849 AcceptableWithRecovery = 1850 isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND); 1851 // FIXME: If we ended up with a typo for a type name or 1852 // Objective-C class name, we're in trouble because the parser 1853 // is in the wrong place to recover. Suggest the typo 1854 // correction, but don't make it a fix-it since we're not going 1855 // to recover well anyway. 1856 AcceptableWithoutRecovery = 1857 isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 1858 } else { 1859 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1860 // because we aren't able to recover. 1861 AcceptableWithoutRecovery = true; 1862 } 1863 1864 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1865 unsigned NoteID = (Corrected.getCorrectionDecl() && 1866 isa<ImplicitParamDecl>(Corrected.getCorrectionDecl())) 1867 ? diag::note_implicit_param_decl 1868 : diag::note_previous_decl; 1869 if (SS.isEmpty()) 1870 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1871 PDiag(NoteID), AcceptableWithRecovery); 1872 else 1873 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1874 << Name << computeDeclContext(SS, false) 1875 << DroppedSpecifier << SS.getRange(), 1876 PDiag(NoteID), AcceptableWithRecovery); 1877 1878 // Tell the callee whether to try to recover. 1879 return !AcceptableWithRecovery; 1880 } 1881 } 1882 R.clear(); 1883 1884 // Emit a special diagnostic for failed member lookups. 1885 // FIXME: computing the declaration context might fail here (?) 1886 if (!SS.isEmpty()) { 1887 Diag(R.getNameLoc(), diag::err_no_member) 1888 << Name << computeDeclContext(SS, false) 1889 << SS.getRange(); 1890 return true; 1891 } 1892 1893 // Give up, we can't recover. 1894 Diag(R.getNameLoc(), diagnostic) << Name; 1895 return true; 1896 } 1897 1898 /// In Microsoft mode, if we are inside a template class whose parent class has 1899 /// dependent base classes, and we can't resolve an unqualified identifier, then 1900 /// assume the identifier is a member of a dependent base class. We can only 1901 /// recover successfully in static methods, instance methods, and other contexts 1902 /// where 'this' is available. This doesn't precisely match MSVC's 1903 /// instantiation model, but it's close enough. 1904 static Expr * 1905 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 1906 DeclarationNameInfo &NameInfo, 1907 SourceLocation TemplateKWLoc, 1908 const TemplateArgumentListInfo *TemplateArgs) { 1909 // Only try to recover from lookup into dependent bases in static methods or 1910 // contexts where 'this' is available. 1911 QualType ThisType = S.getCurrentThisType(); 1912 const CXXRecordDecl *RD = nullptr; 1913 if (!ThisType.isNull()) 1914 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 1915 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 1916 RD = MD->getParent(); 1917 if (!RD || !RD->hasAnyDependentBases()) 1918 return nullptr; 1919 1920 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 1921 // is available, suggest inserting 'this->' as a fixit. 1922 SourceLocation Loc = NameInfo.getLoc(); 1923 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 1924 DB << NameInfo.getName() << RD; 1925 1926 if (!ThisType.isNull()) { 1927 DB << FixItHint::CreateInsertion(Loc, "this->"); 1928 return CXXDependentScopeMemberExpr::Create( 1929 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 1930 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 1931 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 1932 } 1933 1934 // Synthesize a fake NNS that points to the derived class. This will 1935 // perform name lookup during template instantiation. 1936 CXXScopeSpec SS; 1937 auto *NNS = 1938 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 1939 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 1940 return DependentScopeDeclRefExpr::Create( 1941 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 1942 TemplateArgs); 1943 } 1944 1945 ExprResult Sema::ActOnIdExpression(Scope *S, 1946 CXXScopeSpec &SS, 1947 SourceLocation TemplateKWLoc, 1948 UnqualifiedId &Id, 1949 bool HasTrailingLParen, 1950 bool IsAddressOfOperand, 1951 CorrectionCandidateCallback *CCC, 1952 bool IsInlineAsmIdentifier) { 1953 assert(!(IsAddressOfOperand && HasTrailingLParen) && 1954 "cannot be direct & operand and have a trailing lparen"); 1955 if (SS.isInvalid()) 1956 return ExprError(); 1957 1958 TemplateArgumentListInfo TemplateArgsBuffer; 1959 1960 // Decompose the UnqualifiedId into the following data. 1961 DeclarationNameInfo NameInfo; 1962 const TemplateArgumentListInfo *TemplateArgs; 1963 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 1964 1965 DeclarationName Name = NameInfo.getName(); 1966 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1967 SourceLocation NameLoc = NameInfo.getLoc(); 1968 1969 // C++ [temp.dep.expr]p3: 1970 // An id-expression is type-dependent if it contains: 1971 // -- an identifier that was declared with a dependent type, 1972 // (note: handled after lookup) 1973 // -- a template-id that is dependent, 1974 // (note: handled in BuildTemplateIdExpr) 1975 // -- a conversion-function-id that specifies a dependent type, 1976 // -- a nested-name-specifier that contains a class-name that 1977 // names a dependent type. 1978 // Determine whether this is a member of an unknown specialization; 1979 // we need to handle these differently. 1980 bool DependentID = false; 1981 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 1982 Name.getCXXNameType()->isDependentType()) { 1983 DependentID = true; 1984 } else if (SS.isSet()) { 1985 if (DeclContext *DC = computeDeclContext(SS, false)) { 1986 if (RequireCompleteDeclContext(SS, DC)) 1987 return ExprError(); 1988 } else { 1989 DependentID = true; 1990 } 1991 } 1992 1993 if (DependentID) 1994 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 1995 IsAddressOfOperand, TemplateArgs); 1996 1997 // Perform the required lookup. 1998 LookupResult R(*this, NameInfo, 1999 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2000 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2001 if (TemplateArgs) { 2002 // Lookup the template name again to correctly establish the context in 2003 // which it was found. This is really unfortunate as we already did the 2004 // lookup to determine that it was a template name in the first place. If 2005 // this becomes a performance hit, we can work harder to preserve those 2006 // results until we get here but it's likely not worth it. 2007 bool MemberOfUnknownSpecialization; 2008 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2009 MemberOfUnknownSpecialization); 2010 2011 if (MemberOfUnknownSpecialization || 2012 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2013 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2014 IsAddressOfOperand, TemplateArgs); 2015 } else { 2016 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2017 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2018 2019 // If the result might be in a dependent base class, this is a dependent 2020 // id-expression. 2021 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2022 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2023 IsAddressOfOperand, TemplateArgs); 2024 2025 // If this reference is in an Objective-C method, then we need to do 2026 // some special Objective-C lookup, too. 2027 if (IvarLookupFollowUp) { 2028 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2029 if (E.isInvalid()) 2030 return ExprError(); 2031 2032 if (Expr *Ex = E.getAs<Expr>()) 2033 return Ex; 2034 } 2035 } 2036 2037 if (R.isAmbiguous()) 2038 return ExprError(); 2039 2040 // This could be an implicitly declared function reference (legal in C90, 2041 // extension in C99, forbidden in C++). 2042 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2043 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2044 if (D) R.addDecl(D); 2045 } 2046 2047 // Determine whether this name might be a candidate for 2048 // argument-dependent lookup. 2049 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2050 2051 if (R.empty() && !ADL) { 2052 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2053 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2054 TemplateKWLoc, TemplateArgs)) 2055 return E; 2056 } 2057 2058 // Don't diagnose an empty lookup for inline assembly. 2059 if (IsInlineAsmIdentifier) 2060 return ExprError(); 2061 2062 // If this name wasn't predeclared and if this is not a function 2063 // call, diagnose the problem. 2064 CorrectionCandidateCallback DefaultValidator; 2065 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand; 2066 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2067 "Typo correction callback misconfigured"); 2068 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator)) 2069 return ExprError(); 2070 2071 assert(!R.empty() && 2072 "DiagnoseEmptyLookup returned false but added no results"); 2073 2074 // If we found an Objective-C instance variable, let 2075 // LookupInObjCMethod build the appropriate expression to 2076 // reference the ivar. 2077 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2078 R.clear(); 2079 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2080 // In a hopelessly buggy code, Objective-C instance variable 2081 // lookup fails and no expression will be built to reference it. 2082 if (!E.isInvalid() && !E.get()) 2083 return ExprError(); 2084 return E; 2085 } 2086 } 2087 2088 // This is guaranteed from this point on. 2089 assert(!R.empty() || ADL); 2090 2091 // Check whether this might be a C++ implicit instance member access. 2092 // C++ [class.mfct.non-static]p3: 2093 // When an id-expression that is not part of a class member access 2094 // syntax and not used to form a pointer to member is used in the 2095 // body of a non-static member function of class X, if name lookup 2096 // resolves the name in the id-expression to a non-static non-type 2097 // member of some class C, the id-expression is transformed into a 2098 // class member access expression using (*this) as the 2099 // postfix-expression to the left of the . operator. 2100 // 2101 // But we don't actually need to do this for '&' operands if R 2102 // resolved to a function or overloaded function set, because the 2103 // expression is ill-formed if it actually works out to be a 2104 // non-static member function: 2105 // 2106 // C++ [expr.ref]p4: 2107 // Otherwise, if E1.E2 refers to a non-static member function. . . 2108 // [t]he expression can be used only as the left-hand operand of a 2109 // member function call. 2110 // 2111 // There are other safeguards against such uses, but it's important 2112 // to get this right here so that we don't end up making a 2113 // spuriously dependent expression if we're inside a dependent 2114 // instance method. 2115 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2116 bool MightBeImplicitMember; 2117 if (!IsAddressOfOperand) 2118 MightBeImplicitMember = true; 2119 else if (!SS.isEmpty()) 2120 MightBeImplicitMember = false; 2121 else if (R.isOverloadedResult()) 2122 MightBeImplicitMember = false; 2123 else if (R.isUnresolvableResult()) 2124 MightBeImplicitMember = true; 2125 else 2126 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2127 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2128 isa<MSPropertyDecl>(R.getFoundDecl()); 2129 2130 if (MightBeImplicitMember) 2131 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2132 R, TemplateArgs); 2133 } 2134 2135 if (TemplateArgs || TemplateKWLoc.isValid()) { 2136 2137 // In C++1y, if this is a variable template id, then check it 2138 // in BuildTemplateIdExpr(). 2139 // The single lookup result must be a variable template declaration. 2140 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2141 Id.TemplateId->Kind == TNK_Var_template) { 2142 assert(R.getAsSingle<VarTemplateDecl>() && 2143 "There should only be one declaration found."); 2144 } 2145 2146 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2147 } 2148 2149 return BuildDeclarationNameExpr(SS, R, ADL); 2150 } 2151 2152 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2153 /// declaration name, generally during template instantiation. 2154 /// There's a large number of things which don't need to be done along 2155 /// this path. 2156 ExprResult 2157 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2158 const DeclarationNameInfo &NameInfo, 2159 bool IsAddressOfOperand, 2160 TypeSourceInfo **RecoveryTSI) { 2161 DeclContext *DC = computeDeclContext(SS, false); 2162 if (!DC) 2163 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2164 NameInfo, /*TemplateArgs=*/nullptr); 2165 2166 if (RequireCompleteDeclContext(SS, DC)) 2167 return ExprError(); 2168 2169 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2170 LookupQualifiedName(R, DC); 2171 2172 if (R.isAmbiguous()) 2173 return ExprError(); 2174 2175 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2176 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2177 NameInfo, /*TemplateArgs=*/nullptr); 2178 2179 if (R.empty()) { 2180 Diag(NameInfo.getLoc(), diag::err_no_member) 2181 << NameInfo.getName() << DC << SS.getRange(); 2182 return ExprError(); 2183 } 2184 2185 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2186 // Diagnose a missing typename if this resolved unambiguously to a type in 2187 // a dependent context. If we can recover with a type, downgrade this to 2188 // a warning in Microsoft compatibility mode. 2189 unsigned DiagID = diag::err_typename_missing; 2190 if (RecoveryTSI && getLangOpts().MSVCCompat) 2191 DiagID = diag::ext_typename_missing; 2192 SourceLocation Loc = SS.getBeginLoc(); 2193 auto D = Diag(Loc, DiagID); 2194 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2195 << SourceRange(Loc, NameInfo.getEndLoc()); 2196 2197 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2198 // context. 2199 if (!RecoveryTSI) 2200 return ExprError(); 2201 2202 // Only issue the fixit if we're prepared to recover. 2203 D << FixItHint::CreateInsertion(Loc, "typename "); 2204 2205 // Recover by pretending this was an elaborated type. 2206 QualType Ty = Context.getTypeDeclType(TD); 2207 TypeLocBuilder TLB; 2208 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2209 2210 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2211 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2212 QTL.setElaboratedKeywordLoc(SourceLocation()); 2213 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2214 2215 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2216 2217 return ExprEmpty(); 2218 } 2219 2220 // Defend against this resolving to an implicit member access. We usually 2221 // won't get here if this might be a legitimate a class member (we end up in 2222 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2223 // a pointer-to-member or in an unevaluated context in C++11. 2224 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2225 return BuildPossibleImplicitMemberExpr(SS, 2226 /*TemplateKWLoc=*/SourceLocation(), 2227 R, /*TemplateArgs=*/nullptr); 2228 2229 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2230 } 2231 2232 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2233 /// detected that we're currently inside an ObjC method. Perform some 2234 /// additional lookup. 2235 /// 2236 /// Ideally, most of this would be done by lookup, but there's 2237 /// actually quite a lot of extra work involved. 2238 /// 2239 /// Returns a null sentinel to indicate trivial success. 2240 ExprResult 2241 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2242 IdentifierInfo *II, bool AllowBuiltinCreation) { 2243 SourceLocation Loc = Lookup.getNameLoc(); 2244 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2245 2246 // Check for error condition which is already reported. 2247 if (!CurMethod) 2248 return ExprError(); 2249 2250 // There are two cases to handle here. 1) scoped lookup could have failed, 2251 // in which case we should look for an ivar. 2) scoped lookup could have 2252 // found a decl, but that decl is outside the current instance method (i.e. 2253 // a global variable). In these two cases, we do a lookup for an ivar with 2254 // this name, if the lookup sucedes, we replace it our current decl. 2255 2256 // If we're in a class method, we don't normally want to look for 2257 // ivars. But if we don't find anything else, and there's an 2258 // ivar, that's an error. 2259 bool IsClassMethod = CurMethod->isClassMethod(); 2260 2261 bool LookForIvars; 2262 if (Lookup.empty()) 2263 LookForIvars = true; 2264 else if (IsClassMethod) 2265 LookForIvars = false; 2266 else 2267 LookForIvars = (Lookup.isSingleResult() && 2268 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2269 ObjCInterfaceDecl *IFace = nullptr; 2270 if (LookForIvars) { 2271 IFace = CurMethod->getClassInterface(); 2272 ObjCInterfaceDecl *ClassDeclared; 2273 ObjCIvarDecl *IV = nullptr; 2274 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2275 // Diagnose using an ivar in a class method. 2276 if (IsClassMethod) 2277 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2278 << IV->getDeclName()); 2279 2280 // If we're referencing an invalid decl, just return this as a silent 2281 // error node. The error diagnostic was already emitted on the decl. 2282 if (IV->isInvalidDecl()) 2283 return ExprError(); 2284 2285 // Check if referencing a field with __attribute__((deprecated)). 2286 if (DiagnoseUseOfDecl(IV, Loc)) 2287 return ExprError(); 2288 2289 // Diagnose the use of an ivar outside of the declaring class. 2290 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2291 !declaresSameEntity(ClassDeclared, IFace) && 2292 !getLangOpts().DebuggerSupport) 2293 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2294 2295 // FIXME: This should use a new expr for a direct reference, don't 2296 // turn this into Self->ivar, just return a BareIVarExpr or something. 2297 IdentifierInfo &II = Context.Idents.get("self"); 2298 UnqualifiedId SelfName; 2299 SelfName.setIdentifier(&II, SourceLocation()); 2300 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2301 CXXScopeSpec SelfScopeSpec; 2302 SourceLocation TemplateKWLoc; 2303 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2304 SelfName, false, false); 2305 if (SelfExpr.isInvalid()) 2306 return ExprError(); 2307 2308 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2309 if (SelfExpr.isInvalid()) 2310 return ExprError(); 2311 2312 MarkAnyDeclReferenced(Loc, IV, true); 2313 2314 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2315 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2316 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2317 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2318 2319 ObjCIvarRefExpr *Result = new (Context) 2320 ObjCIvarRefExpr(IV, IV->getType(), Loc, IV->getLocation(), 2321 SelfExpr.get(), true, true); 2322 2323 if (getLangOpts().ObjCAutoRefCount) { 2324 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2325 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2326 recordUseOfEvaluatedWeak(Result); 2327 } 2328 if (CurContext->isClosure()) 2329 Diag(Loc, diag::warn_implicitly_retains_self) 2330 << FixItHint::CreateInsertion(Loc, "self->"); 2331 } 2332 2333 return Result; 2334 } 2335 } else if (CurMethod->isInstanceMethod()) { 2336 // We should warn if a local variable hides an ivar. 2337 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2338 ObjCInterfaceDecl *ClassDeclared; 2339 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2340 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2341 declaresSameEntity(IFace, ClassDeclared)) 2342 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2343 } 2344 } 2345 } else if (Lookup.isSingleResult() && 2346 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2347 // If accessing a stand-alone ivar in a class method, this is an error. 2348 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2349 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2350 << IV->getDeclName()); 2351 } 2352 2353 if (Lookup.empty() && II && AllowBuiltinCreation) { 2354 // FIXME. Consolidate this with similar code in LookupName. 2355 if (unsigned BuiltinID = II->getBuiltinID()) { 2356 if (!(getLangOpts().CPlusPlus && 2357 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2358 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2359 S, Lookup.isForRedeclaration(), 2360 Lookup.getNameLoc()); 2361 if (D) Lookup.addDecl(D); 2362 } 2363 } 2364 } 2365 // Sentinel value saying that we didn't do anything special. 2366 return ExprResult((Expr *)nullptr); 2367 } 2368 2369 /// \brief Cast a base object to a member's actual type. 2370 /// 2371 /// Logically this happens in three phases: 2372 /// 2373 /// * First we cast from the base type to the naming class. 2374 /// The naming class is the class into which we were looking 2375 /// when we found the member; it's the qualifier type if a 2376 /// qualifier was provided, and otherwise it's the base type. 2377 /// 2378 /// * Next we cast from the naming class to the declaring class. 2379 /// If the member we found was brought into a class's scope by 2380 /// a using declaration, this is that class; otherwise it's 2381 /// the class declaring the member. 2382 /// 2383 /// * Finally we cast from the declaring class to the "true" 2384 /// declaring class of the member. This conversion does not 2385 /// obey access control. 2386 ExprResult 2387 Sema::PerformObjectMemberConversion(Expr *From, 2388 NestedNameSpecifier *Qualifier, 2389 NamedDecl *FoundDecl, 2390 NamedDecl *Member) { 2391 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2392 if (!RD) 2393 return From; 2394 2395 QualType DestRecordType; 2396 QualType DestType; 2397 QualType FromRecordType; 2398 QualType FromType = From->getType(); 2399 bool PointerConversions = false; 2400 if (isa<FieldDecl>(Member)) { 2401 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2402 2403 if (FromType->getAs<PointerType>()) { 2404 DestType = Context.getPointerType(DestRecordType); 2405 FromRecordType = FromType->getPointeeType(); 2406 PointerConversions = true; 2407 } else { 2408 DestType = DestRecordType; 2409 FromRecordType = FromType; 2410 } 2411 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2412 if (Method->isStatic()) 2413 return From; 2414 2415 DestType = Method->getThisType(Context); 2416 DestRecordType = DestType->getPointeeType(); 2417 2418 if (FromType->getAs<PointerType>()) { 2419 FromRecordType = FromType->getPointeeType(); 2420 PointerConversions = true; 2421 } else { 2422 FromRecordType = FromType; 2423 DestType = DestRecordType; 2424 } 2425 } else { 2426 // No conversion necessary. 2427 return From; 2428 } 2429 2430 if (DestType->isDependentType() || FromType->isDependentType()) 2431 return From; 2432 2433 // If the unqualified types are the same, no conversion is necessary. 2434 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2435 return From; 2436 2437 SourceRange FromRange = From->getSourceRange(); 2438 SourceLocation FromLoc = FromRange.getBegin(); 2439 2440 ExprValueKind VK = From->getValueKind(); 2441 2442 // C++ [class.member.lookup]p8: 2443 // [...] Ambiguities can often be resolved by qualifying a name with its 2444 // class name. 2445 // 2446 // If the member was a qualified name and the qualified referred to a 2447 // specific base subobject type, we'll cast to that intermediate type 2448 // first and then to the object in which the member is declared. That allows 2449 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2450 // 2451 // class Base { public: int x; }; 2452 // class Derived1 : public Base { }; 2453 // class Derived2 : public Base { }; 2454 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2455 // 2456 // void VeryDerived::f() { 2457 // x = 17; // error: ambiguous base subobjects 2458 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2459 // } 2460 if (Qualifier && Qualifier->getAsType()) { 2461 QualType QType = QualType(Qualifier->getAsType(), 0); 2462 assert(QType->isRecordType() && "lookup done with non-record type"); 2463 2464 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2465 2466 // In C++98, the qualifier type doesn't actually have to be a base 2467 // type of the object type, in which case we just ignore it. 2468 // Otherwise build the appropriate casts. 2469 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2470 CXXCastPath BasePath; 2471 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2472 FromLoc, FromRange, &BasePath)) 2473 return ExprError(); 2474 2475 if (PointerConversions) 2476 QType = Context.getPointerType(QType); 2477 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2478 VK, &BasePath).get(); 2479 2480 FromType = QType; 2481 FromRecordType = QRecordType; 2482 2483 // If the qualifier type was the same as the destination type, 2484 // we're done. 2485 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2486 return From; 2487 } 2488 } 2489 2490 bool IgnoreAccess = false; 2491 2492 // If we actually found the member through a using declaration, cast 2493 // down to the using declaration's type. 2494 // 2495 // Pointer equality is fine here because only one declaration of a 2496 // class ever has member declarations. 2497 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2498 assert(isa<UsingShadowDecl>(FoundDecl)); 2499 QualType URecordType = Context.getTypeDeclType( 2500 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2501 2502 // We only need to do this if the naming-class to declaring-class 2503 // conversion is non-trivial. 2504 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2505 assert(IsDerivedFrom(FromRecordType, URecordType)); 2506 CXXCastPath BasePath; 2507 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2508 FromLoc, FromRange, &BasePath)) 2509 return ExprError(); 2510 2511 QualType UType = URecordType; 2512 if (PointerConversions) 2513 UType = Context.getPointerType(UType); 2514 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2515 VK, &BasePath).get(); 2516 FromType = UType; 2517 FromRecordType = URecordType; 2518 } 2519 2520 // We don't do access control for the conversion from the 2521 // declaring class to the true declaring class. 2522 IgnoreAccess = true; 2523 } 2524 2525 CXXCastPath BasePath; 2526 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2527 FromLoc, FromRange, &BasePath, 2528 IgnoreAccess)) 2529 return ExprError(); 2530 2531 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2532 VK, &BasePath); 2533 } 2534 2535 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2536 const LookupResult &R, 2537 bool HasTrailingLParen) { 2538 // Only when used directly as the postfix-expression of a call. 2539 if (!HasTrailingLParen) 2540 return false; 2541 2542 // Never if a scope specifier was provided. 2543 if (SS.isSet()) 2544 return false; 2545 2546 // Only in C++ or ObjC++. 2547 if (!getLangOpts().CPlusPlus) 2548 return false; 2549 2550 // Turn off ADL when we find certain kinds of declarations during 2551 // normal lookup: 2552 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2553 NamedDecl *D = *I; 2554 2555 // C++0x [basic.lookup.argdep]p3: 2556 // -- a declaration of a class member 2557 // Since using decls preserve this property, we check this on the 2558 // original decl. 2559 if (D->isCXXClassMember()) 2560 return false; 2561 2562 // C++0x [basic.lookup.argdep]p3: 2563 // -- a block-scope function declaration that is not a 2564 // using-declaration 2565 // NOTE: we also trigger this for function templates (in fact, we 2566 // don't check the decl type at all, since all other decl types 2567 // turn off ADL anyway). 2568 if (isa<UsingShadowDecl>(D)) 2569 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2570 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2571 return false; 2572 2573 // C++0x [basic.lookup.argdep]p3: 2574 // -- a declaration that is neither a function or a function 2575 // template 2576 // And also for builtin functions. 2577 if (isa<FunctionDecl>(D)) { 2578 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2579 2580 // But also builtin functions. 2581 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2582 return false; 2583 } else if (!isa<FunctionTemplateDecl>(D)) 2584 return false; 2585 } 2586 2587 return true; 2588 } 2589 2590 2591 /// Diagnoses obvious problems with the use of the given declaration 2592 /// as an expression. This is only actually called for lookups that 2593 /// were not overloaded, and it doesn't promise that the declaration 2594 /// will in fact be used. 2595 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2596 if (isa<TypedefNameDecl>(D)) { 2597 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2598 return true; 2599 } 2600 2601 if (isa<ObjCInterfaceDecl>(D)) { 2602 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2603 return true; 2604 } 2605 2606 if (isa<NamespaceDecl>(D)) { 2607 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2608 return true; 2609 } 2610 2611 return false; 2612 } 2613 2614 ExprResult 2615 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2616 LookupResult &R, 2617 bool NeedsADL) { 2618 // If this is a single, fully-resolved result and we don't need ADL, 2619 // just build an ordinary singleton decl ref. 2620 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2621 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2622 R.getRepresentativeDecl()); 2623 2624 // We only need to check the declaration if there's exactly one 2625 // result, because in the overloaded case the results can only be 2626 // functions and function templates. 2627 if (R.isSingleResult() && 2628 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2629 return ExprError(); 2630 2631 // Otherwise, just build an unresolved lookup expression. Suppress 2632 // any lookup-related diagnostics; we'll hash these out later, when 2633 // we've picked a target. 2634 R.suppressDiagnostics(); 2635 2636 UnresolvedLookupExpr *ULE 2637 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2638 SS.getWithLocInContext(Context), 2639 R.getLookupNameInfo(), 2640 NeedsADL, R.isOverloadedResult(), 2641 R.begin(), R.end()); 2642 2643 return ULE; 2644 } 2645 2646 /// \brief Complete semantic analysis for a reference to the given declaration. 2647 ExprResult Sema::BuildDeclarationNameExpr( 2648 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2649 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) { 2650 assert(D && "Cannot refer to a NULL declaration"); 2651 assert(!isa<FunctionTemplateDecl>(D) && 2652 "Cannot refer unambiguously to a function template"); 2653 2654 SourceLocation Loc = NameInfo.getLoc(); 2655 if (CheckDeclInExpr(*this, Loc, D)) 2656 return ExprError(); 2657 2658 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2659 // Specifically diagnose references to class templates that are missing 2660 // a template argument list. 2661 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2662 << Template << SS.getRange(); 2663 Diag(Template->getLocation(), diag::note_template_decl_here); 2664 return ExprError(); 2665 } 2666 2667 // Make sure that we're referring to a value. 2668 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2669 if (!VD) { 2670 Diag(Loc, diag::err_ref_non_value) 2671 << D << SS.getRange(); 2672 Diag(D->getLocation(), diag::note_declared_at); 2673 return ExprError(); 2674 } 2675 2676 // Check whether this declaration can be used. Note that we suppress 2677 // this check when we're going to perform argument-dependent lookup 2678 // on this function name, because this might not be the function 2679 // that overload resolution actually selects. 2680 if (DiagnoseUseOfDecl(VD, Loc)) 2681 return ExprError(); 2682 2683 // Only create DeclRefExpr's for valid Decl's. 2684 if (VD->isInvalidDecl()) 2685 return ExprError(); 2686 2687 // Handle members of anonymous structs and unions. If we got here, 2688 // and the reference is to a class member indirect field, then this 2689 // must be the subject of a pointer-to-member expression. 2690 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2691 if (!indirectField->isCXXClassMember()) 2692 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2693 indirectField); 2694 2695 { 2696 QualType type = VD->getType(); 2697 ExprValueKind valueKind = VK_RValue; 2698 2699 switch (D->getKind()) { 2700 // Ignore all the non-ValueDecl kinds. 2701 #define ABSTRACT_DECL(kind) 2702 #define VALUE(type, base) 2703 #define DECL(type, base) \ 2704 case Decl::type: 2705 #include "clang/AST/DeclNodes.inc" 2706 llvm_unreachable("invalid value decl kind"); 2707 2708 // These shouldn't make it here. 2709 case Decl::ObjCAtDefsField: 2710 case Decl::ObjCIvar: 2711 llvm_unreachable("forming non-member reference to ivar?"); 2712 2713 // Enum constants are always r-values and never references. 2714 // Unresolved using declarations are dependent. 2715 case Decl::EnumConstant: 2716 case Decl::UnresolvedUsingValue: 2717 valueKind = VK_RValue; 2718 break; 2719 2720 // Fields and indirect fields that got here must be for 2721 // pointer-to-member expressions; we just call them l-values for 2722 // internal consistency, because this subexpression doesn't really 2723 // exist in the high-level semantics. 2724 case Decl::Field: 2725 case Decl::IndirectField: 2726 assert(getLangOpts().CPlusPlus && 2727 "building reference to field in C?"); 2728 2729 // These can't have reference type in well-formed programs, but 2730 // for internal consistency we do this anyway. 2731 type = type.getNonReferenceType(); 2732 valueKind = VK_LValue; 2733 break; 2734 2735 // Non-type template parameters are either l-values or r-values 2736 // depending on the type. 2737 case Decl::NonTypeTemplateParm: { 2738 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2739 type = reftype->getPointeeType(); 2740 valueKind = VK_LValue; // even if the parameter is an r-value reference 2741 break; 2742 } 2743 2744 // For non-references, we need to strip qualifiers just in case 2745 // the template parameter was declared as 'const int' or whatever. 2746 valueKind = VK_RValue; 2747 type = type.getUnqualifiedType(); 2748 break; 2749 } 2750 2751 case Decl::Var: 2752 case Decl::VarTemplateSpecialization: 2753 case Decl::VarTemplatePartialSpecialization: 2754 // In C, "extern void blah;" is valid and is an r-value. 2755 if (!getLangOpts().CPlusPlus && 2756 !type.hasQualifiers() && 2757 type->isVoidType()) { 2758 valueKind = VK_RValue; 2759 break; 2760 } 2761 // fallthrough 2762 2763 case Decl::ImplicitParam: 2764 case Decl::ParmVar: { 2765 // These are always l-values. 2766 valueKind = VK_LValue; 2767 type = type.getNonReferenceType(); 2768 2769 // FIXME: Does the addition of const really only apply in 2770 // potentially-evaluated contexts? Since the variable isn't actually 2771 // captured in an unevaluated context, it seems that the answer is no. 2772 if (!isUnevaluatedContext()) { 2773 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2774 if (!CapturedType.isNull()) 2775 type = CapturedType; 2776 } 2777 2778 break; 2779 } 2780 2781 case Decl::Function: { 2782 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2783 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2784 type = Context.BuiltinFnTy; 2785 valueKind = VK_RValue; 2786 break; 2787 } 2788 } 2789 2790 const FunctionType *fty = type->castAs<FunctionType>(); 2791 2792 // If we're referring to a function with an __unknown_anytype 2793 // result type, make the entire expression __unknown_anytype. 2794 if (fty->getReturnType() == Context.UnknownAnyTy) { 2795 type = Context.UnknownAnyTy; 2796 valueKind = VK_RValue; 2797 break; 2798 } 2799 2800 // Functions are l-values in C++. 2801 if (getLangOpts().CPlusPlus) { 2802 valueKind = VK_LValue; 2803 break; 2804 } 2805 2806 // C99 DR 316 says that, if a function type comes from a 2807 // function definition (without a prototype), that type is only 2808 // used for checking compatibility. Therefore, when referencing 2809 // the function, we pretend that we don't have the full function 2810 // type. 2811 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2812 isa<FunctionProtoType>(fty)) 2813 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2814 fty->getExtInfo()); 2815 2816 // Functions are r-values in C. 2817 valueKind = VK_RValue; 2818 break; 2819 } 2820 2821 case Decl::MSProperty: 2822 valueKind = VK_LValue; 2823 break; 2824 2825 case Decl::CXXMethod: 2826 // If we're referring to a method with an __unknown_anytype 2827 // result type, make the entire expression __unknown_anytype. 2828 // This should only be possible with a type written directly. 2829 if (const FunctionProtoType *proto 2830 = dyn_cast<FunctionProtoType>(VD->getType())) 2831 if (proto->getReturnType() == Context.UnknownAnyTy) { 2832 type = Context.UnknownAnyTy; 2833 valueKind = VK_RValue; 2834 break; 2835 } 2836 2837 // C++ methods are l-values if static, r-values if non-static. 2838 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2839 valueKind = VK_LValue; 2840 break; 2841 } 2842 // fallthrough 2843 2844 case Decl::CXXConversion: 2845 case Decl::CXXDestructor: 2846 case Decl::CXXConstructor: 2847 valueKind = VK_RValue; 2848 break; 2849 } 2850 2851 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2852 TemplateArgs); 2853 } 2854 } 2855 2856 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 2857 SmallString<32> &Target) { 2858 Target.resize(CharByteWidth * (Source.size() + 1)); 2859 char *ResultPtr = &Target[0]; 2860 const UTF8 *ErrorPtr; 2861 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 2862 (void)success; 2863 assert(success); 2864 Target.resize(ResultPtr - &Target[0]); 2865 } 2866 2867 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 2868 PredefinedExpr::IdentType IT) { 2869 // Pick the current block, lambda, captured statement or function. 2870 Decl *currentDecl = nullptr; 2871 if (const BlockScopeInfo *BSI = getCurBlock()) 2872 currentDecl = BSI->TheDecl; 2873 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2874 currentDecl = LSI->CallOperator; 2875 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 2876 currentDecl = CSI->TheCapturedDecl; 2877 else 2878 currentDecl = getCurFunctionOrMethodDecl(); 2879 2880 if (!currentDecl) { 2881 Diag(Loc, diag::ext_predef_outside_function); 2882 currentDecl = Context.getTranslationUnitDecl(); 2883 } 2884 2885 QualType ResTy; 2886 StringLiteral *SL = nullptr; 2887 if (cast<DeclContext>(currentDecl)->isDependentContext()) 2888 ResTy = Context.DependentTy; 2889 else { 2890 // Pre-defined identifiers are of type char[x], where x is the length of 2891 // the string. 2892 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 2893 unsigned Length = Str.length(); 2894 2895 llvm::APInt LengthI(32, Length + 1); 2896 if (IT == PredefinedExpr::LFunction) { 2897 ResTy = Context.WideCharTy.withConst(); 2898 SmallString<32> RawChars; 2899 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 2900 Str, RawChars); 2901 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 2902 /*IndexTypeQuals*/ 0); 2903 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 2904 /*Pascal*/ false, ResTy, Loc); 2905 } else { 2906 ResTy = Context.CharTy.withConst(); 2907 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 2908 /*IndexTypeQuals*/ 0); 2909 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 2910 /*Pascal*/ false, ResTy, Loc); 2911 } 2912 } 2913 2914 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 2915 } 2916 2917 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 2918 PredefinedExpr::IdentType IT; 2919 2920 switch (Kind) { 2921 default: llvm_unreachable("Unknown simple primary expr!"); 2922 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 2923 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 2924 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 2925 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 2926 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 2927 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 2928 } 2929 2930 return BuildPredefinedExpr(Loc, IT); 2931 } 2932 2933 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 2934 SmallString<16> CharBuffer; 2935 bool Invalid = false; 2936 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 2937 if (Invalid) 2938 return ExprError(); 2939 2940 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 2941 PP, Tok.getKind()); 2942 if (Literal.hadError()) 2943 return ExprError(); 2944 2945 QualType Ty; 2946 if (Literal.isWide()) 2947 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 2948 else if (Literal.isUTF16()) 2949 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 2950 else if (Literal.isUTF32()) 2951 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 2952 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 2953 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 2954 else 2955 Ty = Context.CharTy; // 'x' -> char in C++ 2956 2957 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 2958 if (Literal.isWide()) 2959 Kind = CharacterLiteral::Wide; 2960 else if (Literal.isUTF16()) 2961 Kind = CharacterLiteral::UTF16; 2962 else if (Literal.isUTF32()) 2963 Kind = CharacterLiteral::UTF32; 2964 2965 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 2966 Tok.getLocation()); 2967 2968 if (Literal.getUDSuffix().empty()) 2969 return Lit; 2970 2971 // We're building a user-defined literal. 2972 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 2973 SourceLocation UDSuffixLoc = 2974 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 2975 2976 // Make sure we're allowed user-defined literals here. 2977 if (!UDLScope) 2978 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 2979 2980 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 2981 // operator "" X (ch) 2982 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 2983 Lit, Tok.getLocation()); 2984 } 2985 2986 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 2987 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 2988 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 2989 Context.IntTy, Loc); 2990 } 2991 2992 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 2993 QualType Ty, SourceLocation Loc) { 2994 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 2995 2996 using llvm::APFloat; 2997 APFloat Val(Format); 2998 2999 APFloat::opStatus result = Literal.GetFloatValue(Val); 3000 3001 // Overflow is always an error, but underflow is only an error if 3002 // we underflowed to zero (APFloat reports denormals as underflow). 3003 if ((result & APFloat::opOverflow) || 3004 ((result & APFloat::opUnderflow) && Val.isZero())) { 3005 unsigned diagnostic; 3006 SmallString<20> buffer; 3007 if (result & APFloat::opOverflow) { 3008 diagnostic = diag::warn_float_overflow; 3009 APFloat::getLargest(Format).toString(buffer); 3010 } else { 3011 diagnostic = diag::warn_float_underflow; 3012 APFloat::getSmallest(Format).toString(buffer); 3013 } 3014 3015 S.Diag(Loc, diagnostic) 3016 << Ty 3017 << StringRef(buffer.data(), buffer.size()); 3018 } 3019 3020 bool isExact = (result == APFloat::opOK); 3021 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3022 } 3023 3024 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3025 assert(E && "Invalid expression"); 3026 3027 if (E->isValueDependent()) 3028 return false; 3029 3030 QualType QT = E->getType(); 3031 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3032 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3033 return true; 3034 } 3035 3036 llvm::APSInt ValueAPS; 3037 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3038 3039 if (R.isInvalid()) 3040 return true; 3041 3042 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3043 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3044 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3045 << ValueAPS.toString(10) << ValueIsPositive; 3046 return true; 3047 } 3048 3049 return false; 3050 } 3051 3052 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3053 // Fast path for a single digit (which is quite common). A single digit 3054 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3055 if (Tok.getLength() == 1) { 3056 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3057 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3058 } 3059 3060 SmallString<128> SpellingBuffer; 3061 // NumericLiteralParser wants to overread by one character. Add padding to 3062 // the buffer in case the token is copied to the buffer. If getSpelling() 3063 // returns a StringRef to the memory buffer, it should have a null char at 3064 // the EOF, so it is also safe. 3065 SpellingBuffer.resize(Tok.getLength() + 1); 3066 3067 // Get the spelling of the token, which eliminates trigraphs, etc. 3068 bool Invalid = false; 3069 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3070 if (Invalid) 3071 return ExprError(); 3072 3073 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3074 if (Literal.hadError) 3075 return ExprError(); 3076 3077 if (Literal.hasUDSuffix()) { 3078 // We're building a user-defined literal. 3079 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3080 SourceLocation UDSuffixLoc = 3081 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3082 3083 // Make sure we're allowed user-defined literals here. 3084 if (!UDLScope) 3085 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3086 3087 QualType CookedTy; 3088 if (Literal.isFloatingLiteral()) { 3089 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3090 // long double, the literal is treated as a call of the form 3091 // operator "" X (f L) 3092 CookedTy = Context.LongDoubleTy; 3093 } else { 3094 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3095 // unsigned long long, the literal is treated as a call of the form 3096 // operator "" X (n ULL) 3097 CookedTy = Context.UnsignedLongLongTy; 3098 } 3099 3100 DeclarationName OpName = 3101 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3102 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3103 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3104 3105 SourceLocation TokLoc = Tok.getLocation(); 3106 3107 // Perform literal operator lookup to determine if we're building a raw 3108 // literal or a cooked one. 3109 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3110 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3111 /*AllowRaw*/true, /*AllowTemplate*/true, 3112 /*AllowStringTemplate*/false)) { 3113 case LOLR_Error: 3114 return ExprError(); 3115 3116 case LOLR_Cooked: { 3117 Expr *Lit; 3118 if (Literal.isFloatingLiteral()) { 3119 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3120 } else { 3121 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3122 if (Literal.GetIntegerValue(ResultVal)) 3123 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3124 << /* Unsigned */ 1; 3125 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3126 Tok.getLocation()); 3127 } 3128 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3129 } 3130 3131 case LOLR_Raw: { 3132 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3133 // literal is treated as a call of the form 3134 // operator "" X ("n") 3135 unsigned Length = Literal.getUDSuffixOffset(); 3136 QualType StrTy = Context.getConstantArrayType( 3137 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3138 ArrayType::Normal, 0); 3139 Expr *Lit = StringLiteral::Create( 3140 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3141 /*Pascal*/false, StrTy, &TokLoc, 1); 3142 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3143 } 3144 3145 case LOLR_Template: { 3146 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3147 // template), L is treated as a call fo the form 3148 // operator "" X <'c1', 'c2', ... 'ck'>() 3149 // where n is the source character sequence c1 c2 ... ck. 3150 TemplateArgumentListInfo ExplicitArgs; 3151 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3152 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3153 llvm::APSInt Value(CharBits, CharIsUnsigned); 3154 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3155 Value = TokSpelling[I]; 3156 TemplateArgument Arg(Context, Value, Context.CharTy); 3157 TemplateArgumentLocInfo ArgInfo; 3158 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3159 } 3160 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3161 &ExplicitArgs); 3162 } 3163 case LOLR_StringTemplate: 3164 llvm_unreachable("unexpected literal operator lookup result"); 3165 } 3166 } 3167 3168 Expr *Res; 3169 3170 if (Literal.isFloatingLiteral()) { 3171 QualType Ty; 3172 if (Literal.isFloat) 3173 Ty = Context.FloatTy; 3174 else if (!Literal.isLong) 3175 Ty = Context.DoubleTy; 3176 else 3177 Ty = Context.LongDoubleTy; 3178 3179 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3180 3181 if (Ty == Context.DoubleTy) { 3182 if (getLangOpts().SinglePrecisionConstants) { 3183 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3184 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) { 3185 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3186 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3187 } 3188 } 3189 } else if (!Literal.isIntegerLiteral()) { 3190 return ExprError(); 3191 } else { 3192 QualType Ty; 3193 3194 // 'long long' is a C99 or C++11 feature. 3195 if (!getLangOpts().C99 && Literal.isLongLong) { 3196 if (getLangOpts().CPlusPlus) 3197 Diag(Tok.getLocation(), 3198 getLangOpts().CPlusPlus11 ? 3199 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3200 else 3201 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3202 } 3203 3204 // Get the value in the widest-possible width. 3205 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3206 // The microsoft literal suffix extensions support 128-bit literals, which 3207 // may be wider than [u]intmax_t. 3208 // FIXME: Actually, they don't. We seem to have accidentally invented the 3209 // i128 suffix. 3210 if (Literal.MicrosoftInteger == 128 && MaxWidth < 128 && 3211 Context.getTargetInfo().hasInt128Type()) 3212 MaxWidth = 128; 3213 llvm::APInt ResultVal(MaxWidth, 0); 3214 3215 if (Literal.GetIntegerValue(ResultVal)) { 3216 // If this value didn't fit into uintmax_t, error and force to ull. 3217 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3218 << /* Unsigned */ 1; 3219 Ty = Context.UnsignedLongLongTy; 3220 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3221 "long long is not intmax_t?"); 3222 } else { 3223 // If this value fits into a ULL, try to figure out what else it fits into 3224 // according to the rules of C99 6.4.4.1p5. 3225 3226 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3227 // be an unsigned int. 3228 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3229 3230 // Check from smallest to largest, picking the smallest type we can. 3231 unsigned Width = 0; 3232 3233 // Microsoft specific integer suffixes are explicitly sized. 3234 if (Literal.MicrosoftInteger) { 3235 if (Literal.MicrosoftInteger > MaxWidth) { 3236 // If this target doesn't support __int128, error and force to ull. 3237 Diag(Tok.getLocation(), diag::err_int128_unsupported); 3238 Width = MaxWidth; 3239 Ty = Context.getIntMaxType(); 3240 } else { 3241 Width = Literal.MicrosoftInteger; 3242 Ty = Context.getIntTypeForBitwidth(Width, 3243 /*Signed=*/!Literal.isUnsigned); 3244 } 3245 } 3246 3247 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3248 // Are int/unsigned possibilities? 3249 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3250 3251 // Does it fit in a unsigned int? 3252 if (ResultVal.isIntN(IntSize)) { 3253 // Does it fit in a signed int? 3254 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3255 Ty = Context.IntTy; 3256 else if (AllowUnsigned) 3257 Ty = Context.UnsignedIntTy; 3258 Width = IntSize; 3259 } 3260 } 3261 3262 // Are long/unsigned long possibilities? 3263 if (Ty.isNull() && !Literal.isLongLong) { 3264 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3265 3266 // Does it fit in a unsigned long? 3267 if (ResultVal.isIntN(LongSize)) { 3268 // Does it fit in a signed long? 3269 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3270 Ty = Context.LongTy; 3271 else if (AllowUnsigned) 3272 Ty = Context.UnsignedLongTy; 3273 Width = LongSize; 3274 } 3275 } 3276 3277 // Check long long if needed. 3278 if (Ty.isNull()) { 3279 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3280 3281 // Does it fit in a unsigned long long? 3282 if (ResultVal.isIntN(LongLongSize)) { 3283 // Does it fit in a signed long long? 3284 // To be compatible with MSVC, hex integer literals ending with the 3285 // LL or i64 suffix are always signed in Microsoft mode. 3286 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3287 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3288 Ty = Context.LongLongTy; 3289 else if (AllowUnsigned) 3290 Ty = Context.UnsignedLongLongTy; 3291 Width = LongLongSize; 3292 } 3293 } 3294 3295 // If we still couldn't decide a type, we probably have something that 3296 // does not fit in a signed long long, but has no U suffix. 3297 if (Ty.isNull()) { 3298 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3299 Ty = Context.UnsignedLongLongTy; 3300 Width = Context.getTargetInfo().getLongLongWidth(); 3301 } 3302 3303 if (ResultVal.getBitWidth() != Width) 3304 ResultVal = ResultVal.trunc(Width); 3305 } 3306 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3307 } 3308 3309 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3310 if (Literal.isImaginary) 3311 Res = new (Context) ImaginaryLiteral(Res, 3312 Context.getComplexType(Res->getType())); 3313 3314 return Res; 3315 } 3316 3317 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3318 assert(E && "ActOnParenExpr() missing expr"); 3319 return new (Context) ParenExpr(L, R, E); 3320 } 3321 3322 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3323 SourceLocation Loc, 3324 SourceRange ArgRange) { 3325 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3326 // scalar or vector data type argument..." 3327 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3328 // type (C99 6.2.5p18) or void. 3329 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3330 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3331 << T << ArgRange; 3332 return true; 3333 } 3334 3335 assert((T->isVoidType() || !T->isIncompleteType()) && 3336 "Scalar types should always be complete"); 3337 return false; 3338 } 3339 3340 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3341 SourceLocation Loc, 3342 SourceRange ArgRange, 3343 UnaryExprOrTypeTrait TraitKind) { 3344 // Invalid types must be hard errors for SFINAE in C++. 3345 if (S.LangOpts.CPlusPlus) 3346 return true; 3347 3348 // C99 6.5.3.4p1: 3349 if (T->isFunctionType() && 3350 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3351 // sizeof(function)/alignof(function) is allowed as an extension. 3352 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3353 << TraitKind << ArgRange; 3354 return false; 3355 } 3356 3357 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3358 // this is an error (OpenCL v1.1 s6.3.k) 3359 if (T->isVoidType()) { 3360 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3361 : diag::ext_sizeof_alignof_void_type; 3362 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3363 return false; 3364 } 3365 3366 return true; 3367 } 3368 3369 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3370 SourceLocation Loc, 3371 SourceRange ArgRange, 3372 UnaryExprOrTypeTrait TraitKind) { 3373 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3374 // runtime doesn't allow it. 3375 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3376 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3377 << T << (TraitKind == UETT_SizeOf) 3378 << ArgRange; 3379 return true; 3380 } 3381 3382 return false; 3383 } 3384 3385 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3386 /// pointer type is equal to T) and emit a warning if it is. 3387 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3388 Expr *E) { 3389 // Don't warn if the operation changed the type. 3390 if (T != E->getType()) 3391 return; 3392 3393 // Now look for array decays. 3394 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3395 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3396 return; 3397 3398 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3399 << ICE->getType() 3400 << ICE->getSubExpr()->getType(); 3401 } 3402 3403 /// \brief Check the constraints on expression operands to unary type expression 3404 /// and type traits. 3405 /// 3406 /// Completes any types necessary and validates the constraints on the operand 3407 /// expression. The logic mostly mirrors the type-based overload, but may modify 3408 /// the expression as it completes the type for that expression through template 3409 /// instantiation, etc. 3410 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3411 UnaryExprOrTypeTrait ExprKind) { 3412 QualType ExprTy = E->getType(); 3413 assert(!ExprTy->isReferenceType()); 3414 3415 if (ExprKind == UETT_VecStep) 3416 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3417 E->getSourceRange()); 3418 3419 // Whitelist some types as extensions 3420 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3421 E->getSourceRange(), ExprKind)) 3422 return false; 3423 3424 // 'alignof' applied to an expression only requires the base element type of 3425 // the expression to be complete. 'sizeof' requires the expression's type to 3426 // be complete (and will attempt to complete it if it's an array of unknown 3427 // bound). 3428 if (ExprKind == UETT_AlignOf) { 3429 if (RequireCompleteType(E->getExprLoc(), 3430 Context.getBaseElementType(E->getType()), 3431 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3432 E->getSourceRange())) 3433 return true; 3434 } else { 3435 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3436 ExprKind, E->getSourceRange())) 3437 return true; 3438 } 3439 3440 // Completing the expression's type may have changed it. 3441 ExprTy = E->getType(); 3442 assert(!ExprTy->isReferenceType()); 3443 3444 if (ExprTy->isFunctionType()) { 3445 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3446 << ExprKind << E->getSourceRange(); 3447 return true; 3448 } 3449 3450 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3451 E->getSourceRange(), ExprKind)) 3452 return true; 3453 3454 if (ExprKind == UETT_SizeOf) { 3455 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3456 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3457 QualType OType = PVD->getOriginalType(); 3458 QualType Type = PVD->getType(); 3459 if (Type->isPointerType() && OType->isArrayType()) { 3460 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3461 << Type << OType; 3462 Diag(PVD->getLocation(), diag::note_declared_at); 3463 } 3464 } 3465 } 3466 3467 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3468 // decays into a pointer and returns an unintended result. This is most 3469 // likely a typo for "sizeof(array) op x". 3470 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3471 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3472 BO->getLHS()); 3473 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3474 BO->getRHS()); 3475 } 3476 } 3477 3478 return false; 3479 } 3480 3481 /// \brief Check the constraints on operands to unary expression and type 3482 /// traits. 3483 /// 3484 /// This will complete any types necessary, and validate the various constraints 3485 /// on those operands. 3486 /// 3487 /// The UsualUnaryConversions() function is *not* called by this routine. 3488 /// C99 6.3.2.1p[2-4] all state: 3489 /// Except when it is the operand of the sizeof operator ... 3490 /// 3491 /// C++ [expr.sizeof]p4 3492 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3493 /// standard conversions are not applied to the operand of sizeof. 3494 /// 3495 /// This policy is followed for all of the unary trait expressions. 3496 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3497 SourceLocation OpLoc, 3498 SourceRange ExprRange, 3499 UnaryExprOrTypeTrait ExprKind) { 3500 if (ExprType->isDependentType()) 3501 return false; 3502 3503 // C++ [expr.sizeof]p2: 3504 // When applied to a reference or a reference type, the result 3505 // is the size of the referenced type. 3506 // C++11 [expr.alignof]p3: 3507 // When alignof is applied to a reference type, the result 3508 // shall be the alignment of the referenced type. 3509 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3510 ExprType = Ref->getPointeeType(); 3511 3512 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3513 // When alignof or _Alignof is applied to an array type, the result 3514 // is the alignment of the element type. 3515 if (ExprKind == UETT_AlignOf) 3516 ExprType = Context.getBaseElementType(ExprType); 3517 3518 if (ExprKind == UETT_VecStep) 3519 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3520 3521 // Whitelist some types as extensions 3522 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3523 ExprKind)) 3524 return false; 3525 3526 if (RequireCompleteType(OpLoc, ExprType, 3527 diag::err_sizeof_alignof_incomplete_type, 3528 ExprKind, ExprRange)) 3529 return true; 3530 3531 if (ExprType->isFunctionType()) { 3532 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3533 << ExprKind << ExprRange; 3534 return true; 3535 } 3536 3537 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3538 ExprKind)) 3539 return true; 3540 3541 return false; 3542 } 3543 3544 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3545 E = E->IgnoreParens(); 3546 3547 // Cannot know anything else if the expression is dependent. 3548 if (E->isTypeDependent()) 3549 return false; 3550 3551 if (E->getObjectKind() == OK_BitField) { 3552 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 3553 << 1 << E->getSourceRange(); 3554 return true; 3555 } 3556 3557 ValueDecl *D = nullptr; 3558 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3559 D = DRE->getDecl(); 3560 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3561 D = ME->getMemberDecl(); 3562 } 3563 3564 // If it's a field, require the containing struct to have a 3565 // complete definition so that we can compute the layout. 3566 // 3567 // This can happen in C++11 onwards, either by naming the member 3568 // in a way that is not transformed into a member access expression 3569 // (in an unevaluated operand, for instance), or by naming the member 3570 // in a trailing-return-type. 3571 // 3572 // For the record, since __alignof__ on expressions is a GCC 3573 // extension, GCC seems to permit this but always gives the 3574 // nonsensical answer 0. 3575 // 3576 // We don't really need the layout here --- we could instead just 3577 // directly check for all the appropriate alignment-lowing 3578 // attributes --- but that would require duplicating a lot of 3579 // logic that just isn't worth duplicating for such a marginal 3580 // use-case. 3581 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3582 // Fast path this check, since we at least know the record has a 3583 // definition if we can find a member of it. 3584 if (!FD->getParent()->isCompleteDefinition()) { 3585 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3586 << E->getSourceRange(); 3587 return true; 3588 } 3589 3590 // Otherwise, if it's a field, and the field doesn't have 3591 // reference type, then it must have a complete type (or be a 3592 // flexible array member, which we explicitly want to 3593 // white-list anyway), which makes the following checks trivial. 3594 if (!FD->getType()->isReferenceType()) 3595 return false; 3596 } 3597 3598 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3599 } 3600 3601 bool Sema::CheckVecStepExpr(Expr *E) { 3602 E = E->IgnoreParens(); 3603 3604 // Cannot know anything else if the expression is dependent. 3605 if (E->isTypeDependent()) 3606 return false; 3607 3608 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3609 } 3610 3611 /// \brief Build a sizeof or alignof expression given a type operand. 3612 ExprResult 3613 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3614 SourceLocation OpLoc, 3615 UnaryExprOrTypeTrait ExprKind, 3616 SourceRange R) { 3617 if (!TInfo) 3618 return ExprError(); 3619 3620 QualType T = TInfo->getType(); 3621 3622 if (!T->isDependentType() && 3623 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3624 return ExprError(); 3625 3626 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3627 return new (Context) UnaryExprOrTypeTraitExpr( 3628 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3629 } 3630 3631 /// \brief Build a sizeof or alignof expression given an expression 3632 /// operand. 3633 ExprResult 3634 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3635 UnaryExprOrTypeTrait ExprKind) { 3636 ExprResult PE = CheckPlaceholderExpr(E); 3637 if (PE.isInvalid()) 3638 return ExprError(); 3639 3640 E = PE.get(); 3641 3642 // Verify that the operand is valid. 3643 bool isInvalid = false; 3644 if (E->isTypeDependent()) { 3645 // Delay type-checking for type-dependent expressions. 3646 } else if (ExprKind == UETT_AlignOf) { 3647 isInvalid = CheckAlignOfExpr(*this, E); 3648 } else if (ExprKind == UETT_VecStep) { 3649 isInvalid = CheckVecStepExpr(E); 3650 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3651 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 3652 isInvalid = true; 3653 } else { 3654 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3655 } 3656 3657 if (isInvalid) 3658 return ExprError(); 3659 3660 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3661 PE = TransformToPotentiallyEvaluated(E); 3662 if (PE.isInvalid()) return ExprError(); 3663 E = PE.get(); 3664 } 3665 3666 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3667 return new (Context) UnaryExprOrTypeTraitExpr( 3668 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 3669 } 3670 3671 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3672 /// expr and the same for @c alignof and @c __alignof 3673 /// Note that the ArgRange is invalid if isType is false. 3674 ExprResult 3675 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3676 UnaryExprOrTypeTrait ExprKind, bool IsType, 3677 void *TyOrEx, const SourceRange &ArgRange) { 3678 // If error parsing type, ignore. 3679 if (!TyOrEx) return ExprError(); 3680 3681 if (IsType) { 3682 TypeSourceInfo *TInfo; 3683 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3684 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3685 } 3686 3687 Expr *ArgEx = (Expr *)TyOrEx; 3688 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3689 return Result; 3690 } 3691 3692 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3693 bool IsReal) { 3694 if (V.get()->isTypeDependent()) 3695 return S.Context.DependentTy; 3696 3697 // _Real and _Imag are only l-values for normal l-values. 3698 if (V.get()->getObjectKind() != OK_Ordinary) { 3699 V = S.DefaultLvalueConversion(V.get()); 3700 if (V.isInvalid()) 3701 return QualType(); 3702 } 3703 3704 // These operators return the element type of a complex type. 3705 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3706 return CT->getElementType(); 3707 3708 // Otherwise they pass through real integer and floating point types here. 3709 if (V.get()->getType()->isArithmeticType()) 3710 return V.get()->getType(); 3711 3712 // Test for placeholders. 3713 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3714 if (PR.isInvalid()) return QualType(); 3715 if (PR.get() != V.get()) { 3716 V = PR; 3717 return CheckRealImagOperand(S, V, Loc, IsReal); 3718 } 3719 3720 // Reject anything else. 3721 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3722 << (IsReal ? "__real" : "__imag"); 3723 return QualType(); 3724 } 3725 3726 3727 3728 ExprResult 3729 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3730 tok::TokenKind Kind, Expr *Input) { 3731 UnaryOperatorKind Opc; 3732 switch (Kind) { 3733 default: llvm_unreachable("Unknown unary op!"); 3734 case tok::plusplus: Opc = UO_PostInc; break; 3735 case tok::minusminus: Opc = UO_PostDec; break; 3736 } 3737 3738 // Since this might is a postfix expression, get rid of ParenListExprs. 3739 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3740 if (Result.isInvalid()) return ExprError(); 3741 Input = Result.get(); 3742 3743 return BuildUnaryOp(S, OpLoc, Opc, Input); 3744 } 3745 3746 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3747 /// 3748 /// \return true on error 3749 static bool checkArithmeticOnObjCPointer(Sema &S, 3750 SourceLocation opLoc, 3751 Expr *op) { 3752 assert(op->getType()->isObjCObjectPointerType()); 3753 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 3754 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 3755 return false; 3756 3757 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3758 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3759 << op->getSourceRange(); 3760 return true; 3761 } 3762 3763 ExprResult 3764 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3765 Expr *idx, SourceLocation rbLoc) { 3766 // Since this might be a postfix expression, get rid of ParenListExprs. 3767 if (isa<ParenListExpr>(base)) { 3768 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3769 if (result.isInvalid()) return ExprError(); 3770 base = result.get(); 3771 } 3772 3773 // Handle any non-overload placeholder types in the base and index 3774 // expressions. We can't handle overloads here because the other 3775 // operand might be an overloadable type, in which case the overload 3776 // resolution for the operator overload should get the first crack 3777 // at the overload. 3778 if (base->getType()->isNonOverloadPlaceholderType()) { 3779 ExprResult result = CheckPlaceholderExpr(base); 3780 if (result.isInvalid()) return ExprError(); 3781 base = result.get(); 3782 } 3783 if (idx->getType()->isNonOverloadPlaceholderType()) { 3784 ExprResult result = CheckPlaceholderExpr(idx); 3785 if (result.isInvalid()) return ExprError(); 3786 idx = result.get(); 3787 } 3788 3789 // Build an unanalyzed expression if either operand is type-dependent. 3790 if (getLangOpts().CPlusPlus && 3791 (base->isTypeDependent() || idx->isTypeDependent())) { 3792 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 3793 VK_LValue, OK_Ordinary, rbLoc); 3794 } 3795 3796 // Use C++ overloaded-operator rules if either operand has record 3797 // type. The spec says to do this if either type is *overloadable*, 3798 // but enum types can't declare subscript operators or conversion 3799 // operators, so there's nothing interesting for overload resolution 3800 // to do if there aren't any record types involved. 3801 // 3802 // ObjC pointers have their own subscripting logic that is not tied 3803 // to overload resolution and so should not take this path. 3804 if (getLangOpts().CPlusPlus && 3805 (base->getType()->isRecordType() || 3806 (!base->getType()->isObjCObjectPointerType() && 3807 idx->getType()->isRecordType()))) { 3808 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3809 } 3810 3811 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3812 } 3813 3814 ExprResult 3815 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3816 Expr *Idx, SourceLocation RLoc) { 3817 Expr *LHSExp = Base; 3818 Expr *RHSExp = Idx; 3819 3820 // Perform default conversions. 3821 if (!LHSExp->getType()->getAs<VectorType>()) { 3822 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 3823 if (Result.isInvalid()) 3824 return ExprError(); 3825 LHSExp = Result.get(); 3826 } 3827 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 3828 if (Result.isInvalid()) 3829 return ExprError(); 3830 RHSExp = Result.get(); 3831 3832 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 3833 ExprValueKind VK = VK_LValue; 3834 ExprObjectKind OK = OK_Ordinary; 3835 3836 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 3837 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 3838 // in the subscript position. As a result, we need to derive the array base 3839 // and index from the expression types. 3840 Expr *BaseExpr, *IndexExpr; 3841 QualType ResultType; 3842 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 3843 BaseExpr = LHSExp; 3844 IndexExpr = RHSExp; 3845 ResultType = Context.DependentTy; 3846 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 3847 BaseExpr = LHSExp; 3848 IndexExpr = RHSExp; 3849 ResultType = PTy->getPointeeType(); 3850 } else if (const ObjCObjectPointerType *PTy = 3851 LHSTy->getAs<ObjCObjectPointerType>()) { 3852 BaseExpr = LHSExp; 3853 IndexExpr = RHSExp; 3854 3855 // Use custom logic if this should be the pseudo-object subscript 3856 // expression. 3857 if (!LangOpts.isSubscriptPointerArithmetic()) 3858 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 3859 nullptr); 3860 3861 ResultType = PTy->getPointeeType(); 3862 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 3863 // Handle the uncommon case of "123[Ptr]". 3864 BaseExpr = RHSExp; 3865 IndexExpr = LHSExp; 3866 ResultType = PTy->getPointeeType(); 3867 } else if (const ObjCObjectPointerType *PTy = 3868 RHSTy->getAs<ObjCObjectPointerType>()) { 3869 // Handle the uncommon case of "123[Ptr]". 3870 BaseExpr = RHSExp; 3871 IndexExpr = LHSExp; 3872 ResultType = PTy->getPointeeType(); 3873 if (!LangOpts.isSubscriptPointerArithmetic()) { 3874 Diag(LLoc, diag::err_subscript_nonfragile_interface) 3875 << ResultType << BaseExpr->getSourceRange(); 3876 return ExprError(); 3877 } 3878 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 3879 BaseExpr = LHSExp; // vectors: V[123] 3880 IndexExpr = RHSExp; 3881 VK = LHSExp->getValueKind(); 3882 if (VK != VK_RValue) 3883 OK = OK_VectorComponent; 3884 3885 // FIXME: need to deal with const... 3886 ResultType = VTy->getElementType(); 3887 } else if (LHSTy->isArrayType()) { 3888 // If we see an array that wasn't promoted by 3889 // DefaultFunctionArrayLvalueConversion, it must be an array that 3890 // wasn't promoted because of the C90 rule that doesn't 3891 // allow promoting non-lvalue arrays. Warn, then 3892 // force the promotion here. 3893 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3894 LHSExp->getSourceRange(); 3895 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 3896 CK_ArrayToPointerDecay).get(); 3897 LHSTy = LHSExp->getType(); 3898 3899 BaseExpr = LHSExp; 3900 IndexExpr = RHSExp; 3901 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 3902 } else if (RHSTy->isArrayType()) { 3903 // Same as previous, except for 123[f().a] case 3904 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 3905 RHSExp->getSourceRange(); 3906 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 3907 CK_ArrayToPointerDecay).get(); 3908 RHSTy = RHSExp->getType(); 3909 3910 BaseExpr = RHSExp; 3911 IndexExpr = LHSExp; 3912 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 3913 } else { 3914 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 3915 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 3916 } 3917 // C99 6.5.2.1p1 3918 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 3919 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 3920 << IndexExpr->getSourceRange()); 3921 3922 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 3923 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 3924 && !IndexExpr->isTypeDependent()) 3925 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 3926 3927 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 3928 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 3929 // type. Note that Functions are not objects, and that (in C99 parlance) 3930 // incomplete types are not object types. 3931 if (ResultType->isFunctionType()) { 3932 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 3933 << ResultType << BaseExpr->getSourceRange(); 3934 return ExprError(); 3935 } 3936 3937 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 3938 // GNU extension: subscripting on pointer to void 3939 Diag(LLoc, diag::ext_gnu_subscript_void_type) 3940 << BaseExpr->getSourceRange(); 3941 3942 // C forbids expressions of unqualified void type from being l-values. 3943 // See IsCForbiddenLValueType. 3944 if (!ResultType.hasQualifiers()) VK = VK_RValue; 3945 } else if (!ResultType->isDependentType() && 3946 RequireCompleteType(LLoc, ResultType, 3947 diag::err_subscript_incomplete_type, BaseExpr)) 3948 return ExprError(); 3949 3950 assert(VK == VK_RValue || LangOpts.CPlusPlus || 3951 !ResultType.isCForbiddenLValueType()); 3952 3953 return new (Context) 3954 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 3955 } 3956 3957 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3958 FunctionDecl *FD, 3959 ParmVarDecl *Param) { 3960 if (Param->hasUnparsedDefaultArg()) { 3961 Diag(CallLoc, 3962 diag::err_use_of_default_argument_to_function_declared_later) << 3963 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 3964 Diag(UnparsedDefaultArgLocs[Param], 3965 diag::note_default_argument_declared_here); 3966 return ExprError(); 3967 } 3968 3969 if (Param->hasUninstantiatedDefaultArg()) { 3970 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 3971 3972 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 3973 Param); 3974 3975 // Instantiate the expression. 3976 MultiLevelTemplateArgumentList MutiLevelArgList 3977 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 3978 3979 InstantiatingTemplate Inst(*this, CallLoc, Param, 3980 MutiLevelArgList.getInnermost()); 3981 if (Inst.isInvalid()) 3982 return ExprError(); 3983 3984 ExprResult Result; 3985 { 3986 // C++ [dcl.fct.default]p5: 3987 // The names in the [default argument] expression are bound, and 3988 // the semantic constraints are checked, at the point where the 3989 // default argument expression appears. 3990 ContextRAII SavedContext(*this, FD); 3991 LocalInstantiationScope Local(*this); 3992 Result = SubstExpr(UninstExpr, MutiLevelArgList); 3993 } 3994 if (Result.isInvalid()) 3995 return ExprError(); 3996 3997 // Check the expression as an initializer for the parameter. 3998 InitializedEntity Entity 3999 = InitializedEntity::InitializeParameter(Context, Param); 4000 InitializationKind Kind 4001 = InitializationKind::CreateCopy(Param->getLocation(), 4002 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4003 Expr *ResultE = Result.getAs<Expr>(); 4004 4005 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4006 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4007 if (Result.isInvalid()) 4008 return ExprError(); 4009 4010 Expr *Arg = Result.getAs<Expr>(); 4011 CheckCompletedExpr(Arg, Param->getOuterLocStart()); 4012 // Build the default argument expression. 4013 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg); 4014 } 4015 4016 // If the default expression creates temporaries, we need to 4017 // push them to the current stack of expression temporaries so they'll 4018 // be properly destroyed. 4019 // FIXME: We should really be rebuilding the default argument with new 4020 // bound temporaries; see the comment in PR5810. 4021 // We don't need to do that with block decls, though, because 4022 // blocks in default argument expression can never capture anything. 4023 if (isa<ExprWithCleanups>(Param->getInit())) { 4024 // Set the "needs cleanups" bit regardless of whether there are 4025 // any explicit objects. 4026 ExprNeedsCleanups = true; 4027 4028 // Append all the objects to the cleanup list. Right now, this 4029 // should always be a no-op, because blocks in default argument 4030 // expressions should never be able to capture anything. 4031 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 4032 "default argument expression has capturing blocks?"); 4033 } 4034 4035 // We already type-checked the argument, so we know it works. 4036 // Just mark all of the declarations in this potentially-evaluated expression 4037 // as being "referenced". 4038 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4039 /*SkipLocalVariables=*/true); 4040 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4041 } 4042 4043 4044 Sema::VariadicCallType 4045 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4046 Expr *Fn) { 4047 if (Proto && Proto->isVariadic()) { 4048 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4049 return VariadicConstructor; 4050 else if (Fn && Fn->getType()->isBlockPointerType()) 4051 return VariadicBlock; 4052 else if (FDecl) { 4053 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4054 if (Method->isInstance()) 4055 return VariadicMethod; 4056 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4057 return VariadicMethod; 4058 return VariadicFunction; 4059 } 4060 return VariadicDoesNotApply; 4061 } 4062 4063 namespace { 4064 class FunctionCallCCC : public FunctionCallFilterCCC { 4065 public: 4066 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4067 unsigned NumArgs, MemberExpr *ME) 4068 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4069 FunctionName(FuncName) {} 4070 4071 bool ValidateCandidate(const TypoCorrection &candidate) override { 4072 if (!candidate.getCorrectionSpecifier() || 4073 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4074 return false; 4075 } 4076 4077 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4078 } 4079 4080 private: 4081 const IdentifierInfo *const FunctionName; 4082 }; 4083 } 4084 4085 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4086 FunctionDecl *FDecl, 4087 ArrayRef<Expr *> Args) { 4088 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4089 DeclarationName FuncName = FDecl->getDeclName(); 4090 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4091 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME); 4092 4093 if (TypoCorrection Corrected = S.CorrectTypo( 4094 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4095 S.getScopeForContext(S.CurContext), nullptr, CCC, 4096 Sema::CTK_ErrorRecovery)) { 4097 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 4098 if (Corrected.isOverloaded()) { 4099 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4100 OverloadCandidateSet::iterator Best; 4101 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 4102 CDEnd = Corrected.end(); 4103 CD != CDEnd; ++CD) { 4104 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 4105 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4106 OCS); 4107 } 4108 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4109 case OR_Success: 4110 ND = Best->Function; 4111 Corrected.setCorrectionDecl(ND); 4112 break; 4113 default: 4114 break; 4115 } 4116 } 4117 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 4118 return Corrected; 4119 } 4120 } 4121 } 4122 return TypoCorrection(); 4123 } 4124 4125 /// ConvertArgumentsForCall - Converts the arguments specified in 4126 /// Args/NumArgs to the parameter types of the function FDecl with 4127 /// function prototype Proto. Call is the call expression itself, and 4128 /// Fn is the function expression. For a C++ member function, this 4129 /// routine does not attempt to convert the object argument. Returns 4130 /// true if the call is ill-formed. 4131 bool 4132 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4133 FunctionDecl *FDecl, 4134 const FunctionProtoType *Proto, 4135 ArrayRef<Expr *> Args, 4136 SourceLocation RParenLoc, 4137 bool IsExecConfig) { 4138 // Bail out early if calling a builtin with custom typechecking. 4139 // We don't need to do this in the 4140 if (FDecl) 4141 if (unsigned ID = FDecl->getBuiltinID()) 4142 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4143 return false; 4144 4145 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4146 // assignment, to the types of the corresponding parameter, ... 4147 unsigned NumParams = Proto->getNumParams(); 4148 bool Invalid = false; 4149 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4150 unsigned FnKind = Fn->getType()->isBlockPointerType() 4151 ? 1 /* block */ 4152 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4153 : 0 /* function */); 4154 4155 // If too few arguments are available (and we don't have default 4156 // arguments for the remaining parameters), don't make the call. 4157 if (Args.size() < NumParams) { 4158 if (Args.size() < MinArgs) { 4159 TypoCorrection TC; 4160 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4161 unsigned diag_id = 4162 MinArgs == NumParams && !Proto->isVariadic() 4163 ? diag::err_typecheck_call_too_few_args_suggest 4164 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4165 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4166 << static_cast<unsigned>(Args.size()) 4167 << TC.getCorrectionRange()); 4168 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4169 Diag(RParenLoc, 4170 MinArgs == NumParams && !Proto->isVariadic() 4171 ? diag::err_typecheck_call_too_few_args_one 4172 : diag::err_typecheck_call_too_few_args_at_least_one) 4173 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4174 else 4175 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4176 ? diag::err_typecheck_call_too_few_args 4177 : diag::err_typecheck_call_too_few_args_at_least) 4178 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4179 << Fn->getSourceRange(); 4180 4181 // Emit the location of the prototype. 4182 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4183 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4184 << FDecl; 4185 4186 return true; 4187 } 4188 Call->setNumArgs(Context, NumParams); 4189 } 4190 4191 // If too many are passed and not variadic, error on the extras and drop 4192 // them. 4193 if (Args.size() > NumParams) { 4194 if (!Proto->isVariadic()) { 4195 TypoCorrection TC; 4196 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4197 unsigned diag_id = 4198 MinArgs == NumParams && !Proto->isVariadic() 4199 ? diag::err_typecheck_call_too_many_args_suggest 4200 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4201 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4202 << static_cast<unsigned>(Args.size()) 4203 << TC.getCorrectionRange()); 4204 } else if (NumParams == 1 && FDecl && 4205 FDecl->getParamDecl(0)->getDeclName()) 4206 Diag(Args[NumParams]->getLocStart(), 4207 MinArgs == NumParams 4208 ? diag::err_typecheck_call_too_many_args_one 4209 : diag::err_typecheck_call_too_many_args_at_most_one) 4210 << FnKind << FDecl->getParamDecl(0) 4211 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4212 << SourceRange(Args[NumParams]->getLocStart(), 4213 Args.back()->getLocEnd()); 4214 else 4215 Diag(Args[NumParams]->getLocStart(), 4216 MinArgs == NumParams 4217 ? diag::err_typecheck_call_too_many_args 4218 : diag::err_typecheck_call_too_many_args_at_most) 4219 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4220 << Fn->getSourceRange() 4221 << SourceRange(Args[NumParams]->getLocStart(), 4222 Args.back()->getLocEnd()); 4223 4224 // Emit the location of the prototype. 4225 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4226 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4227 << FDecl; 4228 4229 // This deletes the extra arguments. 4230 Call->setNumArgs(Context, NumParams); 4231 return true; 4232 } 4233 } 4234 SmallVector<Expr *, 8> AllArgs; 4235 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4236 4237 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4238 Proto, 0, Args, AllArgs, CallType); 4239 if (Invalid) 4240 return true; 4241 unsigned TotalNumArgs = AllArgs.size(); 4242 for (unsigned i = 0; i < TotalNumArgs; ++i) 4243 Call->setArg(i, AllArgs[i]); 4244 4245 return false; 4246 } 4247 4248 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4249 const FunctionProtoType *Proto, 4250 unsigned FirstParam, ArrayRef<Expr *> Args, 4251 SmallVectorImpl<Expr *> &AllArgs, 4252 VariadicCallType CallType, bool AllowExplicit, 4253 bool IsListInitialization) { 4254 unsigned NumParams = Proto->getNumParams(); 4255 bool Invalid = false; 4256 unsigned ArgIx = 0; 4257 // Continue to check argument types (even if we have too few/many args). 4258 for (unsigned i = FirstParam; i < NumParams; i++) { 4259 QualType ProtoArgType = Proto->getParamType(i); 4260 4261 Expr *Arg; 4262 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4263 if (ArgIx < Args.size()) { 4264 Arg = Args[ArgIx++]; 4265 4266 if (RequireCompleteType(Arg->getLocStart(), 4267 ProtoArgType, 4268 diag::err_call_incomplete_argument, Arg)) 4269 return true; 4270 4271 // Strip the unbridged-cast placeholder expression off, if applicable. 4272 bool CFAudited = false; 4273 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4274 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4275 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4276 Arg = stripARCUnbridgedCast(Arg); 4277 else if (getLangOpts().ObjCAutoRefCount && 4278 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4279 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4280 CFAudited = true; 4281 4282 InitializedEntity Entity = 4283 Param ? InitializedEntity::InitializeParameter(Context, Param, 4284 ProtoArgType) 4285 : InitializedEntity::InitializeParameter( 4286 Context, ProtoArgType, Proto->isParamConsumed(i)); 4287 4288 // Remember that parameter belongs to a CF audited API. 4289 if (CFAudited) 4290 Entity.setParameterCFAudited(); 4291 4292 ExprResult ArgE = PerformCopyInitialization( 4293 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4294 if (ArgE.isInvalid()) 4295 return true; 4296 4297 Arg = ArgE.getAs<Expr>(); 4298 } else { 4299 assert(Param && "can't use default arguments without a known callee"); 4300 4301 ExprResult ArgExpr = 4302 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4303 if (ArgExpr.isInvalid()) 4304 return true; 4305 4306 Arg = ArgExpr.getAs<Expr>(); 4307 } 4308 4309 // Check for array bounds violations for each argument to the call. This 4310 // check only triggers warnings when the argument isn't a more complex Expr 4311 // with its own checking, such as a BinaryOperator. 4312 CheckArrayAccess(Arg); 4313 4314 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4315 CheckStaticArrayArgument(CallLoc, Param, Arg); 4316 4317 AllArgs.push_back(Arg); 4318 } 4319 4320 // If this is a variadic call, handle args passed through "...". 4321 if (CallType != VariadicDoesNotApply) { 4322 // Assume that extern "C" functions with variadic arguments that 4323 // return __unknown_anytype aren't *really* variadic. 4324 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4325 FDecl->isExternC()) { 4326 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4327 QualType paramType; // ignored 4328 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType); 4329 Invalid |= arg.isInvalid(); 4330 AllArgs.push_back(arg.get()); 4331 } 4332 4333 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4334 } else { 4335 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4336 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 4337 FDecl); 4338 Invalid |= Arg.isInvalid(); 4339 AllArgs.push_back(Arg.get()); 4340 } 4341 } 4342 4343 // Check for array bounds violations. 4344 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) 4345 CheckArrayAccess(Args[i]); 4346 } 4347 return Invalid; 4348 } 4349 4350 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4351 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4352 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4353 TL = DTL.getOriginalLoc(); 4354 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4355 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4356 << ATL.getLocalSourceRange(); 4357 } 4358 4359 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4360 /// array parameter, check that it is non-null, and that if it is formed by 4361 /// array-to-pointer decay, the underlying array is sufficiently large. 4362 /// 4363 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4364 /// array type derivation, then for each call to the function, the value of the 4365 /// corresponding actual argument shall provide access to the first element of 4366 /// an array with at least as many elements as specified by the size expression. 4367 void 4368 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4369 ParmVarDecl *Param, 4370 const Expr *ArgExpr) { 4371 // Static array parameters are not supported in C++. 4372 if (!Param || getLangOpts().CPlusPlus) 4373 return; 4374 4375 QualType OrigTy = Param->getOriginalType(); 4376 4377 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4378 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4379 return; 4380 4381 if (ArgExpr->isNullPointerConstant(Context, 4382 Expr::NPC_NeverValueDependent)) { 4383 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4384 DiagnoseCalleeStaticArrayParam(*this, Param); 4385 return; 4386 } 4387 4388 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4389 if (!CAT) 4390 return; 4391 4392 const ConstantArrayType *ArgCAT = 4393 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4394 if (!ArgCAT) 4395 return; 4396 4397 if (ArgCAT->getSize().ult(CAT->getSize())) { 4398 Diag(CallLoc, diag::warn_static_array_too_small) 4399 << ArgExpr->getSourceRange() 4400 << (unsigned) ArgCAT->getSize().getZExtValue() 4401 << (unsigned) CAT->getSize().getZExtValue(); 4402 DiagnoseCalleeStaticArrayParam(*this, Param); 4403 } 4404 } 4405 4406 /// Given a function expression of unknown-any type, try to rebuild it 4407 /// to have a function type. 4408 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4409 4410 /// Is the given type a placeholder that we need to lower out 4411 /// immediately during argument processing? 4412 static bool isPlaceholderToRemoveAsArg(QualType type) { 4413 // Placeholders are never sugared. 4414 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4415 if (!placeholder) return false; 4416 4417 switch (placeholder->getKind()) { 4418 // Ignore all the non-placeholder types. 4419 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4420 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4421 #include "clang/AST/BuiltinTypes.def" 4422 return false; 4423 4424 // We cannot lower out overload sets; they might validly be resolved 4425 // by the call machinery. 4426 case BuiltinType::Overload: 4427 return false; 4428 4429 // Unbridged casts in ARC can be handled in some call positions and 4430 // should be left in place. 4431 case BuiltinType::ARCUnbridgedCast: 4432 return false; 4433 4434 // Pseudo-objects should be converted as soon as possible. 4435 case BuiltinType::PseudoObject: 4436 return true; 4437 4438 // The debugger mode could theoretically but currently does not try 4439 // to resolve unknown-typed arguments based on known parameter types. 4440 case BuiltinType::UnknownAny: 4441 return true; 4442 4443 // These are always invalid as call arguments and should be reported. 4444 case BuiltinType::BoundMember: 4445 case BuiltinType::BuiltinFn: 4446 return true; 4447 } 4448 llvm_unreachable("bad builtin type kind"); 4449 } 4450 4451 /// Check an argument list for placeholders that we won't try to 4452 /// handle later. 4453 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4454 // Apply this processing to all the arguments at once instead of 4455 // dying at the first failure. 4456 bool hasInvalid = false; 4457 for (size_t i = 0, e = args.size(); i != e; i++) { 4458 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4459 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4460 if (result.isInvalid()) hasInvalid = true; 4461 else args[i] = result.get(); 4462 } 4463 } 4464 return hasInvalid; 4465 } 4466 4467 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4468 /// This provides the location of the left/right parens and a list of comma 4469 /// locations. 4470 ExprResult 4471 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4472 MultiExprArg ArgExprs, SourceLocation RParenLoc, 4473 Expr *ExecConfig, bool IsExecConfig) { 4474 // Since this might be a postfix expression, get rid of ParenListExprs. 4475 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4476 if (Result.isInvalid()) return ExprError(); 4477 Fn = Result.get(); 4478 4479 if (checkArgsForPlaceholders(*this, ArgExprs)) 4480 return ExprError(); 4481 4482 if (getLangOpts().CPlusPlus) { 4483 // If this is a pseudo-destructor expression, build the call immediately. 4484 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4485 if (!ArgExprs.empty()) { 4486 // Pseudo-destructor calls should not have any arguments. 4487 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4488 << FixItHint::CreateRemoval( 4489 SourceRange(ArgExprs[0]->getLocStart(), 4490 ArgExprs.back()->getLocEnd())); 4491 } 4492 4493 return new (Context) 4494 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 4495 } 4496 if (Fn->getType() == Context.PseudoObjectTy) { 4497 ExprResult result = CheckPlaceholderExpr(Fn); 4498 if (result.isInvalid()) return ExprError(); 4499 Fn = result.get(); 4500 } 4501 4502 // Determine whether this is a dependent call inside a C++ template, 4503 // in which case we won't do any semantic analysis now. 4504 // FIXME: Will need to cache the results of name lookup (including ADL) in 4505 // Fn. 4506 bool Dependent = false; 4507 if (Fn->isTypeDependent()) 4508 Dependent = true; 4509 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 4510 Dependent = true; 4511 4512 if (Dependent) { 4513 if (ExecConfig) { 4514 return new (Context) CUDAKernelCallExpr( 4515 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 4516 Context.DependentTy, VK_RValue, RParenLoc); 4517 } else { 4518 return new (Context) CallExpr( 4519 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 4520 } 4521 } 4522 4523 // Determine whether this is a call to an object (C++ [over.call.object]). 4524 if (Fn->getType()->isRecordType()) 4525 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs, 4526 RParenLoc); 4527 4528 if (Fn->getType() == Context.UnknownAnyTy) { 4529 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4530 if (result.isInvalid()) return ExprError(); 4531 Fn = result.get(); 4532 } 4533 4534 if (Fn->getType() == Context.BoundMemberTy) { 4535 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 4536 } 4537 } 4538 4539 // Check for overloaded calls. This can happen even in C due to extensions. 4540 if (Fn->getType() == Context.OverloadTy) { 4541 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 4542 4543 // We aren't supposed to apply this logic for if there's an '&' involved. 4544 if (!find.HasFormOfMemberPointer) { 4545 OverloadExpr *ovl = find.Expression; 4546 if (isa<UnresolvedLookupExpr>(ovl)) { 4547 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 4548 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 4549 RParenLoc, ExecConfig); 4550 } else { 4551 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, 4552 RParenLoc); 4553 } 4554 } 4555 } 4556 4557 // If we're directly calling a function, get the appropriate declaration. 4558 if (Fn->getType() == Context.UnknownAnyTy) { 4559 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4560 if (result.isInvalid()) return ExprError(); 4561 Fn = result.get(); 4562 } 4563 4564 Expr *NakedFn = Fn->IgnoreParens(); 4565 4566 NamedDecl *NDecl = nullptr; 4567 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 4568 if (UnOp->getOpcode() == UO_AddrOf) 4569 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4570 4571 if (isa<DeclRefExpr>(NakedFn)) 4572 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4573 else if (isa<MemberExpr>(NakedFn)) 4574 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 4575 4576 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 4577 if (FD->hasAttr<EnableIfAttr>()) { 4578 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 4579 Diag(Fn->getLocStart(), 4580 isa<CXXMethodDecl>(FD) ? 4581 diag::err_ovl_no_viable_member_function_in_call : 4582 diag::err_ovl_no_viable_function_in_call) 4583 << FD << FD->getSourceRange(); 4584 Diag(FD->getLocation(), 4585 diag::note_ovl_candidate_disabled_by_enable_if_attr) 4586 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 4587 } 4588 } 4589 } 4590 4591 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 4592 ExecConfig, IsExecConfig); 4593 } 4594 4595 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 4596 /// 4597 /// __builtin_astype( value, dst type ) 4598 /// 4599 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 4600 SourceLocation BuiltinLoc, 4601 SourceLocation RParenLoc) { 4602 ExprValueKind VK = VK_RValue; 4603 ExprObjectKind OK = OK_Ordinary; 4604 QualType DstTy = GetTypeFromParser(ParsedDestTy); 4605 QualType SrcTy = E->getType(); 4606 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 4607 return ExprError(Diag(BuiltinLoc, 4608 diag::err_invalid_astype_of_different_size) 4609 << DstTy 4610 << SrcTy 4611 << E->getSourceRange()); 4612 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 4613 } 4614 4615 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 4616 /// provided arguments. 4617 /// 4618 /// __builtin_convertvector( value, dst type ) 4619 /// 4620 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 4621 SourceLocation BuiltinLoc, 4622 SourceLocation RParenLoc) { 4623 TypeSourceInfo *TInfo; 4624 GetTypeFromParser(ParsedDestTy, &TInfo); 4625 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 4626 } 4627 4628 /// BuildResolvedCallExpr - Build a call to a resolved expression, 4629 /// i.e. an expression not of \p OverloadTy. The expression should 4630 /// unary-convert to an expression of function-pointer or 4631 /// block-pointer type. 4632 /// 4633 /// \param NDecl the declaration being called, if available 4634 ExprResult 4635 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 4636 SourceLocation LParenLoc, 4637 ArrayRef<Expr *> Args, 4638 SourceLocation RParenLoc, 4639 Expr *Config, bool IsExecConfig) { 4640 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 4641 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 4642 4643 // Promote the function operand. 4644 // We special-case function promotion here because we only allow promoting 4645 // builtin functions to function pointers in the callee of a call. 4646 ExprResult Result; 4647 if (BuiltinID && 4648 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 4649 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 4650 CK_BuiltinFnToFnPtr).get(); 4651 } else { 4652 Result = CallExprUnaryConversions(Fn); 4653 } 4654 if (Result.isInvalid()) 4655 return ExprError(); 4656 Fn = Result.get(); 4657 4658 // Make the call expr early, before semantic checks. This guarantees cleanup 4659 // of arguments and function on error. 4660 CallExpr *TheCall; 4661 if (Config) 4662 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 4663 cast<CallExpr>(Config), Args, 4664 Context.BoolTy, VK_RValue, 4665 RParenLoc); 4666 else 4667 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 4668 VK_RValue, RParenLoc); 4669 4670 // Bail out early if calling a builtin with custom typechecking. 4671 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 4672 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 4673 4674 retry: 4675 const FunctionType *FuncT; 4676 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 4677 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 4678 // have type pointer to function". 4679 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 4680 if (!FuncT) 4681 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4682 << Fn->getType() << Fn->getSourceRange()); 4683 } else if (const BlockPointerType *BPT = 4684 Fn->getType()->getAs<BlockPointerType>()) { 4685 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 4686 } else { 4687 // Handle calls to expressions of unknown-any type. 4688 if (Fn->getType() == Context.UnknownAnyTy) { 4689 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 4690 if (rewrite.isInvalid()) return ExprError(); 4691 Fn = rewrite.get(); 4692 TheCall->setCallee(Fn); 4693 goto retry; 4694 } 4695 4696 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 4697 << Fn->getType() << Fn->getSourceRange()); 4698 } 4699 4700 if (getLangOpts().CUDA) { 4701 if (Config) { 4702 // CUDA: Kernel calls must be to global functions 4703 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 4704 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 4705 << FDecl->getName() << Fn->getSourceRange()); 4706 4707 // CUDA: Kernel function must have 'void' return type 4708 if (!FuncT->getReturnType()->isVoidType()) 4709 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 4710 << Fn->getType() << Fn->getSourceRange()); 4711 } else { 4712 // CUDA: Calls to global functions must be configured 4713 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 4714 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 4715 << FDecl->getName() << Fn->getSourceRange()); 4716 } 4717 } 4718 4719 // Check for a valid return type 4720 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 4721 FDecl)) 4722 return ExprError(); 4723 4724 // We know the result type of the call, set it. 4725 TheCall->setType(FuncT->getCallResultType(Context)); 4726 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 4727 4728 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 4729 if (Proto) { 4730 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 4731 IsExecConfig)) 4732 return ExprError(); 4733 } else { 4734 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 4735 4736 if (FDecl) { 4737 // Check if we have too few/too many template arguments, based 4738 // on our knowledge of the function definition. 4739 const FunctionDecl *Def = nullptr; 4740 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 4741 Proto = Def->getType()->getAs<FunctionProtoType>(); 4742 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 4743 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 4744 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 4745 } 4746 4747 // If the function we're calling isn't a function prototype, but we have 4748 // a function prototype from a prior declaratiom, use that prototype. 4749 if (!FDecl->hasPrototype()) 4750 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 4751 } 4752 4753 // Promote the arguments (C99 6.5.2.2p6). 4754 for (unsigned i = 0, e = Args.size(); i != e; i++) { 4755 Expr *Arg = Args[i]; 4756 4757 if (Proto && i < Proto->getNumParams()) { 4758 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4759 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 4760 ExprResult ArgE = 4761 PerformCopyInitialization(Entity, SourceLocation(), Arg); 4762 if (ArgE.isInvalid()) 4763 return true; 4764 4765 Arg = ArgE.getAs<Expr>(); 4766 4767 } else { 4768 ExprResult ArgE = DefaultArgumentPromotion(Arg); 4769 4770 if (ArgE.isInvalid()) 4771 return true; 4772 4773 Arg = ArgE.getAs<Expr>(); 4774 } 4775 4776 if (RequireCompleteType(Arg->getLocStart(), 4777 Arg->getType(), 4778 diag::err_call_incomplete_argument, Arg)) 4779 return ExprError(); 4780 4781 TheCall->setArg(i, Arg); 4782 } 4783 } 4784 4785 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4786 if (!Method->isStatic()) 4787 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 4788 << Fn->getSourceRange()); 4789 4790 // Check for sentinels 4791 if (NDecl) 4792 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 4793 4794 // Do special checking on direct calls to functions. 4795 if (FDecl) { 4796 if (CheckFunctionCall(FDecl, TheCall, Proto)) 4797 return ExprError(); 4798 4799 if (BuiltinID) 4800 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 4801 } else if (NDecl) { 4802 if (CheckPointerCall(NDecl, TheCall, Proto)) 4803 return ExprError(); 4804 } else { 4805 if (CheckOtherCall(TheCall, Proto)) 4806 return ExprError(); 4807 } 4808 4809 return MaybeBindToTemporary(TheCall); 4810 } 4811 4812 ExprResult 4813 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 4814 SourceLocation RParenLoc, Expr *InitExpr) { 4815 assert(Ty && "ActOnCompoundLiteral(): missing type"); 4816 // FIXME: put back this assert when initializers are worked out. 4817 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression"); 4818 4819 TypeSourceInfo *TInfo; 4820 QualType literalType = GetTypeFromParser(Ty, &TInfo); 4821 if (!TInfo) 4822 TInfo = Context.getTrivialTypeSourceInfo(literalType); 4823 4824 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 4825 } 4826 4827 ExprResult 4828 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 4829 SourceLocation RParenLoc, Expr *LiteralExpr) { 4830 QualType literalType = TInfo->getType(); 4831 4832 if (literalType->isArrayType()) { 4833 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 4834 diag::err_illegal_decl_array_incomplete_type, 4835 SourceRange(LParenLoc, 4836 LiteralExpr->getSourceRange().getEnd()))) 4837 return ExprError(); 4838 if (literalType->isVariableArrayType()) 4839 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 4840 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 4841 } else if (!literalType->isDependentType() && 4842 RequireCompleteType(LParenLoc, literalType, 4843 diag::err_typecheck_decl_incomplete_type, 4844 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 4845 return ExprError(); 4846 4847 InitializedEntity Entity 4848 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 4849 InitializationKind Kind 4850 = InitializationKind::CreateCStyleCast(LParenLoc, 4851 SourceRange(LParenLoc, RParenLoc), 4852 /*InitList=*/true); 4853 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 4854 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 4855 &literalType); 4856 if (Result.isInvalid()) 4857 return ExprError(); 4858 LiteralExpr = Result.get(); 4859 4860 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 4861 if (isFileScope && 4862 !LiteralExpr->isTypeDependent() && 4863 !LiteralExpr->isValueDependent() && 4864 !literalType->isDependentType()) { // 6.5.2.5p3 4865 if (CheckForConstantInitializer(LiteralExpr, literalType)) 4866 return ExprError(); 4867 } 4868 4869 // In C, compound literals are l-values for some reason. 4870 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 4871 4872 return MaybeBindToTemporary( 4873 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 4874 VK, LiteralExpr, isFileScope)); 4875 } 4876 4877 ExprResult 4878 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 4879 SourceLocation RBraceLoc) { 4880 // Immediately handle non-overload placeholders. Overloads can be 4881 // resolved contextually, but everything else here can't. 4882 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 4883 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 4884 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 4885 4886 // Ignore failures; dropping the entire initializer list because 4887 // of one failure would be terrible for indexing/etc. 4888 if (result.isInvalid()) continue; 4889 4890 InitArgList[I] = result.get(); 4891 } 4892 } 4893 4894 // Semantic analysis for initializers is done by ActOnDeclarator() and 4895 // CheckInitializer() - it requires knowledge of the object being intialized. 4896 4897 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 4898 RBraceLoc); 4899 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 4900 return E; 4901 } 4902 4903 /// Do an explicit extend of the given block pointer if we're in ARC. 4904 static void maybeExtendBlockObject(Sema &S, ExprResult &E) { 4905 assert(E.get()->getType()->isBlockPointerType()); 4906 assert(E.get()->isRValue()); 4907 4908 // Only do this in an r-value context. 4909 if (!S.getLangOpts().ObjCAutoRefCount) return; 4910 4911 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), 4912 CK_ARCExtendBlockObject, E.get(), 4913 /*base path*/ nullptr, VK_RValue); 4914 S.ExprNeedsCleanups = true; 4915 } 4916 4917 /// Prepare a conversion of the given expression to an ObjC object 4918 /// pointer type. 4919 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 4920 QualType type = E.get()->getType(); 4921 if (type->isObjCObjectPointerType()) { 4922 return CK_BitCast; 4923 } else if (type->isBlockPointerType()) { 4924 maybeExtendBlockObject(*this, E); 4925 return CK_BlockPointerToObjCPointerCast; 4926 } else { 4927 assert(type->isPointerType()); 4928 return CK_CPointerToObjCPointerCast; 4929 } 4930 } 4931 4932 /// Prepares for a scalar cast, performing all the necessary stages 4933 /// except the final cast and returning the kind required. 4934 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 4935 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 4936 // Also, callers should have filtered out the invalid cases with 4937 // pointers. Everything else should be possible. 4938 4939 QualType SrcTy = Src.get()->getType(); 4940 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 4941 return CK_NoOp; 4942 4943 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 4944 case Type::STK_MemberPointer: 4945 llvm_unreachable("member pointer type in C"); 4946 4947 case Type::STK_CPointer: 4948 case Type::STK_BlockPointer: 4949 case Type::STK_ObjCObjectPointer: 4950 switch (DestTy->getScalarTypeKind()) { 4951 case Type::STK_CPointer: { 4952 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 4953 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 4954 if (SrcAS != DestAS) 4955 return CK_AddressSpaceConversion; 4956 return CK_BitCast; 4957 } 4958 case Type::STK_BlockPointer: 4959 return (SrcKind == Type::STK_BlockPointer 4960 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 4961 case Type::STK_ObjCObjectPointer: 4962 if (SrcKind == Type::STK_ObjCObjectPointer) 4963 return CK_BitCast; 4964 if (SrcKind == Type::STK_CPointer) 4965 return CK_CPointerToObjCPointerCast; 4966 maybeExtendBlockObject(*this, Src); 4967 return CK_BlockPointerToObjCPointerCast; 4968 case Type::STK_Bool: 4969 return CK_PointerToBoolean; 4970 case Type::STK_Integral: 4971 return CK_PointerToIntegral; 4972 case Type::STK_Floating: 4973 case Type::STK_FloatingComplex: 4974 case Type::STK_IntegralComplex: 4975 case Type::STK_MemberPointer: 4976 llvm_unreachable("illegal cast from pointer"); 4977 } 4978 llvm_unreachable("Should have returned before this"); 4979 4980 case Type::STK_Bool: // casting from bool is like casting from an integer 4981 case Type::STK_Integral: 4982 switch (DestTy->getScalarTypeKind()) { 4983 case Type::STK_CPointer: 4984 case Type::STK_ObjCObjectPointer: 4985 case Type::STK_BlockPointer: 4986 if (Src.get()->isNullPointerConstant(Context, 4987 Expr::NPC_ValueDependentIsNull)) 4988 return CK_NullToPointer; 4989 return CK_IntegralToPointer; 4990 case Type::STK_Bool: 4991 return CK_IntegralToBoolean; 4992 case Type::STK_Integral: 4993 return CK_IntegralCast; 4994 case Type::STK_Floating: 4995 return CK_IntegralToFloating; 4996 case Type::STK_IntegralComplex: 4997 Src = ImpCastExprToType(Src.get(), 4998 DestTy->castAs<ComplexType>()->getElementType(), 4999 CK_IntegralCast); 5000 return CK_IntegralRealToComplex; 5001 case Type::STK_FloatingComplex: 5002 Src = ImpCastExprToType(Src.get(), 5003 DestTy->castAs<ComplexType>()->getElementType(), 5004 CK_IntegralToFloating); 5005 return CK_FloatingRealToComplex; 5006 case Type::STK_MemberPointer: 5007 llvm_unreachable("member pointer type in C"); 5008 } 5009 llvm_unreachable("Should have returned before this"); 5010 5011 case Type::STK_Floating: 5012 switch (DestTy->getScalarTypeKind()) { 5013 case Type::STK_Floating: 5014 return CK_FloatingCast; 5015 case Type::STK_Bool: 5016 return CK_FloatingToBoolean; 5017 case Type::STK_Integral: 5018 return CK_FloatingToIntegral; 5019 case Type::STK_FloatingComplex: 5020 Src = ImpCastExprToType(Src.get(), 5021 DestTy->castAs<ComplexType>()->getElementType(), 5022 CK_FloatingCast); 5023 return CK_FloatingRealToComplex; 5024 case Type::STK_IntegralComplex: 5025 Src = ImpCastExprToType(Src.get(), 5026 DestTy->castAs<ComplexType>()->getElementType(), 5027 CK_FloatingToIntegral); 5028 return CK_IntegralRealToComplex; 5029 case Type::STK_CPointer: 5030 case Type::STK_ObjCObjectPointer: 5031 case Type::STK_BlockPointer: 5032 llvm_unreachable("valid float->pointer cast?"); 5033 case Type::STK_MemberPointer: 5034 llvm_unreachable("member pointer type in C"); 5035 } 5036 llvm_unreachable("Should have returned before this"); 5037 5038 case Type::STK_FloatingComplex: 5039 switch (DestTy->getScalarTypeKind()) { 5040 case Type::STK_FloatingComplex: 5041 return CK_FloatingComplexCast; 5042 case Type::STK_IntegralComplex: 5043 return CK_FloatingComplexToIntegralComplex; 5044 case Type::STK_Floating: { 5045 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5046 if (Context.hasSameType(ET, DestTy)) 5047 return CK_FloatingComplexToReal; 5048 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5049 return CK_FloatingCast; 5050 } 5051 case Type::STK_Bool: 5052 return CK_FloatingComplexToBoolean; 5053 case Type::STK_Integral: 5054 Src = ImpCastExprToType(Src.get(), 5055 SrcTy->castAs<ComplexType>()->getElementType(), 5056 CK_FloatingComplexToReal); 5057 return CK_FloatingToIntegral; 5058 case Type::STK_CPointer: 5059 case Type::STK_ObjCObjectPointer: 5060 case Type::STK_BlockPointer: 5061 llvm_unreachable("valid complex float->pointer cast?"); 5062 case Type::STK_MemberPointer: 5063 llvm_unreachable("member pointer type in C"); 5064 } 5065 llvm_unreachable("Should have returned before this"); 5066 5067 case Type::STK_IntegralComplex: 5068 switch (DestTy->getScalarTypeKind()) { 5069 case Type::STK_FloatingComplex: 5070 return CK_IntegralComplexToFloatingComplex; 5071 case Type::STK_IntegralComplex: 5072 return CK_IntegralComplexCast; 5073 case Type::STK_Integral: { 5074 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5075 if (Context.hasSameType(ET, DestTy)) 5076 return CK_IntegralComplexToReal; 5077 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5078 return CK_IntegralCast; 5079 } 5080 case Type::STK_Bool: 5081 return CK_IntegralComplexToBoolean; 5082 case Type::STK_Floating: 5083 Src = ImpCastExprToType(Src.get(), 5084 SrcTy->castAs<ComplexType>()->getElementType(), 5085 CK_IntegralComplexToReal); 5086 return CK_IntegralToFloating; 5087 case Type::STK_CPointer: 5088 case Type::STK_ObjCObjectPointer: 5089 case Type::STK_BlockPointer: 5090 llvm_unreachable("valid complex int->pointer cast?"); 5091 case Type::STK_MemberPointer: 5092 llvm_unreachable("member pointer type in C"); 5093 } 5094 llvm_unreachable("Should have returned before this"); 5095 } 5096 5097 llvm_unreachable("Unhandled scalar cast"); 5098 } 5099 5100 static bool breakDownVectorType(QualType type, uint64_t &len, 5101 QualType &eltType) { 5102 // Vectors are simple. 5103 if (const VectorType *vecType = type->getAs<VectorType>()) { 5104 len = vecType->getNumElements(); 5105 eltType = vecType->getElementType(); 5106 assert(eltType->isScalarType()); 5107 return true; 5108 } 5109 5110 // We allow lax conversion to and from non-vector types, but only if 5111 // they're real types (i.e. non-complex, non-pointer scalar types). 5112 if (!type->isRealType()) return false; 5113 5114 len = 1; 5115 eltType = type; 5116 return true; 5117 } 5118 5119 static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) { 5120 uint64_t srcLen, destLen; 5121 QualType srcElt, destElt; 5122 if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false; 5123 if (!breakDownVectorType(destTy, destLen, destElt)) return false; 5124 5125 // ASTContext::getTypeSize will return the size rounded up to a 5126 // power of 2, so instead of using that, we need to use the raw 5127 // element size multiplied by the element count. 5128 uint64_t srcEltSize = S.Context.getTypeSize(srcElt); 5129 uint64_t destEltSize = S.Context.getTypeSize(destElt); 5130 5131 return (srcLen * srcEltSize == destLen * destEltSize); 5132 } 5133 5134 /// Is this a legal conversion between two known vector types? 5135 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5136 assert(destTy->isVectorType() || srcTy->isVectorType()); 5137 5138 if (!Context.getLangOpts().LaxVectorConversions) 5139 return false; 5140 return VectorTypesMatch(*this, srcTy, destTy); 5141 } 5142 5143 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5144 CastKind &Kind) { 5145 assert(VectorTy->isVectorType() && "Not a vector type!"); 5146 5147 if (Ty->isVectorType() || Ty->isIntegerType()) { 5148 if (!VectorTypesMatch(*this, Ty, VectorTy)) 5149 return Diag(R.getBegin(), 5150 Ty->isVectorType() ? 5151 diag::err_invalid_conversion_between_vectors : 5152 diag::err_invalid_conversion_between_vector_and_integer) 5153 << VectorTy << Ty << R; 5154 } else 5155 return Diag(R.getBegin(), 5156 diag::err_invalid_conversion_between_vector_and_scalar) 5157 << VectorTy << Ty << R; 5158 5159 Kind = CK_BitCast; 5160 return false; 5161 } 5162 5163 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5164 Expr *CastExpr, CastKind &Kind) { 5165 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5166 5167 QualType SrcTy = CastExpr->getType(); 5168 5169 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5170 // an ExtVectorType. 5171 // In OpenCL, casts between vectors of different types are not allowed. 5172 // (See OpenCL 6.2). 5173 if (SrcTy->isVectorType()) { 5174 if (!VectorTypesMatch(*this, SrcTy, DestTy) 5175 || (getLangOpts().OpenCL && 5176 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5177 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5178 << DestTy << SrcTy << R; 5179 return ExprError(); 5180 } 5181 Kind = CK_BitCast; 5182 return CastExpr; 5183 } 5184 5185 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5186 // conversion will take place first from scalar to elt type, and then 5187 // splat from elt type to vector. 5188 if (SrcTy->isPointerType()) 5189 return Diag(R.getBegin(), 5190 diag::err_invalid_conversion_between_vector_and_scalar) 5191 << DestTy << SrcTy << R; 5192 5193 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 5194 ExprResult CastExprRes = CastExpr; 5195 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 5196 if (CastExprRes.isInvalid()) 5197 return ExprError(); 5198 CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get(); 5199 5200 Kind = CK_VectorSplat; 5201 return CastExpr; 5202 } 5203 5204 ExprResult 5205 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5206 Declarator &D, ParsedType &Ty, 5207 SourceLocation RParenLoc, Expr *CastExpr) { 5208 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5209 "ActOnCastExpr(): missing type or expr"); 5210 5211 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5212 if (D.isInvalidType()) 5213 return ExprError(); 5214 5215 if (getLangOpts().CPlusPlus) { 5216 // Check that there are no default arguments (C++ only). 5217 CheckExtraCXXDefaultArguments(D); 5218 } 5219 5220 checkUnusedDeclAttributes(D); 5221 5222 QualType castType = castTInfo->getType(); 5223 Ty = CreateParsedType(castType, castTInfo); 5224 5225 bool isVectorLiteral = false; 5226 5227 // Check for an altivec or OpenCL literal, 5228 // i.e. all the elements are integer constants. 5229 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5230 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5231 if ((getLangOpts().AltiVec || getLangOpts().OpenCL) 5232 && castType->isVectorType() && (PE || PLE)) { 5233 if (PLE && PLE->getNumExprs() == 0) { 5234 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5235 return ExprError(); 5236 } 5237 if (PE || PLE->getNumExprs() == 1) { 5238 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5239 if (!E->getType()->isVectorType()) 5240 isVectorLiteral = true; 5241 } 5242 else 5243 isVectorLiteral = true; 5244 } 5245 5246 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5247 // then handle it as such. 5248 if (isVectorLiteral) 5249 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5250 5251 // If the Expr being casted is a ParenListExpr, handle it specially. 5252 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5253 // sequence of BinOp comma operators. 5254 if (isa<ParenListExpr>(CastExpr)) { 5255 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5256 if (Result.isInvalid()) return ExprError(); 5257 CastExpr = Result.get(); 5258 } 5259 5260 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 5261 !getSourceManager().isInSystemMacro(LParenLoc)) 5262 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 5263 5264 CheckTollFreeBridgeCast(castType, CastExpr); 5265 5266 CheckObjCBridgeRelatedCast(castType, CastExpr); 5267 5268 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 5269 } 5270 5271 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 5272 SourceLocation RParenLoc, Expr *E, 5273 TypeSourceInfo *TInfo) { 5274 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 5275 "Expected paren or paren list expression"); 5276 5277 Expr **exprs; 5278 unsigned numExprs; 5279 Expr *subExpr; 5280 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 5281 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 5282 LiteralLParenLoc = PE->getLParenLoc(); 5283 LiteralRParenLoc = PE->getRParenLoc(); 5284 exprs = PE->getExprs(); 5285 numExprs = PE->getNumExprs(); 5286 } else { // isa<ParenExpr> by assertion at function entrance 5287 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 5288 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 5289 subExpr = cast<ParenExpr>(E)->getSubExpr(); 5290 exprs = &subExpr; 5291 numExprs = 1; 5292 } 5293 5294 QualType Ty = TInfo->getType(); 5295 assert(Ty->isVectorType() && "Expected vector type"); 5296 5297 SmallVector<Expr *, 8> initExprs; 5298 const VectorType *VTy = Ty->getAs<VectorType>(); 5299 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 5300 5301 // '(...)' form of vector initialization in AltiVec: the number of 5302 // initializers must be one or must match the size of the vector. 5303 // If a single value is specified in the initializer then it will be 5304 // replicated to all the components of the vector 5305 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 5306 // The number of initializers must be one or must match the size of the 5307 // vector. If a single value is specified in the initializer then it will 5308 // be replicated to all the components of the vector 5309 if (numExprs == 1) { 5310 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5311 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5312 if (Literal.isInvalid()) 5313 return ExprError(); 5314 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5315 PrepareScalarCast(Literal, ElemTy)); 5316 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5317 } 5318 else if (numExprs < numElems) { 5319 Diag(E->getExprLoc(), 5320 diag::err_incorrect_number_of_vector_initializers); 5321 return ExprError(); 5322 } 5323 else 5324 initExprs.append(exprs, exprs + numExprs); 5325 } 5326 else { 5327 // For OpenCL, when the number of initializers is a single value, 5328 // it will be replicated to all components of the vector. 5329 if (getLangOpts().OpenCL && 5330 VTy->getVectorKind() == VectorType::GenericVector && 5331 numExprs == 1) { 5332 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5333 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5334 if (Literal.isInvalid()) 5335 return ExprError(); 5336 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5337 PrepareScalarCast(Literal, ElemTy)); 5338 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5339 } 5340 5341 initExprs.append(exprs, exprs + numExprs); 5342 } 5343 // FIXME: This means that pretty-printing the final AST will produce curly 5344 // braces instead of the original commas. 5345 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 5346 initExprs, LiteralRParenLoc); 5347 initE->setType(Ty); 5348 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 5349 } 5350 5351 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 5352 /// the ParenListExpr into a sequence of comma binary operators. 5353 ExprResult 5354 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 5355 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 5356 if (!E) 5357 return OrigExpr; 5358 5359 ExprResult Result(E->getExpr(0)); 5360 5361 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 5362 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 5363 E->getExpr(i)); 5364 5365 if (Result.isInvalid()) return ExprError(); 5366 5367 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 5368 } 5369 5370 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 5371 SourceLocation R, 5372 MultiExprArg Val) { 5373 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 5374 return expr; 5375 } 5376 5377 /// \brief Emit a specialized diagnostic when one expression is a null pointer 5378 /// constant and the other is not a pointer. Returns true if a diagnostic is 5379 /// emitted. 5380 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 5381 SourceLocation QuestionLoc) { 5382 Expr *NullExpr = LHSExpr; 5383 Expr *NonPointerExpr = RHSExpr; 5384 Expr::NullPointerConstantKind NullKind = 5385 NullExpr->isNullPointerConstant(Context, 5386 Expr::NPC_ValueDependentIsNotNull); 5387 5388 if (NullKind == Expr::NPCK_NotNull) { 5389 NullExpr = RHSExpr; 5390 NonPointerExpr = LHSExpr; 5391 NullKind = 5392 NullExpr->isNullPointerConstant(Context, 5393 Expr::NPC_ValueDependentIsNotNull); 5394 } 5395 5396 if (NullKind == Expr::NPCK_NotNull) 5397 return false; 5398 5399 if (NullKind == Expr::NPCK_ZeroExpression) 5400 return false; 5401 5402 if (NullKind == Expr::NPCK_ZeroLiteral) { 5403 // In this case, check to make sure that we got here from a "NULL" 5404 // string in the source code. 5405 NullExpr = NullExpr->IgnoreParenImpCasts(); 5406 SourceLocation loc = NullExpr->getExprLoc(); 5407 if (!findMacroSpelling(loc, "NULL")) 5408 return false; 5409 } 5410 5411 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 5412 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 5413 << NonPointerExpr->getType() << DiagType 5414 << NonPointerExpr->getSourceRange(); 5415 return true; 5416 } 5417 5418 /// \brief Return false if the condition expression is valid, true otherwise. 5419 static bool checkCondition(Sema &S, Expr *Cond) { 5420 QualType CondTy = Cond->getType(); 5421 5422 // C99 6.5.15p2 5423 if (CondTy->isScalarType()) return false; 5424 5425 // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar. 5426 if (S.getLangOpts().OpenCL && CondTy->isVectorType()) 5427 return false; 5428 5429 // Emit the proper error message. 5430 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ? 5431 diag::err_typecheck_cond_expect_scalar : 5432 diag::err_typecheck_cond_expect_scalar_or_vector) 5433 << CondTy; 5434 return true; 5435 } 5436 5437 /// \brief Return false if the two expressions can be converted to a vector, 5438 /// true otherwise 5439 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS, 5440 ExprResult &RHS, 5441 QualType CondTy) { 5442 // Both operands should be of scalar type. 5443 if (!LHS.get()->getType()->isScalarType()) { 5444 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5445 << CondTy; 5446 return true; 5447 } 5448 if (!RHS.get()->getType()->isScalarType()) { 5449 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar) 5450 << CondTy; 5451 return true; 5452 } 5453 5454 // Implicity convert these scalars to the type of the condition. 5455 LHS = S.ImpCastExprToType(LHS.get(), CondTy, CK_IntegralCast); 5456 RHS = S.ImpCastExprToType(RHS.get(), CondTy, CK_IntegralCast); 5457 return false; 5458 } 5459 5460 /// \brief Handle when one or both operands are void type. 5461 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 5462 ExprResult &RHS) { 5463 Expr *LHSExpr = LHS.get(); 5464 Expr *RHSExpr = RHS.get(); 5465 5466 if (!LHSExpr->getType()->isVoidType()) 5467 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5468 << RHSExpr->getSourceRange(); 5469 if (!RHSExpr->getType()->isVoidType()) 5470 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5471 << LHSExpr->getSourceRange(); 5472 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 5473 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 5474 return S.Context.VoidTy; 5475 } 5476 5477 /// \brief Return false if the NullExpr can be promoted to PointerTy, 5478 /// true otherwise. 5479 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 5480 QualType PointerTy) { 5481 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 5482 !NullExpr.get()->isNullPointerConstant(S.Context, 5483 Expr::NPC_ValueDependentIsNull)) 5484 return true; 5485 5486 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 5487 return false; 5488 } 5489 5490 /// \brief Checks compatibility between two pointers and return the resulting 5491 /// type. 5492 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 5493 ExprResult &RHS, 5494 SourceLocation Loc) { 5495 QualType LHSTy = LHS.get()->getType(); 5496 QualType RHSTy = RHS.get()->getType(); 5497 5498 if (S.Context.hasSameType(LHSTy, RHSTy)) { 5499 // Two identical pointers types are always compatible. 5500 return LHSTy; 5501 } 5502 5503 QualType lhptee, rhptee; 5504 5505 // Get the pointee types. 5506 bool IsBlockPointer = false; 5507 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 5508 lhptee = LHSBTy->getPointeeType(); 5509 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 5510 IsBlockPointer = true; 5511 } else { 5512 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 5513 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 5514 } 5515 5516 // C99 6.5.15p6: If both operands are pointers to compatible types or to 5517 // differently qualified versions of compatible types, the result type is 5518 // a pointer to an appropriately qualified version of the composite 5519 // type. 5520 5521 // Only CVR-qualifiers exist in the standard, and the differently-qualified 5522 // clause doesn't make sense for our extensions. E.g. address space 2 should 5523 // be incompatible with address space 3: they may live on different devices or 5524 // anything. 5525 Qualifiers lhQual = lhptee.getQualifiers(); 5526 Qualifiers rhQual = rhptee.getQualifiers(); 5527 5528 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 5529 lhQual.removeCVRQualifiers(); 5530 rhQual.removeCVRQualifiers(); 5531 5532 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 5533 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 5534 5535 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 5536 5537 if (CompositeTy.isNull()) { 5538 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 5539 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5540 << RHS.get()->getSourceRange(); 5541 // In this situation, we assume void* type. No especially good 5542 // reason, but this is what gcc does, and we do have to pick 5543 // to get a consistent AST. 5544 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 5545 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 5546 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 5547 return incompatTy; 5548 } 5549 5550 // The pointer types are compatible. 5551 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 5552 if (IsBlockPointer) 5553 ResultTy = S.Context.getBlockPointerType(ResultTy); 5554 else 5555 ResultTy = S.Context.getPointerType(ResultTy); 5556 5557 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast); 5558 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast); 5559 return ResultTy; 5560 } 5561 5562 /// \brief Returns true if QT is quelified-id and implements 'NSObject' and/or 5563 /// 'NSCopying' protocols (and nothing else); or QT is an NSObject and optionally 5564 /// implements 'NSObject' and/or NSCopying' protocols (and nothing else). 5565 static bool isObjCPtrBlockCompatible(Sema &S, ASTContext &C, QualType QT) { 5566 if (QT->isObjCIdType()) 5567 return true; 5568 5569 const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>(); 5570 if (!OPT) 5571 return false; 5572 5573 if (ObjCInterfaceDecl *ID = OPT->getInterfaceDecl()) 5574 if (ID->getIdentifier() != &C.Idents.get("NSObject")) 5575 return false; 5576 5577 ObjCProtocolDecl* PNSCopying = 5578 S.LookupProtocol(&C.Idents.get("NSCopying"), SourceLocation()); 5579 ObjCProtocolDecl* PNSObject = 5580 S.LookupProtocol(&C.Idents.get("NSObject"), SourceLocation()); 5581 5582 for (auto *Proto : OPT->quals()) { 5583 if ((PNSCopying && declaresSameEntity(Proto, PNSCopying)) || 5584 (PNSObject && declaresSameEntity(Proto, PNSObject))) 5585 ; 5586 else 5587 return false; 5588 } 5589 return true; 5590 } 5591 5592 /// \brief Return the resulting type when the operands are both block pointers. 5593 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 5594 ExprResult &LHS, 5595 ExprResult &RHS, 5596 SourceLocation Loc) { 5597 QualType LHSTy = LHS.get()->getType(); 5598 QualType RHSTy = RHS.get()->getType(); 5599 5600 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 5601 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 5602 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 5603 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 5604 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 5605 return destType; 5606 } 5607 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 5608 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5609 << RHS.get()->getSourceRange(); 5610 return QualType(); 5611 } 5612 5613 // We have 2 block pointer types. 5614 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5615 } 5616 5617 /// \brief Return the resulting type when the operands are both pointers. 5618 static QualType 5619 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 5620 ExprResult &RHS, 5621 SourceLocation Loc) { 5622 // get the pointer types 5623 QualType LHSTy = LHS.get()->getType(); 5624 QualType RHSTy = RHS.get()->getType(); 5625 5626 // get the "pointed to" types 5627 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5628 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5629 5630 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 5631 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 5632 // Figure out necessary qualifiers (C99 6.5.15p6) 5633 QualType destPointee 5634 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5635 QualType destType = S.Context.getPointerType(destPointee); 5636 // Add qualifiers if necessary. 5637 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 5638 // Promote to void*. 5639 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 5640 return destType; 5641 } 5642 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 5643 QualType destPointee 5644 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5645 QualType destType = S.Context.getPointerType(destPointee); 5646 // Add qualifiers if necessary. 5647 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 5648 // Promote to void*. 5649 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 5650 return destType; 5651 } 5652 5653 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 5654 } 5655 5656 /// \brief Return false if the first expression is not an integer and the second 5657 /// expression is not a pointer, true otherwise. 5658 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 5659 Expr* PointerExpr, SourceLocation Loc, 5660 bool IsIntFirstExpr) { 5661 if (!PointerExpr->getType()->isPointerType() || 5662 !Int.get()->getType()->isIntegerType()) 5663 return false; 5664 5665 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 5666 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 5667 5668 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 5669 << Expr1->getType() << Expr2->getType() 5670 << Expr1->getSourceRange() << Expr2->getSourceRange(); 5671 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 5672 CK_IntegralToPointer); 5673 return true; 5674 } 5675 5676 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 5677 /// In that case, LHS = cond. 5678 /// C99 6.5.15 5679 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 5680 ExprResult &RHS, ExprValueKind &VK, 5681 ExprObjectKind &OK, 5682 SourceLocation QuestionLoc) { 5683 5684 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 5685 if (!LHSResult.isUsable()) return QualType(); 5686 LHS = LHSResult; 5687 5688 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 5689 if (!RHSResult.isUsable()) return QualType(); 5690 RHS = RHSResult; 5691 5692 // C++ is sufficiently different to merit its own checker. 5693 if (getLangOpts().CPlusPlus) 5694 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 5695 5696 VK = VK_RValue; 5697 OK = OK_Ordinary; 5698 5699 // First, check the condition. 5700 Cond = UsualUnaryConversions(Cond.get()); 5701 if (Cond.isInvalid()) 5702 return QualType(); 5703 if (checkCondition(*this, Cond.get())) 5704 return QualType(); 5705 5706 // Now check the two expressions. 5707 if (LHS.get()->getType()->isVectorType() || 5708 RHS.get()->getType()->isVectorType()) 5709 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false); 5710 5711 UsualArithmeticConversions(LHS, RHS); 5712 if (LHS.isInvalid() || RHS.isInvalid()) 5713 return QualType(); 5714 5715 QualType CondTy = Cond.get()->getType(); 5716 QualType LHSTy = LHS.get()->getType(); 5717 QualType RHSTy = RHS.get()->getType(); 5718 5719 // If the condition is a vector, and both operands are scalar, 5720 // attempt to implicity convert them to the vector type to act like the 5721 // built in select. (OpenCL v1.1 s6.3.i) 5722 if (getLangOpts().OpenCL && CondTy->isVectorType()) 5723 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy)) 5724 return QualType(); 5725 5726 // If both operands have arithmetic type, do the usual arithmetic conversions 5727 // to find a common type: C99 6.5.15p3,5. 5728 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) 5729 return LHS.get()->getType(); 5730 5731 // If both operands are the same structure or union type, the result is that 5732 // type. 5733 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 5734 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 5735 if (LHSRT->getDecl() == RHSRT->getDecl()) 5736 // "If both the operands have structure or union type, the result has 5737 // that type." This implies that CV qualifiers are dropped. 5738 return LHSTy.getUnqualifiedType(); 5739 // FIXME: Type of conditional expression must be complete in C mode. 5740 } 5741 5742 // C99 6.5.15p5: "If both operands have void type, the result has void type." 5743 // The following || allows only one side to be void (a GCC-ism). 5744 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 5745 return checkConditionalVoidType(*this, LHS, RHS); 5746 } 5747 5748 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 5749 // the type of the other operand." 5750 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 5751 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 5752 5753 // All objective-c pointer type analysis is done here. 5754 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 5755 QuestionLoc); 5756 if (LHS.isInvalid() || RHS.isInvalid()) 5757 return QualType(); 5758 if (!compositeType.isNull()) 5759 return compositeType; 5760 5761 5762 // Handle block pointer types. 5763 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 5764 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 5765 QuestionLoc); 5766 5767 // Check constraints for C object pointers types (C99 6.5.15p3,6). 5768 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 5769 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 5770 QuestionLoc); 5771 5772 // GCC compatibility: soften pointer/integer mismatch. Note that 5773 // null pointers have been filtered out by this point. 5774 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 5775 /*isIntFirstExpr=*/true)) 5776 return RHSTy; 5777 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 5778 /*isIntFirstExpr=*/false)) 5779 return LHSTy; 5780 5781 // Emit a better diagnostic if one of the expressions is a null pointer 5782 // constant and the other is not a pointer type. In this case, the user most 5783 // likely forgot to take the address of the other expression. 5784 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 5785 return QualType(); 5786 5787 // Otherwise, the operands are not compatible. 5788 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 5789 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5790 << RHS.get()->getSourceRange(); 5791 return QualType(); 5792 } 5793 5794 /// FindCompositeObjCPointerType - Helper method to find composite type of 5795 /// two objective-c pointer types of the two input expressions. 5796 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 5797 SourceLocation QuestionLoc) { 5798 QualType LHSTy = LHS.get()->getType(); 5799 QualType RHSTy = RHS.get()->getType(); 5800 5801 // Handle things like Class and struct objc_class*. Here we case the result 5802 // to the pseudo-builtin, because that will be implicitly cast back to the 5803 // redefinition type if an attempt is made to access its fields. 5804 if (LHSTy->isObjCClassType() && 5805 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 5806 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 5807 return LHSTy; 5808 } 5809 if (RHSTy->isObjCClassType() && 5810 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 5811 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 5812 return RHSTy; 5813 } 5814 // And the same for struct objc_object* / id 5815 if (LHSTy->isObjCIdType() && 5816 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 5817 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 5818 return LHSTy; 5819 } 5820 if (RHSTy->isObjCIdType() && 5821 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 5822 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 5823 return RHSTy; 5824 } 5825 // And the same for struct objc_selector* / SEL 5826 if (Context.isObjCSelType(LHSTy) && 5827 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 5828 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 5829 return LHSTy; 5830 } 5831 if (Context.isObjCSelType(RHSTy) && 5832 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 5833 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 5834 return RHSTy; 5835 } 5836 // Check constraints for Objective-C object pointers types. 5837 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 5838 5839 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 5840 // Two identical object pointer types are always compatible. 5841 return LHSTy; 5842 } 5843 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 5844 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 5845 QualType compositeType = LHSTy; 5846 5847 // If both operands are interfaces and either operand can be 5848 // assigned to the other, use that type as the composite 5849 // type. This allows 5850 // xxx ? (A*) a : (B*) b 5851 // where B is a subclass of A. 5852 // 5853 // Additionally, as for assignment, if either type is 'id' 5854 // allow silent coercion. Finally, if the types are 5855 // incompatible then make sure to use 'id' as the composite 5856 // type so the result is acceptable for sending messages to. 5857 5858 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 5859 // It could return the composite type. 5860 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 5861 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 5862 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 5863 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 5864 } else if ((LHSTy->isObjCQualifiedIdType() || 5865 RHSTy->isObjCQualifiedIdType()) && 5866 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 5867 // Need to handle "id<xx>" explicitly. 5868 // GCC allows qualified id and any Objective-C type to devolve to 5869 // id. Currently localizing to here until clear this should be 5870 // part of ObjCQualifiedIdTypesAreCompatible. 5871 compositeType = Context.getObjCIdType(); 5872 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 5873 compositeType = Context.getObjCIdType(); 5874 } else if (!(compositeType = 5875 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) 5876 ; 5877 else { 5878 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 5879 << LHSTy << RHSTy 5880 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5881 QualType incompatTy = Context.getObjCIdType(); 5882 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 5883 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 5884 return incompatTy; 5885 } 5886 // The object pointer types are compatible. 5887 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 5888 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 5889 return compositeType; 5890 } 5891 // Check Objective-C object pointer types and 'void *' 5892 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 5893 if (getLangOpts().ObjCAutoRefCount) { 5894 // ARC forbids the implicit conversion of object pointers to 'void *', 5895 // so these types are not compatible. 5896 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5897 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5898 LHS = RHS = true; 5899 return QualType(); 5900 } 5901 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 5902 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5903 QualType destPointee 5904 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 5905 QualType destType = Context.getPointerType(destPointee); 5906 // Add qualifiers if necessary. 5907 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 5908 // Promote to void*. 5909 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 5910 return destType; 5911 } 5912 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 5913 if (getLangOpts().ObjCAutoRefCount) { 5914 // ARC forbids the implicit conversion of object pointers to 'void *', 5915 // so these types are not compatible. 5916 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 5917 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 5918 LHS = RHS = true; 5919 return QualType(); 5920 } 5921 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 5922 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 5923 QualType destPointee 5924 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 5925 QualType destType = Context.getPointerType(destPointee); 5926 // Add qualifiers if necessary. 5927 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 5928 // Promote to void*. 5929 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 5930 return destType; 5931 } 5932 return QualType(); 5933 } 5934 5935 /// SuggestParentheses - Emit a note with a fixit hint that wraps 5936 /// ParenRange in parentheses. 5937 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 5938 const PartialDiagnostic &Note, 5939 SourceRange ParenRange) { 5940 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 5941 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 5942 EndLoc.isValid()) { 5943 Self.Diag(Loc, Note) 5944 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 5945 << FixItHint::CreateInsertion(EndLoc, ")"); 5946 } else { 5947 // We can't display the parentheses, so just show the bare note. 5948 Self.Diag(Loc, Note) << ParenRange; 5949 } 5950 } 5951 5952 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 5953 return Opc >= BO_Mul && Opc <= BO_Shr; 5954 } 5955 5956 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 5957 /// expression, either using a built-in or overloaded operator, 5958 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 5959 /// expression. 5960 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 5961 Expr **RHSExprs) { 5962 // Don't strip parenthesis: we should not warn if E is in parenthesis. 5963 E = E->IgnoreImpCasts(); 5964 E = E->IgnoreConversionOperator(); 5965 E = E->IgnoreImpCasts(); 5966 5967 // Built-in binary operator. 5968 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 5969 if (IsArithmeticOp(OP->getOpcode())) { 5970 *Opcode = OP->getOpcode(); 5971 *RHSExprs = OP->getRHS(); 5972 return true; 5973 } 5974 } 5975 5976 // Overloaded operator. 5977 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 5978 if (Call->getNumArgs() != 2) 5979 return false; 5980 5981 // Make sure this is really a binary operator that is safe to pass into 5982 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 5983 OverloadedOperatorKind OO = Call->getOperator(); 5984 if (OO < OO_Plus || OO > OO_Arrow || 5985 OO == OO_PlusPlus || OO == OO_MinusMinus) 5986 return false; 5987 5988 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 5989 if (IsArithmeticOp(OpKind)) { 5990 *Opcode = OpKind; 5991 *RHSExprs = Call->getArg(1); 5992 return true; 5993 } 5994 } 5995 5996 return false; 5997 } 5998 5999 static bool IsLogicOp(BinaryOperatorKind Opc) { 6000 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 6001 } 6002 6003 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 6004 /// or is a logical expression such as (x==y) which has int type, but is 6005 /// commonly interpreted as boolean. 6006 static bool ExprLooksBoolean(Expr *E) { 6007 E = E->IgnoreParenImpCasts(); 6008 6009 if (E->getType()->isBooleanType()) 6010 return true; 6011 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 6012 return IsLogicOp(OP->getOpcode()); 6013 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 6014 return OP->getOpcode() == UO_LNot; 6015 6016 return false; 6017 } 6018 6019 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 6020 /// and binary operator are mixed in a way that suggests the programmer assumed 6021 /// the conditional operator has higher precedence, for example: 6022 /// "int x = a + someBinaryCondition ? 1 : 2". 6023 static void DiagnoseConditionalPrecedence(Sema &Self, 6024 SourceLocation OpLoc, 6025 Expr *Condition, 6026 Expr *LHSExpr, 6027 Expr *RHSExpr) { 6028 BinaryOperatorKind CondOpcode; 6029 Expr *CondRHS; 6030 6031 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 6032 return; 6033 if (!ExprLooksBoolean(CondRHS)) 6034 return; 6035 6036 // The condition is an arithmetic binary expression, with a right- 6037 // hand side that looks boolean, so warn. 6038 6039 Self.Diag(OpLoc, diag::warn_precedence_conditional) 6040 << Condition->getSourceRange() 6041 << BinaryOperator::getOpcodeStr(CondOpcode); 6042 6043 SuggestParentheses(Self, OpLoc, 6044 Self.PDiag(diag::note_precedence_silence) 6045 << BinaryOperator::getOpcodeStr(CondOpcode), 6046 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 6047 6048 SuggestParentheses(Self, OpLoc, 6049 Self.PDiag(diag::note_precedence_conditional_first), 6050 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 6051 } 6052 6053 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 6054 /// in the case of a the GNU conditional expr extension. 6055 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 6056 SourceLocation ColonLoc, 6057 Expr *CondExpr, Expr *LHSExpr, 6058 Expr *RHSExpr) { 6059 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 6060 // was the condition. 6061 OpaqueValueExpr *opaqueValue = nullptr; 6062 Expr *commonExpr = nullptr; 6063 if (!LHSExpr) { 6064 commonExpr = CondExpr; 6065 // Lower out placeholder types first. This is important so that we don't 6066 // try to capture a placeholder. This happens in few cases in C++; such 6067 // as Objective-C++'s dictionary subscripting syntax. 6068 if (commonExpr->hasPlaceholderType()) { 6069 ExprResult result = CheckPlaceholderExpr(commonExpr); 6070 if (!result.isUsable()) return ExprError(); 6071 commonExpr = result.get(); 6072 } 6073 // We usually want to apply unary conversions *before* saving, except 6074 // in the special case of a C++ l-value conditional. 6075 if (!(getLangOpts().CPlusPlus 6076 && !commonExpr->isTypeDependent() 6077 && commonExpr->getValueKind() == RHSExpr->getValueKind() 6078 && commonExpr->isGLValue() 6079 && commonExpr->isOrdinaryOrBitFieldObject() 6080 && RHSExpr->isOrdinaryOrBitFieldObject() 6081 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 6082 ExprResult commonRes = UsualUnaryConversions(commonExpr); 6083 if (commonRes.isInvalid()) 6084 return ExprError(); 6085 commonExpr = commonRes.get(); 6086 } 6087 6088 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 6089 commonExpr->getType(), 6090 commonExpr->getValueKind(), 6091 commonExpr->getObjectKind(), 6092 commonExpr); 6093 LHSExpr = CondExpr = opaqueValue; 6094 } 6095 6096 ExprValueKind VK = VK_RValue; 6097 ExprObjectKind OK = OK_Ordinary; 6098 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 6099 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 6100 VK, OK, QuestionLoc); 6101 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 6102 RHS.isInvalid()) 6103 return ExprError(); 6104 6105 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 6106 RHS.get()); 6107 6108 if (!commonExpr) 6109 return new (Context) 6110 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 6111 RHS.get(), result, VK, OK); 6112 6113 return new (Context) BinaryConditionalOperator( 6114 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 6115 ColonLoc, result, VK, OK); 6116 } 6117 6118 // checkPointerTypesForAssignment - This is a very tricky routine (despite 6119 // being closely modeled after the C99 spec:-). The odd characteristic of this 6120 // routine is it effectively iqnores the qualifiers on the top level pointee. 6121 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 6122 // FIXME: add a couple examples in this comment. 6123 static Sema::AssignConvertType 6124 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 6125 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6126 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6127 6128 // get the "pointed to" type (ignoring qualifiers at the top level) 6129 const Type *lhptee, *rhptee; 6130 Qualifiers lhq, rhq; 6131 std::tie(lhptee, lhq) = 6132 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 6133 std::tie(rhptee, rhq) = 6134 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 6135 6136 Sema::AssignConvertType ConvTy = Sema::Compatible; 6137 6138 // C99 6.5.16.1p1: This following citation is common to constraints 6139 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 6140 // qualifiers of the type *pointed to* by the right; 6141 6142 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 6143 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 6144 lhq.compatiblyIncludesObjCLifetime(rhq)) { 6145 // Ignore lifetime for further calculation. 6146 lhq.removeObjCLifetime(); 6147 rhq.removeObjCLifetime(); 6148 } 6149 6150 if (!lhq.compatiblyIncludes(rhq)) { 6151 // Treat address-space mismatches as fatal. TODO: address subspaces 6152 if (lhq.getAddressSpace() != rhq.getAddressSpace()) 6153 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6154 6155 // It's okay to add or remove GC or lifetime qualifiers when converting to 6156 // and from void*. 6157 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 6158 .compatiblyIncludes( 6159 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 6160 && (lhptee->isVoidType() || rhptee->isVoidType())) 6161 ; // keep old 6162 6163 // Treat lifetime mismatches as fatal. 6164 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 6165 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6166 6167 // For GCC compatibility, other qualifier mismatches are treated 6168 // as still compatible in C. 6169 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6170 } 6171 6172 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 6173 // incomplete type and the other is a pointer to a qualified or unqualified 6174 // version of void... 6175 if (lhptee->isVoidType()) { 6176 if (rhptee->isIncompleteOrObjectType()) 6177 return ConvTy; 6178 6179 // As an extension, we allow cast to/from void* to function pointer. 6180 assert(rhptee->isFunctionType()); 6181 return Sema::FunctionVoidPointer; 6182 } 6183 6184 if (rhptee->isVoidType()) { 6185 if (lhptee->isIncompleteOrObjectType()) 6186 return ConvTy; 6187 6188 // As an extension, we allow cast to/from void* to function pointer. 6189 assert(lhptee->isFunctionType()); 6190 return Sema::FunctionVoidPointer; 6191 } 6192 6193 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 6194 // unqualified versions of compatible types, ... 6195 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 6196 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 6197 // Check if the pointee types are compatible ignoring the sign. 6198 // We explicitly check for char so that we catch "char" vs 6199 // "unsigned char" on systems where "char" is unsigned. 6200 if (lhptee->isCharType()) 6201 ltrans = S.Context.UnsignedCharTy; 6202 else if (lhptee->hasSignedIntegerRepresentation()) 6203 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 6204 6205 if (rhptee->isCharType()) 6206 rtrans = S.Context.UnsignedCharTy; 6207 else if (rhptee->hasSignedIntegerRepresentation()) 6208 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 6209 6210 if (ltrans == rtrans) { 6211 // Types are compatible ignoring the sign. Qualifier incompatibility 6212 // takes priority over sign incompatibility because the sign 6213 // warning can be disabled. 6214 if (ConvTy != Sema::Compatible) 6215 return ConvTy; 6216 6217 return Sema::IncompatiblePointerSign; 6218 } 6219 6220 // If we are a multi-level pointer, it's possible that our issue is simply 6221 // one of qualification - e.g. char ** -> const char ** is not allowed. If 6222 // the eventual target type is the same and the pointers have the same 6223 // level of indirection, this must be the issue. 6224 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 6225 do { 6226 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 6227 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 6228 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 6229 6230 if (lhptee == rhptee) 6231 return Sema::IncompatibleNestedPointerQualifiers; 6232 } 6233 6234 // General pointer incompatibility takes priority over qualifiers. 6235 return Sema::IncompatiblePointer; 6236 } 6237 if (!S.getLangOpts().CPlusPlus && 6238 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 6239 return Sema::IncompatiblePointer; 6240 return ConvTy; 6241 } 6242 6243 /// checkBlockPointerTypesForAssignment - This routine determines whether two 6244 /// block pointer types are compatible or whether a block and normal pointer 6245 /// are compatible. It is more restrict than comparing two function pointer 6246 // types. 6247 static Sema::AssignConvertType 6248 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 6249 QualType RHSType) { 6250 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6251 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6252 6253 QualType lhptee, rhptee; 6254 6255 // get the "pointed to" type (ignoring qualifiers at the top level) 6256 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 6257 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 6258 6259 // In C++, the types have to match exactly. 6260 if (S.getLangOpts().CPlusPlus) 6261 return Sema::IncompatibleBlockPointer; 6262 6263 Sema::AssignConvertType ConvTy = Sema::Compatible; 6264 6265 // For blocks we enforce that qualifiers are identical. 6266 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 6267 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6268 6269 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 6270 return Sema::IncompatibleBlockPointer; 6271 6272 return ConvTy; 6273 } 6274 6275 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 6276 /// for assignment compatibility. 6277 static Sema::AssignConvertType 6278 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 6279 QualType RHSType) { 6280 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 6281 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 6282 6283 if (LHSType->isObjCBuiltinType()) { 6284 // Class is not compatible with ObjC object pointers. 6285 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 6286 !RHSType->isObjCQualifiedClassType()) 6287 return Sema::IncompatiblePointer; 6288 return Sema::Compatible; 6289 } 6290 if (RHSType->isObjCBuiltinType()) { 6291 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 6292 !LHSType->isObjCQualifiedClassType()) 6293 return Sema::IncompatiblePointer; 6294 return Sema::Compatible; 6295 } 6296 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6297 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6298 6299 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 6300 // make an exception for id<P> 6301 !LHSType->isObjCQualifiedIdType()) 6302 return Sema::CompatiblePointerDiscardsQualifiers; 6303 6304 if (S.Context.typesAreCompatible(LHSType, RHSType)) 6305 return Sema::Compatible; 6306 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 6307 return Sema::IncompatibleObjCQualifiedId; 6308 return Sema::IncompatiblePointer; 6309 } 6310 6311 Sema::AssignConvertType 6312 Sema::CheckAssignmentConstraints(SourceLocation Loc, 6313 QualType LHSType, QualType RHSType) { 6314 // Fake up an opaque expression. We don't actually care about what 6315 // cast operations are required, so if CheckAssignmentConstraints 6316 // adds casts to this they'll be wasted, but fortunately that doesn't 6317 // usually happen on valid code. 6318 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 6319 ExprResult RHSPtr = &RHSExpr; 6320 CastKind K = CK_Invalid; 6321 6322 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 6323 } 6324 6325 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 6326 /// has code to accommodate several GCC extensions when type checking 6327 /// pointers. Here are some objectionable examples that GCC considers warnings: 6328 /// 6329 /// int a, *pint; 6330 /// short *pshort; 6331 /// struct foo *pfoo; 6332 /// 6333 /// pint = pshort; // warning: assignment from incompatible pointer type 6334 /// a = pint; // warning: assignment makes integer from pointer without a cast 6335 /// pint = a; // warning: assignment makes pointer from integer without a cast 6336 /// pint = pfoo; // warning: assignment from incompatible pointer type 6337 /// 6338 /// As a result, the code for dealing with pointers is more complex than the 6339 /// C99 spec dictates. 6340 /// 6341 /// Sets 'Kind' for any result kind except Incompatible. 6342 Sema::AssignConvertType 6343 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6344 CastKind &Kind) { 6345 QualType RHSType = RHS.get()->getType(); 6346 QualType OrigLHSType = LHSType; 6347 6348 // Get canonical types. We're not formatting these types, just comparing 6349 // them. 6350 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 6351 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 6352 6353 // Common case: no conversion required. 6354 if (LHSType == RHSType) { 6355 Kind = CK_NoOp; 6356 return Compatible; 6357 } 6358 6359 // If we have an atomic type, try a non-atomic assignment, then just add an 6360 // atomic qualification step. 6361 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 6362 Sema::AssignConvertType result = 6363 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 6364 if (result != Compatible) 6365 return result; 6366 if (Kind != CK_NoOp) 6367 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 6368 Kind = CK_NonAtomicToAtomic; 6369 return Compatible; 6370 } 6371 6372 // If the left-hand side is a reference type, then we are in a 6373 // (rare!) case where we've allowed the use of references in C, 6374 // e.g., as a parameter type in a built-in function. In this case, 6375 // just make sure that the type referenced is compatible with the 6376 // right-hand side type. The caller is responsible for adjusting 6377 // LHSType so that the resulting expression does not have reference 6378 // type. 6379 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 6380 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 6381 Kind = CK_LValueBitCast; 6382 return Compatible; 6383 } 6384 return Incompatible; 6385 } 6386 6387 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 6388 // to the same ExtVector type. 6389 if (LHSType->isExtVectorType()) { 6390 if (RHSType->isExtVectorType()) 6391 return Incompatible; 6392 if (RHSType->isArithmeticType()) { 6393 // CK_VectorSplat does T -> vector T, so first cast to the 6394 // element type. 6395 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 6396 if (elType != RHSType) { 6397 Kind = PrepareScalarCast(RHS, elType); 6398 RHS = ImpCastExprToType(RHS.get(), elType, Kind); 6399 } 6400 Kind = CK_VectorSplat; 6401 return Compatible; 6402 } 6403 } 6404 6405 // Conversions to or from vector type. 6406 if (LHSType->isVectorType() || RHSType->isVectorType()) { 6407 if (LHSType->isVectorType() && RHSType->isVectorType()) { 6408 // Allow assignments of an AltiVec vector type to an equivalent GCC 6409 // vector type and vice versa 6410 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6411 Kind = CK_BitCast; 6412 return Compatible; 6413 } 6414 6415 // If we are allowing lax vector conversions, and LHS and RHS are both 6416 // vectors, the total size only needs to be the same. This is a bitcast; 6417 // no bits are changed but the result type is different. 6418 if (isLaxVectorConversion(RHSType, LHSType)) { 6419 Kind = CK_BitCast; 6420 return IncompatibleVectors; 6421 } 6422 } 6423 return Incompatible; 6424 } 6425 6426 // Arithmetic conversions. 6427 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 6428 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 6429 Kind = PrepareScalarCast(RHS, LHSType); 6430 return Compatible; 6431 } 6432 6433 // Conversions to normal pointers. 6434 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 6435 // U* -> T* 6436 if (isa<PointerType>(RHSType)) { 6437 Kind = CK_BitCast; 6438 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 6439 } 6440 6441 // int -> T* 6442 if (RHSType->isIntegerType()) { 6443 Kind = CK_IntegralToPointer; // FIXME: null? 6444 return IntToPointer; 6445 } 6446 6447 // C pointers are not compatible with ObjC object pointers, 6448 // with two exceptions: 6449 if (isa<ObjCObjectPointerType>(RHSType)) { 6450 // - conversions to void* 6451 if (LHSPointer->getPointeeType()->isVoidType()) { 6452 Kind = CK_BitCast; 6453 return Compatible; 6454 } 6455 6456 // - conversions from 'Class' to the redefinition type 6457 if (RHSType->isObjCClassType() && 6458 Context.hasSameType(LHSType, 6459 Context.getObjCClassRedefinitionType())) { 6460 Kind = CK_BitCast; 6461 return Compatible; 6462 } 6463 6464 Kind = CK_BitCast; 6465 return IncompatiblePointer; 6466 } 6467 6468 // U^ -> void* 6469 if (RHSType->getAs<BlockPointerType>()) { 6470 if (LHSPointer->getPointeeType()->isVoidType()) { 6471 Kind = CK_BitCast; 6472 return Compatible; 6473 } 6474 } 6475 6476 return Incompatible; 6477 } 6478 6479 // Conversions to block pointers. 6480 if (isa<BlockPointerType>(LHSType)) { 6481 // U^ -> T^ 6482 if (RHSType->isBlockPointerType()) { 6483 Kind = CK_BitCast; 6484 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 6485 } 6486 6487 // int or null -> T^ 6488 if (RHSType->isIntegerType()) { 6489 Kind = CK_IntegralToPointer; // FIXME: null 6490 return IntToBlockPointer; 6491 } 6492 6493 // id -> T^ 6494 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 6495 Kind = CK_AnyPointerToBlockPointerCast; 6496 return Compatible; 6497 } 6498 6499 // void* -> T^ 6500 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 6501 if (RHSPT->getPointeeType()->isVoidType()) { 6502 Kind = CK_AnyPointerToBlockPointerCast; 6503 return Compatible; 6504 } 6505 6506 return Incompatible; 6507 } 6508 6509 // Conversions to Objective-C pointers. 6510 if (isa<ObjCObjectPointerType>(LHSType)) { 6511 // A* -> B* 6512 if (RHSType->isObjCObjectPointerType()) { 6513 Kind = CK_BitCast; 6514 Sema::AssignConvertType result = 6515 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 6516 if (getLangOpts().ObjCAutoRefCount && 6517 result == Compatible && 6518 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 6519 result = IncompatibleObjCWeakRef; 6520 return result; 6521 } 6522 6523 // int or null -> A* 6524 if (RHSType->isIntegerType()) { 6525 Kind = CK_IntegralToPointer; // FIXME: null 6526 return IntToPointer; 6527 } 6528 6529 // In general, C pointers are not compatible with ObjC object pointers, 6530 // with two exceptions: 6531 if (isa<PointerType>(RHSType)) { 6532 Kind = CK_CPointerToObjCPointerCast; 6533 6534 // - conversions from 'void*' 6535 if (RHSType->isVoidPointerType()) { 6536 return Compatible; 6537 } 6538 6539 // - conversions to 'Class' from its redefinition type 6540 if (LHSType->isObjCClassType() && 6541 Context.hasSameType(RHSType, 6542 Context.getObjCClassRedefinitionType())) { 6543 return Compatible; 6544 } 6545 6546 return IncompatiblePointer; 6547 } 6548 6549 // Only under strict condition T^ is compatible with an Objective-C pointer. 6550 if (RHSType->isBlockPointerType() && 6551 isObjCPtrBlockCompatible(*this, Context, LHSType)) { 6552 maybeExtendBlockObject(*this, RHS); 6553 Kind = CK_BlockPointerToObjCPointerCast; 6554 return Compatible; 6555 } 6556 6557 return Incompatible; 6558 } 6559 6560 // Conversions from pointers that are not covered by the above. 6561 if (isa<PointerType>(RHSType)) { 6562 // T* -> _Bool 6563 if (LHSType == Context.BoolTy) { 6564 Kind = CK_PointerToBoolean; 6565 return Compatible; 6566 } 6567 6568 // T* -> int 6569 if (LHSType->isIntegerType()) { 6570 Kind = CK_PointerToIntegral; 6571 return PointerToInt; 6572 } 6573 6574 return Incompatible; 6575 } 6576 6577 // Conversions from Objective-C pointers that are not covered by the above. 6578 if (isa<ObjCObjectPointerType>(RHSType)) { 6579 // T* -> _Bool 6580 if (LHSType == Context.BoolTy) { 6581 Kind = CK_PointerToBoolean; 6582 return Compatible; 6583 } 6584 6585 // T* -> int 6586 if (LHSType->isIntegerType()) { 6587 Kind = CK_PointerToIntegral; 6588 return PointerToInt; 6589 } 6590 6591 return Incompatible; 6592 } 6593 6594 // struct A -> struct B 6595 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 6596 if (Context.typesAreCompatible(LHSType, RHSType)) { 6597 Kind = CK_NoOp; 6598 return Compatible; 6599 } 6600 } 6601 6602 return Incompatible; 6603 } 6604 6605 /// \brief Constructs a transparent union from an expression that is 6606 /// used to initialize the transparent union. 6607 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 6608 ExprResult &EResult, QualType UnionType, 6609 FieldDecl *Field) { 6610 // Build an initializer list that designates the appropriate member 6611 // of the transparent union. 6612 Expr *E = EResult.get(); 6613 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 6614 E, SourceLocation()); 6615 Initializer->setType(UnionType); 6616 Initializer->setInitializedFieldInUnion(Field); 6617 6618 // Build a compound literal constructing a value of the transparent 6619 // union type from this initializer list. 6620 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 6621 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 6622 VK_RValue, Initializer, false); 6623 } 6624 6625 Sema::AssignConvertType 6626 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 6627 ExprResult &RHS) { 6628 QualType RHSType = RHS.get()->getType(); 6629 6630 // If the ArgType is a Union type, we want to handle a potential 6631 // transparent_union GCC extension. 6632 const RecordType *UT = ArgType->getAsUnionType(); 6633 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 6634 return Incompatible; 6635 6636 // The field to initialize within the transparent union. 6637 RecordDecl *UD = UT->getDecl(); 6638 FieldDecl *InitField = nullptr; 6639 // It's compatible if the expression matches any of the fields. 6640 for (auto *it : UD->fields()) { 6641 if (it->getType()->isPointerType()) { 6642 // If the transparent union contains a pointer type, we allow: 6643 // 1) void pointer 6644 // 2) null pointer constant 6645 if (RHSType->isPointerType()) 6646 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 6647 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 6648 InitField = it; 6649 break; 6650 } 6651 6652 if (RHS.get()->isNullPointerConstant(Context, 6653 Expr::NPC_ValueDependentIsNull)) { 6654 RHS = ImpCastExprToType(RHS.get(), it->getType(), 6655 CK_NullToPointer); 6656 InitField = it; 6657 break; 6658 } 6659 } 6660 6661 CastKind Kind = CK_Invalid; 6662 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 6663 == Compatible) { 6664 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 6665 InitField = it; 6666 break; 6667 } 6668 } 6669 6670 if (!InitField) 6671 return Incompatible; 6672 6673 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 6674 return Compatible; 6675 } 6676 6677 Sema::AssignConvertType 6678 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6679 bool Diagnose, 6680 bool DiagnoseCFAudited) { 6681 if (getLangOpts().CPlusPlus) { 6682 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 6683 // C++ 5.17p3: If the left operand is not of class type, the 6684 // expression is implicitly converted (C++ 4) to the 6685 // cv-unqualified type of the left operand. 6686 ExprResult Res; 6687 if (Diagnose) { 6688 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6689 AA_Assigning); 6690 } else { 6691 ImplicitConversionSequence ICS = 6692 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6693 /*SuppressUserConversions=*/false, 6694 /*AllowExplicit=*/false, 6695 /*InOverloadResolution=*/false, 6696 /*CStyle=*/false, 6697 /*AllowObjCWritebackConversion=*/false); 6698 if (ICS.isFailure()) 6699 return Incompatible; 6700 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 6701 ICS, AA_Assigning); 6702 } 6703 if (Res.isInvalid()) 6704 return Incompatible; 6705 Sema::AssignConvertType result = Compatible; 6706 if (getLangOpts().ObjCAutoRefCount && 6707 !CheckObjCARCUnavailableWeakConversion(LHSType, 6708 RHS.get()->getType())) 6709 result = IncompatibleObjCWeakRef; 6710 RHS = Res; 6711 return result; 6712 } 6713 6714 // FIXME: Currently, we fall through and treat C++ classes like C 6715 // structures. 6716 // FIXME: We also fall through for atomics; not sure what should 6717 // happen there, though. 6718 } 6719 6720 // C99 6.5.16.1p1: the left operand is a pointer and the right is 6721 // a null pointer constant. 6722 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 6723 LHSType->isBlockPointerType()) && 6724 RHS.get()->isNullPointerConstant(Context, 6725 Expr::NPC_ValueDependentIsNull)) { 6726 CastKind Kind; 6727 CXXCastPath Path; 6728 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false); 6729 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 6730 return Compatible; 6731 } 6732 6733 // This check seems unnatural, however it is necessary to ensure the proper 6734 // conversion of functions/arrays. If the conversion were done for all 6735 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 6736 // expressions that suppress this implicit conversion (&, sizeof). 6737 // 6738 // Suppress this for references: C++ 8.5.3p5. 6739 if (!LHSType->isReferenceType()) { 6740 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 6741 if (RHS.isInvalid()) 6742 return Incompatible; 6743 } 6744 6745 Expr *PRE = RHS.get()->IgnoreParenCasts(); 6746 if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) { 6747 ObjCProtocolDecl *PDecl = OPE->getProtocol(); 6748 if (PDecl && !PDecl->hasDefinition()) { 6749 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 6750 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 6751 } 6752 } 6753 6754 CastKind Kind = CK_Invalid; 6755 Sema::AssignConvertType result = 6756 CheckAssignmentConstraints(LHSType, RHS, Kind); 6757 6758 // C99 6.5.16.1p2: The value of the right operand is converted to the 6759 // type of the assignment expression. 6760 // CheckAssignmentConstraints allows the left-hand side to be a reference, 6761 // so that we can use references in built-in functions even in C. 6762 // The getNonReferenceType() call makes sure that the resulting expression 6763 // does not have reference type. 6764 if (result != Incompatible && RHS.get()->getType() != LHSType) { 6765 QualType Ty = LHSType.getNonLValueExprType(Context); 6766 Expr *E = RHS.get(); 6767 if (getLangOpts().ObjCAutoRefCount) 6768 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 6769 DiagnoseCFAudited); 6770 if (getLangOpts().ObjC1 && 6771 (CheckObjCBridgeRelatedConversions(E->getLocStart(), 6772 LHSType, E->getType(), E) || 6773 ConversionToObjCStringLiteralCheck(LHSType, E))) { 6774 RHS = E; 6775 return Compatible; 6776 } 6777 6778 RHS = ImpCastExprToType(E, Ty, Kind); 6779 } 6780 return result; 6781 } 6782 6783 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 6784 ExprResult &RHS) { 6785 Diag(Loc, diag::err_typecheck_invalid_operands) 6786 << LHS.get()->getType() << RHS.get()->getType() 6787 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6788 return QualType(); 6789 } 6790 6791 /// Try to convert a value of non-vector type to a vector type by converting 6792 /// the type to the element type of the vector and then performing a splat. 6793 /// If the language is OpenCL, we only use conversions that promote scalar 6794 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 6795 /// for float->int. 6796 /// 6797 /// \param scalar - if non-null, actually perform the conversions 6798 /// \return true if the operation fails (but without diagnosing the failure) 6799 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 6800 QualType scalarTy, 6801 QualType vectorEltTy, 6802 QualType vectorTy) { 6803 // The conversion to apply to the scalar before splatting it, 6804 // if necessary. 6805 CastKind scalarCast = CK_Invalid; 6806 6807 if (vectorEltTy->isIntegralType(S.Context)) { 6808 if (!scalarTy->isIntegralType(S.Context)) 6809 return true; 6810 if (S.getLangOpts().OpenCL && 6811 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 6812 return true; 6813 scalarCast = CK_IntegralCast; 6814 } else if (vectorEltTy->isRealFloatingType()) { 6815 if (scalarTy->isRealFloatingType()) { 6816 if (S.getLangOpts().OpenCL && 6817 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 6818 return true; 6819 scalarCast = CK_FloatingCast; 6820 } 6821 else if (scalarTy->isIntegralType(S.Context)) 6822 scalarCast = CK_IntegralToFloating; 6823 else 6824 return true; 6825 } else { 6826 return true; 6827 } 6828 6829 // Adjust scalar if desired. 6830 if (scalar) { 6831 if (scalarCast != CK_Invalid) 6832 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 6833 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 6834 } 6835 return false; 6836 } 6837 6838 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 6839 SourceLocation Loc, bool IsCompAssign) { 6840 if (!IsCompAssign) { 6841 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 6842 if (LHS.isInvalid()) 6843 return QualType(); 6844 } 6845 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 6846 if (RHS.isInvalid()) 6847 return QualType(); 6848 6849 // For conversion purposes, we ignore any qualifiers. 6850 // For example, "const float" and "float" are equivalent. 6851 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 6852 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 6853 6854 // If the vector types are identical, return. 6855 if (Context.hasSameType(LHSType, RHSType)) 6856 return LHSType; 6857 6858 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 6859 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 6860 assert(LHSVecType || RHSVecType); 6861 6862 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 6863 if (LHSVecType && RHSVecType && 6864 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 6865 if (isa<ExtVectorType>(LHSVecType)) { 6866 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 6867 return LHSType; 6868 } 6869 6870 if (!IsCompAssign) 6871 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 6872 return RHSType; 6873 } 6874 6875 // If there's an ext-vector type and a scalar, try to convert the scalar to 6876 // the vector element type and splat. 6877 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 6878 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 6879 LHSVecType->getElementType(), LHSType)) 6880 return LHSType; 6881 } 6882 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 6883 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 6884 LHSType, RHSVecType->getElementType(), 6885 RHSType)) 6886 return RHSType; 6887 } 6888 6889 // If we're allowing lax vector conversions, only the total (data) size 6890 // needs to be the same. 6891 // FIXME: Should we really be allowing this? 6892 // FIXME: We really just pick the LHS type arbitrarily? 6893 if (isLaxVectorConversion(RHSType, LHSType)) { 6894 QualType resultType = LHSType; 6895 RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast); 6896 return resultType; 6897 } 6898 6899 // Okay, the expression is invalid. 6900 6901 // If there's a non-vector, non-real operand, diagnose that. 6902 if ((!RHSVecType && !RHSType->isRealType()) || 6903 (!LHSVecType && !LHSType->isRealType())) { 6904 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 6905 << LHSType << RHSType 6906 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6907 return QualType(); 6908 } 6909 6910 // Otherwise, use the generic diagnostic. 6911 Diag(Loc, diag::err_typecheck_vector_not_convertable) 6912 << LHSType << RHSType 6913 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6914 return QualType(); 6915 } 6916 6917 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 6918 // expression. These are mainly cases where the null pointer is used as an 6919 // integer instead of a pointer. 6920 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 6921 SourceLocation Loc, bool IsCompare) { 6922 // The canonical way to check for a GNU null is with isNullPointerConstant, 6923 // but we use a bit of a hack here for speed; this is a relatively 6924 // hot path, and isNullPointerConstant is slow. 6925 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 6926 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 6927 6928 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 6929 6930 // Avoid analyzing cases where the result will either be invalid (and 6931 // diagnosed as such) or entirely valid and not something to warn about. 6932 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 6933 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 6934 return; 6935 6936 // Comparison operations would not make sense with a null pointer no matter 6937 // what the other expression is. 6938 if (!IsCompare) { 6939 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 6940 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 6941 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 6942 return; 6943 } 6944 6945 // The rest of the operations only make sense with a null pointer 6946 // if the other expression is a pointer. 6947 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 6948 NonNullType->canDecayToPointerType()) 6949 return; 6950 6951 S.Diag(Loc, diag::warn_null_in_comparison_operation) 6952 << LHSNull /* LHS is NULL */ << NonNullType 6953 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6954 } 6955 6956 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 6957 SourceLocation Loc, 6958 bool IsCompAssign, bool IsDiv) { 6959 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6960 6961 if (LHS.get()->getType()->isVectorType() || 6962 RHS.get()->getType()->isVectorType()) 6963 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6964 6965 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6966 if (LHS.isInvalid() || RHS.isInvalid()) 6967 return QualType(); 6968 6969 6970 if (compType.isNull() || !compType->isArithmeticType()) 6971 return InvalidOperands(Loc, LHS, RHS); 6972 6973 // Check for division by zero. 6974 llvm::APSInt RHSValue; 6975 if (IsDiv && !RHS.get()->isValueDependent() && 6976 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 6977 DiagRuntimeBehavior(Loc, RHS.get(), 6978 PDiag(diag::warn_division_by_zero) 6979 << RHS.get()->getSourceRange()); 6980 6981 return compType; 6982 } 6983 6984 QualType Sema::CheckRemainderOperands( 6985 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 6986 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 6987 6988 if (LHS.get()->getType()->isVectorType() || 6989 RHS.get()->getType()->isVectorType()) { 6990 if (LHS.get()->getType()->hasIntegerRepresentation() && 6991 RHS.get()->getType()->hasIntegerRepresentation()) 6992 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 6993 return InvalidOperands(Loc, LHS, RHS); 6994 } 6995 6996 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 6997 if (LHS.isInvalid() || RHS.isInvalid()) 6998 return QualType(); 6999 7000 if (compType.isNull() || !compType->isIntegerType()) 7001 return InvalidOperands(Loc, LHS, RHS); 7002 7003 // Check for remainder by zero. 7004 llvm::APSInt RHSValue; 7005 if (!RHS.get()->isValueDependent() && 7006 RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0) 7007 DiagRuntimeBehavior(Loc, RHS.get(), 7008 PDiag(diag::warn_remainder_by_zero) 7009 << RHS.get()->getSourceRange()); 7010 7011 return compType; 7012 } 7013 7014 /// \brief Diagnose invalid arithmetic on two void pointers. 7015 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 7016 Expr *LHSExpr, Expr *RHSExpr) { 7017 S.Diag(Loc, S.getLangOpts().CPlusPlus 7018 ? diag::err_typecheck_pointer_arith_void_type 7019 : diag::ext_gnu_void_ptr) 7020 << 1 /* two pointers */ << LHSExpr->getSourceRange() 7021 << RHSExpr->getSourceRange(); 7022 } 7023 7024 /// \brief Diagnose invalid arithmetic on a void pointer. 7025 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 7026 Expr *Pointer) { 7027 S.Diag(Loc, S.getLangOpts().CPlusPlus 7028 ? diag::err_typecheck_pointer_arith_void_type 7029 : diag::ext_gnu_void_ptr) 7030 << 0 /* one pointer */ << Pointer->getSourceRange(); 7031 } 7032 7033 /// \brief Diagnose invalid arithmetic on two function pointers. 7034 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 7035 Expr *LHS, Expr *RHS) { 7036 assert(LHS->getType()->isAnyPointerType()); 7037 assert(RHS->getType()->isAnyPointerType()); 7038 S.Diag(Loc, S.getLangOpts().CPlusPlus 7039 ? diag::err_typecheck_pointer_arith_function_type 7040 : diag::ext_gnu_ptr_func_arith) 7041 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 7042 // We only show the second type if it differs from the first. 7043 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 7044 RHS->getType()) 7045 << RHS->getType()->getPointeeType() 7046 << LHS->getSourceRange() << RHS->getSourceRange(); 7047 } 7048 7049 /// \brief Diagnose invalid arithmetic on a function pointer. 7050 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 7051 Expr *Pointer) { 7052 assert(Pointer->getType()->isAnyPointerType()); 7053 S.Diag(Loc, S.getLangOpts().CPlusPlus 7054 ? diag::err_typecheck_pointer_arith_function_type 7055 : diag::ext_gnu_ptr_func_arith) 7056 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 7057 << 0 /* one pointer, so only one type */ 7058 << Pointer->getSourceRange(); 7059 } 7060 7061 /// \brief Emit error if Operand is incomplete pointer type 7062 /// 7063 /// \returns True if pointer has incomplete type 7064 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 7065 Expr *Operand) { 7066 assert(Operand->getType()->isAnyPointerType() && 7067 !Operand->getType()->isDependentType()); 7068 QualType PointeeTy = Operand->getType()->getPointeeType(); 7069 return S.RequireCompleteType(Loc, PointeeTy, 7070 diag::err_typecheck_arithmetic_incomplete_type, 7071 PointeeTy, Operand->getSourceRange()); 7072 } 7073 7074 /// \brief Check the validity of an arithmetic pointer operand. 7075 /// 7076 /// If the operand has pointer type, this code will check for pointer types 7077 /// which are invalid in arithmetic operations. These will be diagnosed 7078 /// appropriately, including whether or not the use is supported as an 7079 /// extension. 7080 /// 7081 /// \returns True when the operand is valid to use (even if as an extension). 7082 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 7083 Expr *Operand) { 7084 if (!Operand->getType()->isAnyPointerType()) return true; 7085 7086 QualType PointeeTy = Operand->getType()->getPointeeType(); 7087 if (PointeeTy->isVoidType()) { 7088 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 7089 return !S.getLangOpts().CPlusPlus; 7090 } 7091 if (PointeeTy->isFunctionType()) { 7092 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 7093 return !S.getLangOpts().CPlusPlus; 7094 } 7095 7096 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 7097 7098 return true; 7099 } 7100 7101 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 7102 /// operands. 7103 /// 7104 /// This routine will diagnose any invalid arithmetic on pointer operands much 7105 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 7106 /// for emitting a single diagnostic even for operations where both LHS and RHS 7107 /// are (potentially problematic) pointers. 7108 /// 7109 /// \returns True when the operand is valid to use (even if as an extension). 7110 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 7111 Expr *LHSExpr, Expr *RHSExpr) { 7112 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 7113 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 7114 if (!isLHSPointer && !isRHSPointer) return true; 7115 7116 QualType LHSPointeeTy, RHSPointeeTy; 7117 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 7118 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 7119 7120 // Check for arithmetic on pointers to incomplete types. 7121 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 7122 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 7123 if (isLHSVoidPtr || isRHSVoidPtr) { 7124 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 7125 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 7126 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 7127 7128 return !S.getLangOpts().CPlusPlus; 7129 } 7130 7131 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 7132 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 7133 if (isLHSFuncPtr || isRHSFuncPtr) { 7134 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 7135 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 7136 RHSExpr); 7137 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 7138 7139 return !S.getLangOpts().CPlusPlus; 7140 } 7141 7142 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 7143 return false; 7144 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 7145 return false; 7146 7147 return true; 7148 } 7149 7150 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 7151 /// literal. 7152 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 7153 Expr *LHSExpr, Expr *RHSExpr) { 7154 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 7155 Expr* IndexExpr = RHSExpr; 7156 if (!StrExpr) { 7157 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 7158 IndexExpr = LHSExpr; 7159 } 7160 7161 bool IsStringPlusInt = StrExpr && 7162 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 7163 if (!IsStringPlusInt) 7164 return; 7165 7166 llvm::APSInt index; 7167 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 7168 unsigned StrLenWithNull = StrExpr->getLength() + 1; 7169 if (index.isNonNegative() && 7170 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 7171 index.isUnsigned())) 7172 return; 7173 } 7174 7175 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7176 Self.Diag(OpLoc, diag::warn_string_plus_int) 7177 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 7178 7179 // Only print a fixit for "str" + int, not for int + "str". 7180 if (IndexExpr == RHSExpr) { 7181 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7182 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7183 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7184 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7185 << FixItHint::CreateInsertion(EndLoc, "]"); 7186 } else 7187 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7188 } 7189 7190 /// \brief Emit a warning when adding a char literal to a string. 7191 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 7192 Expr *LHSExpr, Expr *RHSExpr) { 7193 const DeclRefExpr *StringRefExpr = 7194 dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts()); 7195 const CharacterLiteral *CharExpr = 7196 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 7197 if (!StringRefExpr) { 7198 StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts()); 7199 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 7200 } 7201 7202 if (!CharExpr || !StringRefExpr) 7203 return; 7204 7205 const QualType StringType = StringRefExpr->getType(); 7206 7207 // Return if not a PointerType. 7208 if (!StringType->isAnyPointerType()) 7209 return; 7210 7211 // Return if not a CharacterType. 7212 if (!StringType->getPointeeType()->isAnyCharacterType()) 7213 return; 7214 7215 ASTContext &Ctx = Self.getASTContext(); 7216 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7217 7218 const QualType CharType = CharExpr->getType(); 7219 if (!CharType->isAnyCharacterType() && 7220 CharType->isIntegerType() && 7221 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 7222 Self.Diag(OpLoc, diag::warn_string_plus_char) 7223 << DiagRange << Ctx.CharTy; 7224 } else { 7225 Self.Diag(OpLoc, diag::warn_string_plus_char) 7226 << DiagRange << CharExpr->getType(); 7227 } 7228 7229 // Only print a fixit for str + char, not for char + str. 7230 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 7231 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7232 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7233 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7234 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7235 << FixItHint::CreateInsertion(EndLoc, "]"); 7236 } else { 7237 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7238 } 7239 } 7240 7241 /// \brief Emit error when two pointers are incompatible. 7242 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 7243 Expr *LHSExpr, Expr *RHSExpr) { 7244 assert(LHSExpr->getType()->isAnyPointerType()); 7245 assert(RHSExpr->getType()->isAnyPointerType()); 7246 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 7247 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 7248 << RHSExpr->getSourceRange(); 7249 } 7250 7251 QualType Sema::CheckAdditionOperands( // C99 6.5.6 7252 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 7253 QualType* CompLHSTy) { 7254 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7255 7256 if (LHS.get()->getType()->isVectorType() || 7257 RHS.get()->getType()->isVectorType()) { 7258 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 7259 if (CompLHSTy) *CompLHSTy = compType; 7260 return compType; 7261 } 7262 7263 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7264 if (LHS.isInvalid() || RHS.isInvalid()) 7265 return QualType(); 7266 7267 // Diagnose "string literal" '+' int and string '+' "char literal". 7268 if (Opc == BO_Add) { 7269 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 7270 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 7271 } 7272 7273 // handle the common case first (both operands are arithmetic). 7274 if (!compType.isNull() && compType->isArithmeticType()) { 7275 if (CompLHSTy) *CompLHSTy = compType; 7276 return compType; 7277 } 7278 7279 // Type-checking. Ultimately the pointer's going to be in PExp; 7280 // note that we bias towards the LHS being the pointer. 7281 Expr *PExp = LHS.get(), *IExp = RHS.get(); 7282 7283 bool isObjCPointer; 7284 if (PExp->getType()->isPointerType()) { 7285 isObjCPointer = false; 7286 } else if (PExp->getType()->isObjCObjectPointerType()) { 7287 isObjCPointer = true; 7288 } else { 7289 std::swap(PExp, IExp); 7290 if (PExp->getType()->isPointerType()) { 7291 isObjCPointer = false; 7292 } else if (PExp->getType()->isObjCObjectPointerType()) { 7293 isObjCPointer = true; 7294 } else { 7295 return InvalidOperands(Loc, LHS, RHS); 7296 } 7297 } 7298 assert(PExp->getType()->isAnyPointerType()); 7299 7300 if (!IExp->getType()->isIntegerType()) 7301 return InvalidOperands(Loc, LHS, RHS); 7302 7303 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 7304 return QualType(); 7305 7306 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 7307 return QualType(); 7308 7309 // Check array bounds for pointer arithemtic 7310 CheckArrayAccess(PExp, IExp); 7311 7312 if (CompLHSTy) { 7313 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 7314 if (LHSTy.isNull()) { 7315 LHSTy = LHS.get()->getType(); 7316 if (LHSTy->isPromotableIntegerType()) 7317 LHSTy = Context.getPromotedIntegerType(LHSTy); 7318 } 7319 *CompLHSTy = LHSTy; 7320 } 7321 7322 return PExp->getType(); 7323 } 7324 7325 // C99 6.5.6 7326 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 7327 SourceLocation Loc, 7328 QualType* CompLHSTy) { 7329 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7330 7331 if (LHS.get()->getType()->isVectorType() || 7332 RHS.get()->getType()->isVectorType()) { 7333 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy); 7334 if (CompLHSTy) *CompLHSTy = compType; 7335 return compType; 7336 } 7337 7338 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7339 if (LHS.isInvalid() || RHS.isInvalid()) 7340 return QualType(); 7341 7342 // Enforce type constraints: C99 6.5.6p3. 7343 7344 // Handle the common case first (both operands are arithmetic). 7345 if (!compType.isNull() && compType->isArithmeticType()) { 7346 if (CompLHSTy) *CompLHSTy = compType; 7347 return compType; 7348 } 7349 7350 // Either ptr - int or ptr - ptr. 7351 if (LHS.get()->getType()->isAnyPointerType()) { 7352 QualType lpointee = LHS.get()->getType()->getPointeeType(); 7353 7354 // Diagnose bad cases where we step over interface counts. 7355 if (LHS.get()->getType()->isObjCObjectPointerType() && 7356 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 7357 return QualType(); 7358 7359 // The result type of a pointer-int computation is the pointer type. 7360 if (RHS.get()->getType()->isIntegerType()) { 7361 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 7362 return QualType(); 7363 7364 // Check array bounds for pointer arithemtic 7365 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 7366 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 7367 7368 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7369 return LHS.get()->getType(); 7370 } 7371 7372 // Handle pointer-pointer subtractions. 7373 if (const PointerType *RHSPTy 7374 = RHS.get()->getType()->getAs<PointerType>()) { 7375 QualType rpointee = RHSPTy->getPointeeType(); 7376 7377 if (getLangOpts().CPlusPlus) { 7378 // Pointee types must be the same: C++ [expr.add] 7379 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 7380 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7381 } 7382 } else { 7383 // Pointee types must be compatible C99 6.5.6p3 7384 if (!Context.typesAreCompatible( 7385 Context.getCanonicalType(lpointee).getUnqualifiedType(), 7386 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 7387 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 7388 return QualType(); 7389 } 7390 } 7391 7392 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 7393 LHS.get(), RHS.get())) 7394 return QualType(); 7395 7396 // The pointee type may have zero size. As an extension, a structure or 7397 // union may have zero size or an array may have zero length. In this 7398 // case subtraction does not make sense. 7399 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 7400 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 7401 if (ElementSize.isZero()) { 7402 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 7403 << rpointee.getUnqualifiedType() 7404 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7405 } 7406 } 7407 7408 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 7409 return Context.getPointerDiffType(); 7410 } 7411 } 7412 7413 return InvalidOperands(Loc, LHS, RHS); 7414 } 7415 7416 static bool isScopedEnumerationType(QualType T) { 7417 if (const EnumType *ET = dyn_cast<EnumType>(T)) 7418 return ET->getDecl()->isScoped(); 7419 return false; 7420 } 7421 7422 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 7423 SourceLocation Loc, unsigned Opc, 7424 QualType LHSType) { 7425 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 7426 // so skip remaining warnings as we don't want to modify values within Sema. 7427 if (S.getLangOpts().OpenCL) 7428 return; 7429 7430 llvm::APSInt Right; 7431 // Check right/shifter operand 7432 if (RHS.get()->isValueDependent() || 7433 !RHS.get()->isIntegerConstantExpr(Right, S.Context)) 7434 return; 7435 7436 if (Right.isNegative()) { 7437 S.DiagRuntimeBehavior(Loc, RHS.get(), 7438 S.PDiag(diag::warn_shift_negative) 7439 << RHS.get()->getSourceRange()); 7440 return; 7441 } 7442 llvm::APInt LeftBits(Right.getBitWidth(), 7443 S.Context.getTypeSize(LHS.get()->getType())); 7444 if (Right.uge(LeftBits)) { 7445 S.DiagRuntimeBehavior(Loc, RHS.get(), 7446 S.PDiag(diag::warn_shift_gt_typewidth) 7447 << RHS.get()->getSourceRange()); 7448 return; 7449 } 7450 if (Opc != BO_Shl) 7451 return; 7452 7453 // When left shifting an ICE which is signed, we can check for overflow which 7454 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 7455 // integers have defined behavior modulo one more than the maximum value 7456 // representable in the result type, so never warn for those. 7457 llvm::APSInt Left; 7458 if (LHS.get()->isValueDependent() || 7459 !LHS.get()->isIntegerConstantExpr(Left, S.Context) || 7460 LHSType->hasUnsignedIntegerRepresentation()) 7461 return; 7462 llvm::APInt ResultBits = 7463 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 7464 if (LeftBits.uge(ResultBits)) 7465 return; 7466 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 7467 Result = Result.shl(Right); 7468 7469 // Print the bit representation of the signed integer as an unsigned 7470 // hexadecimal number. 7471 SmallString<40> HexResult; 7472 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 7473 7474 // If we are only missing a sign bit, this is less likely to result in actual 7475 // bugs -- if the result is cast back to an unsigned type, it will have the 7476 // expected value. Thus we place this behind a different warning that can be 7477 // turned off separately if needed. 7478 if (LeftBits == ResultBits - 1) { 7479 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 7480 << HexResult.str() << LHSType 7481 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7482 return; 7483 } 7484 7485 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 7486 << HexResult.str() << Result.getMinSignedBits() << LHSType 7487 << Left.getBitWidth() << LHS.get()->getSourceRange() 7488 << RHS.get()->getSourceRange(); 7489 } 7490 7491 // C99 6.5.7 7492 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 7493 SourceLocation Loc, unsigned Opc, 7494 bool IsCompAssign) { 7495 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7496 7497 // Vector shifts promote their scalar inputs to vector type. 7498 if (LHS.get()->getType()->isVectorType() || 7499 RHS.get()->getType()->isVectorType()) 7500 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 7501 7502 // Shifts don't perform usual arithmetic conversions, they just do integer 7503 // promotions on each operand. C99 6.5.7p3 7504 7505 // For the LHS, do usual unary conversions, but then reset them away 7506 // if this is a compound assignment. 7507 ExprResult OldLHS = LHS; 7508 LHS = UsualUnaryConversions(LHS.get()); 7509 if (LHS.isInvalid()) 7510 return QualType(); 7511 QualType LHSType = LHS.get()->getType(); 7512 if (IsCompAssign) LHS = OldLHS; 7513 7514 // The RHS is simpler. 7515 RHS = UsualUnaryConversions(RHS.get()); 7516 if (RHS.isInvalid()) 7517 return QualType(); 7518 QualType RHSType = RHS.get()->getType(); 7519 7520 // C99 6.5.7p2: Each of the operands shall have integer type. 7521 if (!LHSType->hasIntegerRepresentation() || 7522 !RHSType->hasIntegerRepresentation()) 7523 return InvalidOperands(Loc, LHS, RHS); 7524 7525 // C++0x: Don't allow scoped enums. FIXME: Use something better than 7526 // hasIntegerRepresentation() above instead of this. 7527 if (isScopedEnumerationType(LHSType) || 7528 isScopedEnumerationType(RHSType)) { 7529 return InvalidOperands(Loc, LHS, RHS); 7530 } 7531 // Sanity-check shift operands 7532 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 7533 7534 // "The type of the result is that of the promoted left operand." 7535 return LHSType; 7536 } 7537 7538 static bool IsWithinTemplateSpecialization(Decl *D) { 7539 if (DeclContext *DC = D->getDeclContext()) { 7540 if (isa<ClassTemplateSpecializationDecl>(DC)) 7541 return true; 7542 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 7543 return FD->isFunctionTemplateSpecialization(); 7544 } 7545 return false; 7546 } 7547 7548 /// If two different enums are compared, raise a warning. 7549 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 7550 Expr *RHS) { 7551 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 7552 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 7553 7554 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 7555 if (!LHSEnumType) 7556 return; 7557 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 7558 if (!RHSEnumType) 7559 return; 7560 7561 // Ignore anonymous enums. 7562 if (!LHSEnumType->getDecl()->getIdentifier()) 7563 return; 7564 if (!RHSEnumType->getDecl()->getIdentifier()) 7565 return; 7566 7567 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 7568 return; 7569 7570 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 7571 << LHSStrippedType << RHSStrippedType 7572 << LHS->getSourceRange() << RHS->getSourceRange(); 7573 } 7574 7575 /// \brief Diagnose bad pointer comparisons. 7576 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 7577 ExprResult &LHS, ExprResult &RHS, 7578 bool IsError) { 7579 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 7580 : diag::ext_typecheck_comparison_of_distinct_pointers) 7581 << LHS.get()->getType() << RHS.get()->getType() 7582 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7583 } 7584 7585 /// \brief Returns false if the pointers are converted to a composite type, 7586 /// true otherwise. 7587 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 7588 ExprResult &LHS, ExprResult &RHS) { 7589 // C++ [expr.rel]p2: 7590 // [...] Pointer conversions (4.10) and qualification 7591 // conversions (4.4) are performed on pointer operands (or on 7592 // a pointer operand and a null pointer constant) to bring 7593 // them to their composite pointer type. [...] 7594 // 7595 // C++ [expr.eq]p1 uses the same notion for (in)equality 7596 // comparisons of pointers. 7597 7598 // C++ [expr.eq]p2: 7599 // In addition, pointers to members can be compared, or a pointer to 7600 // member and a null pointer constant. Pointer to member conversions 7601 // (4.11) and qualification conversions (4.4) are performed to bring 7602 // them to a common type. If one operand is a null pointer constant, 7603 // the common type is the type of the other operand. Otherwise, the 7604 // common type is a pointer to member type similar (4.4) to the type 7605 // of one of the operands, with a cv-qualification signature (4.4) 7606 // that is the union of the cv-qualification signatures of the operand 7607 // types. 7608 7609 QualType LHSType = LHS.get()->getType(); 7610 QualType RHSType = RHS.get()->getType(); 7611 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 7612 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 7613 7614 bool NonStandardCompositeType = false; 7615 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType; 7616 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 7617 if (T.isNull()) { 7618 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 7619 return true; 7620 } 7621 7622 if (NonStandardCompositeType) 7623 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 7624 << LHSType << RHSType << T << LHS.get()->getSourceRange() 7625 << RHS.get()->getSourceRange(); 7626 7627 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 7628 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 7629 return false; 7630 } 7631 7632 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 7633 ExprResult &LHS, 7634 ExprResult &RHS, 7635 bool IsError) { 7636 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 7637 : diag::ext_typecheck_comparison_of_fptr_to_void) 7638 << LHS.get()->getType() << RHS.get()->getType() 7639 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7640 } 7641 7642 static bool isObjCObjectLiteral(ExprResult &E) { 7643 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 7644 case Stmt::ObjCArrayLiteralClass: 7645 case Stmt::ObjCDictionaryLiteralClass: 7646 case Stmt::ObjCStringLiteralClass: 7647 case Stmt::ObjCBoxedExprClass: 7648 return true; 7649 default: 7650 // Note that ObjCBoolLiteral is NOT an object literal! 7651 return false; 7652 } 7653 } 7654 7655 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 7656 const ObjCObjectPointerType *Type = 7657 LHS->getType()->getAs<ObjCObjectPointerType>(); 7658 7659 // If this is not actually an Objective-C object, bail out. 7660 if (!Type) 7661 return false; 7662 7663 // Get the LHS object's interface type. 7664 QualType InterfaceType = Type->getPointeeType(); 7665 if (const ObjCObjectType *iQFaceTy = 7666 InterfaceType->getAsObjCQualifiedInterfaceType()) 7667 InterfaceType = iQFaceTy->getBaseType(); 7668 7669 // If the RHS isn't an Objective-C object, bail out. 7670 if (!RHS->getType()->isObjCObjectPointerType()) 7671 return false; 7672 7673 // Try to find the -isEqual: method. 7674 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 7675 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 7676 InterfaceType, 7677 /*instance=*/true); 7678 if (!Method) { 7679 if (Type->isObjCIdType()) { 7680 // For 'id', just check the global pool. 7681 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 7682 /*receiverId=*/true, 7683 /*warn=*/false); 7684 } else { 7685 // Check protocols. 7686 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 7687 /*instance=*/true); 7688 } 7689 } 7690 7691 if (!Method) 7692 return false; 7693 7694 QualType T = Method->parameters()[0]->getType(); 7695 if (!T->isObjCObjectPointerType()) 7696 return false; 7697 7698 QualType R = Method->getReturnType(); 7699 if (!R->isScalarType()) 7700 return false; 7701 7702 return true; 7703 } 7704 7705 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 7706 FromE = FromE->IgnoreParenImpCasts(); 7707 switch (FromE->getStmtClass()) { 7708 default: 7709 break; 7710 case Stmt::ObjCStringLiteralClass: 7711 // "string literal" 7712 return LK_String; 7713 case Stmt::ObjCArrayLiteralClass: 7714 // "array literal" 7715 return LK_Array; 7716 case Stmt::ObjCDictionaryLiteralClass: 7717 // "dictionary literal" 7718 return LK_Dictionary; 7719 case Stmt::BlockExprClass: 7720 return LK_Block; 7721 case Stmt::ObjCBoxedExprClass: { 7722 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 7723 switch (Inner->getStmtClass()) { 7724 case Stmt::IntegerLiteralClass: 7725 case Stmt::FloatingLiteralClass: 7726 case Stmt::CharacterLiteralClass: 7727 case Stmt::ObjCBoolLiteralExprClass: 7728 case Stmt::CXXBoolLiteralExprClass: 7729 // "numeric literal" 7730 return LK_Numeric; 7731 case Stmt::ImplicitCastExprClass: { 7732 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 7733 // Boolean literals can be represented by implicit casts. 7734 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 7735 return LK_Numeric; 7736 break; 7737 } 7738 default: 7739 break; 7740 } 7741 return LK_Boxed; 7742 } 7743 } 7744 return LK_None; 7745 } 7746 7747 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 7748 ExprResult &LHS, ExprResult &RHS, 7749 BinaryOperator::Opcode Opc){ 7750 Expr *Literal; 7751 Expr *Other; 7752 if (isObjCObjectLiteral(LHS)) { 7753 Literal = LHS.get(); 7754 Other = RHS.get(); 7755 } else { 7756 Literal = RHS.get(); 7757 Other = LHS.get(); 7758 } 7759 7760 // Don't warn on comparisons against nil. 7761 Other = Other->IgnoreParenCasts(); 7762 if (Other->isNullPointerConstant(S.getASTContext(), 7763 Expr::NPC_ValueDependentIsNotNull)) 7764 return; 7765 7766 // This should be kept in sync with warn_objc_literal_comparison. 7767 // LK_String should always be after the other literals, since it has its own 7768 // warning flag. 7769 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 7770 assert(LiteralKind != Sema::LK_Block); 7771 if (LiteralKind == Sema::LK_None) { 7772 llvm_unreachable("Unknown Objective-C object literal kind"); 7773 } 7774 7775 if (LiteralKind == Sema::LK_String) 7776 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 7777 << Literal->getSourceRange(); 7778 else 7779 S.Diag(Loc, diag::warn_objc_literal_comparison) 7780 << LiteralKind << Literal->getSourceRange(); 7781 7782 if (BinaryOperator::isEqualityOp(Opc) && 7783 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 7784 SourceLocation Start = LHS.get()->getLocStart(); 7785 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 7786 CharSourceRange OpRange = 7787 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc)); 7788 7789 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 7790 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 7791 << FixItHint::CreateReplacement(OpRange, " isEqual:") 7792 << FixItHint::CreateInsertion(End, "]"); 7793 } 7794 } 7795 7796 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 7797 ExprResult &RHS, 7798 SourceLocation Loc, 7799 unsigned OpaqueOpc) { 7800 // This checking requires bools. 7801 if (!S.getLangOpts().Bool) return; 7802 7803 // Check that left hand side is !something. 7804 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 7805 if (!UO || UO->getOpcode() != UO_LNot) return; 7806 7807 // Only check if the right hand side is non-bool arithmetic type. 7808 if (RHS.get()->getType()->isBooleanType()) return; 7809 7810 // Make sure that the something in !something is not bool. 7811 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 7812 if (SubExpr->getType()->isBooleanType()) return; 7813 7814 // Emit warning. 7815 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 7816 << Loc; 7817 7818 // First note suggest !(x < y) 7819 SourceLocation FirstOpen = SubExpr->getLocStart(); 7820 SourceLocation FirstClose = RHS.get()->getLocEnd(); 7821 FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose); 7822 if (FirstClose.isInvalid()) 7823 FirstOpen = SourceLocation(); 7824 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 7825 << FixItHint::CreateInsertion(FirstOpen, "(") 7826 << FixItHint::CreateInsertion(FirstClose, ")"); 7827 7828 // Second note suggests (!x) < y 7829 SourceLocation SecondOpen = LHS.get()->getLocStart(); 7830 SourceLocation SecondClose = LHS.get()->getLocEnd(); 7831 SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose); 7832 if (SecondClose.isInvalid()) 7833 SecondOpen = SourceLocation(); 7834 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 7835 << FixItHint::CreateInsertion(SecondOpen, "(") 7836 << FixItHint::CreateInsertion(SecondClose, ")"); 7837 } 7838 7839 // Get the decl for a simple expression: a reference to a variable, 7840 // an implicit C++ field reference, or an implicit ObjC ivar reference. 7841 static ValueDecl *getCompareDecl(Expr *E) { 7842 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 7843 return DR->getDecl(); 7844 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 7845 if (Ivar->isFreeIvar()) 7846 return Ivar->getDecl(); 7847 } 7848 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 7849 if (Mem->isImplicitAccess()) 7850 return Mem->getMemberDecl(); 7851 } 7852 return nullptr; 7853 } 7854 7855 // C99 6.5.8, C++ [expr.rel] 7856 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 7857 SourceLocation Loc, unsigned OpaqueOpc, 7858 bool IsRelational) { 7859 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 7860 7861 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 7862 7863 // Handle vector comparisons separately. 7864 if (LHS.get()->getType()->isVectorType() || 7865 RHS.get()->getType()->isVectorType()) 7866 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 7867 7868 QualType LHSType = LHS.get()->getType(); 7869 QualType RHSType = RHS.get()->getType(); 7870 7871 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 7872 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 7873 7874 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 7875 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc); 7876 7877 if (!LHSType->hasFloatingRepresentation() && 7878 !(LHSType->isBlockPointerType() && IsRelational) && 7879 !LHS.get()->getLocStart().isMacroID() && 7880 !RHS.get()->getLocStart().isMacroID() && 7881 ActiveTemplateInstantiations.empty()) { 7882 // For non-floating point types, check for self-comparisons of the form 7883 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 7884 // often indicate logic errors in the program. 7885 // 7886 // NOTE: Don't warn about comparison expressions resulting from macro 7887 // expansion. Also don't warn about comparisons which are only self 7888 // comparisons within a template specialization. The warnings should catch 7889 // obvious cases in the definition of the template anyways. The idea is to 7890 // warn when the typed comparison operator will always evaluate to the same 7891 // result. 7892 ValueDecl *DL = getCompareDecl(LHSStripped); 7893 ValueDecl *DR = getCompareDecl(RHSStripped); 7894 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 7895 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 7896 << 0 // self- 7897 << (Opc == BO_EQ 7898 || Opc == BO_LE 7899 || Opc == BO_GE)); 7900 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 7901 !DL->getType()->isReferenceType() && 7902 !DR->getType()->isReferenceType()) { 7903 // what is it always going to eval to? 7904 char always_evals_to; 7905 switch(Opc) { 7906 case BO_EQ: // e.g. array1 == array2 7907 always_evals_to = 0; // false 7908 break; 7909 case BO_NE: // e.g. array1 != array2 7910 always_evals_to = 1; // true 7911 break; 7912 default: 7913 // best we can say is 'a constant' 7914 always_evals_to = 2; // e.g. array1 <= array2 7915 break; 7916 } 7917 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 7918 << 1 // array 7919 << always_evals_to); 7920 } 7921 7922 if (isa<CastExpr>(LHSStripped)) 7923 LHSStripped = LHSStripped->IgnoreParenCasts(); 7924 if (isa<CastExpr>(RHSStripped)) 7925 RHSStripped = RHSStripped->IgnoreParenCasts(); 7926 7927 // Warn about comparisons against a string constant (unless the other 7928 // operand is null), the user probably wants strcmp. 7929 Expr *literalString = nullptr; 7930 Expr *literalStringStripped = nullptr; 7931 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 7932 !RHSStripped->isNullPointerConstant(Context, 7933 Expr::NPC_ValueDependentIsNull)) { 7934 literalString = LHS.get(); 7935 literalStringStripped = LHSStripped; 7936 } else if ((isa<StringLiteral>(RHSStripped) || 7937 isa<ObjCEncodeExpr>(RHSStripped)) && 7938 !LHSStripped->isNullPointerConstant(Context, 7939 Expr::NPC_ValueDependentIsNull)) { 7940 literalString = RHS.get(); 7941 literalStringStripped = RHSStripped; 7942 } 7943 7944 if (literalString) { 7945 DiagRuntimeBehavior(Loc, nullptr, 7946 PDiag(diag::warn_stringcompare) 7947 << isa<ObjCEncodeExpr>(literalStringStripped) 7948 << literalString->getSourceRange()); 7949 } 7950 } 7951 7952 // C99 6.5.8p3 / C99 6.5.9p4 7953 UsualArithmeticConversions(LHS, RHS); 7954 if (LHS.isInvalid() || RHS.isInvalid()) 7955 return QualType(); 7956 7957 LHSType = LHS.get()->getType(); 7958 RHSType = RHS.get()->getType(); 7959 7960 // The result of comparisons is 'bool' in C++, 'int' in C. 7961 QualType ResultTy = Context.getLogicalOperationType(); 7962 7963 if (IsRelational) { 7964 if (LHSType->isRealType() && RHSType->isRealType()) 7965 return ResultTy; 7966 } else { 7967 // Check for comparisons of floating point operands using != and ==. 7968 if (LHSType->hasFloatingRepresentation()) 7969 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 7970 7971 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 7972 return ResultTy; 7973 } 7974 7975 const Expr::NullPointerConstantKind LHSNullKind = 7976 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 7977 const Expr::NullPointerConstantKind RHSNullKind = 7978 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 7979 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 7980 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 7981 7982 if (!IsRelational && LHSIsNull != RHSIsNull) { 7983 bool IsEquality = Opc == BO_EQ; 7984 if (RHSIsNull) 7985 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 7986 RHS.get()->getSourceRange()); 7987 else 7988 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 7989 LHS.get()->getSourceRange()); 7990 } 7991 7992 // All of the following pointer-related warnings are GCC extensions, except 7993 // when handling null pointer constants. 7994 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 7995 QualType LCanPointeeTy = 7996 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7997 QualType RCanPointeeTy = 7998 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 7999 8000 if (getLangOpts().CPlusPlus) { 8001 if (LCanPointeeTy == RCanPointeeTy) 8002 return ResultTy; 8003 if (!IsRelational && 8004 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 8005 // Valid unless comparison between non-null pointer and function pointer 8006 // This is a gcc extension compatibility comparison. 8007 // In a SFINAE context, we treat this as a hard error to maintain 8008 // conformance with the C++ standard. 8009 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 8010 && !LHSIsNull && !RHSIsNull) { 8011 diagnoseFunctionPointerToVoidComparison( 8012 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 8013 8014 if (isSFINAEContext()) 8015 return QualType(); 8016 8017 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8018 return ResultTy; 8019 } 8020 } 8021 8022 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 8023 return QualType(); 8024 else 8025 return ResultTy; 8026 } 8027 // C99 6.5.9p2 and C99 6.5.8p2 8028 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 8029 RCanPointeeTy.getUnqualifiedType())) { 8030 // Valid unless a relational comparison of function pointers 8031 if (IsRelational && LCanPointeeTy->isFunctionType()) { 8032 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 8033 << LHSType << RHSType << LHS.get()->getSourceRange() 8034 << RHS.get()->getSourceRange(); 8035 } 8036 } else if (!IsRelational && 8037 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 8038 // Valid unless comparison between non-null pointer and function pointer 8039 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 8040 && !LHSIsNull && !RHSIsNull) 8041 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 8042 /*isError*/false); 8043 } else { 8044 // Invalid 8045 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 8046 } 8047 if (LCanPointeeTy != RCanPointeeTy) { 8048 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 8049 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 8050 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 8051 : CK_BitCast; 8052 if (LHSIsNull && !RHSIsNull) 8053 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 8054 else 8055 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 8056 } 8057 return ResultTy; 8058 } 8059 8060 if (getLangOpts().CPlusPlus) { 8061 // Comparison of nullptr_t with itself. 8062 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 8063 return ResultTy; 8064 8065 // Comparison of pointers with null pointer constants and equality 8066 // comparisons of member pointers to null pointer constants. 8067 if (RHSIsNull && 8068 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 8069 (!IsRelational && 8070 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 8071 RHS = ImpCastExprToType(RHS.get(), LHSType, 8072 LHSType->isMemberPointerType() 8073 ? CK_NullToMemberPointer 8074 : CK_NullToPointer); 8075 return ResultTy; 8076 } 8077 if (LHSIsNull && 8078 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 8079 (!IsRelational && 8080 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 8081 LHS = ImpCastExprToType(LHS.get(), RHSType, 8082 RHSType->isMemberPointerType() 8083 ? CK_NullToMemberPointer 8084 : CK_NullToPointer); 8085 return ResultTy; 8086 } 8087 8088 // Comparison of member pointers. 8089 if (!IsRelational && 8090 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 8091 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 8092 return QualType(); 8093 else 8094 return ResultTy; 8095 } 8096 8097 // Handle scoped enumeration types specifically, since they don't promote 8098 // to integers. 8099 if (LHS.get()->getType()->isEnumeralType() && 8100 Context.hasSameUnqualifiedType(LHS.get()->getType(), 8101 RHS.get()->getType())) 8102 return ResultTy; 8103 } 8104 8105 // Handle block pointer types. 8106 if (!IsRelational && LHSType->isBlockPointerType() && 8107 RHSType->isBlockPointerType()) { 8108 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 8109 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 8110 8111 if (!LHSIsNull && !RHSIsNull && 8112 !Context.typesAreCompatible(lpointee, rpointee)) { 8113 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8114 << LHSType << RHSType << LHS.get()->getSourceRange() 8115 << RHS.get()->getSourceRange(); 8116 } 8117 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8118 return ResultTy; 8119 } 8120 8121 // Allow block pointers to be compared with null pointer constants. 8122 if (!IsRelational 8123 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 8124 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 8125 if (!LHSIsNull && !RHSIsNull) { 8126 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 8127 ->getPointeeType()->isVoidType()) 8128 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 8129 ->getPointeeType()->isVoidType()))) 8130 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8131 << LHSType << RHSType << LHS.get()->getSourceRange() 8132 << RHS.get()->getSourceRange(); 8133 } 8134 if (LHSIsNull && !RHSIsNull) 8135 LHS = ImpCastExprToType(LHS.get(), RHSType, 8136 RHSType->isPointerType() ? CK_BitCast 8137 : CK_AnyPointerToBlockPointerCast); 8138 else 8139 RHS = ImpCastExprToType(RHS.get(), LHSType, 8140 LHSType->isPointerType() ? CK_BitCast 8141 : CK_AnyPointerToBlockPointerCast); 8142 return ResultTy; 8143 } 8144 8145 if (LHSType->isObjCObjectPointerType() || 8146 RHSType->isObjCObjectPointerType()) { 8147 const PointerType *LPT = LHSType->getAs<PointerType>(); 8148 const PointerType *RPT = RHSType->getAs<PointerType>(); 8149 if (LPT || RPT) { 8150 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 8151 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 8152 8153 if (!LPtrToVoid && !RPtrToVoid && 8154 !Context.typesAreCompatible(LHSType, RHSType)) { 8155 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8156 /*isError*/false); 8157 } 8158 if (LHSIsNull && !RHSIsNull) { 8159 Expr *E = LHS.get(); 8160 if (getLangOpts().ObjCAutoRefCount) 8161 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 8162 LHS = ImpCastExprToType(E, RHSType, 8163 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8164 } 8165 else { 8166 Expr *E = RHS.get(); 8167 if (getLangOpts().ObjCAutoRefCount) 8168 CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false, 8169 Opc); 8170 RHS = ImpCastExprToType(E, LHSType, 8171 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8172 } 8173 return ResultTy; 8174 } 8175 if (LHSType->isObjCObjectPointerType() && 8176 RHSType->isObjCObjectPointerType()) { 8177 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 8178 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8179 /*isError*/false); 8180 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 8181 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 8182 8183 if (LHSIsNull && !RHSIsNull) 8184 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8185 else 8186 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8187 return ResultTy; 8188 } 8189 } 8190 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 8191 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 8192 unsigned DiagID = 0; 8193 bool isError = false; 8194 if (LangOpts.DebuggerSupport) { 8195 // Under a debugger, allow the comparison of pointers to integers, 8196 // since users tend to want to compare addresses. 8197 } else if ((LHSIsNull && LHSType->isIntegerType()) || 8198 (RHSIsNull && RHSType->isIntegerType())) { 8199 if (IsRelational && !getLangOpts().CPlusPlus) 8200 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 8201 } else if (IsRelational && !getLangOpts().CPlusPlus) 8202 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 8203 else if (getLangOpts().CPlusPlus) { 8204 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 8205 isError = true; 8206 } else 8207 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 8208 8209 if (DiagID) { 8210 Diag(Loc, DiagID) 8211 << LHSType << RHSType << LHS.get()->getSourceRange() 8212 << RHS.get()->getSourceRange(); 8213 if (isError) 8214 return QualType(); 8215 } 8216 8217 if (LHSType->isIntegerType()) 8218 LHS = ImpCastExprToType(LHS.get(), RHSType, 8219 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8220 else 8221 RHS = ImpCastExprToType(RHS.get(), LHSType, 8222 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8223 return ResultTy; 8224 } 8225 8226 // Handle block pointers. 8227 if (!IsRelational && RHSIsNull 8228 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 8229 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8230 return ResultTy; 8231 } 8232 if (!IsRelational && LHSIsNull 8233 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 8234 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 8235 return ResultTy; 8236 } 8237 8238 return InvalidOperands(Loc, LHS, RHS); 8239 } 8240 8241 8242 // Return a signed type that is of identical size and number of elements. 8243 // For floating point vectors, return an integer type of identical size 8244 // and number of elements. 8245 QualType Sema::GetSignedVectorType(QualType V) { 8246 const VectorType *VTy = V->getAs<VectorType>(); 8247 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 8248 if (TypeSize == Context.getTypeSize(Context.CharTy)) 8249 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 8250 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 8251 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 8252 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 8253 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 8254 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 8255 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 8256 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 8257 "Unhandled vector element size in vector compare"); 8258 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 8259 } 8260 8261 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 8262 /// operates on extended vector types. Instead of producing an IntTy result, 8263 /// like a scalar comparison, a vector comparison produces a vector of integer 8264 /// types. 8265 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 8266 SourceLocation Loc, 8267 bool IsRelational) { 8268 // Check to make sure we're operating on vectors of the same type and width, 8269 // Allowing one side to be a scalar of element type. 8270 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false); 8271 if (vType.isNull()) 8272 return vType; 8273 8274 QualType LHSType = LHS.get()->getType(); 8275 8276 // If AltiVec, the comparison results in a numeric type, i.e. 8277 // bool for C++, int for C 8278 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 8279 return Context.getLogicalOperationType(); 8280 8281 // For non-floating point types, check for self-comparisons of the form 8282 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 8283 // often indicate logic errors in the program. 8284 if (!LHSType->hasFloatingRepresentation() && 8285 ActiveTemplateInstantiations.empty()) { 8286 if (DeclRefExpr* DRL 8287 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 8288 if (DeclRefExpr* DRR 8289 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 8290 if (DRL->getDecl() == DRR->getDecl()) 8291 DiagRuntimeBehavior(Loc, nullptr, 8292 PDiag(diag::warn_comparison_always) 8293 << 0 // self- 8294 << 2 // "a constant" 8295 ); 8296 } 8297 8298 // Check for comparisons of floating point operands using != and ==. 8299 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 8300 assert (RHS.get()->getType()->hasFloatingRepresentation()); 8301 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 8302 } 8303 8304 // Return a signed type for the vector. 8305 return GetSignedVectorType(LHSType); 8306 } 8307 8308 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 8309 SourceLocation Loc) { 8310 // Ensure that either both operands are of the same vector type, or 8311 // one operand is of a vector type and the other is of its element type. 8312 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false); 8313 if (vType.isNull()) 8314 return InvalidOperands(Loc, LHS, RHS); 8315 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 8316 vType->hasFloatingRepresentation()) 8317 return InvalidOperands(Loc, LHS, RHS); 8318 8319 return GetSignedVectorType(LHS.get()->getType()); 8320 } 8321 8322 inline QualType Sema::CheckBitwiseOperands( 8323 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8324 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8325 8326 if (LHS.get()->getType()->isVectorType() || 8327 RHS.get()->getType()->isVectorType()) { 8328 if (LHS.get()->getType()->hasIntegerRepresentation() && 8329 RHS.get()->getType()->hasIntegerRepresentation()) 8330 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign); 8331 8332 return InvalidOperands(Loc, LHS, RHS); 8333 } 8334 8335 ExprResult LHSResult = LHS, RHSResult = RHS; 8336 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 8337 IsCompAssign); 8338 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 8339 return QualType(); 8340 LHS = LHSResult.get(); 8341 RHS = RHSResult.get(); 8342 8343 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 8344 return compType; 8345 return InvalidOperands(Loc, LHS, RHS); 8346 } 8347 8348 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 8349 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 8350 8351 // Check vector operands differently. 8352 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 8353 return CheckVectorLogicalOperands(LHS, RHS, Loc); 8354 8355 // Diagnose cases where the user write a logical and/or but probably meant a 8356 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 8357 // is a constant. 8358 if (LHS.get()->getType()->isIntegerType() && 8359 !LHS.get()->getType()->isBooleanType() && 8360 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 8361 // Don't warn in macros or template instantiations. 8362 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 8363 // If the RHS can be constant folded, and if it constant folds to something 8364 // that isn't 0 or 1 (which indicate a potential logical operation that 8365 // happened to fold to true/false) then warn. 8366 // Parens on the RHS are ignored. 8367 llvm::APSInt Result; 8368 if (RHS.get()->EvaluateAsInt(Result, Context)) 8369 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 8370 !RHS.get()->getExprLoc().isMacroID()) || 8371 (Result != 0 && Result != 1)) { 8372 Diag(Loc, diag::warn_logical_instead_of_bitwise) 8373 << RHS.get()->getSourceRange() 8374 << (Opc == BO_LAnd ? "&&" : "||"); 8375 // Suggest replacing the logical operator with the bitwise version 8376 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 8377 << (Opc == BO_LAnd ? "&" : "|") 8378 << FixItHint::CreateReplacement(SourceRange( 8379 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 8380 getLangOpts())), 8381 Opc == BO_LAnd ? "&" : "|"); 8382 if (Opc == BO_LAnd) 8383 // Suggest replacing "Foo() && kNonZero" with "Foo()" 8384 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 8385 << FixItHint::CreateRemoval( 8386 SourceRange( 8387 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 8388 0, getSourceManager(), 8389 getLangOpts()), 8390 RHS.get()->getLocEnd())); 8391 } 8392 } 8393 8394 if (!Context.getLangOpts().CPlusPlus) { 8395 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 8396 // not operate on the built-in scalar and vector float types. 8397 if (Context.getLangOpts().OpenCL && 8398 Context.getLangOpts().OpenCLVersion < 120) { 8399 if (LHS.get()->getType()->isFloatingType() || 8400 RHS.get()->getType()->isFloatingType()) 8401 return InvalidOperands(Loc, LHS, RHS); 8402 } 8403 8404 LHS = UsualUnaryConversions(LHS.get()); 8405 if (LHS.isInvalid()) 8406 return QualType(); 8407 8408 RHS = UsualUnaryConversions(RHS.get()); 8409 if (RHS.isInvalid()) 8410 return QualType(); 8411 8412 if (!LHS.get()->getType()->isScalarType() || 8413 !RHS.get()->getType()->isScalarType()) 8414 return InvalidOperands(Loc, LHS, RHS); 8415 8416 return Context.IntTy; 8417 } 8418 8419 // The following is safe because we only use this method for 8420 // non-overloadable operands. 8421 8422 // C++ [expr.log.and]p1 8423 // C++ [expr.log.or]p1 8424 // The operands are both contextually converted to type bool. 8425 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 8426 if (LHSRes.isInvalid()) 8427 return InvalidOperands(Loc, LHS, RHS); 8428 LHS = LHSRes; 8429 8430 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 8431 if (RHSRes.isInvalid()) 8432 return InvalidOperands(Loc, LHS, RHS); 8433 RHS = RHSRes; 8434 8435 // C++ [expr.log.and]p2 8436 // C++ [expr.log.or]p2 8437 // The result is a bool. 8438 return Context.BoolTy; 8439 } 8440 8441 static bool IsReadonlyMessage(Expr *E, Sema &S) { 8442 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 8443 if (!ME) return false; 8444 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 8445 ObjCMessageExpr *Base = 8446 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 8447 if (!Base) return false; 8448 return Base->getMethodDecl() != nullptr; 8449 } 8450 8451 /// Is the given expression (which must be 'const') a reference to a 8452 /// variable which was originally non-const, but which has become 8453 /// 'const' due to being captured within a block? 8454 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 8455 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 8456 assert(E->isLValue() && E->getType().isConstQualified()); 8457 E = E->IgnoreParens(); 8458 8459 // Must be a reference to a declaration from an enclosing scope. 8460 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 8461 if (!DRE) return NCCK_None; 8462 if (!DRE->refersToEnclosingLocal()) return NCCK_None; 8463 8464 // The declaration must be a variable which is not declared 'const'. 8465 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 8466 if (!var) return NCCK_None; 8467 if (var->getType().isConstQualified()) return NCCK_None; 8468 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 8469 8470 // Decide whether the first capture was for a block or a lambda. 8471 DeclContext *DC = S.CurContext, *Prev = nullptr; 8472 while (DC != var->getDeclContext()) { 8473 Prev = DC; 8474 DC = DC->getParent(); 8475 } 8476 // Unless we have an init-capture, we've gone one step too far. 8477 if (!var->isInitCapture()) 8478 DC = Prev; 8479 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 8480 } 8481 8482 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 8483 /// emit an error and return true. If so, return false. 8484 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 8485 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 8486 SourceLocation OrigLoc = Loc; 8487 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 8488 &Loc); 8489 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 8490 IsLV = Expr::MLV_InvalidMessageExpression; 8491 if (IsLV == Expr::MLV_Valid) 8492 return false; 8493 8494 unsigned Diag = 0; 8495 bool NeedType = false; 8496 switch (IsLV) { // C99 6.5.16p2 8497 case Expr::MLV_ConstQualified: 8498 Diag = diag::err_typecheck_assign_const; 8499 8500 // Use a specialized diagnostic when we're assigning to an object 8501 // from an enclosing function or block. 8502 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 8503 if (NCCK == NCCK_Block) 8504 Diag = diag::err_block_decl_ref_not_modifiable_lvalue; 8505 else 8506 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue; 8507 break; 8508 } 8509 8510 // In ARC, use some specialized diagnostics for occasions where we 8511 // infer 'const'. These are always pseudo-strong variables. 8512 if (S.getLangOpts().ObjCAutoRefCount) { 8513 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 8514 if (declRef && isa<VarDecl>(declRef->getDecl())) { 8515 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 8516 8517 // Use the normal diagnostic if it's pseudo-__strong but the 8518 // user actually wrote 'const'. 8519 if (var->isARCPseudoStrong() && 8520 (!var->getTypeSourceInfo() || 8521 !var->getTypeSourceInfo()->getType().isConstQualified())) { 8522 // There are two pseudo-strong cases: 8523 // - self 8524 ObjCMethodDecl *method = S.getCurMethodDecl(); 8525 if (method && var == method->getSelfDecl()) 8526 Diag = method->isClassMethod() 8527 ? diag::err_typecheck_arc_assign_self_class_method 8528 : diag::err_typecheck_arc_assign_self; 8529 8530 // - fast enumeration variables 8531 else 8532 Diag = diag::err_typecheck_arr_assign_enumeration; 8533 8534 SourceRange Assign; 8535 if (Loc != OrigLoc) 8536 Assign = SourceRange(OrigLoc, OrigLoc); 8537 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 8538 // We need to preserve the AST regardless, so migration tool 8539 // can do its job. 8540 return false; 8541 } 8542 } 8543 } 8544 8545 break; 8546 case Expr::MLV_ArrayType: 8547 case Expr::MLV_ArrayTemporary: 8548 Diag = diag::err_typecheck_array_not_modifiable_lvalue; 8549 NeedType = true; 8550 break; 8551 case Expr::MLV_NotObjectType: 8552 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue; 8553 NeedType = true; 8554 break; 8555 case Expr::MLV_LValueCast: 8556 Diag = diag::err_typecheck_lvalue_casts_not_supported; 8557 break; 8558 case Expr::MLV_Valid: 8559 llvm_unreachable("did not take early return for MLV_Valid"); 8560 case Expr::MLV_InvalidExpression: 8561 case Expr::MLV_MemberFunction: 8562 case Expr::MLV_ClassTemporary: 8563 Diag = diag::err_typecheck_expression_not_modifiable_lvalue; 8564 break; 8565 case Expr::MLV_IncompleteType: 8566 case Expr::MLV_IncompleteVoidType: 8567 return S.RequireCompleteType(Loc, E->getType(), 8568 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 8569 case Expr::MLV_DuplicateVectorComponents: 8570 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 8571 break; 8572 case Expr::MLV_NoSetterProperty: 8573 llvm_unreachable("readonly properties should be processed differently"); 8574 case Expr::MLV_InvalidMessageExpression: 8575 Diag = diag::error_readonly_message_assignment; 8576 break; 8577 case Expr::MLV_SubObjCPropertySetting: 8578 Diag = diag::error_no_subobject_property_setting; 8579 break; 8580 } 8581 8582 SourceRange Assign; 8583 if (Loc != OrigLoc) 8584 Assign = SourceRange(OrigLoc, OrigLoc); 8585 if (NeedType) 8586 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign; 8587 else 8588 S.Diag(Loc, Diag) << E->getSourceRange() << Assign; 8589 return true; 8590 } 8591 8592 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 8593 SourceLocation Loc, 8594 Sema &Sema) { 8595 // C / C++ fields 8596 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 8597 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 8598 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 8599 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 8600 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 8601 } 8602 8603 // Objective-C instance variables 8604 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 8605 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 8606 if (OL && OR && OL->getDecl() == OR->getDecl()) { 8607 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 8608 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 8609 if (RL && RR && RL->getDecl() == RR->getDecl()) 8610 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 8611 } 8612 } 8613 8614 // C99 6.5.16.1 8615 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 8616 SourceLocation Loc, 8617 QualType CompoundType) { 8618 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 8619 8620 // Verify that LHS is a modifiable lvalue, and emit error if not. 8621 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 8622 return QualType(); 8623 8624 QualType LHSType = LHSExpr->getType(); 8625 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 8626 CompoundType; 8627 AssignConvertType ConvTy; 8628 if (CompoundType.isNull()) { 8629 Expr *RHSCheck = RHS.get(); 8630 8631 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 8632 8633 QualType LHSTy(LHSType); 8634 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 8635 if (RHS.isInvalid()) 8636 return QualType(); 8637 // Special case of NSObject attributes on c-style pointer types. 8638 if (ConvTy == IncompatiblePointer && 8639 ((Context.isObjCNSObjectType(LHSType) && 8640 RHSType->isObjCObjectPointerType()) || 8641 (Context.isObjCNSObjectType(RHSType) && 8642 LHSType->isObjCObjectPointerType()))) 8643 ConvTy = Compatible; 8644 8645 if (ConvTy == Compatible && 8646 LHSType->isObjCObjectType()) 8647 Diag(Loc, diag::err_objc_object_assignment) 8648 << LHSType; 8649 8650 // If the RHS is a unary plus or minus, check to see if they = and + are 8651 // right next to each other. If so, the user may have typo'd "x =+ 4" 8652 // instead of "x += 4". 8653 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 8654 RHSCheck = ICE->getSubExpr(); 8655 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 8656 if ((UO->getOpcode() == UO_Plus || 8657 UO->getOpcode() == UO_Minus) && 8658 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 8659 // Only if the two operators are exactly adjacent. 8660 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 8661 // And there is a space or other character before the subexpr of the 8662 // unary +/-. We don't want to warn on "x=-1". 8663 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 8664 UO->getSubExpr()->getLocStart().isFileID()) { 8665 Diag(Loc, diag::warn_not_compound_assign) 8666 << (UO->getOpcode() == UO_Plus ? "+" : "-") 8667 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 8668 } 8669 } 8670 8671 if (ConvTy == Compatible) { 8672 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 8673 // Warn about retain cycles where a block captures the LHS, but 8674 // not if the LHS is a simple variable into which the block is 8675 // being stored...unless that variable can be captured by reference! 8676 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 8677 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 8678 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 8679 checkRetainCycles(LHSExpr, RHS.get()); 8680 8681 // It is safe to assign a weak reference into a strong variable. 8682 // Although this code can still have problems: 8683 // id x = self.weakProp; 8684 // id y = self.weakProp; 8685 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8686 // paths through the function. This should be revisited if 8687 // -Wrepeated-use-of-weak is made flow-sensitive. 8688 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 8689 RHS.get()->getLocStart())) 8690 getCurFunction()->markSafeWeakUse(RHS.get()); 8691 8692 } else if (getLangOpts().ObjCAutoRefCount) { 8693 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 8694 } 8695 } 8696 } else { 8697 // Compound assignment "x += y" 8698 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 8699 } 8700 8701 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 8702 RHS.get(), AA_Assigning)) 8703 return QualType(); 8704 8705 CheckForNullPointerDereference(*this, LHSExpr); 8706 8707 // C99 6.5.16p3: The type of an assignment expression is the type of the 8708 // left operand unless the left operand has qualified type, in which case 8709 // it is the unqualified version of the type of the left operand. 8710 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 8711 // is converted to the type of the assignment expression (above). 8712 // C++ 5.17p1: the type of the assignment expression is that of its left 8713 // operand. 8714 return (getLangOpts().CPlusPlus 8715 ? LHSType : LHSType.getUnqualifiedType()); 8716 } 8717 8718 // C99 6.5.17 8719 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 8720 SourceLocation Loc) { 8721 LHS = S.CheckPlaceholderExpr(LHS.get()); 8722 RHS = S.CheckPlaceholderExpr(RHS.get()); 8723 if (LHS.isInvalid() || RHS.isInvalid()) 8724 return QualType(); 8725 8726 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 8727 // operands, but not unary promotions. 8728 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 8729 8730 // So we treat the LHS as a ignored value, and in C++ we allow the 8731 // containing site to determine what should be done with the RHS. 8732 LHS = S.IgnoredValueConversions(LHS.get()); 8733 if (LHS.isInvalid()) 8734 return QualType(); 8735 8736 S.DiagnoseUnusedExprResult(LHS.get()); 8737 8738 if (!S.getLangOpts().CPlusPlus) { 8739 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 8740 if (RHS.isInvalid()) 8741 return QualType(); 8742 if (!RHS.get()->getType()->isVoidType()) 8743 S.RequireCompleteType(Loc, RHS.get()->getType(), 8744 diag::err_incomplete_type); 8745 } 8746 8747 return RHS.get()->getType(); 8748 } 8749 8750 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 8751 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 8752 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 8753 ExprValueKind &VK, 8754 ExprObjectKind &OK, 8755 SourceLocation OpLoc, 8756 bool IsInc, bool IsPrefix) { 8757 if (Op->isTypeDependent()) 8758 return S.Context.DependentTy; 8759 8760 QualType ResType = Op->getType(); 8761 // Atomic types can be used for increment / decrement where the non-atomic 8762 // versions can, so ignore the _Atomic() specifier for the purpose of 8763 // checking. 8764 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8765 ResType = ResAtomicType->getValueType(); 8766 8767 assert(!ResType.isNull() && "no type for increment/decrement expression"); 8768 8769 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 8770 // Decrement of bool is not allowed. 8771 if (!IsInc) { 8772 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 8773 return QualType(); 8774 } 8775 // Increment of bool sets it to true, but is deprecated. 8776 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 8777 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 8778 // Error on enum increments and decrements in C++ mode 8779 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 8780 return QualType(); 8781 } else if (ResType->isRealType()) { 8782 // OK! 8783 } else if (ResType->isPointerType()) { 8784 // C99 6.5.2.4p2, 6.5.6p2 8785 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 8786 return QualType(); 8787 } else if (ResType->isObjCObjectPointerType()) { 8788 // On modern runtimes, ObjC pointer arithmetic is forbidden. 8789 // Otherwise, we just need a complete type. 8790 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 8791 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 8792 return QualType(); 8793 } else if (ResType->isAnyComplexType()) { 8794 // C99 does not support ++/-- on complex types, we allow as an extension. 8795 S.Diag(OpLoc, diag::ext_integer_increment_complex) 8796 << ResType << Op->getSourceRange(); 8797 } else if (ResType->isPlaceholderType()) { 8798 ExprResult PR = S.CheckPlaceholderExpr(Op); 8799 if (PR.isInvalid()) return QualType(); 8800 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 8801 IsInc, IsPrefix); 8802 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 8803 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 8804 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 8805 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 8806 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 8807 } else { 8808 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 8809 << ResType << int(IsInc) << Op->getSourceRange(); 8810 return QualType(); 8811 } 8812 // At this point, we know we have a real, complex or pointer type. 8813 // Now make sure the operand is a modifiable lvalue. 8814 if (CheckForModifiableLvalue(Op, OpLoc, S)) 8815 return QualType(); 8816 // In C++, a prefix increment is the same type as the operand. Otherwise 8817 // (in C or with postfix), the increment is the unqualified type of the 8818 // operand. 8819 if (IsPrefix && S.getLangOpts().CPlusPlus) { 8820 VK = VK_LValue; 8821 OK = Op->getObjectKind(); 8822 return ResType; 8823 } else { 8824 VK = VK_RValue; 8825 return ResType.getUnqualifiedType(); 8826 } 8827 } 8828 8829 8830 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 8831 /// This routine allows us to typecheck complex/recursive expressions 8832 /// where the declaration is needed for type checking. We only need to 8833 /// handle cases when the expression references a function designator 8834 /// or is an lvalue. Here are some examples: 8835 /// - &(x) => x 8836 /// - &*****f => f for f a function designator. 8837 /// - &s.xx => s 8838 /// - &s.zz[1].yy -> s, if zz is an array 8839 /// - *(x + 1) -> x, if x is an array 8840 /// - &"123"[2] -> 0 8841 /// - & __real__ x -> x 8842 static ValueDecl *getPrimaryDecl(Expr *E) { 8843 switch (E->getStmtClass()) { 8844 case Stmt::DeclRefExprClass: 8845 return cast<DeclRefExpr>(E)->getDecl(); 8846 case Stmt::MemberExprClass: 8847 // If this is an arrow operator, the address is an offset from 8848 // the base's value, so the object the base refers to is 8849 // irrelevant. 8850 if (cast<MemberExpr>(E)->isArrow()) 8851 return nullptr; 8852 // Otherwise, the expression refers to a part of the base 8853 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 8854 case Stmt::ArraySubscriptExprClass: { 8855 // FIXME: This code shouldn't be necessary! We should catch the implicit 8856 // promotion of register arrays earlier. 8857 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 8858 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 8859 if (ICE->getSubExpr()->getType()->isArrayType()) 8860 return getPrimaryDecl(ICE->getSubExpr()); 8861 } 8862 return nullptr; 8863 } 8864 case Stmt::UnaryOperatorClass: { 8865 UnaryOperator *UO = cast<UnaryOperator>(E); 8866 8867 switch(UO->getOpcode()) { 8868 case UO_Real: 8869 case UO_Imag: 8870 case UO_Extension: 8871 return getPrimaryDecl(UO->getSubExpr()); 8872 default: 8873 return nullptr; 8874 } 8875 } 8876 case Stmt::ParenExprClass: 8877 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 8878 case Stmt::ImplicitCastExprClass: 8879 // If the result of an implicit cast is an l-value, we care about 8880 // the sub-expression; otherwise, the result here doesn't matter. 8881 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 8882 default: 8883 return nullptr; 8884 } 8885 } 8886 8887 namespace { 8888 enum { 8889 AO_Bit_Field = 0, 8890 AO_Vector_Element = 1, 8891 AO_Property_Expansion = 2, 8892 AO_Register_Variable = 3, 8893 AO_No_Error = 4 8894 }; 8895 } 8896 /// \brief Diagnose invalid operand for address of operations. 8897 /// 8898 /// \param Type The type of operand which cannot have its address taken. 8899 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 8900 Expr *E, unsigned Type) { 8901 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 8902 } 8903 8904 /// CheckAddressOfOperand - The operand of & must be either a function 8905 /// designator or an lvalue designating an object. If it is an lvalue, the 8906 /// object cannot be declared with storage class register or be a bit field. 8907 /// Note: The usual conversions are *not* applied to the operand of the & 8908 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 8909 /// In C++, the operand might be an overloaded function name, in which case 8910 /// we allow the '&' but retain the overloaded-function type. 8911 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 8912 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 8913 if (PTy->getKind() == BuiltinType::Overload) { 8914 Expr *E = OrigOp.get()->IgnoreParens(); 8915 if (!isa<OverloadExpr>(E)) { 8916 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 8917 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 8918 << OrigOp.get()->getSourceRange(); 8919 return QualType(); 8920 } 8921 8922 OverloadExpr *Ovl = cast<OverloadExpr>(E); 8923 if (isa<UnresolvedMemberExpr>(Ovl)) 8924 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 8925 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8926 << OrigOp.get()->getSourceRange(); 8927 return QualType(); 8928 } 8929 8930 return Context.OverloadTy; 8931 } 8932 8933 if (PTy->getKind() == BuiltinType::UnknownAny) 8934 return Context.UnknownAnyTy; 8935 8936 if (PTy->getKind() == BuiltinType::BoundMember) { 8937 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8938 << OrigOp.get()->getSourceRange(); 8939 return QualType(); 8940 } 8941 8942 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 8943 if (OrigOp.isInvalid()) return QualType(); 8944 } 8945 8946 if (OrigOp.get()->isTypeDependent()) 8947 return Context.DependentTy; 8948 8949 assert(!OrigOp.get()->getType()->isPlaceholderType()); 8950 8951 // Make sure to ignore parentheses in subsequent checks 8952 Expr *op = OrigOp.get()->IgnoreParens(); 8953 8954 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 8955 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 8956 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 8957 return QualType(); 8958 } 8959 8960 if (getLangOpts().C99) { 8961 // Implement C99-only parts of addressof rules. 8962 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 8963 if (uOp->getOpcode() == UO_Deref) 8964 // Per C99 6.5.3.2, the address of a deref always returns a valid result 8965 // (assuming the deref expression is valid). 8966 return uOp->getSubExpr()->getType(); 8967 } 8968 // Technically, there should be a check for array subscript 8969 // expressions here, but the result of one is always an lvalue anyway. 8970 } 8971 ValueDecl *dcl = getPrimaryDecl(op); 8972 Expr::LValueClassification lval = op->ClassifyLValue(Context); 8973 unsigned AddressOfError = AO_No_Error; 8974 8975 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 8976 bool sfinae = (bool)isSFINAEContext(); 8977 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 8978 : diag::ext_typecheck_addrof_temporary) 8979 << op->getType() << op->getSourceRange(); 8980 if (sfinae) 8981 return QualType(); 8982 // Materialize the temporary as an lvalue so that we can take its address. 8983 OrigOp = op = new (Context) 8984 MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 8985 } else if (isa<ObjCSelectorExpr>(op)) { 8986 return Context.getPointerType(op->getType()); 8987 } else if (lval == Expr::LV_MemberFunction) { 8988 // If it's an instance method, make a member pointer. 8989 // The expression must have exactly the form &A::foo. 8990 8991 // If the underlying expression isn't a decl ref, give up. 8992 if (!isa<DeclRefExpr>(op)) { 8993 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 8994 << OrigOp.get()->getSourceRange(); 8995 return QualType(); 8996 } 8997 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 8998 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 8999 9000 // The id-expression was parenthesized. 9001 if (OrigOp.get() != DRE) { 9002 Diag(OpLoc, diag::err_parens_pointer_member_function) 9003 << OrigOp.get()->getSourceRange(); 9004 9005 // The method was named without a qualifier. 9006 } else if (!DRE->getQualifier()) { 9007 if (MD->getParent()->getName().empty()) 9008 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 9009 << op->getSourceRange(); 9010 else { 9011 SmallString<32> Str; 9012 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 9013 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 9014 << op->getSourceRange() 9015 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 9016 } 9017 } 9018 9019 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 9020 if (isa<CXXDestructorDecl>(MD)) 9021 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 9022 9023 QualType MPTy = Context.getMemberPointerType( 9024 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 9025 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 9026 RequireCompleteType(OpLoc, MPTy, 0); 9027 return MPTy; 9028 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 9029 // C99 6.5.3.2p1 9030 // The operand must be either an l-value or a function designator 9031 if (!op->getType()->isFunctionType()) { 9032 // Use a special diagnostic for loads from property references. 9033 if (isa<PseudoObjectExpr>(op)) { 9034 AddressOfError = AO_Property_Expansion; 9035 } else { 9036 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 9037 << op->getType() << op->getSourceRange(); 9038 return QualType(); 9039 } 9040 } 9041 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 9042 // The operand cannot be a bit-field 9043 AddressOfError = AO_Bit_Field; 9044 } else if (op->getObjectKind() == OK_VectorComponent) { 9045 // The operand cannot be an element of a vector 9046 AddressOfError = AO_Vector_Element; 9047 } else if (dcl) { // C99 6.5.3.2p1 9048 // We have an lvalue with a decl. Make sure the decl is not declared 9049 // with the register storage-class specifier. 9050 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 9051 // in C++ it is not error to take address of a register 9052 // variable (c++03 7.1.1P3) 9053 if (vd->getStorageClass() == SC_Register && 9054 !getLangOpts().CPlusPlus) { 9055 AddressOfError = AO_Register_Variable; 9056 } 9057 } else if (isa<FunctionTemplateDecl>(dcl)) { 9058 return Context.OverloadTy; 9059 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 9060 // Okay: we can take the address of a field. 9061 // Could be a pointer to member, though, if there is an explicit 9062 // scope qualifier for the class. 9063 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 9064 DeclContext *Ctx = dcl->getDeclContext(); 9065 if (Ctx && Ctx->isRecord()) { 9066 if (dcl->getType()->isReferenceType()) { 9067 Diag(OpLoc, 9068 diag::err_cannot_form_pointer_to_member_of_reference_type) 9069 << dcl->getDeclName() << dcl->getType(); 9070 return QualType(); 9071 } 9072 9073 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 9074 Ctx = Ctx->getParent(); 9075 9076 QualType MPTy = Context.getMemberPointerType( 9077 op->getType(), 9078 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 9079 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 9080 RequireCompleteType(OpLoc, MPTy, 0); 9081 return MPTy; 9082 } 9083 } 9084 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 9085 llvm_unreachable("Unknown/unexpected decl type"); 9086 } 9087 9088 if (AddressOfError != AO_No_Error) { 9089 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 9090 return QualType(); 9091 } 9092 9093 if (lval == Expr::LV_IncompleteVoidType) { 9094 // Taking the address of a void variable is technically illegal, but we 9095 // allow it in cases which are otherwise valid. 9096 // Example: "extern void x; void* y = &x;". 9097 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 9098 } 9099 9100 // If the operand has type "type", the result has type "pointer to type". 9101 if (op->getType()->isObjCObjectType()) 9102 return Context.getObjCObjectPointerType(op->getType()); 9103 return Context.getPointerType(op->getType()); 9104 } 9105 9106 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 9107 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 9108 SourceLocation OpLoc) { 9109 if (Op->isTypeDependent()) 9110 return S.Context.DependentTy; 9111 9112 ExprResult ConvResult = S.UsualUnaryConversions(Op); 9113 if (ConvResult.isInvalid()) 9114 return QualType(); 9115 Op = ConvResult.get(); 9116 QualType OpTy = Op->getType(); 9117 QualType Result; 9118 9119 if (isa<CXXReinterpretCastExpr>(Op)) { 9120 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 9121 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 9122 Op->getSourceRange()); 9123 } 9124 9125 if (const PointerType *PT = OpTy->getAs<PointerType>()) 9126 Result = PT->getPointeeType(); 9127 else if (const ObjCObjectPointerType *OPT = 9128 OpTy->getAs<ObjCObjectPointerType>()) 9129 Result = OPT->getPointeeType(); 9130 else { 9131 ExprResult PR = S.CheckPlaceholderExpr(Op); 9132 if (PR.isInvalid()) return QualType(); 9133 if (PR.get() != Op) 9134 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 9135 } 9136 9137 if (Result.isNull()) { 9138 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 9139 << OpTy << Op->getSourceRange(); 9140 return QualType(); 9141 } 9142 9143 // Note that per both C89 and C99, indirection is always legal, even if Result 9144 // is an incomplete type or void. It would be possible to warn about 9145 // dereferencing a void pointer, but it's completely well-defined, and such a 9146 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 9147 // for pointers to 'void' but is fine for any other pointer type: 9148 // 9149 // C++ [expr.unary.op]p1: 9150 // [...] the expression to which [the unary * operator] is applied shall 9151 // be a pointer to an object type, or a pointer to a function type 9152 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 9153 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 9154 << OpTy << Op->getSourceRange(); 9155 9156 // Dereferences are usually l-values... 9157 VK = VK_LValue; 9158 9159 // ...except that certain expressions are never l-values in C. 9160 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 9161 VK = VK_RValue; 9162 9163 return Result; 9164 } 9165 9166 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode( 9167 tok::TokenKind Kind) { 9168 BinaryOperatorKind Opc; 9169 switch (Kind) { 9170 default: llvm_unreachable("Unknown binop!"); 9171 case tok::periodstar: Opc = BO_PtrMemD; break; 9172 case tok::arrowstar: Opc = BO_PtrMemI; break; 9173 case tok::star: Opc = BO_Mul; break; 9174 case tok::slash: Opc = BO_Div; break; 9175 case tok::percent: Opc = BO_Rem; break; 9176 case tok::plus: Opc = BO_Add; break; 9177 case tok::minus: Opc = BO_Sub; break; 9178 case tok::lessless: Opc = BO_Shl; break; 9179 case tok::greatergreater: Opc = BO_Shr; break; 9180 case tok::lessequal: Opc = BO_LE; break; 9181 case tok::less: Opc = BO_LT; break; 9182 case tok::greaterequal: Opc = BO_GE; break; 9183 case tok::greater: Opc = BO_GT; break; 9184 case tok::exclaimequal: Opc = BO_NE; break; 9185 case tok::equalequal: Opc = BO_EQ; break; 9186 case tok::amp: Opc = BO_And; break; 9187 case tok::caret: Opc = BO_Xor; break; 9188 case tok::pipe: Opc = BO_Or; break; 9189 case tok::ampamp: Opc = BO_LAnd; break; 9190 case tok::pipepipe: Opc = BO_LOr; break; 9191 case tok::equal: Opc = BO_Assign; break; 9192 case tok::starequal: Opc = BO_MulAssign; break; 9193 case tok::slashequal: Opc = BO_DivAssign; break; 9194 case tok::percentequal: Opc = BO_RemAssign; break; 9195 case tok::plusequal: Opc = BO_AddAssign; break; 9196 case tok::minusequal: Opc = BO_SubAssign; break; 9197 case tok::lesslessequal: Opc = BO_ShlAssign; break; 9198 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 9199 case tok::ampequal: Opc = BO_AndAssign; break; 9200 case tok::caretequal: Opc = BO_XorAssign; break; 9201 case tok::pipeequal: Opc = BO_OrAssign; break; 9202 case tok::comma: Opc = BO_Comma; break; 9203 } 9204 return Opc; 9205 } 9206 9207 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 9208 tok::TokenKind Kind) { 9209 UnaryOperatorKind Opc; 9210 switch (Kind) { 9211 default: llvm_unreachable("Unknown unary op!"); 9212 case tok::plusplus: Opc = UO_PreInc; break; 9213 case tok::minusminus: Opc = UO_PreDec; break; 9214 case tok::amp: Opc = UO_AddrOf; break; 9215 case tok::star: Opc = UO_Deref; break; 9216 case tok::plus: Opc = UO_Plus; break; 9217 case tok::minus: Opc = UO_Minus; break; 9218 case tok::tilde: Opc = UO_Not; break; 9219 case tok::exclaim: Opc = UO_LNot; break; 9220 case tok::kw___real: Opc = UO_Real; break; 9221 case tok::kw___imag: Opc = UO_Imag; break; 9222 case tok::kw___extension__: Opc = UO_Extension; break; 9223 } 9224 return Opc; 9225 } 9226 9227 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 9228 /// This warning is only emitted for builtin assignment operations. It is also 9229 /// suppressed in the event of macro expansions. 9230 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 9231 SourceLocation OpLoc) { 9232 if (!S.ActiveTemplateInstantiations.empty()) 9233 return; 9234 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 9235 return; 9236 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 9237 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 9238 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 9239 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 9240 if (!LHSDeclRef || !RHSDeclRef || 9241 LHSDeclRef->getLocation().isMacroID() || 9242 RHSDeclRef->getLocation().isMacroID()) 9243 return; 9244 const ValueDecl *LHSDecl = 9245 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 9246 const ValueDecl *RHSDecl = 9247 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 9248 if (LHSDecl != RHSDecl) 9249 return; 9250 if (LHSDecl->getType().isVolatileQualified()) 9251 return; 9252 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 9253 if (RefTy->getPointeeType().isVolatileQualified()) 9254 return; 9255 9256 S.Diag(OpLoc, diag::warn_self_assignment) 9257 << LHSDeclRef->getType() 9258 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9259 } 9260 9261 /// Check if a bitwise-& is performed on an Objective-C pointer. This 9262 /// is usually indicative of introspection within the Objective-C pointer. 9263 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 9264 SourceLocation OpLoc) { 9265 if (!S.getLangOpts().ObjC1) 9266 return; 9267 9268 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 9269 const Expr *LHS = L.get(); 9270 const Expr *RHS = R.get(); 9271 9272 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 9273 ObjCPointerExpr = LHS; 9274 OtherExpr = RHS; 9275 } 9276 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 9277 ObjCPointerExpr = RHS; 9278 OtherExpr = LHS; 9279 } 9280 9281 // This warning is deliberately made very specific to reduce false 9282 // positives with logic that uses '&' for hashing. This logic mainly 9283 // looks for code trying to introspect into tagged pointers, which 9284 // code should generally never do. 9285 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 9286 unsigned Diag = diag::warn_objc_pointer_masking; 9287 // Determine if we are introspecting the result of performSelectorXXX. 9288 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 9289 // Special case messages to -performSelector and friends, which 9290 // can return non-pointer values boxed in a pointer value. 9291 // Some clients may wish to silence warnings in this subcase. 9292 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 9293 Selector S = ME->getSelector(); 9294 StringRef SelArg0 = S.getNameForSlot(0); 9295 if (SelArg0.startswith("performSelector")) 9296 Diag = diag::warn_objc_pointer_masking_performSelector; 9297 } 9298 9299 S.Diag(OpLoc, Diag) 9300 << ObjCPointerExpr->getSourceRange(); 9301 } 9302 } 9303 9304 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 9305 /// operator @p Opc at location @c TokLoc. This routine only supports 9306 /// built-in operations; ActOnBinOp handles overloaded operators. 9307 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 9308 BinaryOperatorKind Opc, 9309 Expr *LHSExpr, Expr *RHSExpr) { 9310 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 9311 // The syntax only allows initializer lists on the RHS of assignment, 9312 // so we don't need to worry about accepting invalid code for 9313 // non-assignment operators. 9314 // C++11 5.17p9: 9315 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 9316 // of x = {} is x = T(). 9317 InitializationKind Kind = 9318 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 9319 InitializedEntity Entity = 9320 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 9321 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 9322 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 9323 if (Init.isInvalid()) 9324 return Init; 9325 RHSExpr = Init.get(); 9326 } 9327 9328 ExprResult LHS = LHSExpr, RHS = RHSExpr; 9329 QualType ResultTy; // Result type of the binary operator. 9330 // The following two variables are used for compound assignment operators 9331 QualType CompLHSTy; // Type of LHS after promotions for computation 9332 QualType CompResultTy; // Type of computation result 9333 ExprValueKind VK = VK_RValue; 9334 ExprObjectKind OK = OK_Ordinary; 9335 9336 switch (Opc) { 9337 case BO_Assign: 9338 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 9339 if (getLangOpts().CPlusPlus && 9340 LHS.get()->getObjectKind() != OK_ObjCProperty) { 9341 VK = LHS.get()->getValueKind(); 9342 OK = LHS.get()->getObjectKind(); 9343 } 9344 if (!ResultTy.isNull()) 9345 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 9346 break; 9347 case BO_PtrMemD: 9348 case BO_PtrMemI: 9349 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 9350 Opc == BO_PtrMemI); 9351 break; 9352 case BO_Mul: 9353 case BO_Div: 9354 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 9355 Opc == BO_Div); 9356 break; 9357 case BO_Rem: 9358 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 9359 break; 9360 case BO_Add: 9361 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 9362 break; 9363 case BO_Sub: 9364 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 9365 break; 9366 case BO_Shl: 9367 case BO_Shr: 9368 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 9369 break; 9370 case BO_LE: 9371 case BO_LT: 9372 case BO_GE: 9373 case BO_GT: 9374 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 9375 break; 9376 case BO_EQ: 9377 case BO_NE: 9378 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 9379 break; 9380 case BO_And: 9381 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 9382 case BO_Xor: 9383 case BO_Or: 9384 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 9385 break; 9386 case BO_LAnd: 9387 case BO_LOr: 9388 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 9389 break; 9390 case BO_MulAssign: 9391 case BO_DivAssign: 9392 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 9393 Opc == BO_DivAssign); 9394 CompLHSTy = CompResultTy; 9395 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9396 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9397 break; 9398 case BO_RemAssign: 9399 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 9400 CompLHSTy = CompResultTy; 9401 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9402 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9403 break; 9404 case BO_AddAssign: 9405 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 9406 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9407 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9408 break; 9409 case BO_SubAssign: 9410 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 9411 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9412 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9413 break; 9414 case BO_ShlAssign: 9415 case BO_ShrAssign: 9416 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 9417 CompLHSTy = CompResultTy; 9418 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9419 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9420 break; 9421 case BO_AndAssign: 9422 case BO_OrAssign: // fallthrough 9423 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 9424 case BO_XorAssign: 9425 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 9426 CompLHSTy = CompResultTy; 9427 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 9428 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 9429 break; 9430 case BO_Comma: 9431 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 9432 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 9433 VK = RHS.get()->getValueKind(); 9434 OK = RHS.get()->getObjectKind(); 9435 } 9436 break; 9437 } 9438 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 9439 return ExprError(); 9440 9441 // Check for array bounds violations for both sides of the BinaryOperator 9442 CheckArrayAccess(LHS.get()); 9443 CheckArrayAccess(RHS.get()); 9444 9445 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 9446 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 9447 &Context.Idents.get("object_setClass"), 9448 SourceLocation(), LookupOrdinaryName); 9449 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 9450 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 9451 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 9452 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 9453 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 9454 FixItHint::CreateInsertion(RHSLocEnd, ")"); 9455 } 9456 else 9457 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 9458 } 9459 else if (const ObjCIvarRefExpr *OIRE = 9460 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 9461 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 9462 9463 if (CompResultTy.isNull()) 9464 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 9465 OK, OpLoc, FPFeatures.fp_contract); 9466 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 9467 OK_ObjCProperty) { 9468 VK = VK_LValue; 9469 OK = LHS.get()->getObjectKind(); 9470 } 9471 return new (Context) CompoundAssignOperator( 9472 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 9473 OpLoc, FPFeatures.fp_contract); 9474 } 9475 9476 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 9477 /// operators are mixed in a way that suggests that the programmer forgot that 9478 /// comparison operators have higher precedence. The most typical example of 9479 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 9480 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 9481 SourceLocation OpLoc, Expr *LHSExpr, 9482 Expr *RHSExpr) { 9483 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 9484 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 9485 9486 // Check that one of the sides is a comparison operator. 9487 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 9488 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 9489 if (!isLeftComp && !isRightComp) 9490 return; 9491 9492 // Bitwise operations are sometimes used as eager logical ops. 9493 // Don't diagnose this. 9494 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 9495 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 9496 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise)) 9497 return; 9498 9499 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 9500 OpLoc) 9501 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 9502 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 9503 SourceRange ParensRange = isLeftComp ? 9504 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 9505 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 9506 9507 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 9508 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 9509 SuggestParentheses(Self, OpLoc, 9510 Self.PDiag(diag::note_precedence_silence) << OpStr, 9511 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 9512 SuggestParentheses(Self, OpLoc, 9513 Self.PDiag(diag::note_precedence_bitwise_first) 9514 << BinaryOperator::getOpcodeStr(Opc), 9515 ParensRange); 9516 } 9517 9518 /// \brief It accepts a '&' expr that is inside a '|' one. 9519 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression 9520 /// in parentheses. 9521 static void 9522 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 9523 BinaryOperator *Bop) { 9524 assert(Bop->getOpcode() == BO_And); 9525 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 9526 << Bop->getSourceRange() << OpLoc; 9527 SuggestParentheses(Self, Bop->getOperatorLoc(), 9528 Self.PDiag(diag::note_precedence_silence) 9529 << Bop->getOpcodeStr(), 9530 Bop->getSourceRange()); 9531 } 9532 9533 /// \brief It accepts a '&&' expr that is inside a '||' one. 9534 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 9535 /// in parentheses. 9536 static void 9537 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 9538 BinaryOperator *Bop) { 9539 assert(Bop->getOpcode() == BO_LAnd); 9540 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 9541 << Bop->getSourceRange() << OpLoc; 9542 SuggestParentheses(Self, Bop->getOperatorLoc(), 9543 Self.PDiag(diag::note_precedence_silence) 9544 << Bop->getOpcodeStr(), 9545 Bop->getSourceRange()); 9546 } 9547 9548 /// \brief Returns true if the given expression can be evaluated as a constant 9549 /// 'true'. 9550 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 9551 bool Res; 9552 return !E->isValueDependent() && 9553 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 9554 } 9555 9556 /// \brief Returns true if the given expression can be evaluated as a constant 9557 /// 'false'. 9558 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 9559 bool Res; 9560 return !E->isValueDependent() && 9561 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 9562 } 9563 9564 /// \brief Look for '&&' in the left hand of a '||' expr. 9565 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 9566 Expr *LHSExpr, Expr *RHSExpr) { 9567 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 9568 if (Bop->getOpcode() == BO_LAnd) { 9569 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 9570 if (EvaluatesAsFalse(S, RHSExpr)) 9571 return; 9572 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 9573 if (!EvaluatesAsTrue(S, Bop->getLHS())) 9574 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 9575 } else if (Bop->getOpcode() == BO_LOr) { 9576 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 9577 // If it's "a || b && 1 || c" we didn't warn earlier for 9578 // "a || b && 1", but warn now. 9579 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 9580 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 9581 } 9582 } 9583 } 9584 } 9585 9586 /// \brief Look for '&&' in the right hand of a '||' expr. 9587 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 9588 Expr *LHSExpr, Expr *RHSExpr) { 9589 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 9590 if (Bop->getOpcode() == BO_LAnd) { 9591 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 9592 if (EvaluatesAsFalse(S, LHSExpr)) 9593 return; 9594 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 9595 if (!EvaluatesAsTrue(S, Bop->getRHS())) 9596 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 9597 } 9598 } 9599 } 9600 9601 /// \brief Look for '&' in the left or right hand of a '|' expr. 9602 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 9603 Expr *OrArg) { 9604 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 9605 if (Bop->getOpcode() == BO_And) 9606 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 9607 } 9608 } 9609 9610 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 9611 Expr *SubExpr, StringRef Shift) { 9612 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 9613 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 9614 StringRef Op = Bop->getOpcodeStr(); 9615 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 9616 << Bop->getSourceRange() << OpLoc << Shift << Op; 9617 SuggestParentheses(S, Bop->getOperatorLoc(), 9618 S.PDiag(diag::note_precedence_silence) << Op, 9619 Bop->getSourceRange()); 9620 } 9621 } 9622 } 9623 9624 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 9625 Expr *LHSExpr, Expr *RHSExpr) { 9626 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 9627 if (!OCE) 9628 return; 9629 9630 FunctionDecl *FD = OCE->getDirectCallee(); 9631 if (!FD || !FD->isOverloadedOperator()) 9632 return; 9633 9634 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 9635 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 9636 return; 9637 9638 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 9639 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 9640 << (Kind == OO_LessLess); 9641 SuggestParentheses(S, OCE->getOperatorLoc(), 9642 S.PDiag(diag::note_precedence_silence) 9643 << (Kind == OO_LessLess ? "<<" : ">>"), 9644 OCE->getSourceRange()); 9645 SuggestParentheses(S, OpLoc, 9646 S.PDiag(diag::note_evaluate_comparison_first), 9647 SourceRange(OCE->getArg(1)->getLocStart(), 9648 RHSExpr->getLocEnd())); 9649 } 9650 9651 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 9652 /// precedence. 9653 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 9654 SourceLocation OpLoc, Expr *LHSExpr, 9655 Expr *RHSExpr){ 9656 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 9657 if (BinaryOperator::isBitwiseOp(Opc)) 9658 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 9659 9660 // Diagnose "arg1 & arg2 | arg3" 9661 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9662 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 9663 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 9664 } 9665 9666 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 9667 // We don't warn for 'assert(a || b && "bad")' since this is safe. 9668 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 9669 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 9670 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 9671 } 9672 9673 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 9674 || Opc == BO_Shr) { 9675 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 9676 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 9677 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 9678 } 9679 9680 // Warn on overloaded shift operators and comparisons, such as: 9681 // cout << 5 == 4; 9682 if (BinaryOperator::isComparisonOp(Opc)) 9683 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 9684 } 9685 9686 // Binary Operators. 'Tok' is the token for the operator. 9687 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 9688 tok::TokenKind Kind, 9689 Expr *LHSExpr, Expr *RHSExpr) { 9690 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 9691 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 9692 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 9693 9694 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 9695 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 9696 9697 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 9698 } 9699 9700 /// Build an overloaded binary operator expression in the given scope. 9701 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 9702 BinaryOperatorKind Opc, 9703 Expr *LHS, Expr *RHS) { 9704 // Find all of the overloaded operators visible from this 9705 // point. We perform both an operator-name lookup from the local 9706 // scope and an argument-dependent lookup based on the types of 9707 // the arguments. 9708 UnresolvedSet<16> Functions; 9709 OverloadedOperatorKind OverOp 9710 = BinaryOperator::getOverloadedOperator(Opc); 9711 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 9712 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 9713 RHS->getType(), Functions); 9714 9715 // Build the (potentially-overloaded, potentially-dependent) 9716 // binary operation. 9717 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 9718 } 9719 9720 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 9721 BinaryOperatorKind Opc, 9722 Expr *LHSExpr, Expr *RHSExpr) { 9723 // We want to end up calling one of checkPseudoObjectAssignment 9724 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 9725 // both expressions are overloadable or either is type-dependent), 9726 // or CreateBuiltinBinOp (in any other case). We also want to get 9727 // any placeholder types out of the way. 9728 9729 // Handle pseudo-objects in the LHS. 9730 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 9731 // Assignments with a pseudo-object l-value need special analysis. 9732 if (pty->getKind() == BuiltinType::PseudoObject && 9733 BinaryOperator::isAssignmentOp(Opc)) 9734 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 9735 9736 // Don't resolve overloads if the other type is overloadable. 9737 if (pty->getKind() == BuiltinType::Overload) { 9738 // We can't actually test that if we still have a placeholder, 9739 // though. Fortunately, none of the exceptions we see in that 9740 // code below are valid when the LHS is an overload set. Note 9741 // that an overload set can be dependently-typed, but it never 9742 // instantiates to having an overloadable type. 9743 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9744 if (resolvedRHS.isInvalid()) return ExprError(); 9745 RHSExpr = resolvedRHS.get(); 9746 9747 if (RHSExpr->isTypeDependent() || 9748 RHSExpr->getType()->isOverloadableType()) 9749 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9750 } 9751 9752 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 9753 if (LHS.isInvalid()) return ExprError(); 9754 LHSExpr = LHS.get(); 9755 } 9756 9757 // Handle pseudo-objects in the RHS. 9758 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 9759 // An overload in the RHS can potentially be resolved by the type 9760 // being assigned to. 9761 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 9762 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9763 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9764 9765 if (LHSExpr->getType()->isOverloadableType()) 9766 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9767 9768 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9769 } 9770 9771 // Don't resolve overloads if the other type is overloadable. 9772 if (pty->getKind() == BuiltinType::Overload && 9773 LHSExpr->getType()->isOverloadableType()) 9774 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9775 9776 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 9777 if (!resolvedRHS.isUsable()) return ExprError(); 9778 RHSExpr = resolvedRHS.get(); 9779 } 9780 9781 if (getLangOpts().CPlusPlus) { 9782 // If either expression is type-dependent, always build an 9783 // overloaded op. 9784 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 9785 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9786 9787 // Otherwise, build an overloaded op if either expression has an 9788 // overloadable type. 9789 if (LHSExpr->getType()->isOverloadableType() || 9790 RHSExpr->getType()->isOverloadableType()) 9791 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 9792 } 9793 9794 // Build a built-in binary operation. 9795 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 9796 } 9797 9798 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 9799 UnaryOperatorKind Opc, 9800 Expr *InputExpr) { 9801 ExprResult Input = InputExpr; 9802 ExprValueKind VK = VK_RValue; 9803 ExprObjectKind OK = OK_Ordinary; 9804 QualType resultType; 9805 switch (Opc) { 9806 case UO_PreInc: 9807 case UO_PreDec: 9808 case UO_PostInc: 9809 case UO_PostDec: 9810 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 9811 OpLoc, 9812 Opc == UO_PreInc || 9813 Opc == UO_PostInc, 9814 Opc == UO_PreInc || 9815 Opc == UO_PreDec); 9816 break; 9817 case UO_AddrOf: 9818 resultType = CheckAddressOfOperand(Input, OpLoc); 9819 break; 9820 case UO_Deref: { 9821 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 9822 if (Input.isInvalid()) return ExprError(); 9823 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 9824 break; 9825 } 9826 case UO_Plus: 9827 case UO_Minus: 9828 Input = UsualUnaryConversions(Input.get()); 9829 if (Input.isInvalid()) return ExprError(); 9830 resultType = Input.get()->getType(); 9831 if (resultType->isDependentType()) 9832 break; 9833 if (resultType->isArithmeticType() || // C99 6.5.3.3p1 9834 resultType->isVectorType()) 9835 break; 9836 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 9837 Opc == UO_Plus && 9838 resultType->isPointerType()) 9839 break; 9840 9841 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9842 << resultType << Input.get()->getSourceRange()); 9843 9844 case UO_Not: // bitwise complement 9845 Input = UsualUnaryConversions(Input.get()); 9846 if (Input.isInvalid()) 9847 return ExprError(); 9848 resultType = Input.get()->getType(); 9849 if (resultType->isDependentType()) 9850 break; 9851 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 9852 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 9853 // C99 does not support '~' for complex conjugation. 9854 Diag(OpLoc, diag::ext_integer_complement_complex) 9855 << resultType << Input.get()->getSourceRange(); 9856 else if (resultType->hasIntegerRepresentation()) 9857 break; 9858 else if (resultType->isExtVectorType()) { 9859 if (Context.getLangOpts().OpenCL) { 9860 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 9861 // on vector float types. 9862 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9863 if (!T->isIntegerType()) 9864 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9865 << resultType << Input.get()->getSourceRange()); 9866 } 9867 break; 9868 } else { 9869 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9870 << resultType << Input.get()->getSourceRange()); 9871 } 9872 break; 9873 9874 case UO_LNot: // logical negation 9875 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 9876 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 9877 if (Input.isInvalid()) return ExprError(); 9878 resultType = Input.get()->getType(); 9879 9880 // Though we still have to promote half FP to float... 9881 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 9882 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 9883 resultType = Context.FloatTy; 9884 } 9885 9886 if (resultType->isDependentType()) 9887 break; 9888 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 9889 // C99 6.5.3.3p1: ok, fallthrough; 9890 if (Context.getLangOpts().CPlusPlus) { 9891 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 9892 // operand contextually converted to bool. 9893 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 9894 ScalarTypeToBooleanCastKind(resultType)); 9895 } else if (Context.getLangOpts().OpenCL && 9896 Context.getLangOpts().OpenCLVersion < 120) { 9897 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9898 // operate on scalar float types. 9899 if (!resultType->isIntegerType()) 9900 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9901 << resultType << Input.get()->getSourceRange()); 9902 } 9903 } else if (resultType->isExtVectorType()) { 9904 if (Context.getLangOpts().OpenCL && 9905 Context.getLangOpts().OpenCLVersion < 120) { 9906 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 9907 // operate on vector float types. 9908 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 9909 if (!T->isIntegerType()) 9910 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9911 << resultType << Input.get()->getSourceRange()); 9912 } 9913 // Vector logical not returns the signed variant of the operand type. 9914 resultType = GetSignedVectorType(resultType); 9915 break; 9916 } else { 9917 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 9918 << resultType << Input.get()->getSourceRange()); 9919 } 9920 9921 // LNot always has type int. C99 6.5.3.3p5. 9922 // In C++, it's bool. C++ 5.3.1p8 9923 resultType = Context.getLogicalOperationType(); 9924 break; 9925 case UO_Real: 9926 case UO_Imag: 9927 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 9928 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 9929 // complex l-values to ordinary l-values and all other values to r-values. 9930 if (Input.isInvalid()) return ExprError(); 9931 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 9932 if (Input.get()->getValueKind() != VK_RValue && 9933 Input.get()->getObjectKind() == OK_Ordinary) 9934 VK = Input.get()->getValueKind(); 9935 } else if (!getLangOpts().CPlusPlus) { 9936 // In C, a volatile scalar is read by __imag. In C++, it is not. 9937 Input = DefaultLvalueConversion(Input.get()); 9938 } 9939 break; 9940 case UO_Extension: 9941 resultType = Input.get()->getType(); 9942 VK = Input.get()->getValueKind(); 9943 OK = Input.get()->getObjectKind(); 9944 break; 9945 } 9946 if (resultType.isNull() || Input.isInvalid()) 9947 return ExprError(); 9948 9949 // Check for array bounds violations in the operand of the UnaryOperator, 9950 // except for the '*' and '&' operators that have to be handled specially 9951 // by CheckArrayAccess (as there are special cases like &array[arraysize] 9952 // that are explicitly defined as valid by the standard). 9953 if (Opc != UO_AddrOf && Opc != UO_Deref) 9954 CheckArrayAccess(Input.get()); 9955 9956 return new (Context) 9957 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 9958 } 9959 9960 /// \brief Determine whether the given expression is a qualified member 9961 /// access expression, of a form that could be turned into a pointer to member 9962 /// with the address-of operator. 9963 static bool isQualifiedMemberAccess(Expr *E) { 9964 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9965 if (!DRE->getQualifier()) 9966 return false; 9967 9968 ValueDecl *VD = DRE->getDecl(); 9969 if (!VD->isCXXClassMember()) 9970 return false; 9971 9972 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 9973 return true; 9974 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 9975 return Method->isInstance(); 9976 9977 return false; 9978 } 9979 9980 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 9981 if (!ULE->getQualifier()) 9982 return false; 9983 9984 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 9985 DEnd = ULE->decls_end(); 9986 D != DEnd; ++D) { 9987 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 9988 if (Method->isInstance()) 9989 return true; 9990 } else { 9991 // Overload set does not contain methods. 9992 break; 9993 } 9994 } 9995 9996 return false; 9997 } 9998 9999 return false; 10000 } 10001 10002 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 10003 UnaryOperatorKind Opc, Expr *Input) { 10004 // First things first: handle placeholders so that the 10005 // overloaded-operator check considers the right type. 10006 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 10007 // Increment and decrement of pseudo-object references. 10008 if (pty->getKind() == BuiltinType::PseudoObject && 10009 UnaryOperator::isIncrementDecrementOp(Opc)) 10010 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 10011 10012 // extension is always a builtin operator. 10013 if (Opc == UO_Extension) 10014 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10015 10016 // & gets special logic for several kinds of placeholder. 10017 // The builtin code knows what to do. 10018 if (Opc == UO_AddrOf && 10019 (pty->getKind() == BuiltinType::Overload || 10020 pty->getKind() == BuiltinType::UnknownAny || 10021 pty->getKind() == BuiltinType::BoundMember)) 10022 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10023 10024 // Anything else needs to be handled now. 10025 ExprResult Result = CheckPlaceholderExpr(Input); 10026 if (Result.isInvalid()) return ExprError(); 10027 Input = Result.get(); 10028 } 10029 10030 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 10031 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 10032 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 10033 // Find all of the overloaded operators visible from this 10034 // point. We perform both an operator-name lookup from the local 10035 // scope and an argument-dependent lookup based on the types of 10036 // the arguments. 10037 UnresolvedSet<16> Functions; 10038 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 10039 if (S && OverOp != OO_None) 10040 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 10041 Functions); 10042 10043 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 10044 } 10045 10046 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10047 } 10048 10049 // Unary Operators. 'Tok' is the token for the operator. 10050 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 10051 tok::TokenKind Op, Expr *Input) { 10052 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 10053 } 10054 10055 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 10056 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 10057 LabelDecl *TheDecl) { 10058 TheDecl->markUsed(Context); 10059 // Create the AST node. The address of a label always has type 'void*'. 10060 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 10061 Context.getPointerType(Context.VoidTy)); 10062 } 10063 10064 /// Given the last statement in a statement-expression, check whether 10065 /// the result is a producing expression (like a call to an 10066 /// ns_returns_retained function) and, if so, rebuild it to hoist the 10067 /// release out of the full-expression. Otherwise, return null. 10068 /// Cannot fail. 10069 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 10070 // Should always be wrapped with one of these. 10071 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 10072 if (!cleanups) return nullptr; 10073 10074 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 10075 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 10076 return nullptr; 10077 10078 // Splice out the cast. This shouldn't modify any interesting 10079 // features of the statement. 10080 Expr *producer = cast->getSubExpr(); 10081 assert(producer->getType() == cast->getType()); 10082 assert(producer->getValueKind() == cast->getValueKind()); 10083 cleanups->setSubExpr(producer); 10084 return cleanups; 10085 } 10086 10087 void Sema::ActOnStartStmtExpr() { 10088 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 10089 } 10090 10091 void Sema::ActOnStmtExprError() { 10092 // Note that function is also called by TreeTransform when leaving a 10093 // StmtExpr scope without rebuilding anything. 10094 10095 DiscardCleanupsInEvaluationContext(); 10096 PopExpressionEvaluationContext(); 10097 } 10098 10099 ExprResult 10100 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 10101 SourceLocation RPLoc) { // "({..})" 10102 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 10103 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 10104 10105 if (hasAnyUnrecoverableErrorsInThisFunction()) 10106 DiscardCleanupsInEvaluationContext(); 10107 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 10108 PopExpressionEvaluationContext(); 10109 10110 bool isFileScope 10111 = (getCurFunctionOrMethodDecl() == nullptr) && (getCurBlock() == nullptr); 10112 if (isFileScope) 10113 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope)); 10114 10115 // FIXME: there are a variety of strange constraints to enforce here, for 10116 // example, it is not possible to goto into a stmt expression apparently. 10117 // More semantic analysis is needed. 10118 10119 // If there are sub-stmts in the compound stmt, take the type of the last one 10120 // as the type of the stmtexpr. 10121 QualType Ty = Context.VoidTy; 10122 bool StmtExprMayBindToTemp = false; 10123 if (!Compound->body_empty()) { 10124 Stmt *LastStmt = Compound->body_back(); 10125 LabelStmt *LastLabelStmt = nullptr; 10126 // If LastStmt is a label, skip down through into the body. 10127 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 10128 LastLabelStmt = Label; 10129 LastStmt = Label->getSubStmt(); 10130 } 10131 10132 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 10133 // Do function/array conversion on the last expression, but not 10134 // lvalue-to-rvalue. However, initialize an unqualified type. 10135 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 10136 if (LastExpr.isInvalid()) 10137 return ExprError(); 10138 Ty = LastExpr.get()->getType().getUnqualifiedType(); 10139 10140 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 10141 // In ARC, if the final expression ends in a consume, splice 10142 // the consume out and bind it later. In the alternate case 10143 // (when dealing with a retainable type), the result 10144 // initialization will create a produce. In both cases the 10145 // result will be +1, and we'll need to balance that out with 10146 // a bind. 10147 if (Expr *rebuiltLastStmt 10148 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 10149 LastExpr = rebuiltLastStmt; 10150 } else { 10151 LastExpr = PerformCopyInitialization( 10152 InitializedEntity::InitializeResult(LPLoc, 10153 Ty, 10154 false), 10155 SourceLocation(), 10156 LastExpr); 10157 } 10158 10159 if (LastExpr.isInvalid()) 10160 return ExprError(); 10161 if (LastExpr.get() != nullptr) { 10162 if (!LastLabelStmt) 10163 Compound->setLastStmt(LastExpr.get()); 10164 else 10165 LastLabelStmt->setSubStmt(LastExpr.get()); 10166 StmtExprMayBindToTemp = true; 10167 } 10168 } 10169 } 10170 } 10171 10172 // FIXME: Check that expression type is complete/non-abstract; statement 10173 // expressions are not lvalues. 10174 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 10175 if (StmtExprMayBindToTemp) 10176 return MaybeBindToTemporary(ResStmtExpr); 10177 return ResStmtExpr; 10178 } 10179 10180 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 10181 TypeSourceInfo *TInfo, 10182 OffsetOfComponent *CompPtr, 10183 unsigned NumComponents, 10184 SourceLocation RParenLoc) { 10185 QualType ArgTy = TInfo->getType(); 10186 bool Dependent = ArgTy->isDependentType(); 10187 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 10188 10189 // We must have at least one component that refers to the type, and the first 10190 // one is known to be a field designator. Verify that the ArgTy represents 10191 // a struct/union/class. 10192 if (!Dependent && !ArgTy->isRecordType()) 10193 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 10194 << ArgTy << TypeRange); 10195 10196 // Type must be complete per C99 7.17p3 because a declaring a variable 10197 // with an incomplete type would be ill-formed. 10198 if (!Dependent 10199 && RequireCompleteType(BuiltinLoc, ArgTy, 10200 diag::err_offsetof_incomplete_type, TypeRange)) 10201 return ExprError(); 10202 10203 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 10204 // GCC extension, diagnose them. 10205 // FIXME: This diagnostic isn't actually visible because the location is in 10206 // a system header! 10207 if (NumComponents != 1) 10208 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 10209 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 10210 10211 bool DidWarnAboutNonPOD = false; 10212 QualType CurrentType = ArgTy; 10213 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 10214 SmallVector<OffsetOfNode, 4> Comps; 10215 SmallVector<Expr*, 4> Exprs; 10216 for (unsigned i = 0; i != NumComponents; ++i) { 10217 const OffsetOfComponent &OC = CompPtr[i]; 10218 if (OC.isBrackets) { 10219 // Offset of an array sub-field. TODO: Should we allow vector elements? 10220 if (!CurrentType->isDependentType()) { 10221 const ArrayType *AT = Context.getAsArrayType(CurrentType); 10222 if(!AT) 10223 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 10224 << CurrentType); 10225 CurrentType = AT->getElementType(); 10226 } else 10227 CurrentType = Context.DependentTy; 10228 10229 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 10230 if (IdxRval.isInvalid()) 10231 return ExprError(); 10232 Expr *Idx = IdxRval.get(); 10233 10234 // The expression must be an integral expression. 10235 // FIXME: An integral constant expression? 10236 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 10237 !Idx->getType()->isIntegerType()) 10238 return ExprError(Diag(Idx->getLocStart(), 10239 diag::err_typecheck_subscript_not_integer) 10240 << Idx->getSourceRange()); 10241 10242 // Record this array index. 10243 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 10244 Exprs.push_back(Idx); 10245 continue; 10246 } 10247 10248 // Offset of a field. 10249 if (CurrentType->isDependentType()) { 10250 // We have the offset of a field, but we can't look into the dependent 10251 // type. Just record the identifier of the field. 10252 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 10253 CurrentType = Context.DependentTy; 10254 continue; 10255 } 10256 10257 // We need to have a complete type to look into. 10258 if (RequireCompleteType(OC.LocStart, CurrentType, 10259 diag::err_offsetof_incomplete_type)) 10260 return ExprError(); 10261 10262 // Look for the designated field. 10263 const RecordType *RC = CurrentType->getAs<RecordType>(); 10264 if (!RC) 10265 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 10266 << CurrentType); 10267 RecordDecl *RD = RC->getDecl(); 10268 10269 // C++ [lib.support.types]p5: 10270 // The macro offsetof accepts a restricted set of type arguments in this 10271 // International Standard. type shall be a POD structure or a POD union 10272 // (clause 9). 10273 // C++11 [support.types]p4: 10274 // If type is not a standard-layout class (Clause 9), the results are 10275 // undefined. 10276 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 10277 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 10278 unsigned DiagID = 10279 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 10280 : diag::ext_offsetof_non_pod_type; 10281 10282 if (!IsSafe && !DidWarnAboutNonPOD && 10283 DiagRuntimeBehavior(BuiltinLoc, nullptr, 10284 PDiag(DiagID) 10285 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 10286 << CurrentType)) 10287 DidWarnAboutNonPOD = true; 10288 } 10289 10290 // Look for the field. 10291 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 10292 LookupQualifiedName(R, RD); 10293 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 10294 IndirectFieldDecl *IndirectMemberDecl = nullptr; 10295 if (!MemberDecl) { 10296 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 10297 MemberDecl = IndirectMemberDecl->getAnonField(); 10298 } 10299 10300 if (!MemberDecl) 10301 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 10302 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 10303 OC.LocEnd)); 10304 10305 // C99 7.17p3: 10306 // (If the specified member is a bit-field, the behavior is undefined.) 10307 // 10308 // We diagnose this as an error. 10309 if (MemberDecl->isBitField()) { 10310 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 10311 << MemberDecl->getDeclName() 10312 << SourceRange(BuiltinLoc, RParenLoc); 10313 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 10314 return ExprError(); 10315 } 10316 10317 RecordDecl *Parent = MemberDecl->getParent(); 10318 if (IndirectMemberDecl) 10319 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 10320 10321 // If the member was found in a base class, introduce OffsetOfNodes for 10322 // the base class indirections. 10323 CXXBasePaths Paths; 10324 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 10325 if (Paths.getDetectedVirtual()) { 10326 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 10327 << MemberDecl->getDeclName() 10328 << SourceRange(BuiltinLoc, RParenLoc); 10329 return ExprError(); 10330 } 10331 10332 CXXBasePath &Path = Paths.front(); 10333 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 10334 B != BEnd; ++B) 10335 Comps.push_back(OffsetOfNode(B->Base)); 10336 } 10337 10338 if (IndirectMemberDecl) { 10339 for (auto *FI : IndirectMemberDecl->chain()) { 10340 assert(isa<FieldDecl>(FI)); 10341 Comps.push_back(OffsetOfNode(OC.LocStart, 10342 cast<FieldDecl>(FI), OC.LocEnd)); 10343 } 10344 } else 10345 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 10346 10347 CurrentType = MemberDecl->getType().getNonReferenceType(); 10348 } 10349 10350 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 10351 Comps, Exprs, RParenLoc); 10352 } 10353 10354 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 10355 SourceLocation BuiltinLoc, 10356 SourceLocation TypeLoc, 10357 ParsedType ParsedArgTy, 10358 OffsetOfComponent *CompPtr, 10359 unsigned NumComponents, 10360 SourceLocation RParenLoc) { 10361 10362 TypeSourceInfo *ArgTInfo; 10363 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 10364 if (ArgTy.isNull()) 10365 return ExprError(); 10366 10367 if (!ArgTInfo) 10368 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 10369 10370 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 10371 RParenLoc); 10372 } 10373 10374 10375 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 10376 Expr *CondExpr, 10377 Expr *LHSExpr, Expr *RHSExpr, 10378 SourceLocation RPLoc) { 10379 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 10380 10381 ExprValueKind VK = VK_RValue; 10382 ExprObjectKind OK = OK_Ordinary; 10383 QualType resType; 10384 bool ValueDependent = false; 10385 bool CondIsTrue = false; 10386 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 10387 resType = Context.DependentTy; 10388 ValueDependent = true; 10389 } else { 10390 // The conditional expression is required to be a constant expression. 10391 llvm::APSInt condEval(32); 10392 ExprResult CondICE 10393 = VerifyIntegerConstantExpression(CondExpr, &condEval, 10394 diag::err_typecheck_choose_expr_requires_constant, false); 10395 if (CondICE.isInvalid()) 10396 return ExprError(); 10397 CondExpr = CondICE.get(); 10398 CondIsTrue = condEval.getZExtValue(); 10399 10400 // If the condition is > zero, then the AST type is the same as the LSHExpr. 10401 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 10402 10403 resType = ActiveExpr->getType(); 10404 ValueDependent = ActiveExpr->isValueDependent(); 10405 VK = ActiveExpr->getValueKind(); 10406 OK = ActiveExpr->getObjectKind(); 10407 } 10408 10409 return new (Context) 10410 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 10411 CondIsTrue, resType->isDependentType(), ValueDependent); 10412 } 10413 10414 //===----------------------------------------------------------------------===// 10415 // Clang Extensions. 10416 //===----------------------------------------------------------------------===// 10417 10418 /// ActOnBlockStart - This callback is invoked when a block literal is started. 10419 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 10420 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 10421 10422 if (LangOpts.CPlusPlus) { 10423 Decl *ManglingContextDecl; 10424 if (MangleNumberingContext *MCtx = 10425 getCurrentMangleNumberContext(Block->getDeclContext(), 10426 ManglingContextDecl)) { 10427 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 10428 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 10429 } 10430 } 10431 10432 PushBlockScope(CurScope, Block); 10433 CurContext->addDecl(Block); 10434 if (CurScope) 10435 PushDeclContext(CurScope, Block); 10436 else 10437 CurContext = Block; 10438 10439 getCurBlock()->HasImplicitReturnType = true; 10440 10441 // Enter a new evaluation context to insulate the block from any 10442 // cleanups from the enclosing full-expression. 10443 PushExpressionEvaluationContext(PotentiallyEvaluated); 10444 } 10445 10446 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 10447 Scope *CurScope) { 10448 assert(ParamInfo.getIdentifier() == nullptr && 10449 "block-id should have no identifier!"); 10450 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 10451 BlockScopeInfo *CurBlock = getCurBlock(); 10452 10453 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 10454 QualType T = Sig->getType(); 10455 10456 // FIXME: We should allow unexpanded parameter packs here, but that would, 10457 // in turn, make the block expression contain unexpanded parameter packs. 10458 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 10459 // Drop the parameters. 10460 FunctionProtoType::ExtProtoInfo EPI; 10461 EPI.HasTrailingReturn = false; 10462 EPI.TypeQuals |= DeclSpec::TQ_const; 10463 T = Context.getFunctionType(Context.DependentTy, None, EPI); 10464 Sig = Context.getTrivialTypeSourceInfo(T); 10465 } 10466 10467 // GetTypeForDeclarator always produces a function type for a block 10468 // literal signature. Furthermore, it is always a FunctionProtoType 10469 // unless the function was written with a typedef. 10470 assert(T->isFunctionType() && 10471 "GetTypeForDeclarator made a non-function block signature"); 10472 10473 // Look for an explicit signature in that function type. 10474 FunctionProtoTypeLoc ExplicitSignature; 10475 10476 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 10477 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 10478 10479 // Check whether that explicit signature was synthesized by 10480 // GetTypeForDeclarator. If so, don't save that as part of the 10481 // written signature. 10482 if (ExplicitSignature.getLocalRangeBegin() == 10483 ExplicitSignature.getLocalRangeEnd()) { 10484 // This would be much cheaper if we stored TypeLocs instead of 10485 // TypeSourceInfos. 10486 TypeLoc Result = ExplicitSignature.getReturnLoc(); 10487 unsigned Size = Result.getFullDataSize(); 10488 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 10489 Sig->getTypeLoc().initializeFullCopy(Result, Size); 10490 10491 ExplicitSignature = FunctionProtoTypeLoc(); 10492 } 10493 } 10494 10495 CurBlock->TheDecl->setSignatureAsWritten(Sig); 10496 CurBlock->FunctionType = T; 10497 10498 const FunctionType *Fn = T->getAs<FunctionType>(); 10499 QualType RetTy = Fn->getReturnType(); 10500 bool isVariadic = 10501 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 10502 10503 CurBlock->TheDecl->setIsVariadic(isVariadic); 10504 10505 // Context.DependentTy is used as a placeholder for a missing block 10506 // return type. TODO: what should we do with declarators like: 10507 // ^ * { ... } 10508 // If the answer is "apply template argument deduction".... 10509 if (RetTy != Context.DependentTy) { 10510 CurBlock->ReturnType = RetTy; 10511 CurBlock->TheDecl->setBlockMissingReturnType(false); 10512 CurBlock->HasImplicitReturnType = false; 10513 } 10514 10515 // Push block parameters from the declarator if we had them. 10516 SmallVector<ParmVarDecl*, 8> Params; 10517 if (ExplicitSignature) { 10518 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 10519 ParmVarDecl *Param = ExplicitSignature.getParam(I); 10520 if (Param->getIdentifier() == nullptr && 10521 !Param->isImplicit() && 10522 !Param->isInvalidDecl() && 10523 !getLangOpts().CPlusPlus) 10524 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 10525 Params.push_back(Param); 10526 } 10527 10528 // Fake up parameter variables if we have a typedef, like 10529 // ^ fntype { ... } 10530 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 10531 for (const auto &I : Fn->param_types()) { 10532 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 10533 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 10534 Params.push_back(Param); 10535 } 10536 } 10537 10538 // Set the parameters on the block decl. 10539 if (!Params.empty()) { 10540 CurBlock->TheDecl->setParams(Params); 10541 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 10542 CurBlock->TheDecl->param_end(), 10543 /*CheckParameterNames=*/false); 10544 } 10545 10546 // Finally we can process decl attributes. 10547 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 10548 10549 // Put the parameter variables in scope. 10550 for (auto AI : CurBlock->TheDecl->params()) { 10551 AI->setOwningFunction(CurBlock->TheDecl); 10552 10553 // If this has an identifier, add it to the scope stack. 10554 if (AI->getIdentifier()) { 10555 CheckShadow(CurBlock->TheScope, AI); 10556 10557 PushOnScopeChains(AI, CurBlock->TheScope); 10558 } 10559 } 10560 } 10561 10562 /// ActOnBlockError - If there is an error parsing a block, this callback 10563 /// is invoked to pop the information about the block from the action impl. 10564 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 10565 // Leave the expression-evaluation context. 10566 DiscardCleanupsInEvaluationContext(); 10567 PopExpressionEvaluationContext(); 10568 10569 // Pop off CurBlock, handle nested blocks. 10570 PopDeclContext(); 10571 PopFunctionScopeInfo(); 10572 } 10573 10574 /// ActOnBlockStmtExpr - This is called when the body of a block statement 10575 /// literal was successfully completed. ^(int x){...} 10576 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 10577 Stmt *Body, Scope *CurScope) { 10578 // If blocks are disabled, emit an error. 10579 if (!LangOpts.Blocks) 10580 Diag(CaretLoc, diag::err_blocks_disable); 10581 10582 // Leave the expression-evaluation context. 10583 if (hasAnyUnrecoverableErrorsInThisFunction()) 10584 DiscardCleanupsInEvaluationContext(); 10585 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 10586 PopExpressionEvaluationContext(); 10587 10588 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 10589 10590 if (BSI->HasImplicitReturnType) 10591 deduceClosureReturnType(*BSI); 10592 10593 PopDeclContext(); 10594 10595 QualType RetTy = Context.VoidTy; 10596 if (!BSI->ReturnType.isNull()) 10597 RetTy = BSI->ReturnType; 10598 10599 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 10600 QualType BlockTy; 10601 10602 // Set the captured variables on the block. 10603 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 10604 SmallVector<BlockDecl::Capture, 4> Captures; 10605 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 10606 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 10607 if (Cap.isThisCapture()) 10608 continue; 10609 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 10610 Cap.isNested(), Cap.getInitExpr()); 10611 Captures.push_back(NewCap); 10612 } 10613 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(), 10614 BSI->CXXThisCaptureIndex != 0); 10615 10616 // If the user wrote a function type in some form, try to use that. 10617 if (!BSI->FunctionType.isNull()) { 10618 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 10619 10620 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 10621 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 10622 10623 // Turn protoless block types into nullary block types. 10624 if (isa<FunctionNoProtoType>(FTy)) { 10625 FunctionProtoType::ExtProtoInfo EPI; 10626 EPI.ExtInfo = Ext; 10627 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10628 10629 // Otherwise, if we don't need to change anything about the function type, 10630 // preserve its sugar structure. 10631 } else if (FTy->getReturnType() == RetTy && 10632 (!NoReturn || FTy->getNoReturnAttr())) { 10633 BlockTy = BSI->FunctionType; 10634 10635 // Otherwise, make the minimal modifications to the function type. 10636 } else { 10637 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 10638 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10639 EPI.TypeQuals = 0; // FIXME: silently? 10640 EPI.ExtInfo = Ext; 10641 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 10642 } 10643 10644 // If we don't have a function type, just build one from nothing. 10645 } else { 10646 FunctionProtoType::ExtProtoInfo EPI; 10647 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 10648 BlockTy = Context.getFunctionType(RetTy, None, EPI); 10649 } 10650 10651 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 10652 BSI->TheDecl->param_end()); 10653 BlockTy = Context.getBlockPointerType(BlockTy); 10654 10655 // If needed, diagnose invalid gotos and switches in the block. 10656 if (getCurFunction()->NeedsScopeChecking() && 10657 !PP.isCodeCompletionEnabled()) 10658 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 10659 10660 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 10661 10662 // Try to apply the named return value optimization. We have to check again 10663 // if we can do this, though, because blocks keep return statements around 10664 // to deduce an implicit return type. 10665 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 10666 !BSI->TheDecl->isDependentContext()) 10667 computeNRVO(Body, BSI); 10668 10669 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 10670 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 10671 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 10672 10673 // If the block isn't obviously global, i.e. it captures anything at 10674 // all, then we need to do a few things in the surrounding context: 10675 if (Result->getBlockDecl()->hasCaptures()) { 10676 // First, this expression has a new cleanup object. 10677 ExprCleanupObjects.push_back(Result->getBlockDecl()); 10678 ExprNeedsCleanups = true; 10679 10680 // It also gets a branch-protected scope if any of the captured 10681 // variables needs destruction. 10682 for (const auto &CI : Result->getBlockDecl()->captures()) { 10683 const VarDecl *var = CI.getVariable(); 10684 if (var->getType().isDestructedType() != QualType::DK_none) { 10685 getCurFunction()->setHasBranchProtectedScope(); 10686 break; 10687 } 10688 } 10689 } 10690 10691 return Result; 10692 } 10693 10694 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 10695 Expr *E, ParsedType Ty, 10696 SourceLocation RPLoc) { 10697 TypeSourceInfo *TInfo; 10698 GetTypeFromParser(Ty, &TInfo); 10699 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 10700 } 10701 10702 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 10703 Expr *E, TypeSourceInfo *TInfo, 10704 SourceLocation RPLoc) { 10705 Expr *OrigExpr = E; 10706 10707 // Get the va_list type 10708 QualType VaListType = Context.getBuiltinVaListType(); 10709 if (VaListType->isArrayType()) { 10710 // Deal with implicit array decay; for example, on x86-64, 10711 // va_list is an array, but it's supposed to decay to 10712 // a pointer for va_arg. 10713 VaListType = Context.getArrayDecayedType(VaListType); 10714 // Make sure the input expression also decays appropriately. 10715 ExprResult Result = UsualUnaryConversions(E); 10716 if (Result.isInvalid()) 10717 return ExprError(); 10718 E = Result.get(); 10719 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 10720 // If va_list is a record type and we are compiling in C++ mode, 10721 // check the argument using reference binding. 10722 InitializedEntity Entity 10723 = InitializedEntity::InitializeParameter(Context, 10724 Context.getLValueReferenceType(VaListType), false); 10725 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 10726 if (Init.isInvalid()) 10727 return ExprError(); 10728 E = Init.getAs<Expr>(); 10729 } else { 10730 // Otherwise, the va_list argument must be an l-value because 10731 // it is modified by va_arg. 10732 if (!E->isTypeDependent() && 10733 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 10734 return ExprError(); 10735 } 10736 10737 if (!E->isTypeDependent() && 10738 !Context.hasSameType(VaListType, E->getType())) { 10739 return ExprError(Diag(E->getLocStart(), 10740 diag::err_first_argument_to_va_arg_not_of_type_va_list) 10741 << OrigExpr->getType() << E->getSourceRange()); 10742 } 10743 10744 if (!TInfo->getType()->isDependentType()) { 10745 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 10746 diag::err_second_parameter_to_va_arg_incomplete, 10747 TInfo->getTypeLoc())) 10748 return ExprError(); 10749 10750 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 10751 TInfo->getType(), 10752 diag::err_second_parameter_to_va_arg_abstract, 10753 TInfo->getTypeLoc())) 10754 return ExprError(); 10755 10756 if (!TInfo->getType().isPODType(Context)) { 10757 Diag(TInfo->getTypeLoc().getBeginLoc(), 10758 TInfo->getType()->isObjCLifetimeType() 10759 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 10760 : diag::warn_second_parameter_to_va_arg_not_pod) 10761 << TInfo->getType() 10762 << TInfo->getTypeLoc().getSourceRange(); 10763 } 10764 10765 // Check for va_arg where arguments of the given type will be promoted 10766 // (i.e. this va_arg is guaranteed to have undefined behavior). 10767 QualType PromoteType; 10768 if (TInfo->getType()->isPromotableIntegerType()) { 10769 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 10770 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 10771 PromoteType = QualType(); 10772 } 10773 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 10774 PromoteType = Context.DoubleTy; 10775 if (!PromoteType.isNull()) 10776 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 10777 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 10778 << TInfo->getType() 10779 << PromoteType 10780 << TInfo->getTypeLoc().getSourceRange()); 10781 } 10782 10783 QualType T = TInfo->getType().getNonLValueExprType(Context); 10784 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T); 10785 } 10786 10787 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 10788 // The type of __null will be int or long, depending on the size of 10789 // pointers on the target. 10790 QualType Ty; 10791 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 10792 if (pw == Context.getTargetInfo().getIntWidth()) 10793 Ty = Context.IntTy; 10794 else if (pw == Context.getTargetInfo().getLongWidth()) 10795 Ty = Context.LongTy; 10796 else if (pw == Context.getTargetInfo().getLongLongWidth()) 10797 Ty = Context.LongLongTy; 10798 else { 10799 llvm_unreachable("I don't know size of pointer!"); 10800 } 10801 10802 return new (Context) GNUNullExpr(Ty, TokenLoc); 10803 } 10804 10805 bool 10806 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) { 10807 if (!getLangOpts().ObjC1) 10808 return false; 10809 10810 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 10811 if (!PT) 10812 return false; 10813 10814 if (!PT->isObjCIdType()) { 10815 // Check if the destination is the 'NSString' interface. 10816 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 10817 if (!ID || !ID->getIdentifier()->isStr("NSString")) 10818 return false; 10819 } 10820 10821 // Ignore any parens, implicit casts (should only be 10822 // array-to-pointer decays), and not-so-opaque values. The last is 10823 // important for making this trigger for property assignments. 10824 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 10825 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 10826 if (OV->getSourceExpr()) 10827 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 10828 10829 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 10830 if (!SL || !SL->isAscii()) 10831 return false; 10832 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 10833 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 10834 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 10835 return true; 10836 } 10837 10838 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 10839 SourceLocation Loc, 10840 QualType DstType, QualType SrcType, 10841 Expr *SrcExpr, AssignmentAction Action, 10842 bool *Complained) { 10843 if (Complained) 10844 *Complained = false; 10845 10846 // Decode the result (notice that AST's are still created for extensions). 10847 bool CheckInferredResultType = false; 10848 bool isInvalid = false; 10849 unsigned DiagKind = 0; 10850 FixItHint Hint; 10851 ConversionFixItGenerator ConvHints; 10852 bool MayHaveConvFixit = false; 10853 bool MayHaveFunctionDiff = false; 10854 const ObjCInterfaceDecl *IFace = nullptr; 10855 const ObjCProtocolDecl *PDecl = nullptr; 10856 10857 switch (ConvTy) { 10858 case Compatible: 10859 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 10860 return false; 10861 10862 case PointerToInt: 10863 DiagKind = diag::ext_typecheck_convert_pointer_int; 10864 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10865 MayHaveConvFixit = true; 10866 break; 10867 case IntToPointer: 10868 DiagKind = diag::ext_typecheck_convert_int_pointer; 10869 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10870 MayHaveConvFixit = true; 10871 break; 10872 case IncompatiblePointer: 10873 DiagKind = 10874 (Action == AA_Passing_CFAudited ? 10875 diag::err_arc_typecheck_convert_incompatible_pointer : 10876 diag::ext_typecheck_convert_incompatible_pointer); 10877 CheckInferredResultType = DstType->isObjCObjectPointerType() && 10878 SrcType->isObjCObjectPointerType(); 10879 if (Hint.isNull() && !CheckInferredResultType) { 10880 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10881 } 10882 else if (CheckInferredResultType) { 10883 SrcType = SrcType.getUnqualifiedType(); 10884 DstType = DstType.getUnqualifiedType(); 10885 } 10886 MayHaveConvFixit = true; 10887 break; 10888 case IncompatiblePointerSign: 10889 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 10890 break; 10891 case FunctionVoidPointer: 10892 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 10893 break; 10894 case IncompatiblePointerDiscardsQualifiers: { 10895 // Perform array-to-pointer decay if necessary. 10896 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 10897 10898 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 10899 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 10900 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 10901 DiagKind = diag::err_typecheck_incompatible_address_space; 10902 break; 10903 10904 10905 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 10906 DiagKind = diag::err_typecheck_incompatible_ownership; 10907 break; 10908 } 10909 10910 llvm_unreachable("unknown error case for discarding qualifiers!"); 10911 // fallthrough 10912 } 10913 case CompatiblePointerDiscardsQualifiers: 10914 // If the qualifiers lost were because we were applying the 10915 // (deprecated) C++ conversion from a string literal to a char* 10916 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 10917 // Ideally, this check would be performed in 10918 // checkPointerTypesForAssignment. However, that would require a 10919 // bit of refactoring (so that the second argument is an 10920 // expression, rather than a type), which should be done as part 10921 // of a larger effort to fix checkPointerTypesForAssignment for 10922 // C++ semantics. 10923 if (getLangOpts().CPlusPlus && 10924 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 10925 return false; 10926 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 10927 break; 10928 case IncompatibleNestedPointerQualifiers: 10929 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 10930 break; 10931 case IntToBlockPointer: 10932 DiagKind = diag::err_int_to_block_pointer; 10933 break; 10934 case IncompatibleBlockPointer: 10935 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 10936 break; 10937 case IncompatibleObjCQualifiedId: { 10938 if (SrcType->isObjCQualifiedIdType()) { 10939 const ObjCObjectPointerType *srcOPT = 10940 SrcType->getAs<ObjCObjectPointerType>(); 10941 for (auto *srcProto : srcOPT->quals()) { 10942 PDecl = srcProto; 10943 break; 10944 } 10945 if (const ObjCInterfaceType *IFaceT = 10946 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 10947 IFace = IFaceT->getDecl(); 10948 } 10949 else if (DstType->isObjCQualifiedIdType()) { 10950 const ObjCObjectPointerType *dstOPT = 10951 DstType->getAs<ObjCObjectPointerType>(); 10952 for (auto *dstProto : dstOPT->quals()) { 10953 PDecl = dstProto; 10954 break; 10955 } 10956 if (const ObjCInterfaceType *IFaceT = 10957 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 10958 IFace = IFaceT->getDecl(); 10959 } 10960 DiagKind = diag::warn_incompatible_qualified_id; 10961 break; 10962 } 10963 case IncompatibleVectors: 10964 DiagKind = diag::warn_incompatible_vectors; 10965 break; 10966 case IncompatibleObjCWeakRef: 10967 DiagKind = diag::err_arc_weak_unavailable_assign; 10968 break; 10969 case Incompatible: 10970 DiagKind = diag::err_typecheck_convert_incompatible; 10971 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 10972 MayHaveConvFixit = true; 10973 isInvalid = true; 10974 MayHaveFunctionDiff = true; 10975 break; 10976 } 10977 10978 QualType FirstType, SecondType; 10979 switch (Action) { 10980 case AA_Assigning: 10981 case AA_Initializing: 10982 // The destination type comes first. 10983 FirstType = DstType; 10984 SecondType = SrcType; 10985 break; 10986 10987 case AA_Returning: 10988 case AA_Passing: 10989 case AA_Passing_CFAudited: 10990 case AA_Converting: 10991 case AA_Sending: 10992 case AA_Casting: 10993 // The source type comes first. 10994 FirstType = SrcType; 10995 SecondType = DstType; 10996 break; 10997 } 10998 10999 PartialDiagnostic FDiag = PDiag(DiagKind); 11000 if (Action == AA_Passing_CFAudited) 11001 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 11002 else 11003 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 11004 11005 // If we can fix the conversion, suggest the FixIts. 11006 assert(ConvHints.isNull() || Hint.isNull()); 11007 if (!ConvHints.isNull()) { 11008 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 11009 HE = ConvHints.Hints.end(); HI != HE; ++HI) 11010 FDiag << *HI; 11011 } else { 11012 FDiag << Hint; 11013 } 11014 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 11015 11016 if (MayHaveFunctionDiff) 11017 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 11018 11019 Diag(Loc, FDiag); 11020 if (DiagKind == diag::warn_incompatible_qualified_id && 11021 PDecl && IFace && !IFace->hasDefinition()) 11022 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 11023 << IFace->getName() << PDecl->getName(); 11024 11025 if (SecondType == Context.OverloadTy) 11026 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 11027 FirstType); 11028 11029 if (CheckInferredResultType) 11030 EmitRelatedResultTypeNote(SrcExpr); 11031 11032 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 11033 EmitRelatedResultTypeNoteForReturn(DstType); 11034 11035 if (Complained) 11036 *Complained = true; 11037 return isInvalid; 11038 } 11039 11040 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 11041 llvm::APSInt *Result) { 11042 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 11043 public: 11044 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 11045 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 11046 } 11047 } Diagnoser; 11048 11049 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 11050 } 11051 11052 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 11053 llvm::APSInt *Result, 11054 unsigned DiagID, 11055 bool AllowFold) { 11056 class IDDiagnoser : public VerifyICEDiagnoser { 11057 unsigned DiagID; 11058 11059 public: 11060 IDDiagnoser(unsigned DiagID) 11061 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 11062 11063 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 11064 S.Diag(Loc, DiagID) << SR; 11065 } 11066 } Diagnoser(DiagID); 11067 11068 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 11069 } 11070 11071 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 11072 SourceRange SR) { 11073 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 11074 } 11075 11076 ExprResult 11077 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 11078 VerifyICEDiagnoser &Diagnoser, 11079 bool AllowFold) { 11080 SourceLocation DiagLoc = E->getLocStart(); 11081 11082 if (getLangOpts().CPlusPlus11) { 11083 // C++11 [expr.const]p5: 11084 // If an expression of literal class type is used in a context where an 11085 // integral constant expression is required, then that class type shall 11086 // have a single non-explicit conversion function to an integral or 11087 // unscoped enumeration type 11088 ExprResult Converted; 11089 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 11090 public: 11091 CXX11ConvertDiagnoser(bool Silent) 11092 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 11093 Silent, true) {} 11094 11095 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 11096 QualType T) override { 11097 return S.Diag(Loc, diag::err_ice_not_integral) << T; 11098 } 11099 11100 SemaDiagnosticBuilder diagnoseIncomplete( 11101 Sema &S, SourceLocation Loc, QualType T) override { 11102 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 11103 } 11104 11105 SemaDiagnosticBuilder diagnoseExplicitConv( 11106 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 11107 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 11108 } 11109 11110 SemaDiagnosticBuilder noteExplicitConv( 11111 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 11112 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 11113 << ConvTy->isEnumeralType() << ConvTy; 11114 } 11115 11116 SemaDiagnosticBuilder diagnoseAmbiguous( 11117 Sema &S, SourceLocation Loc, QualType T) override { 11118 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 11119 } 11120 11121 SemaDiagnosticBuilder noteAmbiguous( 11122 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 11123 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 11124 << ConvTy->isEnumeralType() << ConvTy; 11125 } 11126 11127 SemaDiagnosticBuilder diagnoseConversion( 11128 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 11129 llvm_unreachable("conversion functions are permitted"); 11130 } 11131 } ConvertDiagnoser(Diagnoser.Suppress); 11132 11133 Converted = PerformContextualImplicitConversion(DiagLoc, E, 11134 ConvertDiagnoser); 11135 if (Converted.isInvalid()) 11136 return Converted; 11137 E = Converted.get(); 11138 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 11139 return ExprError(); 11140 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 11141 // An ICE must be of integral or unscoped enumeration type. 11142 if (!Diagnoser.Suppress) 11143 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 11144 return ExprError(); 11145 } 11146 11147 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 11148 // in the non-ICE case. 11149 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 11150 if (Result) 11151 *Result = E->EvaluateKnownConstInt(Context); 11152 return E; 11153 } 11154 11155 Expr::EvalResult EvalResult; 11156 SmallVector<PartialDiagnosticAt, 8> Notes; 11157 EvalResult.Diag = &Notes; 11158 11159 // Try to evaluate the expression, and produce diagnostics explaining why it's 11160 // not a constant expression as a side-effect. 11161 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 11162 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 11163 11164 // In C++11, we can rely on diagnostics being produced for any expression 11165 // which is not a constant expression. If no diagnostics were produced, then 11166 // this is a constant expression. 11167 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 11168 if (Result) 11169 *Result = EvalResult.Val.getInt(); 11170 return E; 11171 } 11172 11173 // If our only note is the usual "invalid subexpression" note, just point 11174 // the caret at its location rather than producing an essentially 11175 // redundant note. 11176 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11177 diag::note_invalid_subexpr_in_const_expr) { 11178 DiagLoc = Notes[0].first; 11179 Notes.clear(); 11180 } 11181 11182 if (!Folded || !AllowFold) { 11183 if (!Diagnoser.Suppress) { 11184 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 11185 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11186 Diag(Notes[I].first, Notes[I].second); 11187 } 11188 11189 return ExprError(); 11190 } 11191 11192 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 11193 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11194 Diag(Notes[I].first, Notes[I].second); 11195 11196 if (Result) 11197 *Result = EvalResult.Val.getInt(); 11198 return E; 11199 } 11200 11201 namespace { 11202 // Handle the case where we conclude a expression which we speculatively 11203 // considered to be unevaluated is actually evaluated. 11204 class TransformToPE : public TreeTransform<TransformToPE> { 11205 typedef TreeTransform<TransformToPE> BaseTransform; 11206 11207 public: 11208 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 11209 11210 // Make sure we redo semantic analysis 11211 bool AlwaysRebuild() { return true; } 11212 11213 // Make sure we handle LabelStmts correctly. 11214 // FIXME: This does the right thing, but maybe we need a more general 11215 // fix to TreeTransform? 11216 StmtResult TransformLabelStmt(LabelStmt *S) { 11217 S->getDecl()->setStmt(nullptr); 11218 return BaseTransform::TransformLabelStmt(S); 11219 } 11220 11221 // We need to special-case DeclRefExprs referring to FieldDecls which 11222 // are not part of a member pointer formation; normal TreeTransforming 11223 // doesn't catch this case because of the way we represent them in the AST. 11224 // FIXME: This is a bit ugly; is it really the best way to handle this 11225 // case? 11226 // 11227 // Error on DeclRefExprs referring to FieldDecls. 11228 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 11229 if (isa<FieldDecl>(E->getDecl()) && 11230 !SemaRef.isUnevaluatedContext()) 11231 return SemaRef.Diag(E->getLocation(), 11232 diag::err_invalid_non_static_member_use) 11233 << E->getDecl() << E->getSourceRange(); 11234 11235 return BaseTransform::TransformDeclRefExpr(E); 11236 } 11237 11238 // Exception: filter out member pointer formation 11239 ExprResult TransformUnaryOperator(UnaryOperator *E) { 11240 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 11241 return E; 11242 11243 return BaseTransform::TransformUnaryOperator(E); 11244 } 11245 11246 ExprResult TransformLambdaExpr(LambdaExpr *E) { 11247 // Lambdas never need to be transformed. 11248 return E; 11249 } 11250 }; 11251 } 11252 11253 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 11254 assert(isUnevaluatedContext() && 11255 "Should only transform unevaluated expressions"); 11256 ExprEvalContexts.back().Context = 11257 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 11258 if (isUnevaluatedContext()) 11259 return E; 11260 return TransformToPE(*this).TransformExpr(E); 11261 } 11262 11263 void 11264 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 11265 Decl *LambdaContextDecl, 11266 bool IsDecltype) { 11267 ExprEvalContexts.push_back( 11268 ExpressionEvaluationContextRecord(NewContext, 11269 ExprCleanupObjects.size(), 11270 ExprNeedsCleanups, 11271 LambdaContextDecl, 11272 IsDecltype)); 11273 ExprNeedsCleanups = false; 11274 if (!MaybeODRUseExprs.empty()) 11275 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 11276 } 11277 11278 void 11279 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 11280 ReuseLambdaContextDecl_t, 11281 bool IsDecltype) { 11282 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 11283 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 11284 } 11285 11286 void Sema::PopExpressionEvaluationContext() { 11287 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 11288 11289 if (!Rec.Lambdas.empty()) { 11290 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 11291 unsigned D; 11292 if (Rec.isUnevaluated()) { 11293 // C++11 [expr.prim.lambda]p2: 11294 // A lambda-expression shall not appear in an unevaluated operand 11295 // (Clause 5). 11296 D = diag::err_lambda_unevaluated_operand; 11297 } else { 11298 // C++1y [expr.const]p2: 11299 // A conditional-expression e is a core constant expression unless the 11300 // evaluation of e, following the rules of the abstract machine, would 11301 // evaluate [...] a lambda-expression. 11302 D = diag::err_lambda_in_constant_expression; 11303 } 11304 for (const auto *L : Rec.Lambdas) 11305 Diag(L->getLocStart(), D); 11306 } else { 11307 // Mark the capture expressions odr-used. This was deferred 11308 // during lambda expression creation. 11309 for (auto *Lambda : Rec.Lambdas) { 11310 for (auto *C : Lambda->capture_inits()) 11311 MarkDeclarationsReferencedInExpr(C); 11312 } 11313 } 11314 } 11315 11316 // When are coming out of an unevaluated context, clear out any 11317 // temporaries that we may have created as part of the evaluation of 11318 // the expression in that context: they aren't relevant because they 11319 // will never be constructed. 11320 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 11321 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 11322 ExprCleanupObjects.end()); 11323 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 11324 CleanupVarDeclMarking(); 11325 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 11326 // Otherwise, merge the contexts together. 11327 } else { 11328 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 11329 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 11330 Rec.SavedMaybeODRUseExprs.end()); 11331 } 11332 11333 // Pop the current expression evaluation context off the stack. 11334 ExprEvalContexts.pop_back(); 11335 } 11336 11337 void Sema::DiscardCleanupsInEvaluationContext() { 11338 ExprCleanupObjects.erase( 11339 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 11340 ExprCleanupObjects.end()); 11341 ExprNeedsCleanups = false; 11342 MaybeODRUseExprs.clear(); 11343 } 11344 11345 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 11346 if (!E->getType()->isVariablyModifiedType()) 11347 return E; 11348 return TransformToPotentiallyEvaluated(E); 11349 } 11350 11351 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 11352 // Do not mark anything as "used" within a dependent context; wait for 11353 // an instantiation. 11354 if (SemaRef.CurContext->isDependentContext()) 11355 return false; 11356 11357 switch (SemaRef.ExprEvalContexts.back().Context) { 11358 case Sema::Unevaluated: 11359 case Sema::UnevaluatedAbstract: 11360 // We are in an expression that is not potentially evaluated; do nothing. 11361 // (Depending on how you read the standard, we actually do need to do 11362 // something here for null pointer constants, but the standard's 11363 // definition of a null pointer constant is completely crazy.) 11364 return false; 11365 11366 case Sema::ConstantEvaluated: 11367 case Sema::PotentiallyEvaluated: 11368 // We are in a potentially evaluated expression (or a constant-expression 11369 // in C++03); we need to do implicit template instantiation, implicitly 11370 // define class members, and mark most declarations as used. 11371 return true; 11372 11373 case Sema::PotentiallyEvaluatedIfUsed: 11374 // Referenced declarations will only be used if the construct in the 11375 // containing expression is used. 11376 return false; 11377 } 11378 llvm_unreachable("Invalid context"); 11379 } 11380 11381 /// \brief Mark a function referenced, and check whether it is odr-used 11382 /// (C++ [basic.def.odr]p2, C99 6.9p3) 11383 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 11384 bool OdrUse) { 11385 assert(Func && "No function?"); 11386 11387 Func->setReferenced(); 11388 11389 // C++11 [basic.def.odr]p3: 11390 // A function whose name appears as a potentially-evaluated expression is 11391 // odr-used if it is the unique lookup result or the selected member of a 11392 // set of overloaded functions [...]. 11393 // 11394 // We (incorrectly) mark overload resolution as an unevaluated context, so we 11395 // can just check that here. Skip the rest of this function if we've already 11396 // marked the function as used. 11397 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) { 11398 // C++11 [temp.inst]p3: 11399 // Unless a function template specialization has been explicitly 11400 // instantiated or explicitly specialized, the function template 11401 // specialization is implicitly instantiated when the specialization is 11402 // referenced in a context that requires a function definition to exist. 11403 // 11404 // We consider constexpr function templates to be referenced in a context 11405 // that requires a definition to exist whenever they are referenced. 11406 // 11407 // FIXME: This instantiates constexpr functions too frequently. If this is 11408 // really an unevaluated context (and we're not just in the definition of a 11409 // function template or overload resolution or other cases which we 11410 // incorrectly consider to be unevaluated contexts), and we're not in a 11411 // subexpression which we actually need to evaluate (for instance, a 11412 // template argument, array bound or an expression in a braced-init-list), 11413 // we are not permitted to instantiate this constexpr function definition. 11414 // 11415 // FIXME: This also implicitly defines special members too frequently. They 11416 // are only supposed to be implicitly defined if they are odr-used, but they 11417 // are not odr-used from constant expressions in unevaluated contexts. 11418 // However, they cannot be referenced if they are deleted, and they are 11419 // deleted whenever the implicit definition of the special member would 11420 // fail. 11421 if (!Func->isConstexpr() || Func->getBody()) 11422 return; 11423 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 11424 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 11425 return; 11426 } 11427 11428 // Note that this declaration has been used. 11429 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 11430 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 11431 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 11432 if (Constructor->isDefaultConstructor()) { 11433 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 11434 return; 11435 DefineImplicitDefaultConstructor(Loc, Constructor); 11436 } else if (Constructor->isCopyConstructor()) { 11437 DefineImplicitCopyConstructor(Loc, Constructor); 11438 } else if (Constructor->isMoveConstructor()) { 11439 DefineImplicitMoveConstructor(Loc, Constructor); 11440 } 11441 } else if (Constructor->getInheritedConstructor()) { 11442 DefineInheritingConstructor(Loc, Constructor); 11443 } 11444 } else if (CXXDestructorDecl *Destructor = 11445 dyn_cast<CXXDestructorDecl>(Func)) { 11446 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 11447 if (Destructor->isDefaulted() && !Destructor->isDeleted()) 11448 DefineImplicitDestructor(Loc, Destructor); 11449 if (Destructor->isVirtual()) 11450 MarkVTableUsed(Loc, Destructor->getParent()); 11451 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 11452 if (MethodDecl->isOverloadedOperator() && 11453 MethodDecl->getOverloadedOperator() == OO_Equal) { 11454 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 11455 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 11456 if (MethodDecl->isCopyAssignmentOperator()) 11457 DefineImplicitCopyAssignment(Loc, MethodDecl); 11458 else 11459 DefineImplicitMoveAssignment(Loc, MethodDecl); 11460 } 11461 } else if (isa<CXXConversionDecl>(MethodDecl) && 11462 MethodDecl->getParent()->isLambda()) { 11463 CXXConversionDecl *Conversion = 11464 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 11465 if (Conversion->isLambdaToBlockPointerConversion()) 11466 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 11467 else 11468 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 11469 } else if (MethodDecl->isVirtual()) 11470 MarkVTableUsed(Loc, MethodDecl->getParent()); 11471 } 11472 11473 // Recursive functions should be marked when used from another function. 11474 // FIXME: Is this really right? 11475 if (CurContext == Func) return; 11476 11477 // Resolve the exception specification for any function which is 11478 // used: CodeGen will need it. 11479 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 11480 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 11481 ResolveExceptionSpec(Loc, FPT); 11482 11483 if (!OdrUse) return; 11484 11485 // Implicit instantiation of function templates and member functions of 11486 // class templates. 11487 if (Func->isImplicitlyInstantiable()) { 11488 bool AlreadyInstantiated = false; 11489 SourceLocation PointOfInstantiation = Loc; 11490 if (FunctionTemplateSpecializationInfo *SpecInfo 11491 = Func->getTemplateSpecializationInfo()) { 11492 if (SpecInfo->getPointOfInstantiation().isInvalid()) 11493 SpecInfo->setPointOfInstantiation(Loc); 11494 else if (SpecInfo->getTemplateSpecializationKind() 11495 == TSK_ImplicitInstantiation) { 11496 AlreadyInstantiated = true; 11497 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 11498 } 11499 } else if (MemberSpecializationInfo *MSInfo 11500 = Func->getMemberSpecializationInfo()) { 11501 if (MSInfo->getPointOfInstantiation().isInvalid()) 11502 MSInfo->setPointOfInstantiation(Loc); 11503 else if (MSInfo->getTemplateSpecializationKind() 11504 == TSK_ImplicitInstantiation) { 11505 AlreadyInstantiated = true; 11506 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 11507 } 11508 } 11509 11510 if (!AlreadyInstantiated || Func->isConstexpr()) { 11511 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 11512 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 11513 ActiveTemplateInstantiations.size()) 11514 PendingLocalImplicitInstantiations.push_back( 11515 std::make_pair(Func, PointOfInstantiation)); 11516 else if (Func->isConstexpr()) 11517 // Do not defer instantiations of constexpr functions, to avoid the 11518 // expression evaluator needing to call back into Sema if it sees a 11519 // call to such a function. 11520 InstantiateFunctionDefinition(PointOfInstantiation, Func); 11521 else { 11522 PendingInstantiations.push_back(std::make_pair(Func, 11523 PointOfInstantiation)); 11524 // Notify the consumer that a function was implicitly instantiated. 11525 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 11526 } 11527 } 11528 } else { 11529 // Walk redefinitions, as some of them may be instantiable. 11530 for (auto i : Func->redecls()) { 11531 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 11532 MarkFunctionReferenced(Loc, i); 11533 } 11534 } 11535 11536 // Keep track of used but undefined functions. 11537 if (!Func->isDefined()) { 11538 if (mightHaveNonExternalLinkage(Func)) 11539 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 11540 else if (Func->getMostRecentDecl()->isInlined() && 11541 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 11542 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 11543 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 11544 } 11545 11546 // Normally the most current decl is marked used while processing the use and 11547 // any subsequent decls are marked used by decl merging. This fails with 11548 // template instantiation since marking can happen at the end of the file 11549 // and, because of the two phase lookup, this function is called with at 11550 // decl in the middle of a decl chain. We loop to maintain the invariant 11551 // that once a decl is used, all decls after it are also used. 11552 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 11553 F->markUsed(Context); 11554 if (F == Func) 11555 break; 11556 } 11557 } 11558 11559 static void 11560 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 11561 VarDecl *var, DeclContext *DC) { 11562 DeclContext *VarDC = var->getDeclContext(); 11563 11564 // If the parameter still belongs to the translation unit, then 11565 // we're actually just using one parameter in the declaration of 11566 // the next. 11567 if (isa<ParmVarDecl>(var) && 11568 isa<TranslationUnitDecl>(VarDC)) 11569 return; 11570 11571 // For C code, don't diagnose about capture if we're not actually in code 11572 // right now; it's impossible to write a non-constant expression outside of 11573 // function context, so we'll get other (more useful) diagnostics later. 11574 // 11575 // For C++, things get a bit more nasty... it would be nice to suppress this 11576 // diagnostic for certain cases like using a local variable in an array bound 11577 // for a member of a local class, but the correct predicate is not obvious. 11578 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 11579 return; 11580 11581 if (isa<CXXMethodDecl>(VarDC) && 11582 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 11583 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 11584 << var->getIdentifier(); 11585 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 11586 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 11587 << var->getIdentifier() << fn->getDeclName(); 11588 } else if (isa<BlockDecl>(VarDC)) { 11589 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 11590 << var->getIdentifier(); 11591 } else { 11592 // FIXME: Is there any other context where a local variable can be 11593 // declared? 11594 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 11595 << var->getIdentifier(); 11596 } 11597 11598 S.Diag(var->getLocation(), diag::note_entity_declared_at) 11599 << var->getIdentifier(); 11600 11601 // FIXME: Add additional diagnostic info about class etc. which prevents 11602 // capture. 11603 } 11604 11605 11606 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 11607 bool &SubCapturesAreNested, 11608 QualType &CaptureType, 11609 QualType &DeclRefType) { 11610 // Check whether we've already captured it. 11611 if (CSI->CaptureMap.count(Var)) { 11612 // If we found a capture, any subcaptures are nested. 11613 SubCapturesAreNested = true; 11614 11615 // Retrieve the capture type for this variable. 11616 CaptureType = CSI->getCapture(Var).getCaptureType(); 11617 11618 // Compute the type of an expression that refers to this variable. 11619 DeclRefType = CaptureType.getNonReferenceType(); 11620 11621 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 11622 if (Cap.isCopyCapture() && 11623 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 11624 DeclRefType.addConst(); 11625 return true; 11626 } 11627 return false; 11628 } 11629 11630 // Only block literals, captured statements, and lambda expressions can 11631 // capture; other scopes don't work. 11632 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 11633 SourceLocation Loc, 11634 const bool Diagnose, Sema &S) { 11635 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 11636 return getLambdaAwareParentOfDeclContext(DC); 11637 else { 11638 if (Diagnose) 11639 diagnoseUncapturableValueReference(S, Loc, Var, DC); 11640 } 11641 return nullptr; 11642 } 11643 11644 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 11645 // certain types of variables (unnamed, variably modified types etc.) 11646 // so check for eligibility. 11647 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 11648 SourceLocation Loc, 11649 const bool Diagnose, Sema &S) { 11650 11651 bool IsBlock = isa<BlockScopeInfo>(CSI); 11652 bool IsLambda = isa<LambdaScopeInfo>(CSI); 11653 11654 // Lambdas are not allowed to capture unnamed variables 11655 // (e.g. anonymous unions). 11656 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 11657 // assuming that's the intent. 11658 if (IsLambda && !Var->getDeclName()) { 11659 if (Diagnose) { 11660 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 11661 S.Diag(Var->getLocation(), diag::note_declared_at); 11662 } 11663 return false; 11664 } 11665 11666 // Prohibit variably-modified types in blocks; they're difficult to deal with. 11667 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 11668 if (Diagnose) { 11669 S.Diag(Loc, diag::err_ref_vm_type); 11670 S.Diag(Var->getLocation(), diag::note_previous_decl) 11671 << Var->getDeclName(); 11672 } 11673 return false; 11674 } 11675 // Prohibit structs with flexible array members too. 11676 // We cannot capture what is in the tail end of the struct. 11677 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 11678 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 11679 if (Diagnose) { 11680 if (IsBlock) 11681 S.Diag(Loc, diag::err_ref_flexarray_type); 11682 else 11683 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 11684 << Var->getDeclName(); 11685 S.Diag(Var->getLocation(), diag::note_previous_decl) 11686 << Var->getDeclName(); 11687 } 11688 return false; 11689 } 11690 } 11691 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11692 // Lambdas and captured statements are not allowed to capture __block 11693 // variables; they don't support the expected semantics. 11694 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 11695 if (Diagnose) { 11696 S.Diag(Loc, diag::err_capture_block_variable) 11697 << Var->getDeclName() << !IsLambda; 11698 S.Diag(Var->getLocation(), diag::note_previous_decl) 11699 << Var->getDeclName(); 11700 } 11701 return false; 11702 } 11703 11704 return true; 11705 } 11706 11707 // Returns true if the capture by block was successful. 11708 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 11709 SourceLocation Loc, 11710 const bool BuildAndDiagnose, 11711 QualType &CaptureType, 11712 QualType &DeclRefType, 11713 const bool Nested, 11714 Sema &S) { 11715 Expr *CopyExpr = nullptr; 11716 bool ByRef = false; 11717 11718 // Blocks are not allowed to capture arrays. 11719 if (CaptureType->isArrayType()) { 11720 if (BuildAndDiagnose) { 11721 S.Diag(Loc, diag::err_ref_array_type); 11722 S.Diag(Var->getLocation(), diag::note_previous_decl) 11723 << Var->getDeclName(); 11724 } 11725 return false; 11726 } 11727 11728 // Forbid the block-capture of autoreleasing variables. 11729 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 11730 if (BuildAndDiagnose) { 11731 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 11732 << /*block*/ 0; 11733 S.Diag(Var->getLocation(), diag::note_previous_decl) 11734 << Var->getDeclName(); 11735 } 11736 return false; 11737 } 11738 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 11739 if (HasBlocksAttr || CaptureType->isReferenceType()) { 11740 // Block capture by reference does not change the capture or 11741 // declaration reference types. 11742 ByRef = true; 11743 } else { 11744 // Block capture by copy introduces 'const'. 11745 CaptureType = CaptureType.getNonReferenceType().withConst(); 11746 DeclRefType = CaptureType; 11747 11748 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 11749 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 11750 // The capture logic needs the destructor, so make sure we mark it. 11751 // Usually this is unnecessary because most local variables have 11752 // their destructors marked at declaration time, but parameters are 11753 // an exception because it's technically only the call site that 11754 // actually requires the destructor. 11755 if (isa<ParmVarDecl>(Var)) 11756 S.FinalizeVarWithDestructor(Var, Record); 11757 11758 // Enter a new evaluation context to insulate the copy 11759 // full-expression. 11760 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 11761 11762 // According to the blocks spec, the capture of a variable from 11763 // the stack requires a const copy constructor. This is not true 11764 // of the copy/move done to move a __block variable to the heap. 11765 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 11766 DeclRefType.withConst(), 11767 VK_LValue, Loc); 11768 11769 ExprResult Result 11770 = S.PerformCopyInitialization( 11771 InitializedEntity::InitializeBlock(Var->getLocation(), 11772 CaptureType, false), 11773 Loc, DeclRef); 11774 11775 // Build a full-expression copy expression if initialization 11776 // succeeded and used a non-trivial constructor. Recover from 11777 // errors by pretending that the copy isn't necessary. 11778 if (!Result.isInvalid() && 11779 !cast<CXXConstructExpr>(Result.get())->getConstructor() 11780 ->isTrivial()) { 11781 Result = S.MaybeCreateExprWithCleanups(Result); 11782 CopyExpr = Result.get(); 11783 } 11784 } 11785 } 11786 } 11787 11788 // Actually capture the variable. 11789 if (BuildAndDiagnose) 11790 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 11791 SourceLocation(), CaptureType, CopyExpr); 11792 11793 return true; 11794 11795 } 11796 11797 11798 /// \brief Capture the given variable in the captured region. 11799 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 11800 VarDecl *Var, 11801 SourceLocation Loc, 11802 const bool BuildAndDiagnose, 11803 QualType &CaptureType, 11804 QualType &DeclRefType, 11805 const bool RefersToEnclosingLocal, 11806 Sema &S) { 11807 11808 // By default, capture variables by reference. 11809 bool ByRef = true; 11810 // Using an LValue reference type is consistent with Lambdas (see below). 11811 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 11812 Expr *CopyExpr = nullptr; 11813 if (BuildAndDiagnose) { 11814 // The current implementation assumes that all variables are captured 11815 // by references. Since there is no capture by copy, no expression 11816 // evaluation will be needed. 11817 RecordDecl *RD = RSI->TheRecordDecl; 11818 11819 FieldDecl *Field 11820 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 11821 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 11822 nullptr, false, ICIS_NoInit); 11823 Field->setImplicit(true); 11824 Field->setAccess(AS_private); 11825 RD->addDecl(Field); 11826 11827 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11828 DeclRefType, VK_LValue, Loc); 11829 Var->setReferenced(true); 11830 Var->markUsed(S.Context); 11831 } 11832 11833 // Actually capture the variable. 11834 if (BuildAndDiagnose) 11835 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc, 11836 SourceLocation(), CaptureType, CopyExpr); 11837 11838 11839 return true; 11840 } 11841 11842 /// \brief Create a field within the lambda class for the variable 11843 /// being captured. Handle Array captures. 11844 static ExprResult addAsFieldToClosureType(Sema &S, 11845 LambdaScopeInfo *LSI, 11846 VarDecl *Var, QualType FieldType, 11847 QualType DeclRefType, 11848 SourceLocation Loc, 11849 bool RefersToEnclosingLocal) { 11850 CXXRecordDecl *Lambda = LSI->Lambda; 11851 11852 // Build the non-static data member. 11853 FieldDecl *Field 11854 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 11855 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 11856 nullptr, false, ICIS_NoInit); 11857 Field->setImplicit(true); 11858 Field->setAccess(AS_private); 11859 Lambda->addDecl(Field); 11860 11861 // C++11 [expr.prim.lambda]p21: 11862 // When the lambda-expression is evaluated, the entities that 11863 // are captured by copy are used to direct-initialize each 11864 // corresponding non-static data member of the resulting closure 11865 // object. (For array members, the array elements are 11866 // direct-initialized in increasing subscript order.) These 11867 // initializations are performed in the (unspecified) order in 11868 // which the non-static data members are declared. 11869 11870 // Introduce a new evaluation context for the initialization, so 11871 // that temporaries introduced as part of the capture are retained 11872 // to be re-"exported" from the lambda expression itself. 11873 EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated); 11874 11875 // C++ [expr.prim.labda]p12: 11876 // An entity captured by a lambda-expression is odr-used (3.2) in 11877 // the scope containing the lambda-expression. 11878 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 11879 DeclRefType, VK_LValue, Loc); 11880 Var->setReferenced(true); 11881 Var->markUsed(S.Context); 11882 11883 // When the field has array type, create index variables for each 11884 // dimension of the array. We use these index variables to subscript 11885 // the source array, and other clients (e.g., CodeGen) will perform 11886 // the necessary iteration with these index variables. 11887 SmallVector<VarDecl *, 4> IndexVariables; 11888 QualType BaseType = FieldType; 11889 QualType SizeType = S.Context.getSizeType(); 11890 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size()); 11891 while (const ConstantArrayType *Array 11892 = S.Context.getAsConstantArrayType(BaseType)) { 11893 // Create the iteration variable for this array index. 11894 IdentifierInfo *IterationVarName = nullptr; 11895 { 11896 SmallString<8> Str; 11897 llvm::raw_svector_ostream OS(Str); 11898 OS << "__i" << IndexVariables.size(); 11899 IterationVarName = &S.Context.Idents.get(OS.str()); 11900 } 11901 VarDecl *IterationVar 11902 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 11903 IterationVarName, SizeType, 11904 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 11905 SC_None); 11906 IndexVariables.push_back(IterationVar); 11907 LSI->ArrayIndexVars.push_back(IterationVar); 11908 11909 // Create a reference to the iteration variable. 11910 ExprResult IterationVarRef 11911 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc); 11912 assert(!IterationVarRef.isInvalid() && 11913 "Reference to invented variable cannot fail!"); 11914 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.get()); 11915 assert(!IterationVarRef.isInvalid() && 11916 "Conversion of invented variable cannot fail!"); 11917 11918 // Subscript the array with this iteration variable. 11919 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr( 11920 Ref, Loc, IterationVarRef.get(), Loc); 11921 if (Subscript.isInvalid()) { 11922 S.CleanupVarDeclMarking(); 11923 S.DiscardCleanupsInEvaluationContext(); 11924 return ExprError(); 11925 } 11926 11927 Ref = Subscript.get(); 11928 BaseType = Array->getElementType(); 11929 } 11930 11931 // Construct the entity that we will be initializing. For an array, this 11932 // will be first element in the array, which may require several levels 11933 // of array-subscript entities. 11934 SmallVector<InitializedEntity, 4> Entities; 11935 Entities.reserve(1 + IndexVariables.size()); 11936 Entities.push_back( 11937 InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(), 11938 Field->getType(), Loc)); 11939 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I) 11940 Entities.push_back(InitializedEntity::InitializeElement(S.Context, 11941 0, 11942 Entities.back())); 11943 11944 InitializationKind InitKind 11945 = InitializationKind::CreateDirect(Loc, Loc, Loc); 11946 InitializationSequence Init(S, Entities.back(), InitKind, Ref); 11947 ExprResult Result(true); 11948 if (!Init.Diagnose(S, Entities.back(), InitKind, Ref)) 11949 Result = Init.Perform(S, Entities.back(), InitKind, Ref); 11950 11951 // If this initialization requires any cleanups (e.g., due to a 11952 // default argument to a copy constructor), note that for the 11953 // lambda. 11954 if (S.ExprNeedsCleanups) 11955 LSI->ExprNeedsCleanups = true; 11956 11957 // Exit the expression evaluation context used for the capture. 11958 S.CleanupVarDeclMarking(); 11959 S.DiscardCleanupsInEvaluationContext(); 11960 return Result; 11961 } 11962 11963 11964 11965 /// \brief Capture the given variable in the lambda. 11966 static bool captureInLambda(LambdaScopeInfo *LSI, 11967 VarDecl *Var, 11968 SourceLocation Loc, 11969 const bool BuildAndDiagnose, 11970 QualType &CaptureType, 11971 QualType &DeclRefType, 11972 const bool RefersToEnclosingLocal, 11973 const Sema::TryCaptureKind Kind, 11974 SourceLocation EllipsisLoc, 11975 const bool IsTopScope, 11976 Sema &S) { 11977 11978 // Determine whether we are capturing by reference or by value. 11979 bool ByRef = false; 11980 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 11981 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 11982 } else { 11983 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 11984 } 11985 11986 // Compute the type of the field that will capture this variable. 11987 if (ByRef) { 11988 // C++11 [expr.prim.lambda]p15: 11989 // An entity is captured by reference if it is implicitly or 11990 // explicitly captured but not captured by copy. It is 11991 // unspecified whether additional unnamed non-static data 11992 // members are declared in the closure type for entities 11993 // captured by reference. 11994 // 11995 // FIXME: It is not clear whether we want to build an lvalue reference 11996 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 11997 // to do the former, while EDG does the latter. Core issue 1249 will 11998 // clarify, but for now we follow GCC because it's a more permissive and 11999 // easily defensible position. 12000 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 12001 } else { 12002 // C++11 [expr.prim.lambda]p14: 12003 // For each entity captured by copy, an unnamed non-static 12004 // data member is declared in the closure type. The 12005 // declaration order of these members is unspecified. The type 12006 // of such a data member is the type of the corresponding 12007 // captured entity if the entity is not a reference to an 12008 // object, or the referenced type otherwise. [Note: If the 12009 // captured entity is a reference to a function, the 12010 // corresponding data member is also a reference to a 12011 // function. - end note ] 12012 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 12013 if (!RefType->getPointeeType()->isFunctionType()) 12014 CaptureType = RefType->getPointeeType(); 12015 } 12016 12017 // Forbid the lambda copy-capture of autoreleasing variables. 12018 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 12019 if (BuildAndDiagnose) { 12020 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 12021 S.Diag(Var->getLocation(), diag::note_previous_decl) 12022 << Var->getDeclName(); 12023 } 12024 return false; 12025 } 12026 12027 // Make sure that by-copy captures are of a complete and non-abstract type. 12028 if (BuildAndDiagnose) { 12029 if (!CaptureType->isDependentType() && 12030 S.RequireCompleteType(Loc, CaptureType, 12031 diag::err_capture_of_incomplete_type, 12032 Var->getDeclName())) 12033 return false; 12034 12035 if (S.RequireNonAbstractType(Loc, CaptureType, 12036 diag::err_capture_of_abstract_type)) 12037 return false; 12038 } 12039 } 12040 12041 // Capture this variable in the lambda. 12042 Expr *CopyExpr = nullptr; 12043 if (BuildAndDiagnose) { 12044 ExprResult Result = addAsFieldToClosureType(S, LSI, Var, 12045 CaptureType, DeclRefType, Loc, 12046 RefersToEnclosingLocal); 12047 if (!Result.isInvalid()) 12048 CopyExpr = Result.get(); 12049 } 12050 12051 // Compute the type of a reference to this captured variable. 12052 if (ByRef) 12053 DeclRefType = CaptureType.getNonReferenceType(); 12054 else { 12055 // C++ [expr.prim.lambda]p5: 12056 // The closure type for a lambda-expression has a public inline 12057 // function call operator [...]. This function call operator is 12058 // declared const (9.3.1) if and only if the lambda-expression’s 12059 // parameter-declaration-clause is not followed by mutable. 12060 DeclRefType = CaptureType.getNonReferenceType(); 12061 if (!LSI->Mutable && !CaptureType->isReferenceType()) 12062 DeclRefType.addConst(); 12063 } 12064 12065 // Add the capture. 12066 if (BuildAndDiagnose) 12067 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal, 12068 Loc, EllipsisLoc, CaptureType, CopyExpr); 12069 12070 return true; 12071 } 12072 12073 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc, 12074 TryCaptureKind Kind, SourceLocation EllipsisLoc, 12075 bool BuildAndDiagnose, 12076 QualType &CaptureType, 12077 QualType &DeclRefType, 12078 const unsigned *const FunctionScopeIndexToStopAt) { 12079 bool Nested = false; 12080 12081 DeclContext *DC = CurContext; 12082 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 12083 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 12084 // We need to sync up the Declaration Context with the 12085 // FunctionScopeIndexToStopAt 12086 if (FunctionScopeIndexToStopAt) { 12087 unsigned FSIndex = FunctionScopes.size() - 1; 12088 while (FSIndex != MaxFunctionScopesIndex) { 12089 DC = getLambdaAwareParentOfDeclContext(DC); 12090 --FSIndex; 12091 } 12092 } 12093 12094 12095 // If the variable is declared in the current context (and is not an 12096 // init-capture), there is no need to capture it. 12097 if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true; 12098 if (!Var->hasLocalStorage()) return true; 12099 12100 // Walk up the stack to determine whether we can capture the variable, 12101 // performing the "simple" checks that don't depend on type. We stop when 12102 // we've either hit the declared scope of the variable or find an existing 12103 // capture of that variable. We start from the innermost capturing-entity 12104 // (the DC) and ensure that all intervening capturing-entities 12105 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 12106 // declcontext can either capture the variable or have already captured 12107 // the variable. 12108 CaptureType = Var->getType(); 12109 DeclRefType = CaptureType.getNonReferenceType(); 12110 bool Explicit = (Kind != TryCapture_Implicit); 12111 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 12112 do { 12113 // Only block literals, captured statements, and lambda expressions can 12114 // capture; other scopes don't work. 12115 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 12116 ExprLoc, 12117 BuildAndDiagnose, 12118 *this); 12119 if (!ParentDC) return true; 12120 12121 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 12122 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 12123 12124 12125 // Check whether we've already captured it. 12126 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 12127 DeclRefType)) 12128 break; 12129 // If we are instantiating a generic lambda call operator body, 12130 // we do not want to capture new variables. What was captured 12131 // during either a lambdas transformation or initial parsing 12132 // should be used. 12133 if (isGenericLambdaCallOperatorSpecialization(DC)) { 12134 if (BuildAndDiagnose) { 12135 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 12136 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 12137 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 12138 Diag(Var->getLocation(), diag::note_previous_decl) 12139 << Var->getDeclName(); 12140 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 12141 } else 12142 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 12143 } 12144 return true; 12145 } 12146 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 12147 // certain types of variables (unnamed, variably modified types etc.) 12148 // so check for eligibility. 12149 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 12150 return true; 12151 12152 // Try to capture variable-length arrays types. 12153 if (Var->getType()->isVariablyModifiedType()) { 12154 // We're going to walk down into the type and look for VLA 12155 // expressions. 12156 QualType QTy = Var->getType(); 12157 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 12158 QTy = PVD->getOriginalType(); 12159 do { 12160 const Type *Ty = QTy.getTypePtr(); 12161 switch (Ty->getTypeClass()) { 12162 #define TYPE(Class, Base) 12163 #define ABSTRACT_TYPE(Class, Base) 12164 #define NON_CANONICAL_TYPE(Class, Base) 12165 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 12166 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 12167 #include "clang/AST/TypeNodes.def" 12168 QTy = QualType(); 12169 break; 12170 // These types are never variably-modified. 12171 case Type::Builtin: 12172 case Type::Complex: 12173 case Type::Vector: 12174 case Type::ExtVector: 12175 case Type::Record: 12176 case Type::Enum: 12177 case Type::Elaborated: 12178 case Type::TemplateSpecialization: 12179 case Type::ObjCObject: 12180 case Type::ObjCInterface: 12181 case Type::ObjCObjectPointer: 12182 llvm_unreachable("type class is never variably-modified!"); 12183 case Type::Adjusted: 12184 QTy = cast<AdjustedType>(Ty)->getOriginalType(); 12185 break; 12186 case Type::Decayed: 12187 QTy = cast<DecayedType>(Ty)->getPointeeType(); 12188 break; 12189 case Type::Pointer: 12190 QTy = cast<PointerType>(Ty)->getPointeeType(); 12191 break; 12192 case Type::BlockPointer: 12193 QTy = cast<BlockPointerType>(Ty)->getPointeeType(); 12194 break; 12195 case Type::LValueReference: 12196 case Type::RValueReference: 12197 QTy = cast<ReferenceType>(Ty)->getPointeeType(); 12198 break; 12199 case Type::MemberPointer: 12200 QTy = cast<MemberPointerType>(Ty)->getPointeeType(); 12201 break; 12202 case Type::ConstantArray: 12203 case Type::IncompleteArray: 12204 // Losing element qualification here is fine. 12205 QTy = cast<ArrayType>(Ty)->getElementType(); 12206 break; 12207 case Type::VariableArray: { 12208 // Losing element qualification here is fine. 12209 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 12210 12211 // Unknown size indication requires no size computation. 12212 // Otherwise, evaluate and record it. 12213 if (auto Size = VAT->getSizeExpr()) { 12214 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 12215 if (!LSI->isVLATypeCaptured(VAT)) { 12216 auto ExprLoc = Size->getExprLoc(); 12217 auto SizeType = Context.getSizeType(); 12218 auto Lambda = LSI->Lambda; 12219 12220 // Build the non-static data member. 12221 auto Field = FieldDecl::Create( 12222 Context, Lambda, ExprLoc, ExprLoc, 12223 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 12224 /*BW*/ nullptr, /*Mutable*/ false, 12225 /*InitStyle*/ ICIS_NoInit); 12226 Field->setImplicit(true); 12227 Field->setAccess(AS_private); 12228 Field->setCapturedVLAType(VAT); 12229 Lambda->addDecl(Field); 12230 12231 LSI->addVLATypeCapture(ExprLoc, SizeType); 12232 } 12233 } else { 12234 // Immediately mark all referenced vars for CapturedStatements, 12235 // they all are captured by reference. 12236 MarkDeclarationsReferencedInExpr(Size); 12237 } 12238 } 12239 QTy = VAT->getElementType(); 12240 break; 12241 } 12242 case Type::FunctionProto: 12243 case Type::FunctionNoProto: 12244 QTy = cast<FunctionType>(Ty)->getReturnType(); 12245 break; 12246 case Type::Paren: 12247 case Type::TypeOf: 12248 case Type::UnaryTransform: 12249 case Type::Attributed: 12250 case Type::SubstTemplateTypeParm: 12251 case Type::PackExpansion: 12252 // Keep walking after single level desugaring. 12253 QTy = QTy.getSingleStepDesugaredType(getASTContext()); 12254 break; 12255 case Type::Typedef: 12256 QTy = cast<TypedefType>(Ty)->desugar(); 12257 break; 12258 case Type::Decltype: 12259 QTy = cast<DecltypeType>(Ty)->desugar(); 12260 break; 12261 case Type::Auto: 12262 QTy = cast<AutoType>(Ty)->getDeducedType(); 12263 break; 12264 case Type::TypeOfExpr: 12265 QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 12266 break; 12267 case Type::Atomic: 12268 QTy = cast<AtomicType>(Ty)->getValueType(); 12269 break; 12270 } 12271 } while (!QTy.isNull() && QTy->isVariablyModifiedType()); 12272 } 12273 12274 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 12275 // No capture-default, and this is not an explicit capture 12276 // so cannot capture this variable. 12277 if (BuildAndDiagnose) { 12278 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 12279 Diag(Var->getLocation(), diag::note_previous_decl) 12280 << Var->getDeclName(); 12281 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 12282 diag::note_lambda_decl); 12283 // FIXME: If we error out because an outer lambda can not implicitly 12284 // capture a variable that an inner lambda explicitly captures, we 12285 // should have the inner lambda do the explicit capture - because 12286 // it makes for cleaner diagnostics later. This would purely be done 12287 // so that the diagnostic does not misleadingly claim that a variable 12288 // can not be captured by a lambda implicitly even though it is captured 12289 // explicitly. Suggestion: 12290 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 12291 // at the function head 12292 // - cache the StartingDeclContext - this must be a lambda 12293 // - captureInLambda in the innermost lambda the variable. 12294 } 12295 return true; 12296 } 12297 12298 FunctionScopesIndex--; 12299 DC = ParentDC; 12300 Explicit = false; 12301 } while (!Var->getDeclContext()->Equals(DC)); 12302 12303 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 12304 // computing the type of the capture at each step, checking type-specific 12305 // requirements, and adding captures if requested. 12306 // If the variable had already been captured previously, we start capturing 12307 // at the lambda nested within that one. 12308 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 12309 ++I) { 12310 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 12311 12312 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 12313 if (!captureInBlock(BSI, Var, ExprLoc, 12314 BuildAndDiagnose, CaptureType, 12315 DeclRefType, Nested, *this)) 12316 return true; 12317 Nested = true; 12318 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 12319 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 12320 BuildAndDiagnose, CaptureType, 12321 DeclRefType, Nested, *this)) 12322 return true; 12323 Nested = true; 12324 } else { 12325 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 12326 if (!captureInLambda(LSI, Var, ExprLoc, 12327 BuildAndDiagnose, CaptureType, 12328 DeclRefType, Nested, Kind, EllipsisLoc, 12329 /*IsTopScope*/I == N - 1, *this)) 12330 return true; 12331 Nested = true; 12332 } 12333 } 12334 return false; 12335 } 12336 12337 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 12338 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 12339 QualType CaptureType; 12340 QualType DeclRefType; 12341 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 12342 /*BuildAndDiagnose=*/true, CaptureType, 12343 DeclRefType, nullptr); 12344 } 12345 12346 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 12347 QualType CaptureType; 12348 QualType DeclRefType; 12349 12350 // Determine whether we can capture this variable. 12351 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 12352 /*BuildAndDiagnose=*/false, CaptureType, 12353 DeclRefType, nullptr)) 12354 return QualType(); 12355 12356 return DeclRefType; 12357 } 12358 12359 12360 12361 // If either the type of the variable or the initializer is dependent, 12362 // return false. Otherwise, determine whether the variable is a constant 12363 // expression. Use this if you need to know if a variable that might or 12364 // might not be dependent is truly a constant expression. 12365 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 12366 ASTContext &Context) { 12367 12368 if (Var->getType()->isDependentType()) 12369 return false; 12370 const VarDecl *DefVD = nullptr; 12371 Var->getAnyInitializer(DefVD); 12372 if (!DefVD) 12373 return false; 12374 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 12375 Expr *Init = cast<Expr>(Eval->Value); 12376 if (Init->isValueDependent()) 12377 return false; 12378 return IsVariableAConstantExpression(Var, Context); 12379 } 12380 12381 12382 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 12383 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 12384 // an object that satisfies the requirements for appearing in a 12385 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 12386 // is immediately applied." This function handles the lvalue-to-rvalue 12387 // conversion part. 12388 MaybeODRUseExprs.erase(E->IgnoreParens()); 12389 12390 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 12391 // to a variable that is a constant expression, and if so, identify it as 12392 // a reference to a variable that does not involve an odr-use of that 12393 // variable. 12394 if (LambdaScopeInfo *LSI = getCurLambda()) { 12395 Expr *SansParensExpr = E->IgnoreParens(); 12396 VarDecl *Var = nullptr; 12397 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 12398 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 12399 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 12400 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 12401 12402 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 12403 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 12404 } 12405 } 12406 12407 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 12408 if (!Res.isUsable()) 12409 return Res; 12410 12411 // If a constant-expression is a reference to a variable where we delay 12412 // deciding whether it is an odr-use, just assume we will apply the 12413 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 12414 // (a non-type template argument), we have special handling anyway. 12415 UpdateMarkingForLValueToRValue(Res.get()); 12416 return Res; 12417 } 12418 12419 void Sema::CleanupVarDeclMarking() { 12420 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 12421 e = MaybeODRUseExprs.end(); 12422 i != e; ++i) { 12423 VarDecl *Var; 12424 SourceLocation Loc; 12425 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 12426 Var = cast<VarDecl>(DRE->getDecl()); 12427 Loc = DRE->getLocation(); 12428 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 12429 Var = cast<VarDecl>(ME->getMemberDecl()); 12430 Loc = ME->getMemberLoc(); 12431 } else { 12432 llvm_unreachable("Unexpected expression"); 12433 } 12434 12435 MarkVarDeclODRUsed(Var, Loc, *this, 12436 /*MaxFunctionScopeIndex Pointer*/ nullptr); 12437 } 12438 12439 MaybeODRUseExprs.clear(); 12440 } 12441 12442 12443 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 12444 VarDecl *Var, Expr *E) { 12445 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 12446 "Invalid Expr argument to DoMarkVarDeclReferenced"); 12447 Var->setReferenced(); 12448 12449 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 12450 bool MarkODRUsed = true; 12451 12452 // If the context is not potentially evaluated, this is not an odr-use and 12453 // does not trigger instantiation. 12454 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 12455 if (SemaRef.isUnevaluatedContext()) 12456 return; 12457 12458 // If we don't yet know whether this context is going to end up being an 12459 // evaluated context, and we're referencing a variable from an enclosing 12460 // scope, add a potential capture. 12461 // 12462 // FIXME: Is this necessary? These contexts are only used for default 12463 // arguments, where local variables can't be used. 12464 const bool RefersToEnclosingScope = 12465 (SemaRef.CurContext != Var->getDeclContext() && 12466 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 12467 if (RefersToEnclosingScope) { 12468 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 12469 // If a variable could potentially be odr-used, defer marking it so 12470 // until we finish analyzing the full expression for any 12471 // lvalue-to-rvalue 12472 // or discarded value conversions that would obviate odr-use. 12473 // Add it to the list of potential captures that will be analyzed 12474 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 12475 // unless the variable is a reference that was initialized by a constant 12476 // expression (this will never need to be captured or odr-used). 12477 assert(E && "Capture variable should be used in an expression."); 12478 if (!Var->getType()->isReferenceType() || 12479 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 12480 LSI->addPotentialCapture(E->IgnoreParens()); 12481 } 12482 } 12483 12484 if (!isTemplateInstantiation(TSK)) 12485 return; 12486 12487 // Instantiate, but do not mark as odr-used, variable templates. 12488 MarkODRUsed = false; 12489 } 12490 12491 VarTemplateSpecializationDecl *VarSpec = 12492 dyn_cast<VarTemplateSpecializationDecl>(Var); 12493 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 12494 "Can't instantiate a partial template specialization."); 12495 12496 // Perform implicit instantiation of static data members, static data member 12497 // templates of class templates, and variable template specializations. Delay 12498 // instantiations of variable templates, except for those that could be used 12499 // in a constant expression. 12500 if (isTemplateInstantiation(TSK)) { 12501 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 12502 12503 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 12504 if (Var->getPointOfInstantiation().isInvalid()) { 12505 // This is a modification of an existing AST node. Notify listeners. 12506 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 12507 L->StaticDataMemberInstantiated(Var); 12508 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 12509 // Don't bother trying to instantiate it again, unless we might need 12510 // its initializer before we get to the end of the TU. 12511 TryInstantiating = false; 12512 } 12513 12514 if (Var->getPointOfInstantiation().isInvalid()) 12515 Var->setTemplateSpecializationKind(TSK, Loc); 12516 12517 if (TryInstantiating) { 12518 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 12519 bool InstantiationDependent = false; 12520 bool IsNonDependent = 12521 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 12522 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 12523 : true; 12524 12525 // Do not instantiate specializations that are still type-dependent. 12526 if (IsNonDependent) { 12527 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 12528 // Do not defer instantiations of variables which could be used in a 12529 // constant expression. 12530 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 12531 } else { 12532 SemaRef.PendingInstantiations 12533 .push_back(std::make_pair(Var, PointOfInstantiation)); 12534 } 12535 } 12536 } 12537 } 12538 12539 if(!MarkODRUsed) return; 12540 12541 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 12542 // the requirements for appearing in a constant expression (5.19) and, if 12543 // it is an object, the lvalue-to-rvalue conversion (4.1) 12544 // is immediately applied." We check the first part here, and 12545 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 12546 // Note that we use the C++11 definition everywhere because nothing in 12547 // C++03 depends on whether we get the C++03 version correct. The second 12548 // part does not apply to references, since they are not objects. 12549 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 12550 // A reference initialized by a constant expression can never be 12551 // odr-used, so simply ignore it. 12552 if (!Var->getType()->isReferenceType()) 12553 SemaRef.MaybeODRUseExprs.insert(E); 12554 } else 12555 MarkVarDeclODRUsed(Var, Loc, SemaRef, 12556 /*MaxFunctionScopeIndex ptr*/ nullptr); 12557 } 12558 12559 /// \brief Mark a variable referenced, and check whether it is odr-used 12560 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 12561 /// used directly for normal expressions referring to VarDecl. 12562 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 12563 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 12564 } 12565 12566 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 12567 Decl *D, Expr *E, bool OdrUse) { 12568 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 12569 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 12570 return; 12571 } 12572 12573 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 12574 12575 // If this is a call to a method via a cast, also mark the method in the 12576 // derived class used in case codegen can devirtualize the call. 12577 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 12578 if (!ME) 12579 return; 12580 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 12581 if (!MD) 12582 return; 12583 // Only attempt to devirtualize if this is truly a virtual call. 12584 bool IsVirtualCall = MD->isVirtual() && !ME->hasQualifier(); 12585 if (!IsVirtualCall) 12586 return; 12587 const Expr *Base = ME->getBase(); 12588 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 12589 if (!MostDerivedClassDecl) 12590 return; 12591 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 12592 if (!DM || DM->isPure()) 12593 return; 12594 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 12595 } 12596 12597 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 12598 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 12599 // TODO: update this with DR# once a defect report is filed. 12600 // C++11 defect. The address of a pure member should not be an ODR use, even 12601 // if it's a qualified reference. 12602 bool OdrUse = true; 12603 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 12604 if (Method->isVirtual()) 12605 OdrUse = false; 12606 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 12607 } 12608 12609 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 12610 void Sema::MarkMemberReferenced(MemberExpr *E) { 12611 // C++11 [basic.def.odr]p2: 12612 // A non-overloaded function whose name appears as a potentially-evaluated 12613 // expression or a member of a set of candidate functions, if selected by 12614 // overload resolution when referred to from a potentially-evaluated 12615 // expression, is odr-used, unless it is a pure virtual function and its 12616 // name is not explicitly qualified. 12617 bool OdrUse = true; 12618 if (!E->hasQualifier()) { 12619 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 12620 if (Method->isPure()) 12621 OdrUse = false; 12622 } 12623 SourceLocation Loc = E->getMemberLoc().isValid() ? 12624 E->getMemberLoc() : E->getLocStart(); 12625 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 12626 } 12627 12628 /// \brief Perform marking for a reference to an arbitrary declaration. It 12629 /// marks the declaration referenced, and performs odr-use checking for 12630 /// functions and variables. This method should not be used when building a 12631 /// normal expression which refers to a variable. 12632 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 12633 if (OdrUse) { 12634 if (auto *VD = dyn_cast<VarDecl>(D)) { 12635 MarkVariableReferenced(Loc, VD); 12636 return; 12637 } 12638 } 12639 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 12640 MarkFunctionReferenced(Loc, FD, OdrUse); 12641 return; 12642 } 12643 D->setReferenced(); 12644 } 12645 12646 namespace { 12647 // Mark all of the declarations referenced 12648 // FIXME: Not fully implemented yet! We need to have a better understanding 12649 // of when we're entering 12650 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 12651 Sema &S; 12652 SourceLocation Loc; 12653 12654 public: 12655 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 12656 12657 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 12658 12659 bool TraverseTemplateArgument(const TemplateArgument &Arg); 12660 bool TraverseRecordType(RecordType *T); 12661 }; 12662 } 12663 12664 bool MarkReferencedDecls::TraverseTemplateArgument( 12665 const TemplateArgument &Arg) { 12666 if (Arg.getKind() == TemplateArgument::Declaration) { 12667 if (Decl *D = Arg.getAsDecl()) 12668 S.MarkAnyDeclReferenced(Loc, D, true); 12669 } 12670 12671 return Inherited::TraverseTemplateArgument(Arg); 12672 } 12673 12674 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 12675 if (ClassTemplateSpecializationDecl *Spec 12676 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 12677 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 12678 return TraverseTemplateArguments(Args.data(), Args.size()); 12679 } 12680 12681 return true; 12682 } 12683 12684 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 12685 MarkReferencedDecls Marker(*this, Loc); 12686 Marker.TraverseType(Context.getCanonicalType(T)); 12687 } 12688 12689 namespace { 12690 /// \brief Helper class that marks all of the declarations referenced by 12691 /// potentially-evaluated subexpressions as "referenced". 12692 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 12693 Sema &S; 12694 bool SkipLocalVariables; 12695 12696 public: 12697 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 12698 12699 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 12700 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 12701 12702 void VisitDeclRefExpr(DeclRefExpr *E) { 12703 // If we were asked not to visit local variables, don't. 12704 if (SkipLocalVariables) { 12705 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 12706 if (VD->hasLocalStorage()) 12707 return; 12708 } 12709 12710 S.MarkDeclRefReferenced(E); 12711 } 12712 12713 void VisitMemberExpr(MemberExpr *E) { 12714 S.MarkMemberReferenced(E); 12715 Inherited::VisitMemberExpr(E); 12716 } 12717 12718 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 12719 S.MarkFunctionReferenced(E->getLocStart(), 12720 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 12721 Visit(E->getSubExpr()); 12722 } 12723 12724 void VisitCXXNewExpr(CXXNewExpr *E) { 12725 if (E->getOperatorNew()) 12726 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 12727 if (E->getOperatorDelete()) 12728 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 12729 Inherited::VisitCXXNewExpr(E); 12730 } 12731 12732 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 12733 if (E->getOperatorDelete()) 12734 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 12735 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 12736 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 12737 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 12738 S.MarkFunctionReferenced(E->getLocStart(), 12739 S.LookupDestructor(Record)); 12740 } 12741 12742 Inherited::VisitCXXDeleteExpr(E); 12743 } 12744 12745 void VisitCXXConstructExpr(CXXConstructExpr *E) { 12746 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 12747 Inherited::VisitCXXConstructExpr(E); 12748 } 12749 12750 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 12751 Visit(E->getExpr()); 12752 } 12753 12754 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 12755 Inherited::VisitImplicitCastExpr(E); 12756 12757 if (E->getCastKind() == CK_LValueToRValue) 12758 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 12759 } 12760 }; 12761 } 12762 12763 /// \brief Mark any declarations that appear within this expression or any 12764 /// potentially-evaluated subexpressions as "referenced". 12765 /// 12766 /// \param SkipLocalVariables If true, don't mark local variables as 12767 /// 'referenced'. 12768 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 12769 bool SkipLocalVariables) { 12770 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 12771 } 12772 12773 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 12774 /// of the program being compiled. 12775 /// 12776 /// This routine emits the given diagnostic when the code currently being 12777 /// type-checked is "potentially evaluated", meaning that there is a 12778 /// possibility that the code will actually be executable. Code in sizeof() 12779 /// expressions, code used only during overload resolution, etc., are not 12780 /// potentially evaluated. This routine will suppress such diagnostics or, 12781 /// in the absolutely nutty case of potentially potentially evaluated 12782 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 12783 /// later. 12784 /// 12785 /// This routine should be used for all diagnostics that describe the run-time 12786 /// behavior of a program, such as passing a non-POD value through an ellipsis. 12787 /// Failure to do so will likely result in spurious diagnostics or failures 12788 /// during overload resolution or within sizeof/alignof/typeof/typeid. 12789 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 12790 const PartialDiagnostic &PD) { 12791 switch (ExprEvalContexts.back().Context) { 12792 case Unevaluated: 12793 case UnevaluatedAbstract: 12794 // The argument will never be evaluated, so don't complain. 12795 break; 12796 12797 case ConstantEvaluated: 12798 // Relevant diagnostics should be produced by constant evaluation. 12799 break; 12800 12801 case PotentiallyEvaluated: 12802 case PotentiallyEvaluatedIfUsed: 12803 if (Statement && getCurFunctionOrMethodDecl()) { 12804 FunctionScopes.back()->PossiblyUnreachableDiags. 12805 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 12806 } 12807 else 12808 Diag(Loc, PD); 12809 12810 return true; 12811 } 12812 12813 return false; 12814 } 12815 12816 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 12817 CallExpr *CE, FunctionDecl *FD) { 12818 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 12819 return false; 12820 12821 // If we're inside a decltype's expression, don't check for a valid return 12822 // type or construct temporaries until we know whether this is the last call. 12823 if (ExprEvalContexts.back().IsDecltype) { 12824 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 12825 return false; 12826 } 12827 12828 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 12829 FunctionDecl *FD; 12830 CallExpr *CE; 12831 12832 public: 12833 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 12834 : FD(FD), CE(CE) { } 12835 12836 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 12837 if (!FD) { 12838 S.Diag(Loc, diag::err_call_incomplete_return) 12839 << T << CE->getSourceRange(); 12840 return; 12841 } 12842 12843 S.Diag(Loc, diag::err_call_function_incomplete_return) 12844 << CE->getSourceRange() << FD->getDeclName() << T; 12845 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 12846 << FD->getDeclName(); 12847 } 12848 } Diagnoser(FD, CE); 12849 12850 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 12851 return true; 12852 12853 return false; 12854 } 12855 12856 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 12857 // will prevent this condition from triggering, which is what we want. 12858 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 12859 SourceLocation Loc; 12860 12861 unsigned diagnostic = diag::warn_condition_is_assignment; 12862 bool IsOrAssign = false; 12863 12864 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 12865 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 12866 return; 12867 12868 IsOrAssign = Op->getOpcode() == BO_OrAssign; 12869 12870 // Greylist some idioms by putting them into a warning subcategory. 12871 if (ObjCMessageExpr *ME 12872 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 12873 Selector Sel = ME->getSelector(); 12874 12875 // self = [<foo> init...] 12876 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 12877 diagnostic = diag::warn_condition_is_idiomatic_assignment; 12878 12879 // <foo> = [<bar> nextObject] 12880 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 12881 diagnostic = diag::warn_condition_is_idiomatic_assignment; 12882 } 12883 12884 Loc = Op->getOperatorLoc(); 12885 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 12886 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 12887 return; 12888 12889 IsOrAssign = Op->getOperator() == OO_PipeEqual; 12890 Loc = Op->getOperatorLoc(); 12891 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 12892 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 12893 else { 12894 // Not an assignment. 12895 return; 12896 } 12897 12898 Diag(Loc, diagnostic) << E->getSourceRange(); 12899 12900 SourceLocation Open = E->getLocStart(); 12901 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 12902 Diag(Loc, diag::note_condition_assign_silence) 12903 << FixItHint::CreateInsertion(Open, "(") 12904 << FixItHint::CreateInsertion(Close, ")"); 12905 12906 if (IsOrAssign) 12907 Diag(Loc, diag::note_condition_or_assign_to_comparison) 12908 << FixItHint::CreateReplacement(Loc, "!="); 12909 else 12910 Diag(Loc, diag::note_condition_assign_to_comparison) 12911 << FixItHint::CreateReplacement(Loc, "=="); 12912 } 12913 12914 /// \brief Redundant parentheses over an equality comparison can indicate 12915 /// that the user intended an assignment used as condition. 12916 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 12917 // Don't warn if the parens came from a macro. 12918 SourceLocation parenLoc = ParenE->getLocStart(); 12919 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 12920 return; 12921 // Don't warn for dependent expressions. 12922 if (ParenE->isTypeDependent()) 12923 return; 12924 12925 Expr *E = ParenE->IgnoreParens(); 12926 12927 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 12928 if (opE->getOpcode() == BO_EQ && 12929 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 12930 == Expr::MLV_Valid) { 12931 SourceLocation Loc = opE->getOperatorLoc(); 12932 12933 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 12934 SourceRange ParenERange = ParenE->getSourceRange(); 12935 Diag(Loc, diag::note_equality_comparison_silence) 12936 << FixItHint::CreateRemoval(ParenERange.getBegin()) 12937 << FixItHint::CreateRemoval(ParenERange.getEnd()); 12938 Diag(Loc, diag::note_equality_comparison_to_assign) 12939 << FixItHint::CreateReplacement(Loc, "="); 12940 } 12941 } 12942 12943 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 12944 DiagnoseAssignmentAsCondition(E); 12945 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 12946 DiagnoseEqualityWithExtraParens(parenE); 12947 12948 ExprResult result = CheckPlaceholderExpr(E); 12949 if (result.isInvalid()) return ExprError(); 12950 E = result.get(); 12951 12952 if (!E->isTypeDependent()) { 12953 if (getLangOpts().CPlusPlus) 12954 return CheckCXXBooleanCondition(E); // C++ 6.4p4 12955 12956 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 12957 if (ERes.isInvalid()) 12958 return ExprError(); 12959 E = ERes.get(); 12960 12961 QualType T = E->getType(); 12962 if (!T->isScalarType()) { // C99 6.8.4.1p1 12963 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 12964 << T << E->getSourceRange(); 12965 return ExprError(); 12966 } 12967 } 12968 12969 return E; 12970 } 12971 12972 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 12973 Expr *SubExpr) { 12974 if (!SubExpr) 12975 return ExprError(); 12976 12977 return CheckBooleanCondition(SubExpr, Loc); 12978 } 12979 12980 namespace { 12981 /// A visitor for rebuilding a call to an __unknown_any expression 12982 /// to have an appropriate type. 12983 struct RebuildUnknownAnyFunction 12984 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 12985 12986 Sema &S; 12987 12988 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 12989 12990 ExprResult VisitStmt(Stmt *S) { 12991 llvm_unreachable("unexpected statement!"); 12992 } 12993 12994 ExprResult VisitExpr(Expr *E) { 12995 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 12996 << E->getSourceRange(); 12997 return ExprError(); 12998 } 12999 13000 /// Rebuild an expression which simply semantically wraps another 13001 /// expression which it shares the type and value kind of. 13002 template <class T> ExprResult rebuildSugarExpr(T *E) { 13003 ExprResult SubResult = Visit(E->getSubExpr()); 13004 if (SubResult.isInvalid()) return ExprError(); 13005 13006 Expr *SubExpr = SubResult.get(); 13007 E->setSubExpr(SubExpr); 13008 E->setType(SubExpr->getType()); 13009 E->setValueKind(SubExpr->getValueKind()); 13010 assert(E->getObjectKind() == OK_Ordinary); 13011 return E; 13012 } 13013 13014 ExprResult VisitParenExpr(ParenExpr *E) { 13015 return rebuildSugarExpr(E); 13016 } 13017 13018 ExprResult VisitUnaryExtension(UnaryOperator *E) { 13019 return rebuildSugarExpr(E); 13020 } 13021 13022 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 13023 ExprResult SubResult = Visit(E->getSubExpr()); 13024 if (SubResult.isInvalid()) return ExprError(); 13025 13026 Expr *SubExpr = SubResult.get(); 13027 E->setSubExpr(SubExpr); 13028 E->setType(S.Context.getPointerType(SubExpr->getType())); 13029 assert(E->getValueKind() == VK_RValue); 13030 assert(E->getObjectKind() == OK_Ordinary); 13031 return E; 13032 } 13033 13034 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 13035 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 13036 13037 E->setType(VD->getType()); 13038 13039 assert(E->getValueKind() == VK_RValue); 13040 if (S.getLangOpts().CPlusPlus && 13041 !(isa<CXXMethodDecl>(VD) && 13042 cast<CXXMethodDecl>(VD)->isInstance())) 13043 E->setValueKind(VK_LValue); 13044 13045 return E; 13046 } 13047 13048 ExprResult VisitMemberExpr(MemberExpr *E) { 13049 return resolveDecl(E, E->getMemberDecl()); 13050 } 13051 13052 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 13053 return resolveDecl(E, E->getDecl()); 13054 } 13055 }; 13056 } 13057 13058 /// Given a function expression of unknown-any type, try to rebuild it 13059 /// to have a function type. 13060 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 13061 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 13062 if (Result.isInvalid()) return ExprError(); 13063 return S.DefaultFunctionArrayConversion(Result.get()); 13064 } 13065 13066 namespace { 13067 /// A visitor for rebuilding an expression of type __unknown_anytype 13068 /// into one which resolves the type directly on the referring 13069 /// expression. Strict preservation of the original source 13070 /// structure is not a goal. 13071 struct RebuildUnknownAnyExpr 13072 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 13073 13074 Sema &S; 13075 13076 /// The current destination type. 13077 QualType DestType; 13078 13079 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 13080 : S(S), DestType(CastType) {} 13081 13082 ExprResult VisitStmt(Stmt *S) { 13083 llvm_unreachable("unexpected statement!"); 13084 } 13085 13086 ExprResult VisitExpr(Expr *E) { 13087 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 13088 << E->getSourceRange(); 13089 return ExprError(); 13090 } 13091 13092 ExprResult VisitCallExpr(CallExpr *E); 13093 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 13094 13095 /// Rebuild an expression which simply semantically wraps another 13096 /// expression which it shares the type and value kind of. 13097 template <class T> ExprResult rebuildSugarExpr(T *E) { 13098 ExprResult SubResult = Visit(E->getSubExpr()); 13099 if (SubResult.isInvalid()) return ExprError(); 13100 Expr *SubExpr = SubResult.get(); 13101 E->setSubExpr(SubExpr); 13102 E->setType(SubExpr->getType()); 13103 E->setValueKind(SubExpr->getValueKind()); 13104 assert(E->getObjectKind() == OK_Ordinary); 13105 return E; 13106 } 13107 13108 ExprResult VisitParenExpr(ParenExpr *E) { 13109 return rebuildSugarExpr(E); 13110 } 13111 13112 ExprResult VisitUnaryExtension(UnaryOperator *E) { 13113 return rebuildSugarExpr(E); 13114 } 13115 13116 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 13117 const PointerType *Ptr = DestType->getAs<PointerType>(); 13118 if (!Ptr) { 13119 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 13120 << E->getSourceRange(); 13121 return ExprError(); 13122 } 13123 assert(E->getValueKind() == VK_RValue); 13124 assert(E->getObjectKind() == OK_Ordinary); 13125 E->setType(DestType); 13126 13127 // Build the sub-expression as if it were an object of the pointee type. 13128 DestType = Ptr->getPointeeType(); 13129 ExprResult SubResult = Visit(E->getSubExpr()); 13130 if (SubResult.isInvalid()) return ExprError(); 13131 E->setSubExpr(SubResult.get()); 13132 return E; 13133 } 13134 13135 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 13136 13137 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 13138 13139 ExprResult VisitMemberExpr(MemberExpr *E) { 13140 return resolveDecl(E, E->getMemberDecl()); 13141 } 13142 13143 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 13144 return resolveDecl(E, E->getDecl()); 13145 } 13146 }; 13147 } 13148 13149 /// Rebuilds a call expression which yielded __unknown_anytype. 13150 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 13151 Expr *CalleeExpr = E->getCallee(); 13152 13153 enum FnKind { 13154 FK_MemberFunction, 13155 FK_FunctionPointer, 13156 FK_BlockPointer 13157 }; 13158 13159 FnKind Kind; 13160 QualType CalleeType = CalleeExpr->getType(); 13161 if (CalleeType == S.Context.BoundMemberTy) { 13162 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 13163 Kind = FK_MemberFunction; 13164 CalleeType = Expr::findBoundMemberType(CalleeExpr); 13165 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 13166 CalleeType = Ptr->getPointeeType(); 13167 Kind = FK_FunctionPointer; 13168 } else { 13169 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 13170 Kind = FK_BlockPointer; 13171 } 13172 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 13173 13174 // Verify that this is a legal result type of a function. 13175 if (DestType->isArrayType() || DestType->isFunctionType()) { 13176 unsigned diagID = diag::err_func_returning_array_function; 13177 if (Kind == FK_BlockPointer) 13178 diagID = diag::err_block_returning_array_function; 13179 13180 S.Diag(E->getExprLoc(), diagID) 13181 << DestType->isFunctionType() << DestType; 13182 return ExprError(); 13183 } 13184 13185 // Otherwise, go ahead and set DestType as the call's result. 13186 E->setType(DestType.getNonLValueExprType(S.Context)); 13187 E->setValueKind(Expr::getValueKindForType(DestType)); 13188 assert(E->getObjectKind() == OK_Ordinary); 13189 13190 // Rebuild the function type, replacing the result type with DestType. 13191 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 13192 if (Proto) { 13193 // __unknown_anytype(...) is a special case used by the debugger when 13194 // it has no idea what a function's signature is. 13195 // 13196 // We want to build this call essentially under the K&R 13197 // unprototyped rules, but making a FunctionNoProtoType in C++ 13198 // would foul up all sorts of assumptions. However, we cannot 13199 // simply pass all arguments as variadic arguments, nor can we 13200 // portably just call the function under a non-variadic type; see 13201 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 13202 // However, it turns out that in practice it is generally safe to 13203 // call a function declared as "A foo(B,C,D);" under the prototype 13204 // "A foo(B,C,D,...);". The only known exception is with the 13205 // Windows ABI, where any variadic function is implicitly cdecl 13206 // regardless of its normal CC. Therefore we change the parameter 13207 // types to match the types of the arguments. 13208 // 13209 // This is a hack, but it is far superior to moving the 13210 // corresponding target-specific code from IR-gen to Sema/AST. 13211 13212 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 13213 SmallVector<QualType, 8> ArgTypes; 13214 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 13215 ArgTypes.reserve(E->getNumArgs()); 13216 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 13217 Expr *Arg = E->getArg(i); 13218 QualType ArgType = Arg->getType(); 13219 if (E->isLValue()) { 13220 ArgType = S.Context.getLValueReferenceType(ArgType); 13221 } else if (E->isXValue()) { 13222 ArgType = S.Context.getRValueReferenceType(ArgType); 13223 } 13224 ArgTypes.push_back(ArgType); 13225 } 13226 ParamTypes = ArgTypes; 13227 } 13228 DestType = S.Context.getFunctionType(DestType, ParamTypes, 13229 Proto->getExtProtoInfo()); 13230 } else { 13231 DestType = S.Context.getFunctionNoProtoType(DestType, 13232 FnType->getExtInfo()); 13233 } 13234 13235 // Rebuild the appropriate pointer-to-function type. 13236 switch (Kind) { 13237 case FK_MemberFunction: 13238 // Nothing to do. 13239 break; 13240 13241 case FK_FunctionPointer: 13242 DestType = S.Context.getPointerType(DestType); 13243 break; 13244 13245 case FK_BlockPointer: 13246 DestType = S.Context.getBlockPointerType(DestType); 13247 break; 13248 } 13249 13250 // Finally, we can recurse. 13251 ExprResult CalleeResult = Visit(CalleeExpr); 13252 if (!CalleeResult.isUsable()) return ExprError(); 13253 E->setCallee(CalleeResult.get()); 13254 13255 // Bind a temporary if necessary. 13256 return S.MaybeBindToTemporary(E); 13257 } 13258 13259 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 13260 // Verify that this is a legal result type of a call. 13261 if (DestType->isArrayType() || DestType->isFunctionType()) { 13262 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 13263 << DestType->isFunctionType() << DestType; 13264 return ExprError(); 13265 } 13266 13267 // Rewrite the method result type if available. 13268 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 13269 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 13270 Method->setReturnType(DestType); 13271 } 13272 13273 // Change the type of the message. 13274 E->setType(DestType.getNonReferenceType()); 13275 E->setValueKind(Expr::getValueKindForType(DestType)); 13276 13277 return S.MaybeBindToTemporary(E); 13278 } 13279 13280 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 13281 // The only case we should ever see here is a function-to-pointer decay. 13282 if (E->getCastKind() == CK_FunctionToPointerDecay) { 13283 assert(E->getValueKind() == VK_RValue); 13284 assert(E->getObjectKind() == OK_Ordinary); 13285 13286 E->setType(DestType); 13287 13288 // Rebuild the sub-expression as the pointee (function) type. 13289 DestType = DestType->castAs<PointerType>()->getPointeeType(); 13290 13291 ExprResult Result = Visit(E->getSubExpr()); 13292 if (!Result.isUsable()) return ExprError(); 13293 13294 E->setSubExpr(Result.get()); 13295 return E; 13296 } else if (E->getCastKind() == CK_LValueToRValue) { 13297 assert(E->getValueKind() == VK_RValue); 13298 assert(E->getObjectKind() == OK_Ordinary); 13299 13300 assert(isa<BlockPointerType>(E->getType())); 13301 13302 E->setType(DestType); 13303 13304 // The sub-expression has to be a lvalue reference, so rebuild it as such. 13305 DestType = S.Context.getLValueReferenceType(DestType); 13306 13307 ExprResult Result = Visit(E->getSubExpr()); 13308 if (!Result.isUsable()) return ExprError(); 13309 13310 E->setSubExpr(Result.get()); 13311 return E; 13312 } else { 13313 llvm_unreachable("Unhandled cast type!"); 13314 } 13315 } 13316 13317 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 13318 ExprValueKind ValueKind = VK_LValue; 13319 QualType Type = DestType; 13320 13321 // We know how to make this work for certain kinds of decls: 13322 13323 // - functions 13324 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 13325 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 13326 DestType = Ptr->getPointeeType(); 13327 ExprResult Result = resolveDecl(E, VD); 13328 if (Result.isInvalid()) return ExprError(); 13329 return S.ImpCastExprToType(Result.get(), Type, 13330 CK_FunctionToPointerDecay, VK_RValue); 13331 } 13332 13333 if (!Type->isFunctionType()) { 13334 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 13335 << VD << E->getSourceRange(); 13336 return ExprError(); 13337 } 13338 13339 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 13340 if (MD->isInstance()) { 13341 ValueKind = VK_RValue; 13342 Type = S.Context.BoundMemberTy; 13343 } 13344 13345 // Function references aren't l-values in C. 13346 if (!S.getLangOpts().CPlusPlus) 13347 ValueKind = VK_RValue; 13348 13349 // - variables 13350 } else if (isa<VarDecl>(VD)) { 13351 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 13352 Type = RefTy->getPointeeType(); 13353 } else if (Type->isFunctionType()) { 13354 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 13355 << VD << E->getSourceRange(); 13356 return ExprError(); 13357 } 13358 13359 // - nothing else 13360 } else { 13361 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 13362 << VD << E->getSourceRange(); 13363 return ExprError(); 13364 } 13365 13366 // Modifying the declaration like this is friendly to IR-gen but 13367 // also really dangerous. 13368 VD->setType(DestType); 13369 E->setType(Type); 13370 E->setValueKind(ValueKind); 13371 return E; 13372 } 13373 13374 /// Check a cast of an unknown-any type. We intentionally only 13375 /// trigger this for C-style casts. 13376 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 13377 Expr *CastExpr, CastKind &CastKind, 13378 ExprValueKind &VK, CXXCastPath &Path) { 13379 // Rewrite the casted expression from scratch. 13380 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 13381 if (!result.isUsable()) return ExprError(); 13382 13383 CastExpr = result.get(); 13384 VK = CastExpr->getValueKind(); 13385 CastKind = CK_NoOp; 13386 13387 return CastExpr; 13388 } 13389 13390 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 13391 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 13392 } 13393 13394 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 13395 Expr *arg, QualType ¶mType) { 13396 // If the syntactic form of the argument is not an explicit cast of 13397 // any sort, just do default argument promotion. 13398 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 13399 if (!castArg) { 13400 ExprResult result = DefaultArgumentPromotion(arg); 13401 if (result.isInvalid()) return ExprError(); 13402 paramType = result.get()->getType(); 13403 return result; 13404 } 13405 13406 // Otherwise, use the type that was written in the explicit cast. 13407 assert(!arg->hasPlaceholderType()); 13408 paramType = castArg->getTypeAsWritten(); 13409 13410 // Copy-initialize a parameter of that type. 13411 InitializedEntity entity = 13412 InitializedEntity::InitializeParameter(Context, paramType, 13413 /*consumed*/ false); 13414 return PerformCopyInitialization(entity, callLoc, arg); 13415 } 13416 13417 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 13418 Expr *orig = E; 13419 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 13420 while (true) { 13421 E = E->IgnoreParenImpCasts(); 13422 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 13423 E = call->getCallee(); 13424 diagID = diag::err_uncasted_call_of_unknown_any; 13425 } else { 13426 break; 13427 } 13428 } 13429 13430 SourceLocation loc; 13431 NamedDecl *d; 13432 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 13433 loc = ref->getLocation(); 13434 d = ref->getDecl(); 13435 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 13436 loc = mem->getMemberLoc(); 13437 d = mem->getMemberDecl(); 13438 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 13439 diagID = diag::err_uncasted_call_of_unknown_any; 13440 loc = msg->getSelectorStartLoc(); 13441 d = msg->getMethodDecl(); 13442 if (!d) { 13443 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 13444 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 13445 << orig->getSourceRange(); 13446 return ExprError(); 13447 } 13448 } else { 13449 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 13450 << E->getSourceRange(); 13451 return ExprError(); 13452 } 13453 13454 S.Diag(loc, diagID) << d << orig->getSourceRange(); 13455 13456 // Never recoverable. 13457 return ExprError(); 13458 } 13459 13460 /// Check for operands with placeholder types and complain if found. 13461 /// Returns true if there was an error and no recovery was possible. 13462 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 13463 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 13464 if (!placeholderType) return E; 13465 13466 switch (placeholderType->getKind()) { 13467 13468 // Overloaded expressions. 13469 case BuiltinType::Overload: { 13470 // Try to resolve a single function template specialization. 13471 // This is obligatory. 13472 ExprResult result = E; 13473 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 13474 return result; 13475 13476 // If that failed, try to recover with a call. 13477 } else { 13478 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 13479 /*complain*/ true); 13480 return result; 13481 } 13482 } 13483 13484 // Bound member functions. 13485 case BuiltinType::BoundMember: { 13486 ExprResult result = E; 13487 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function), 13488 /*complain*/ true); 13489 return result; 13490 } 13491 13492 // ARC unbridged casts. 13493 case BuiltinType::ARCUnbridgedCast: { 13494 Expr *realCast = stripARCUnbridgedCast(E); 13495 diagnoseARCUnbridgedCast(realCast); 13496 return realCast; 13497 } 13498 13499 // Expressions of unknown type. 13500 case BuiltinType::UnknownAny: 13501 return diagnoseUnknownAnyExpr(*this, E); 13502 13503 // Pseudo-objects. 13504 case BuiltinType::PseudoObject: 13505 return checkPseudoObjectRValue(E); 13506 13507 case BuiltinType::BuiltinFn: { 13508 // Accept __noop without parens by implicitly converting it to a call expr. 13509 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 13510 if (DRE) { 13511 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 13512 if (FD->getBuiltinID() == Builtin::BI__noop) { 13513 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 13514 CK_BuiltinFnToFnPtr).get(); 13515 return new (Context) CallExpr(Context, E, None, Context.IntTy, 13516 VK_RValue, SourceLocation()); 13517 } 13518 } 13519 13520 Diag(E->getLocStart(), diag::err_builtin_fn_use); 13521 return ExprError(); 13522 } 13523 13524 // Everything else should be impossible. 13525 #define BUILTIN_TYPE(Id, SingletonId) \ 13526 case BuiltinType::Id: 13527 #define PLACEHOLDER_TYPE(Id, SingletonId) 13528 #include "clang/AST/BuiltinTypes.def" 13529 break; 13530 } 13531 13532 llvm_unreachable("invalid placeholder type!"); 13533 } 13534 13535 bool Sema::CheckCaseExpression(Expr *E) { 13536 if (E->isTypeDependent()) 13537 return true; 13538 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 13539 return E->getType()->isIntegralOrEnumerationType(); 13540 return false; 13541 } 13542 13543 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 13544 ExprResult 13545 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 13546 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 13547 "Unknown Objective-C Boolean value!"); 13548 QualType BoolT = Context.ObjCBuiltinBoolTy; 13549 if (!Context.getBOOLDecl()) { 13550 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 13551 Sema::LookupOrdinaryName); 13552 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 13553 NamedDecl *ND = Result.getFoundDecl(); 13554 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 13555 Context.setBOOLDecl(TD); 13556 } 13557 } 13558 if (Context.getBOOLDecl()) 13559 BoolT = Context.getBOOLType(); 13560 return new (Context) 13561 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 13562 } 13563