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/ExprOpenMP.h" 28 #include "clang/AST/RecursiveASTVisitor.h" 29 #include "clang/AST/TypeLoc.h" 30 #include "clang/Basic/PartialDiagnostic.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/LiteralSupport.h" 34 #include "clang/Lex/Preprocessor.h" 35 #include "clang/Sema/AnalysisBasedWarnings.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Designator.h" 39 #include "clang/Sema/Initialization.h" 40 #include "clang/Sema/Lookup.h" 41 #include "clang/Sema/ParsedTemplate.h" 42 #include "clang/Sema/Scope.h" 43 #include "clang/Sema/ScopeInfo.h" 44 #include "clang/Sema/SemaFixItUtils.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/Support/ConvertUTF.h" 47 using namespace clang; 48 using namespace sema; 49 50 /// \brief Determine whether the use of this declaration is valid, without 51 /// emitting diagnostics. 52 bool Sema::CanUseDecl(NamedDecl *D) { 53 // See if this is an auto-typed variable whose initializer we are parsing. 54 if (ParsingInitForAutoVars.count(D)) 55 return false; 56 57 // See if this is a deleted function. 58 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 59 if (FD->isDeleted()) 60 return false; 61 62 // If the function has a deduced return type, and we can't deduce it, 63 // then we can't use it either. 64 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 65 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 66 return false; 67 } 68 69 // See if this function is unavailable. 70 if (D->getAvailability() == AR_Unavailable && 71 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 72 return false; 73 74 return true; 75 } 76 77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 78 // Warn if this is used but marked unused. 79 if (D->hasAttr<UnusedAttr>()) { 80 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 81 if (DC && !DC->hasAttr<UnusedAttr>()) 82 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 83 } 84 } 85 86 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) { 87 const auto *OMD = dyn_cast<ObjCMethodDecl>(D); 88 if (!OMD) 89 return false; 90 const ObjCInterfaceDecl *OID = OMD->getClassInterface(); 91 if (!OID) 92 return false; 93 94 for (const ObjCCategoryDecl *Cat : OID->visible_categories()) 95 if (ObjCMethodDecl *CatMeth = 96 Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod())) 97 if (!CatMeth->hasAttr<AvailabilityAttr>()) 98 return true; 99 return false; 100 } 101 102 static AvailabilityResult 103 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc, 104 const ObjCInterfaceDecl *UnknownObjCClass, 105 bool ObjCPropertyAccess) { 106 // See if this declaration is unavailable or deprecated. 107 std::string Message; 108 AvailabilityResult Result = D->getAvailability(&Message); 109 110 // For typedefs, if the typedef declaration appears available look 111 // to the underlying type to see if it is more restrictive. 112 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 113 if (Result == AR_Available) { 114 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 115 D = TT->getDecl(); 116 Result = D->getAvailability(&Message); 117 continue; 118 } 119 } 120 break; 121 } 122 123 // Forward class declarations get their attributes from their definition. 124 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) { 125 if (IDecl->getDefinition()) { 126 D = IDecl->getDefinition(); 127 Result = D->getAvailability(&Message); 128 } 129 } 130 131 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) 132 if (Result == AR_Available) { 133 const DeclContext *DC = ECD->getDeclContext(); 134 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC)) 135 Result = TheEnumDecl->getAvailability(&Message); 136 } 137 138 const ObjCPropertyDecl *ObjCPDecl = nullptr; 139 if (Result == AR_Deprecated || Result == AR_Unavailable || 140 AR_NotYetIntroduced) { 141 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 142 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 143 AvailabilityResult PDeclResult = PD->getAvailability(nullptr); 144 if (PDeclResult == Result) 145 ObjCPDecl = PD; 146 } 147 } 148 } 149 150 switch (Result) { 151 case AR_Available: 152 break; 153 154 case AR_Deprecated: 155 if (S.getCurContextAvailability() != AR_Deprecated) 156 S.EmitAvailabilityWarning(Sema::AD_Deprecation, 157 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 158 ObjCPropertyAccess); 159 break; 160 161 case AR_NotYetIntroduced: { 162 // Don't do this for enums, they can't be redeclared. 163 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D)) 164 break; 165 166 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited(); 167 // Objective-C method declarations in categories are not modelled as 168 // redeclarations, so manually look for a redeclaration in a category 169 // if necessary. 170 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D)) 171 Warn = false; 172 // In general, D will point to the most recent redeclaration. However, 173 // for `@class A;` decls, this isn't true -- manually go through the 174 // redecl chain in that case. 175 if (Warn && isa<ObjCInterfaceDecl>(D)) 176 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn; 177 Redecl = Redecl->getPreviousDecl()) 178 if (!Redecl->hasAttr<AvailabilityAttr>() || 179 Redecl->getAttr<AvailabilityAttr>()->isInherited()) 180 Warn = false; 181 182 if (Warn) 183 S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc, 184 UnknownObjCClass, ObjCPDecl, 185 ObjCPropertyAccess); 186 break; 187 } 188 189 case AR_Unavailable: 190 if (S.getCurContextAvailability() != AR_Unavailable) 191 S.EmitAvailabilityWarning(Sema::AD_Unavailable, 192 D, Message, Loc, UnknownObjCClass, ObjCPDecl, 193 ObjCPropertyAccess); 194 break; 195 196 } 197 return Result; 198 } 199 200 /// \brief Emit a note explaining that this function is deleted. 201 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 202 assert(Decl->isDeleted()); 203 204 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 205 206 if (Method && Method->isDeleted() && Method->isDefaulted()) { 207 // If the method was explicitly defaulted, point at that declaration. 208 if (!Method->isImplicit()) 209 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 210 211 // Try to diagnose why this special member function was implicitly 212 // deleted. This might fail, if that reason no longer applies. 213 CXXSpecialMember CSM = getSpecialMember(Method); 214 if (CSM != CXXInvalid) 215 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true); 216 217 return; 218 } 219 220 if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) { 221 if (CXXConstructorDecl *BaseCD = 222 const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) { 223 Diag(Decl->getLocation(), diag::note_inherited_deleted_here); 224 if (BaseCD->isDeleted()) { 225 NoteDeletedFunction(BaseCD); 226 } else { 227 // FIXME: An explanation of why exactly it can't be inherited 228 // would be nice. 229 Diag(BaseCD->getLocation(), diag::note_cannot_inherit); 230 } 231 return; 232 } 233 } 234 235 Diag(Decl->getLocation(), diag::note_availability_specified_here) 236 << Decl << true; 237 } 238 239 /// \brief Determine whether a FunctionDecl was ever declared with an 240 /// explicit storage class. 241 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 242 for (auto I : D->redecls()) { 243 if (I->getStorageClass() != SC_None) 244 return true; 245 } 246 return false; 247 } 248 249 /// \brief Check whether we're in an extern inline function and referring to a 250 /// variable or function with internal linkage (C11 6.7.4p3). 251 /// 252 /// This is only a warning because we used to silently accept this code, but 253 /// in many cases it will not behave correctly. This is not enabled in C++ mode 254 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 255 /// and so while there may still be user mistakes, most of the time we can't 256 /// prove that there are errors. 257 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 258 const NamedDecl *D, 259 SourceLocation Loc) { 260 // This is disabled under C++; there are too many ways for this to fire in 261 // contexts where the warning is a false positive, or where it is technically 262 // correct but benign. 263 if (S.getLangOpts().CPlusPlus) 264 return; 265 266 // Check if this is an inlined function or method. 267 FunctionDecl *Current = S.getCurFunctionDecl(); 268 if (!Current) 269 return; 270 if (!Current->isInlined()) 271 return; 272 if (!Current->isExternallyVisible()) 273 return; 274 275 // Check if the decl has internal linkage. 276 if (D->getFormalLinkage() != InternalLinkage) 277 return; 278 279 // Downgrade from ExtWarn to Extension if 280 // (1) the supposedly external inline function is in the main file, 281 // and probably won't be included anywhere else. 282 // (2) the thing we're referencing is a pure function. 283 // (3) the thing we're referencing is another inline function. 284 // This last can give us false negatives, but it's better than warning on 285 // wrappers for simple C library functions. 286 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 287 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 288 if (!DowngradeWarning && UsedFn) 289 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 290 291 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 292 : diag::ext_internal_in_extern_inline) 293 << /*IsVar=*/!UsedFn << D; 294 295 S.MaybeSuggestAddingStaticToDecl(Current); 296 297 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 298 << D; 299 } 300 301 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 302 const FunctionDecl *First = Cur->getFirstDecl(); 303 304 // Suggest "static" on the function, if possible. 305 if (!hasAnyExplicitStorageClass(First)) { 306 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 307 Diag(DeclBegin, diag::note_convert_inline_to_static) 308 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 309 } 310 } 311 312 /// \brief Determine whether the use of this declaration is valid, and 313 /// emit any corresponding diagnostics. 314 /// 315 /// This routine diagnoses various problems with referencing 316 /// declarations that can occur when using a declaration. For example, 317 /// it might warn if a deprecated or unavailable declaration is being 318 /// used, or produce an error (and return true) if a C++0x deleted 319 /// function is being used. 320 /// 321 /// \returns true if there was an error (this declaration cannot be 322 /// referenced), false otherwise. 323 /// 324 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 325 const ObjCInterfaceDecl *UnknownObjCClass, 326 bool ObjCPropertyAccess) { 327 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 328 // If there were any diagnostics suppressed by template argument deduction, 329 // emit them now. 330 SuppressedDiagnosticsMap::iterator 331 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 332 if (Pos != SuppressedDiagnostics.end()) { 333 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second; 334 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I) 335 Diag(Suppressed[I].first, Suppressed[I].second); 336 337 // Clear out the list of suppressed diagnostics, so that we don't emit 338 // them again for this specialization. However, we don't obsolete this 339 // entry from the table, because we want to avoid ever emitting these 340 // diagnostics again. 341 Suppressed.clear(); 342 } 343 344 // C++ [basic.start.main]p3: 345 // The function 'main' shall not be used within a program. 346 if (cast<FunctionDecl>(D)->isMain()) 347 Diag(Loc, diag::ext_main_used); 348 } 349 350 // See if this is an auto-typed variable whose initializer we are parsing. 351 if (ParsingInitForAutoVars.count(D)) { 352 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 353 << D->getDeclName(); 354 return true; 355 } 356 357 // See if this is a deleted function. 358 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 359 if (FD->isDeleted()) { 360 Diag(Loc, diag::err_deleted_function_use); 361 NoteDeletedFunction(FD); 362 return true; 363 } 364 365 // If the function has a deduced return type, and we can't deduce it, 366 // then we can't use it either. 367 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 368 DeduceReturnType(FD, Loc)) 369 return true; 370 } 371 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass, 372 ObjCPropertyAccess); 373 374 DiagnoseUnusedOfDecl(*this, D, Loc); 375 376 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 377 378 return false; 379 } 380 381 /// \brief Retrieve the message suffix that should be added to a 382 /// diagnostic complaining about the given function being deleted or 383 /// unavailable. 384 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 385 std::string Message; 386 if (FD->getAvailability(&Message)) 387 return ": " + Message; 388 389 return std::string(); 390 } 391 392 /// DiagnoseSentinelCalls - This routine checks whether a call or 393 /// message-send is to a declaration with the sentinel attribute, and 394 /// if so, it checks that the requirements of the sentinel are 395 /// satisfied. 396 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 397 ArrayRef<Expr *> Args) { 398 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 399 if (!attr) 400 return; 401 402 // The number of formal parameters of the declaration. 403 unsigned numFormalParams; 404 405 // The kind of declaration. This is also an index into a %select in 406 // the diagnostic. 407 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 408 409 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 410 numFormalParams = MD->param_size(); 411 calleeType = CT_Method; 412 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 413 numFormalParams = FD->param_size(); 414 calleeType = CT_Function; 415 } else if (isa<VarDecl>(D)) { 416 QualType type = cast<ValueDecl>(D)->getType(); 417 const FunctionType *fn = nullptr; 418 if (const PointerType *ptr = type->getAs<PointerType>()) { 419 fn = ptr->getPointeeType()->getAs<FunctionType>(); 420 if (!fn) return; 421 calleeType = CT_Function; 422 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 423 fn = ptr->getPointeeType()->castAs<FunctionType>(); 424 calleeType = CT_Block; 425 } else { 426 return; 427 } 428 429 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 430 numFormalParams = proto->getNumParams(); 431 } else { 432 numFormalParams = 0; 433 } 434 } else { 435 return; 436 } 437 438 // "nullPos" is the number of formal parameters at the end which 439 // effectively count as part of the variadic arguments. This is 440 // useful if you would prefer to not have *any* formal parameters, 441 // but the language forces you to have at least one. 442 unsigned nullPos = attr->getNullPos(); 443 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 444 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 445 446 // The number of arguments which should follow the sentinel. 447 unsigned numArgsAfterSentinel = attr->getSentinel(); 448 449 // If there aren't enough arguments for all the formal parameters, 450 // the sentinel, and the args after the sentinel, complain. 451 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 452 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 453 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 454 return; 455 } 456 457 // Otherwise, find the sentinel expression. 458 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 459 if (!sentinelExpr) return; 460 if (sentinelExpr->isValueDependent()) return; 461 if (Context.isSentinelNullExpr(sentinelExpr)) return; 462 463 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 464 // or 'NULL' if those are actually defined in the context. Only use 465 // 'nil' for ObjC methods, where it's much more likely that the 466 // variadic arguments form a list of object pointers. 467 SourceLocation MissingNilLoc 468 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd()); 469 std::string NullValue; 470 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 471 NullValue = "nil"; 472 else if (getLangOpts().CPlusPlus11) 473 NullValue = "nullptr"; 474 else if (PP.isMacroDefined("NULL")) 475 NullValue = "NULL"; 476 else 477 NullValue = "(void*) 0"; 478 479 if (MissingNilLoc.isInvalid()) 480 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 481 else 482 Diag(MissingNilLoc, diag::warn_missing_sentinel) 483 << int(calleeType) 484 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 485 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 486 } 487 488 SourceRange Sema::getExprRange(Expr *E) const { 489 return E ? E->getSourceRange() : SourceRange(); 490 } 491 492 //===----------------------------------------------------------------------===// 493 // Standard Promotions and Conversions 494 //===----------------------------------------------------------------------===// 495 496 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 497 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) { 498 // Handle any placeholder expressions which made it here. 499 if (E->getType()->isPlaceholderType()) { 500 ExprResult result = CheckPlaceholderExpr(E); 501 if (result.isInvalid()) return ExprError(); 502 E = result.get(); 503 } 504 505 QualType Ty = E->getType(); 506 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 507 508 if (Ty->isFunctionType()) { 509 // If we are here, we are not calling a function but taking 510 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3). 511 if (getLangOpts().OpenCL) { 512 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 513 return ExprError(); 514 } 515 E = ImpCastExprToType(E, Context.getPointerType(Ty), 516 CK_FunctionToPointerDecay).get(); 517 } else if (Ty->isArrayType()) { 518 // In C90 mode, arrays only promote to pointers if the array expression is 519 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 520 // type 'array of type' is converted to an expression that has type 'pointer 521 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 522 // that has type 'array of type' ...". The relevant change is "an lvalue" 523 // (C90) to "an expression" (C99). 524 // 525 // C++ 4.2p1: 526 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 527 // T" can be converted to an rvalue of type "pointer to T". 528 // 529 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 530 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 531 CK_ArrayToPointerDecay).get(); 532 } 533 return E; 534 } 535 536 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 537 // Check to see if we are dereferencing a null pointer. If so, 538 // and if not volatile-qualified, this is undefined behavior that the 539 // optimizer will delete, so warn about it. People sometimes try to use this 540 // to get a deterministic trap and are surprised by clang's behavior. This 541 // only handles the pattern "*null", which is a very syntactic check. 542 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 543 if (UO->getOpcode() == UO_Deref && 544 UO->getSubExpr()->IgnoreParenCasts()-> 545 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 546 !UO->getType().isVolatileQualified()) { 547 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 548 S.PDiag(diag::warn_indirection_through_null) 549 << UO->getSubExpr()->getSourceRange()); 550 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 551 S.PDiag(diag::note_indirection_through_null)); 552 } 553 } 554 555 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 556 SourceLocation AssignLoc, 557 const Expr* RHS) { 558 const ObjCIvarDecl *IV = OIRE->getDecl(); 559 if (!IV) 560 return; 561 562 DeclarationName MemberName = IV->getDeclName(); 563 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 564 if (!Member || !Member->isStr("isa")) 565 return; 566 567 const Expr *Base = OIRE->getBase(); 568 QualType BaseType = Base->getType(); 569 if (OIRE->isArrow()) 570 BaseType = BaseType->getPointeeType(); 571 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 572 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 573 ObjCInterfaceDecl *ClassDeclared = nullptr; 574 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 575 if (!ClassDeclared->getSuperClass() 576 && (*ClassDeclared->ivar_begin()) == IV) { 577 if (RHS) { 578 NamedDecl *ObjectSetClass = 579 S.LookupSingleName(S.TUScope, 580 &S.Context.Idents.get("object_setClass"), 581 SourceLocation(), S.LookupOrdinaryName); 582 if (ObjectSetClass) { 583 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd()); 584 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 585 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 586 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 587 AssignLoc), ",") << 588 FixItHint::CreateInsertion(RHSLocEnd, ")"); 589 } 590 else 591 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 592 } else { 593 NamedDecl *ObjectGetClass = 594 S.LookupSingleName(S.TUScope, 595 &S.Context.Idents.get("object_getClass"), 596 SourceLocation(), S.LookupOrdinaryName); 597 if (ObjectGetClass) 598 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 599 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 600 FixItHint::CreateReplacement( 601 SourceRange(OIRE->getOpLoc(), 602 OIRE->getLocEnd()), ")"); 603 else 604 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 605 } 606 S.Diag(IV->getLocation(), diag::note_ivar_decl); 607 } 608 } 609 } 610 611 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 612 // Handle any placeholder expressions which made it here. 613 if (E->getType()->isPlaceholderType()) { 614 ExprResult result = CheckPlaceholderExpr(E); 615 if (result.isInvalid()) return ExprError(); 616 E = result.get(); 617 } 618 619 // C++ [conv.lval]p1: 620 // A glvalue of a non-function, non-array type T can be 621 // converted to a prvalue. 622 if (!E->isGLValue()) return E; 623 624 QualType T = E->getType(); 625 assert(!T.isNull() && "r-value conversion on typeless expression?"); 626 627 // We don't want to throw lvalue-to-rvalue casts on top of 628 // expressions of certain types in C++. 629 if (getLangOpts().CPlusPlus && 630 (E->getType() == Context.OverloadTy || 631 T->isDependentType() || 632 T->isRecordType())) 633 return E; 634 635 // The C standard is actually really unclear on this point, and 636 // DR106 tells us what the result should be but not why. It's 637 // generally best to say that void types just doesn't undergo 638 // lvalue-to-rvalue at all. Note that expressions of unqualified 639 // 'void' type are never l-values, but qualified void can be. 640 if (T->isVoidType()) 641 return E; 642 643 // OpenCL usually rejects direct accesses to values of 'half' type. 644 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 645 T->isHalfType()) { 646 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 647 << 0 << T; 648 return ExprError(); 649 } 650 651 CheckForNullPointerDereference(*this, E); 652 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 653 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 654 &Context.Idents.get("object_getClass"), 655 SourceLocation(), LookupOrdinaryName); 656 if (ObjectGetClass) 657 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 658 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 659 FixItHint::CreateReplacement( 660 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 661 else 662 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 663 } 664 else if (const ObjCIvarRefExpr *OIRE = 665 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 666 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 667 668 // C++ [conv.lval]p1: 669 // [...] If T is a non-class type, the type of the prvalue is the 670 // cv-unqualified version of T. Otherwise, the type of the 671 // rvalue is T. 672 // 673 // C99 6.3.2.1p2: 674 // If the lvalue has qualified type, the value has the unqualified 675 // version of the type of the lvalue; otherwise, the value has the 676 // type of the lvalue. 677 if (T.hasQualifiers()) 678 T = T.getUnqualifiedType(); 679 680 UpdateMarkingForLValueToRValue(E); 681 682 // Loading a __weak object implicitly retains the value, so we need a cleanup to 683 // balance that. 684 if (getLangOpts().ObjCAutoRefCount && 685 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 686 ExprNeedsCleanups = true; 687 688 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 689 nullptr, VK_RValue); 690 691 // C11 6.3.2.1p2: 692 // ... if the lvalue has atomic type, the value has the non-atomic version 693 // of the type of the lvalue ... 694 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 695 T = Atomic->getValueType().getUnqualifiedType(); 696 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 697 nullptr, VK_RValue); 698 } 699 700 return Res; 701 } 702 703 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) { 704 ExprResult Res = DefaultFunctionArrayConversion(E); 705 if (Res.isInvalid()) 706 return ExprError(); 707 Res = DefaultLvalueConversion(Res.get()); 708 if (Res.isInvalid()) 709 return ExprError(); 710 return Res; 711 } 712 713 /// CallExprUnaryConversions - a special case of an unary conversion 714 /// performed on a function designator of a call expression. 715 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 716 QualType Ty = E->getType(); 717 ExprResult Res = E; 718 // Only do implicit cast for a function type, but not for a pointer 719 // to function type. 720 if (Ty->isFunctionType()) { 721 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 722 CK_FunctionToPointerDecay).get(); 723 if (Res.isInvalid()) 724 return ExprError(); 725 } 726 Res = DefaultLvalueConversion(Res.get()); 727 if (Res.isInvalid()) 728 return ExprError(); 729 return Res.get(); 730 } 731 732 /// UsualUnaryConversions - Performs various conversions that are common to most 733 /// operators (C99 6.3). The conversions of array and function types are 734 /// sometimes suppressed. For example, the array->pointer conversion doesn't 735 /// apply if the array is an argument to the sizeof or address (&) operators. 736 /// In these instances, this routine should *not* be called. 737 ExprResult Sema::UsualUnaryConversions(Expr *E) { 738 // First, convert to an r-value. 739 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 740 if (Res.isInvalid()) 741 return ExprError(); 742 E = Res.get(); 743 744 QualType Ty = E->getType(); 745 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 746 747 // Half FP have to be promoted to float unless it is natively supported 748 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 749 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 750 751 // Try to perform integral promotions if the object has a theoretically 752 // promotable type. 753 if (Ty->isIntegralOrUnscopedEnumerationType()) { 754 // C99 6.3.1.1p2: 755 // 756 // The following may be used in an expression wherever an int or 757 // unsigned int may be used: 758 // - an object or expression with an integer type whose integer 759 // conversion rank is less than or equal to the rank of int 760 // and unsigned int. 761 // - A bit-field of type _Bool, int, signed int, or unsigned int. 762 // 763 // If an int can represent all values of the original type, the 764 // value is converted to an int; otherwise, it is converted to an 765 // unsigned int. These are called the integer promotions. All 766 // other types are unchanged by the integer promotions. 767 768 QualType PTy = Context.isPromotableBitField(E); 769 if (!PTy.isNull()) { 770 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 771 return E; 772 } 773 if (Ty->isPromotableIntegerType()) { 774 QualType PT = Context.getPromotedIntegerType(Ty); 775 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 776 return E; 777 } 778 } 779 return E; 780 } 781 782 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 783 /// do not have a prototype. Arguments that have type float or __fp16 784 /// are promoted to double. All other argument types are converted by 785 /// UsualUnaryConversions(). 786 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 787 QualType Ty = E->getType(); 788 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 789 790 ExprResult Res = UsualUnaryConversions(E); 791 if (Res.isInvalid()) 792 return ExprError(); 793 E = Res.get(); 794 795 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 796 // double. 797 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 798 if (BTy && (BTy->getKind() == BuiltinType::Half || 799 BTy->getKind() == BuiltinType::Float)) 800 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 801 802 // C++ performs lvalue-to-rvalue conversion as a default argument 803 // promotion, even on class types, but note: 804 // C++11 [conv.lval]p2: 805 // When an lvalue-to-rvalue conversion occurs in an unevaluated 806 // operand or a subexpression thereof the value contained in the 807 // referenced object is not accessed. Otherwise, if the glvalue 808 // has a class type, the conversion copy-initializes a temporary 809 // of type T from the glvalue and the result of the conversion 810 // is a prvalue for the temporary. 811 // FIXME: add some way to gate this entire thing for correctness in 812 // potentially potentially evaluated contexts. 813 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 814 ExprResult Temp = PerformCopyInitialization( 815 InitializedEntity::InitializeTemporary(E->getType()), 816 E->getExprLoc(), E); 817 if (Temp.isInvalid()) 818 return ExprError(); 819 E = Temp.get(); 820 } 821 822 return E; 823 } 824 825 /// Determine the degree of POD-ness for an expression. 826 /// Incomplete types are considered POD, since this check can be performed 827 /// when we're in an unevaluated context. 828 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 829 if (Ty->isIncompleteType()) { 830 // C++11 [expr.call]p7: 831 // After these conversions, if the argument does not have arithmetic, 832 // enumeration, pointer, pointer to member, or class type, the program 833 // is ill-formed. 834 // 835 // Since we've already performed array-to-pointer and function-to-pointer 836 // decay, the only such type in C++ is cv void. This also handles 837 // initializer lists as variadic arguments. 838 if (Ty->isVoidType()) 839 return VAK_Invalid; 840 841 if (Ty->isObjCObjectType()) 842 return VAK_Invalid; 843 return VAK_Valid; 844 } 845 846 if (Ty.isCXX98PODType(Context)) 847 return VAK_Valid; 848 849 // C++11 [expr.call]p7: 850 // Passing a potentially-evaluated argument of class type (Clause 9) 851 // having a non-trivial copy constructor, a non-trivial move constructor, 852 // or a non-trivial destructor, with no corresponding parameter, 853 // is conditionally-supported with implementation-defined semantics. 854 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 855 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 856 if (!Record->hasNonTrivialCopyConstructor() && 857 !Record->hasNonTrivialMoveConstructor() && 858 !Record->hasNonTrivialDestructor()) 859 return VAK_ValidInCXX11; 860 861 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 862 return VAK_Valid; 863 864 if (Ty->isObjCObjectType()) 865 return VAK_Invalid; 866 867 if (getLangOpts().MSVCCompat) 868 return VAK_MSVCUndefined; 869 870 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 871 // permitted to reject them. We should consider doing so. 872 return VAK_Undefined; 873 } 874 875 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 876 // Don't allow one to pass an Objective-C interface to a vararg. 877 const QualType &Ty = E->getType(); 878 VarArgKind VAK = isValidVarArgType(Ty); 879 880 // Complain about passing non-POD types through varargs. 881 switch (VAK) { 882 case VAK_ValidInCXX11: 883 DiagRuntimeBehavior( 884 E->getLocStart(), nullptr, 885 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 886 << Ty << CT); 887 // Fall through. 888 case VAK_Valid: 889 if (Ty->isRecordType()) { 890 // This is unlikely to be what the user intended. If the class has a 891 // 'c_str' member function, the user probably meant to call that. 892 DiagRuntimeBehavior(E->getLocStart(), nullptr, 893 PDiag(diag::warn_pass_class_arg_to_vararg) 894 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 895 } 896 break; 897 898 case VAK_Undefined: 899 case VAK_MSVCUndefined: 900 DiagRuntimeBehavior( 901 E->getLocStart(), nullptr, 902 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 903 << getLangOpts().CPlusPlus11 << Ty << CT); 904 break; 905 906 case VAK_Invalid: 907 if (Ty->isObjCObjectType()) 908 DiagRuntimeBehavior( 909 E->getLocStart(), nullptr, 910 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 911 << Ty << CT); 912 else 913 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 914 << isa<InitListExpr>(E) << Ty << CT; 915 break; 916 } 917 } 918 919 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 920 /// will create a trap if the resulting type is not a POD type. 921 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 922 FunctionDecl *FDecl) { 923 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 924 // Strip the unbridged-cast placeholder expression off, if applicable. 925 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 926 (CT == VariadicMethod || 927 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 928 E = stripARCUnbridgedCast(E); 929 930 // Otherwise, do normal placeholder checking. 931 } else { 932 ExprResult ExprRes = CheckPlaceholderExpr(E); 933 if (ExprRes.isInvalid()) 934 return ExprError(); 935 E = ExprRes.get(); 936 } 937 } 938 939 ExprResult ExprRes = DefaultArgumentPromotion(E); 940 if (ExprRes.isInvalid()) 941 return ExprError(); 942 E = ExprRes.get(); 943 944 // Diagnostics regarding non-POD argument types are 945 // emitted along with format string checking in Sema::CheckFunctionCall(). 946 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 947 // Turn this into a trap. 948 CXXScopeSpec SS; 949 SourceLocation TemplateKWLoc; 950 UnqualifiedId Name; 951 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 952 E->getLocStart()); 953 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 954 Name, true, false); 955 if (TrapFn.isInvalid()) 956 return ExprError(); 957 958 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 959 E->getLocStart(), None, 960 E->getLocEnd()); 961 if (Call.isInvalid()) 962 return ExprError(); 963 964 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 965 Call.get(), E); 966 if (Comma.isInvalid()) 967 return ExprError(); 968 return Comma.get(); 969 } 970 971 if (!getLangOpts().CPlusPlus && 972 RequireCompleteType(E->getExprLoc(), E->getType(), 973 diag::err_call_incomplete_argument)) 974 return ExprError(); 975 976 return E; 977 } 978 979 /// \brief Converts an integer to complex float type. Helper function of 980 /// UsualArithmeticConversions() 981 /// 982 /// \return false if the integer expression is an integer type and is 983 /// successfully converted to the complex type. 984 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 985 ExprResult &ComplexExpr, 986 QualType IntTy, 987 QualType ComplexTy, 988 bool SkipCast) { 989 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 990 if (SkipCast) return false; 991 if (IntTy->isIntegerType()) { 992 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 993 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 994 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 995 CK_FloatingRealToComplex); 996 } else { 997 assert(IntTy->isComplexIntegerType()); 998 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 999 CK_IntegralComplexToFloatingComplex); 1000 } 1001 return false; 1002 } 1003 1004 /// \brief Handle arithmetic conversion with complex types. Helper function of 1005 /// UsualArithmeticConversions() 1006 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1007 ExprResult &RHS, QualType LHSType, 1008 QualType RHSType, 1009 bool IsCompAssign) { 1010 // if we have an integer operand, the result is the complex type. 1011 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1012 /*skipCast*/false)) 1013 return LHSType; 1014 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1015 /*skipCast*/IsCompAssign)) 1016 return RHSType; 1017 1018 // This handles complex/complex, complex/float, or float/complex. 1019 // When both operands are complex, the shorter operand is converted to the 1020 // type of the longer, and that is the type of the result. This corresponds 1021 // to what is done when combining two real floating-point operands. 1022 // The fun begins when size promotion occur across type domains. 1023 // From H&S 6.3.4: When one operand is complex and the other is a real 1024 // floating-point type, the less precise type is converted, within it's 1025 // real or complex domain, to the precision of the other type. For example, 1026 // when combining a "long double" with a "double _Complex", the 1027 // "double _Complex" is promoted to "long double _Complex". 1028 1029 // Compute the rank of the two types, regardless of whether they are complex. 1030 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1031 1032 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1033 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1034 QualType LHSElementType = 1035 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1036 QualType RHSElementType = 1037 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1038 1039 QualType ResultType = S.Context.getComplexType(LHSElementType); 1040 if (Order < 0) { 1041 // Promote the precision of the LHS if not an assignment. 1042 ResultType = S.Context.getComplexType(RHSElementType); 1043 if (!IsCompAssign) { 1044 if (LHSComplexType) 1045 LHS = 1046 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1047 else 1048 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1049 } 1050 } else if (Order > 0) { 1051 // Promote the precision of the RHS. 1052 if (RHSComplexType) 1053 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1054 else 1055 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1056 } 1057 return ResultType; 1058 } 1059 1060 /// \brief Hande arithmetic conversion from integer to float. Helper function 1061 /// of UsualArithmeticConversions() 1062 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1063 ExprResult &IntExpr, 1064 QualType FloatTy, QualType IntTy, 1065 bool ConvertFloat, bool ConvertInt) { 1066 if (IntTy->isIntegerType()) { 1067 if (ConvertInt) 1068 // Convert intExpr to the lhs floating point type. 1069 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1070 CK_IntegralToFloating); 1071 return FloatTy; 1072 } 1073 1074 // Convert both sides to the appropriate complex float. 1075 assert(IntTy->isComplexIntegerType()); 1076 QualType result = S.Context.getComplexType(FloatTy); 1077 1078 // _Complex int -> _Complex float 1079 if (ConvertInt) 1080 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1081 CK_IntegralComplexToFloatingComplex); 1082 1083 // float -> _Complex float 1084 if (ConvertFloat) 1085 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1086 CK_FloatingRealToComplex); 1087 1088 return result; 1089 } 1090 1091 /// \brief Handle arithmethic conversion with floating point types. Helper 1092 /// function of UsualArithmeticConversions() 1093 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1094 ExprResult &RHS, QualType LHSType, 1095 QualType RHSType, bool IsCompAssign) { 1096 bool LHSFloat = LHSType->isRealFloatingType(); 1097 bool RHSFloat = RHSType->isRealFloatingType(); 1098 1099 // If we have two real floating types, convert the smaller operand 1100 // to the bigger result. 1101 if (LHSFloat && RHSFloat) { 1102 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1103 if (order > 0) { 1104 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1105 return LHSType; 1106 } 1107 1108 assert(order < 0 && "illegal float comparison"); 1109 if (!IsCompAssign) 1110 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1111 return RHSType; 1112 } 1113 1114 if (LHSFloat) { 1115 // Half FP has to be promoted to float unless it is natively supported 1116 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1117 LHSType = S.Context.FloatTy; 1118 1119 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1120 /*convertFloat=*/!IsCompAssign, 1121 /*convertInt=*/ true); 1122 } 1123 assert(RHSFloat); 1124 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1125 /*convertInt=*/ true, 1126 /*convertFloat=*/!IsCompAssign); 1127 } 1128 1129 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1130 1131 namespace { 1132 /// These helper callbacks are placed in an anonymous namespace to 1133 /// permit their use as function template parameters. 1134 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1135 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1136 } 1137 1138 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1139 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1140 CK_IntegralComplexCast); 1141 } 1142 } 1143 1144 /// \brief Handle integer arithmetic conversions. Helper function of 1145 /// UsualArithmeticConversions() 1146 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1147 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1148 ExprResult &RHS, QualType LHSType, 1149 QualType RHSType, bool IsCompAssign) { 1150 // The rules for this case are in C99 6.3.1.8 1151 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1152 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1153 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1154 if (LHSSigned == RHSSigned) { 1155 // Same signedness; use the higher-ranked type 1156 if (order >= 0) { 1157 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1158 return LHSType; 1159 } else if (!IsCompAssign) 1160 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1161 return RHSType; 1162 } else if (order != (LHSSigned ? 1 : -1)) { 1163 // The unsigned type has greater than or equal rank to the 1164 // signed type, so use the unsigned type 1165 if (RHSSigned) { 1166 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1167 return LHSType; 1168 } else if (!IsCompAssign) 1169 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1170 return RHSType; 1171 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1172 // The two types are different widths; if we are here, that 1173 // means the signed type is larger than the unsigned type, so 1174 // use the signed type. 1175 if (LHSSigned) { 1176 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1177 return LHSType; 1178 } else if (!IsCompAssign) 1179 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1180 return RHSType; 1181 } else { 1182 // The signed type is higher-ranked than the unsigned type, 1183 // but isn't actually any bigger (like unsigned int and long 1184 // on most 32-bit systems). Use the unsigned type corresponding 1185 // to the signed type. 1186 QualType result = 1187 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1188 RHS = (*doRHSCast)(S, RHS.get(), result); 1189 if (!IsCompAssign) 1190 LHS = (*doLHSCast)(S, LHS.get(), result); 1191 return result; 1192 } 1193 } 1194 1195 /// \brief Handle conversions with GCC complex int extension. Helper function 1196 /// of UsualArithmeticConversions() 1197 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1198 ExprResult &RHS, QualType LHSType, 1199 QualType RHSType, 1200 bool IsCompAssign) { 1201 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1202 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1203 1204 if (LHSComplexInt && RHSComplexInt) { 1205 QualType LHSEltType = LHSComplexInt->getElementType(); 1206 QualType RHSEltType = RHSComplexInt->getElementType(); 1207 QualType ScalarType = 1208 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1209 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1210 1211 return S.Context.getComplexType(ScalarType); 1212 } 1213 1214 if (LHSComplexInt) { 1215 QualType LHSEltType = LHSComplexInt->getElementType(); 1216 QualType ScalarType = 1217 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1218 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1219 QualType ComplexType = S.Context.getComplexType(ScalarType); 1220 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1221 CK_IntegralRealToComplex); 1222 1223 return ComplexType; 1224 } 1225 1226 assert(RHSComplexInt); 1227 1228 QualType RHSEltType = RHSComplexInt->getElementType(); 1229 QualType ScalarType = 1230 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1231 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1232 QualType ComplexType = S.Context.getComplexType(ScalarType); 1233 1234 if (!IsCompAssign) 1235 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1236 CK_IntegralRealToComplex); 1237 return ComplexType; 1238 } 1239 1240 /// UsualArithmeticConversions - Performs various conversions that are common to 1241 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1242 /// routine returns the first non-arithmetic type found. The client is 1243 /// responsible for emitting appropriate error diagnostics. 1244 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1245 bool IsCompAssign) { 1246 if (!IsCompAssign) { 1247 LHS = UsualUnaryConversions(LHS.get()); 1248 if (LHS.isInvalid()) 1249 return QualType(); 1250 } 1251 1252 RHS = UsualUnaryConversions(RHS.get()); 1253 if (RHS.isInvalid()) 1254 return QualType(); 1255 1256 // For conversion purposes, we ignore any qualifiers. 1257 // For example, "const float" and "float" are equivalent. 1258 QualType LHSType = 1259 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1260 QualType RHSType = 1261 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1262 1263 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1264 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1265 LHSType = AtomicLHS->getValueType(); 1266 1267 // If both types are identical, no conversion is needed. 1268 if (LHSType == RHSType) 1269 return LHSType; 1270 1271 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1272 // The caller can deal with this (e.g. pointer + int). 1273 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1274 return QualType(); 1275 1276 // Apply unary and bitfield promotions to the LHS's type. 1277 QualType LHSUnpromotedType = LHSType; 1278 if (LHSType->isPromotableIntegerType()) 1279 LHSType = Context.getPromotedIntegerType(LHSType); 1280 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1281 if (!LHSBitfieldPromoteTy.isNull()) 1282 LHSType = LHSBitfieldPromoteTy; 1283 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1284 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1285 1286 // If both types are identical, no conversion is needed. 1287 if (LHSType == RHSType) 1288 return LHSType; 1289 1290 // At this point, we have two different arithmetic types. 1291 1292 // Handle complex types first (C99 6.3.1.8p1). 1293 if (LHSType->isComplexType() || RHSType->isComplexType()) 1294 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1295 IsCompAssign); 1296 1297 // Now handle "real" floating types (i.e. float, double, long double). 1298 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1299 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1300 IsCompAssign); 1301 1302 // Handle GCC complex int extension. 1303 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1304 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1305 IsCompAssign); 1306 1307 // Finally, we have two differing integer types. 1308 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1309 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1310 } 1311 1312 1313 //===----------------------------------------------------------------------===// 1314 // Semantic Analysis for various Expression Types 1315 //===----------------------------------------------------------------------===// 1316 1317 1318 ExprResult 1319 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1320 SourceLocation DefaultLoc, 1321 SourceLocation RParenLoc, 1322 Expr *ControllingExpr, 1323 ArrayRef<ParsedType> ArgTypes, 1324 ArrayRef<Expr *> ArgExprs) { 1325 unsigned NumAssocs = ArgTypes.size(); 1326 assert(NumAssocs == ArgExprs.size()); 1327 1328 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1329 for (unsigned i = 0; i < NumAssocs; ++i) { 1330 if (ArgTypes[i]) 1331 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1332 else 1333 Types[i] = nullptr; 1334 } 1335 1336 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1337 ControllingExpr, 1338 llvm::makeArrayRef(Types, NumAssocs), 1339 ArgExprs); 1340 delete [] Types; 1341 return ER; 1342 } 1343 1344 ExprResult 1345 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1346 SourceLocation DefaultLoc, 1347 SourceLocation RParenLoc, 1348 Expr *ControllingExpr, 1349 ArrayRef<TypeSourceInfo *> Types, 1350 ArrayRef<Expr *> Exprs) { 1351 unsigned NumAssocs = Types.size(); 1352 assert(NumAssocs == Exprs.size()); 1353 if (ControllingExpr->getType()->isPlaceholderType()) { 1354 ExprResult result = CheckPlaceholderExpr(ControllingExpr); 1355 if (result.isInvalid()) return ExprError(); 1356 ControllingExpr = result.get(); 1357 } 1358 1359 // The controlling expression is an unevaluated operand, so side effects are 1360 // likely unintended. 1361 if (ActiveTemplateInstantiations.empty() && 1362 ControllingExpr->HasSideEffects(Context, false)) 1363 Diag(ControllingExpr->getExprLoc(), 1364 diag::warn_side_effects_unevaluated_context); 1365 1366 bool TypeErrorFound = false, 1367 IsResultDependent = ControllingExpr->isTypeDependent(), 1368 ContainsUnexpandedParameterPack 1369 = ControllingExpr->containsUnexpandedParameterPack(); 1370 1371 for (unsigned i = 0; i < NumAssocs; ++i) { 1372 if (Exprs[i]->containsUnexpandedParameterPack()) 1373 ContainsUnexpandedParameterPack = true; 1374 1375 if (Types[i]) { 1376 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1377 ContainsUnexpandedParameterPack = true; 1378 1379 if (Types[i]->getType()->isDependentType()) { 1380 IsResultDependent = true; 1381 } else { 1382 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1383 // complete object type other than a variably modified type." 1384 unsigned D = 0; 1385 if (Types[i]->getType()->isIncompleteType()) 1386 D = diag::err_assoc_type_incomplete; 1387 else if (!Types[i]->getType()->isObjectType()) 1388 D = diag::err_assoc_type_nonobject; 1389 else if (Types[i]->getType()->isVariablyModifiedType()) 1390 D = diag::err_assoc_type_variably_modified; 1391 1392 if (D != 0) { 1393 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1394 << Types[i]->getTypeLoc().getSourceRange() 1395 << Types[i]->getType(); 1396 TypeErrorFound = true; 1397 } 1398 1399 // C11 6.5.1.1p2 "No two generic associations in the same generic 1400 // selection shall specify compatible types." 1401 for (unsigned j = i+1; j < NumAssocs; ++j) 1402 if (Types[j] && !Types[j]->getType()->isDependentType() && 1403 Context.typesAreCompatible(Types[i]->getType(), 1404 Types[j]->getType())) { 1405 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1406 diag::err_assoc_compatible_types) 1407 << Types[j]->getTypeLoc().getSourceRange() 1408 << Types[j]->getType() 1409 << Types[i]->getType(); 1410 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1411 diag::note_compat_assoc) 1412 << Types[i]->getTypeLoc().getSourceRange() 1413 << Types[i]->getType(); 1414 TypeErrorFound = true; 1415 } 1416 } 1417 } 1418 } 1419 if (TypeErrorFound) 1420 return ExprError(); 1421 1422 // If we determined that the generic selection is result-dependent, don't 1423 // try to compute the result expression. 1424 if (IsResultDependent) 1425 return new (Context) GenericSelectionExpr( 1426 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1427 ContainsUnexpandedParameterPack); 1428 1429 SmallVector<unsigned, 1> CompatIndices; 1430 unsigned DefaultIndex = -1U; 1431 for (unsigned i = 0; i < NumAssocs; ++i) { 1432 if (!Types[i]) 1433 DefaultIndex = i; 1434 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1435 Types[i]->getType())) 1436 CompatIndices.push_back(i); 1437 } 1438 1439 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1440 // type compatible with at most one of the types named in its generic 1441 // association list." 1442 if (CompatIndices.size() > 1) { 1443 // We strip parens here because the controlling expression is typically 1444 // parenthesized in macro definitions. 1445 ControllingExpr = ControllingExpr->IgnoreParens(); 1446 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1447 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1448 << (unsigned) CompatIndices.size(); 1449 for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(), 1450 E = CompatIndices.end(); I != E; ++I) { 1451 Diag(Types[*I]->getTypeLoc().getBeginLoc(), 1452 diag::note_compat_assoc) 1453 << Types[*I]->getTypeLoc().getSourceRange() 1454 << Types[*I]->getType(); 1455 } 1456 return ExprError(); 1457 } 1458 1459 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1460 // its controlling expression shall have type compatible with exactly one of 1461 // the types named in its generic association list." 1462 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1463 // We strip parens here because the controlling expression is typically 1464 // parenthesized in macro definitions. 1465 ControllingExpr = ControllingExpr->IgnoreParens(); 1466 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1467 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1468 return ExprError(); 1469 } 1470 1471 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1472 // type name that is compatible with the type of the controlling expression, 1473 // then the result expression of the generic selection is the expression 1474 // in that generic association. Otherwise, the result expression of the 1475 // generic selection is the expression in the default generic association." 1476 unsigned ResultIndex = 1477 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1478 1479 return new (Context) GenericSelectionExpr( 1480 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1481 ContainsUnexpandedParameterPack, ResultIndex); 1482 } 1483 1484 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1485 /// location of the token and the offset of the ud-suffix within it. 1486 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1487 unsigned Offset) { 1488 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1489 S.getLangOpts()); 1490 } 1491 1492 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1493 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1494 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1495 IdentifierInfo *UDSuffix, 1496 SourceLocation UDSuffixLoc, 1497 ArrayRef<Expr*> Args, 1498 SourceLocation LitEndLoc) { 1499 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1500 1501 QualType ArgTy[2]; 1502 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1503 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1504 if (ArgTy[ArgIdx]->isArrayType()) 1505 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1506 } 1507 1508 DeclarationName OpName = 1509 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1510 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1511 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1512 1513 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1514 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1515 /*AllowRaw*/false, /*AllowTemplate*/false, 1516 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1517 return ExprError(); 1518 1519 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1520 } 1521 1522 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1523 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1524 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1525 /// multiple tokens. However, the common case is that StringToks points to one 1526 /// string. 1527 /// 1528 ExprResult 1529 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1530 assert(!StringToks.empty() && "Must have at least one string!"); 1531 1532 StringLiteralParser Literal(StringToks, PP); 1533 if (Literal.hadError) 1534 return ExprError(); 1535 1536 SmallVector<SourceLocation, 4> StringTokLocs; 1537 for (unsigned i = 0; i != StringToks.size(); ++i) 1538 StringTokLocs.push_back(StringToks[i].getLocation()); 1539 1540 QualType CharTy = Context.CharTy; 1541 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1542 if (Literal.isWide()) { 1543 CharTy = Context.getWideCharType(); 1544 Kind = StringLiteral::Wide; 1545 } else if (Literal.isUTF8()) { 1546 Kind = StringLiteral::UTF8; 1547 } else if (Literal.isUTF16()) { 1548 CharTy = Context.Char16Ty; 1549 Kind = StringLiteral::UTF16; 1550 } else if (Literal.isUTF32()) { 1551 CharTy = Context.Char32Ty; 1552 Kind = StringLiteral::UTF32; 1553 } else if (Literal.isPascal()) { 1554 CharTy = Context.UnsignedCharTy; 1555 } 1556 1557 QualType CharTyConst = CharTy; 1558 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1559 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1560 CharTyConst.addConst(); 1561 1562 // Get an array type for the string, according to C99 6.4.5. This includes 1563 // the nul terminator character as well as the string length for pascal 1564 // strings. 1565 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1566 llvm::APInt(32, Literal.GetNumStringChars()+1), 1567 ArrayType::Normal, 0); 1568 1569 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1570 if (getLangOpts().OpenCL) { 1571 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1572 } 1573 1574 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1575 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1576 Kind, Literal.Pascal, StrTy, 1577 &StringTokLocs[0], 1578 StringTokLocs.size()); 1579 if (Literal.getUDSuffix().empty()) 1580 return Lit; 1581 1582 // We're building a user-defined literal. 1583 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1584 SourceLocation UDSuffixLoc = 1585 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1586 Literal.getUDSuffixOffset()); 1587 1588 // Make sure we're allowed user-defined literals here. 1589 if (!UDLScope) 1590 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1591 1592 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1593 // operator "" X (str, len) 1594 QualType SizeType = Context.getSizeType(); 1595 1596 DeclarationName OpName = 1597 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1598 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1599 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1600 1601 QualType ArgTy[] = { 1602 Context.getArrayDecayedType(StrTy), SizeType 1603 }; 1604 1605 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1606 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1607 /*AllowRaw*/false, /*AllowTemplate*/false, 1608 /*AllowStringTemplate*/true)) { 1609 1610 case LOLR_Cooked: { 1611 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1612 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1613 StringTokLocs[0]); 1614 Expr *Args[] = { Lit, LenArg }; 1615 1616 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1617 } 1618 1619 case LOLR_StringTemplate: { 1620 TemplateArgumentListInfo ExplicitArgs; 1621 1622 unsigned CharBits = Context.getIntWidth(CharTy); 1623 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1624 llvm::APSInt Value(CharBits, CharIsUnsigned); 1625 1626 TemplateArgument TypeArg(CharTy); 1627 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1628 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1629 1630 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1631 Value = Lit->getCodeUnit(I); 1632 TemplateArgument Arg(Context, Value, CharTy); 1633 TemplateArgumentLocInfo ArgInfo; 1634 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1635 } 1636 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1637 &ExplicitArgs); 1638 } 1639 case LOLR_Raw: 1640 case LOLR_Template: 1641 llvm_unreachable("unexpected literal operator lookup result"); 1642 case LOLR_Error: 1643 return ExprError(); 1644 } 1645 llvm_unreachable("unexpected literal operator lookup result"); 1646 } 1647 1648 ExprResult 1649 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1650 SourceLocation Loc, 1651 const CXXScopeSpec *SS) { 1652 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1653 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1654 } 1655 1656 /// BuildDeclRefExpr - Build an expression that references a 1657 /// declaration that does not require a closure capture. 1658 ExprResult 1659 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1660 const DeclarationNameInfo &NameInfo, 1661 const CXXScopeSpec *SS, NamedDecl *FoundD, 1662 const TemplateArgumentListInfo *TemplateArgs) { 1663 if (getLangOpts().CUDA) 1664 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1665 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1666 if (CheckCUDATarget(Caller, Callee)) { 1667 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1668 << IdentifyCUDATarget(Callee) << D->getIdentifier() 1669 << IdentifyCUDATarget(Caller); 1670 Diag(D->getLocation(), diag::note_previous_decl) 1671 << D->getIdentifier(); 1672 return ExprError(); 1673 } 1674 } 1675 1676 bool RefersToCapturedVariable = 1677 isa<VarDecl>(D) && 1678 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1679 1680 DeclRefExpr *E; 1681 if (isa<VarTemplateSpecializationDecl>(D)) { 1682 VarTemplateSpecializationDecl *VarSpec = 1683 cast<VarTemplateSpecializationDecl>(D); 1684 1685 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1686 : NestedNameSpecifierLoc(), 1687 VarSpec->getTemplateKeywordLoc(), D, 1688 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1689 FoundD, TemplateArgs); 1690 } else { 1691 assert(!TemplateArgs && "No template arguments for non-variable" 1692 " template specialization references"); 1693 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1694 : NestedNameSpecifierLoc(), 1695 SourceLocation(), D, RefersToCapturedVariable, 1696 NameInfo, Ty, VK, FoundD); 1697 } 1698 1699 MarkDeclRefReferenced(E); 1700 1701 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) && 1702 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1703 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1704 recordUseOfEvaluatedWeak(E); 1705 1706 // Just in case we're building an illegal pointer-to-member. 1707 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1708 if (FD && FD->isBitField()) 1709 E->setObjectKind(OK_BitField); 1710 1711 return E; 1712 } 1713 1714 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1715 /// possibly a list of template arguments. 1716 /// 1717 /// If this produces template arguments, it is permitted to call 1718 /// DecomposeTemplateName. 1719 /// 1720 /// This actually loses a lot of source location information for 1721 /// non-standard name kinds; we should consider preserving that in 1722 /// some way. 1723 void 1724 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1725 TemplateArgumentListInfo &Buffer, 1726 DeclarationNameInfo &NameInfo, 1727 const TemplateArgumentListInfo *&TemplateArgs) { 1728 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1729 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1730 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1731 1732 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1733 Id.TemplateId->NumArgs); 1734 translateTemplateArguments(TemplateArgsPtr, Buffer); 1735 1736 TemplateName TName = Id.TemplateId->Template.get(); 1737 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1738 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1739 TemplateArgs = &Buffer; 1740 } else { 1741 NameInfo = GetNameFromUnqualifiedId(Id); 1742 TemplateArgs = nullptr; 1743 } 1744 } 1745 1746 static void emitEmptyLookupTypoDiagnostic( 1747 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1748 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1749 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1750 DeclContext *Ctx = 1751 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1752 if (!TC) { 1753 // Emit a special diagnostic for failed member lookups. 1754 // FIXME: computing the declaration context might fail here (?) 1755 if (Ctx) 1756 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1757 << SS.getRange(); 1758 else 1759 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1760 return; 1761 } 1762 1763 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1764 bool DroppedSpecifier = 1765 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1766 unsigned NoteID = 1767 (TC.getCorrectionDecl() && isa<ImplicitParamDecl>(TC.getCorrectionDecl())) 1768 ? diag::note_implicit_param_decl 1769 : diag::note_previous_decl; 1770 if (!Ctx) 1771 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1772 SemaRef.PDiag(NoteID)); 1773 else 1774 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1775 << Typo << Ctx << DroppedSpecifier 1776 << SS.getRange(), 1777 SemaRef.PDiag(NoteID)); 1778 } 1779 1780 /// Diagnose an empty lookup. 1781 /// 1782 /// \return false if new lookup candidates were found 1783 bool 1784 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1785 std::unique_ptr<CorrectionCandidateCallback> CCC, 1786 TemplateArgumentListInfo *ExplicitTemplateArgs, 1787 ArrayRef<Expr *> Args, TypoExpr **Out) { 1788 DeclarationName Name = R.getLookupName(); 1789 1790 unsigned diagnostic = diag::err_undeclared_var_use; 1791 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1792 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1793 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1794 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1795 diagnostic = diag::err_undeclared_use; 1796 diagnostic_suggest = diag::err_undeclared_use_suggest; 1797 } 1798 1799 // If the original lookup was an unqualified lookup, fake an 1800 // unqualified lookup. This is useful when (for example) the 1801 // original lookup would not have found something because it was a 1802 // dependent name. 1803 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty()) 1804 ? CurContext : nullptr; 1805 while (DC) { 1806 if (isa<CXXRecordDecl>(DC)) { 1807 LookupQualifiedName(R, DC); 1808 1809 if (!R.empty()) { 1810 // Don't give errors about ambiguities in this lookup. 1811 R.suppressDiagnostics(); 1812 1813 // During a default argument instantiation the CurContext points 1814 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1815 // function parameter list, hence add an explicit check. 1816 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1817 ActiveTemplateInstantiations.back().Kind == 1818 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1819 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1820 bool isInstance = CurMethod && 1821 CurMethod->isInstance() && 1822 DC == CurMethod->getParent() && !isDefaultArgument; 1823 1824 1825 // Give a code modification hint to insert 'this->'. 1826 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1827 // Actually quite difficult! 1828 if (getLangOpts().MSVCCompat) 1829 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1830 if (isInstance) { 1831 Diag(R.getNameLoc(), diagnostic) << Name 1832 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1833 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>( 1834 CallsUndergoingInstantiation.back()->getCallee()); 1835 1836 CXXMethodDecl *DepMethod; 1837 if (CurMethod->isDependentContext()) 1838 DepMethod = CurMethod; 1839 else if (CurMethod->getTemplatedKind() == 1840 FunctionDecl::TK_FunctionTemplateSpecialization) 1841 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()-> 1842 getInstantiatedFromMemberTemplate()->getTemplatedDecl()); 1843 else 1844 DepMethod = cast<CXXMethodDecl>( 1845 CurMethod->getInstantiatedFromMemberFunction()); 1846 assert(DepMethod && "No template pattern found"); 1847 1848 QualType DepThisType = DepMethod->getThisType(Context); 1849 CheckCXXThisCapture(R.getNameLoc()); 1850 CXXThisExpr *DepThis = new (Context) CXXThisExpr( 1851 R.getNameLoc(), DepThisType, false); 1852 TemplateArgumentListInfo TList; 1853 if (ULE->hasExplicitTemplateArgs()) 1854 ULE->copyTemplateArgumentsInto(TList); 1855 1856 CXXScopeSpec SS; 1857 SS.Adopt(ULE->getQualifierLoc()); 1858 CXXDependentScopeMemberExpr *DepExpr = 1859 CXXDependentScopeMemberExpr::Create( 1860 Context, DepThis, DepThisType, true, SourceLocation(), 1861 SS.getWithLocInContext(Context), 1862 ULE->getTemplateKeywordLoc(), nullptr, 1863 R.getLookupNameInfo(), 1864 ULE->hasExplicitTemplateArgs() ? &TList : nullptr); 1865 CallsUndergoingInstantiation.back()->setCallee(DepExpr); 1866 } else { 1867 Diag(R.getNameLoc(), diagnostic) << Name; 1868 } 1869 1870 // Do we really want to note all of these? 1871 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1872 Diag((*I)->getLocation(), diag::note_dependent_var_use); 1873 1874 // Return true if we are inside a default argument instantiation 1875 // and the found name refers to an instance member function, otherwise 1876 // the function calling DiagnoseEmptyLookup will try to create an 1877 // implicit member call and this is wrong for default argument. 1878 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1879 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1880 return true; 1881 } 1882 1883 // Tell the callee to try to recover. 1884 return false; 1885 } 1886 1887 R.clear(); 1888 } 1889 1890 // In Microsoft mode, if we are performing lookup from within a friend 1891 // function definition declared at class scope then we must set 1892 // DC to the lexical parent to be able to search into the parent 1893 // class. 1894 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1895 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1896 DC->getLexicalParent()->isRecord()) 1897 DC = DC->getLexicalParent(); 1898 else 1899 DC = DC->getParent(); 1900 } 1901 1902 // We didn't find anything, so try to correct for a typo. 1903 TypoCorrection Corrected; 1904 if (S && Out) { 1905 SourceLocation TypoLoc = R.getNameLoc(); 1906 assert(!ExplicitTemplateArgs && 1907 "Diagnosing an empty lookup with explicit template args!"); 1908 *Out = CorrectTypoDelayed( 1909 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1910 [=](const TypoCorrection &TC) { 1911 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1912 diagnostic, diagnostic_suggest); 1913 }, 1914 nullptr, CTK_ErrorRecovery); 1915 if (*Out) 1916 return true; 1917 } else if (S && (Corrected = 1918 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1919 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1920 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1921 bool DroppedSpecifier = 1922 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1923 R.setLookupName(Corrected.getCorrection()); 1924 1925 bool AcceptableWithRecovery = false; 1926 bool AcceptableWithoutRecovery = false; 1927 NamedDecl *ND = Corrected.getCorrectionDecl(); 1928 if (ND) { 1929 if (Corrected.isOverloaded()) { 1930 OverloadCandidateSet OCS(R.getNameLoc(), 1931 OverloadCandidateSet::CSK_Normal); 1932 OverloadCandidateSet::iterator Best; 1933 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 1934 CDEnd = Corrected.end(); 1935 CD != CDEnd; ++CD) { 1936 if (FunctionTemplateDecl *FTD = 1937 dyn_cast<FunctionTemplateDecl>(*CD)) 1938 AddTemplateOverloadCandidate( 1939 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1940 Args, OCS); 1941 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 1942 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1943 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1944 Args, OCS); 1945 } 1946 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1947 case OR_Success: 1948 ND = Best->Function; 1949 Corrected.setCorrectionDecl(ND); 1950 break; 1951 default: 1952 // FIXME: Arbitrarily pick the first declaration for the note. 1953 Corrected.setCorrectionDecl(ND); 1954 break; 1955 } 1956 } 1957 R.addDecl(ND); 1958 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1959 CXXRecordDecl *Record = nullptr; 1960 if (Corrected.getCorrectionSpecifier()) { 1961 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1962 Record = Ty->getAsCXXRecordDecl(); 1963 } 1964 if (!Record) 1965 Record = cast<CXXRecordDecl>( 1966 ND->getDeclContext()->getRedeclContext()); 1967 R.setNamingClass(Record); 1968 } 1969 1970 AcceptableWithRecovery = 1971 isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND); 1972 // FIXME: If we ended up with a typo for a type name or 1973 // Objective-C class name, we're in trouble because the parser 1974 // is in the wrong place to recover. Suggest the typo 1975 // correction, but don't make it a fix-it since we're not going 1976 // to recover well anyway. 1977 AcceptableWithoutRecovery = 1978 isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 1979 } else { 1980 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1981 // because we aren't able to recover. 1982 AcceptableWithoutRecovery = true; 1983 } 1984 1985 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1986 unsigned NoteID = (Corrected.getCorrectionDecl() && 1987 isa<ImplicitParamDecl>(Corrected.getCorrectionDecl())) 1988 ? diag::note_implicit_param_decl 1989 : diag::note_previous_decl; 1990 if (SS.isEmpty()) 1991 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1992 PDiag(NoteID), AcceptableWithRecovery); 1993 else 1994 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1995 << Name << computeDeclContext(SS, false) 1996 << DroppedSpecifier << SS.getRange(), 1997 PDiag(NoteID), AcceptableWithRecovery); 1998 1999 // Tell the callee whether to try to recover. 2000 return !AcceptableWithRecovery; 2001 } 2002 } 2003 R.clear(); 2004 2005 // Emit a special diagnostic for failed member lookups. 2006 // FIXME: computing the declaration context might fail here (?) 2007 if (!SS.isEmpty()) { 2008 Diag(R.getNameLoc(), diag::err_no_member) 2009 << Name << computeDeclContext(SS, false) 2010 << SS.getRange(); 2011 return true; 2012 } 2013 2014 // Give up, we can't recover. 2015 Diag(R.getNameLoc(), diagnostic) << Name; 2016 return true; 2017 } 2018 2019 /// In Microsoft mode, if we are inside a template class whose parent class has 2020 /// dependent base classes, and we can't resolve an unqualified identifier, then 2021 /// assume the identifier is a member of a dependent base class. We can only 2022 /// recover successfully in static methods, instance methods, and other contexts 2023 /// where 'this' is available. This doesn't precisely match MSVC's 2024 /// instantiation model, but it's close enough. 2025 static Expr * 2026 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2027 DeclarationNameInfo &NameInfo, 2028 SourceLocation TemplateKWLoc, 2029 const TemplateArgumentListInfo *TemplateArgs) { 2030 // Only try to recover from lookup into dependent bases in static methods or 2031 // contexts where 'this' is available. 2032 QualType ThisType = S.getCurrentThisType(); 2033 const CXXRecordDecl *RD = nullptr; 2034 if (!ThisType.isNull()) 2035 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2036 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2037 RD = MD->getParent(); 2038 if (!RD || !RD->hasAnyDependentBases()) 2039 return nullptr; 2040 2041 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2042 // is available, suggest inserting 'this->' as a fixit. 2043 SourceLocation Loc = NameInfo.getLoc(); 2044 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2045 DB << NameInfo.getName() << RD; 2046 2047 if (!ThisType.isNull()) { 2048 DB << FixItHint::CreateInsertion(Loc, "this->"); 2049 return CXXDependentScopeMemberExpr::Create( 2050 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2051 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2052 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2053 } 2054 2055 // Synthesize a fake NNS that points to the derived class. This will 2056 // perform name lookup during template instantiation. 2057 CXXScopeSpec SS; 2058 auto *NNS = 2059 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2060 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2061 return DependentScopeDeclRefExpr::Create( 2062 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2063 TemplateArgs); 2064 } 2065 2066 ExprResult 2067 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2068 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2069 bool HasTrailingLParen, bool IsAddressOfOperand, 2070 std::unique_ptr<CorrectionCandidateCallback> CCC, 2071 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2072 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2073 "cannot be direct & operand and have a trailing lparen"); 2074 if (SS.isInvalid()) 2075 return ExprError(); 2076 2077 TemplateArgumentListInfo TemplateArgsBuffer; 2078 2079 // Decompose the UnqualifiedId into the following data. 2080 DeclarationNameInfo NameInfo; 2081 const TemplateArgumentListInfo *TemplateArgs; 2082 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2083 2084 DeclarationName Name = NameInfo.getName(); 2085 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2086 SourceLocation NameLoc = NameInfo.getLoc(); 2087 2088 // C++ [temp.dep.expr]p3: 2089 // An id-expression is type-dependent if it contains: 2090 // -- an identifier that was declared with a dependent type, 2091 // (note: handled after lookup) 2092 // -- a template-id that is dependent, 2093 // (note: handled in BuildTemplateIdExpr) 2094 // -- a conversion-function-id that specifies a dependent type, 2095 // -- a nested-name-specifier that contains a class-name that 2096 // names a dependent type. 2097 // Determine whether this is a member of an unknown specialization; 2098 // we need to handle these differently. 2099 bool DependentID = false; 2100 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2101 Name.getCXXNameType()->isDependentType()) { 2102 DependentID = true; 2103 } else if (SS.isSet()) { 2104 if (DeclContext *DC = computeDeclContext(SS, false)) { 2105 if (RequireCompleteDeclContext(SS, DC)) 2106 return ExprError(); 2107 } else { 2108 DependentID = true; 2109 } 2110 } 2111 2112 if (DependentID) 2113 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2114 IsAddressOfOperand, TemplateArgs); 2115 2116 // Perform the required lookup. 2117 LookupResult R(*this, NameInfo, 2118 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2119 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2120 if (TemplateArgs) { 2121 // Lookup the template name again to correctly establish the context in 2122 // which it was found. This is really unfortunate as we already did the 2123 // lookup to determine that it was a template name in the first place. If 2124 // this becomes a performance hit, we can work harder to preserve those 2125 // results until we get here but it's likely not worth it. 2126 bool MemberOfUnknownSpecialization; 2127 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2128 MemberOfUnknownSpecialization); 2129 2130 if (MemberOfUnknownSpecialization || 2131 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2132 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2133 IsAddressOfOperand, TemplateArgs); 2134 } else { 2135 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2136 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2137 2138 // If the result might be in a dependent base class, this is a dependent 2139 // id-expression. 2140 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2141 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2142 IsAddressOfOperand, TemplateArgs); 2143 2144 // If this reference is in an Objective-C method, then we need to do 2145 // some special Objective-C lookup, too. 2146 if (IvarLookupFollowUp) { 2147 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2148 if (E.isInvalid()) 2149 return ExprError(); 2150 2151 if (Expr *Ex = E.getAs<Expr>()) 2152 return Ex; 2153 } 2154 } 2155 2156 if (R.isAmbiguous()) 2157 return ExprError(); 2158 2159 // This could be an implicitly declared function reference (legal in C90, 2160 // extension in C99, forbidden in C++). 2161 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2162 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2163 if (D) R.addDecl(D); 2164 } 2165 2166 // Determine whether this name might be a candidate for 2167 // argument-dependent lookup. 2168 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2169 2170 if (R.empty() && !ADL) { 2171 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2172 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2173 TemplateKWLoc, TemplateArgs)) 2174 return E; 2175 } 2176 2177 // Don't diagnose an empty lookup for inline assembly. 2178 if (IsInlineAsmIdentifier) 2179 return ExprError(); 2180 2181 // If this name wasn't predeclared and if this is not a function 2182 // call, diagnose the problem. 2183 TypoExpr *TE = nullptr; 2184 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2185 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2186 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2187 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2188 "Typo correction callback misconfigured"); 2189 if (CCC) { 2190 // Make sure the callback knows what the typo being diagnosed is. 2191 CCC->setTypoName(II); 2192 if (SS.isValid()) 2193 CCC->setTypoNNS(SS.getScopeRep()); 2194 } 2195 if (DiagnoseEmptyLookup(S, SS, R, 2196 CCC ? std::move(CCC) : std::move(DefaultValidator), 2197 nullptr, None, &TE)) { 2198 if (TE && KeywordReplacement) { 2199 auto &State = getTypoExprState(TE); 2200 auto BestTC = State.Consumer->getNextCorrection(); 2201 if (BestTC.isKeyword()) { 2202 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2203 if (State.DiagHandler) 2204 State.DiagHandler(BestTC); 2205 KeywordReplacement->startToken(); 2206 KeywordReplacement->setKind(II->getTokenID()); 2207 KeywordReplacement->setIdentifierInfo(II); 2208 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2209 // Clean up the state associated with the TypoExpr, since it has 2210 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2211 clearDelayedTypo(TE); 2212 // Signal that a correction to a keyword was performed by returning a 2213 // valid-but-null ExprResult. 2214 return (Expr*)nullptr; 2215 } 2216 State.Consumer->resetCorrectionStream(); 2217 } 2218 return TE ? TE : ExprError(); 2219 } 2220 2221 assert(!R.empty() && 2222 "DiagnoseEmptyLookup returned false but added no results"); 2223 2224 // If we found an Objective-C instance variable, let 2225 // LookupInObjCMethod build the appropriate expression to 2226 // reference the ivar. 2227 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2228 R.clear(); 2229 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2230 // In a hopelessly buggy code, Objective-C instance variable 2231 // lookup fails and no expression will be built to reference it. 2232 if (!E.isInvalid() && !E.get()) 2233 return ExprError(); 2234 return E; 2235 } 2236 } 2237 2238 // This is guaranteed from this point on. 2239 assert(!R.empty() || ADL); 2240 2241 // Check whether this might be a C++ implicit instance member access. 2242 // C++ [class.mfct.non-static]p3: 2243 // When an id-expression that is not part of a class member access 2244 // syntax and not used to form a pointer to member is used in the 2245 // body of a non-static member function of class X, if name lookup 2246 // resolves the name in the id-expression to a non-static non-type 2247 // member of some class C, the id-expression is transformed into a 2248 // class member access expression using (*this) as the 2249 // postfix-expression to the left of the . operator. 2250 // 2251 // But we don't actually need to do this for '&' operands if R 2252 // resolved to a function or overloaded function set, because the 2253 // expression is ill-formed if it actually works out to be a 2254 // non-static member function: 2255 // 2256 // C++ [expr.ref]p4: 2257 // Otherwise, if E1.E2 refers to a non-static member function. . . 2258 // [t]he expression can be used only as the left-hand operand of a 2259 // member function call. 2260 // 2261 // There are other safeguards against such uses, but it's important 2262 // to get this right here so that we don't end up making a 2263 // spuriously dependent expression if we're inside a dependent 2264 // instance method. 2265 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2266 bool MightBeImplicitMember; 2267 if (!IsAddressOfOperand) 2268 MightBeImplicitMember = true; 2269 else if (!SS.isEmpty()) 2270 MightBeImplicitMember = false; 2271 else if (R.isOverloadedResult()) 2272 MightBeImplicitMember = false; 2273 else if (R.isUnresolvableResult()) 2274 MightBeImplicitMember = true; 2275 else 2276 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2277 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2278 isa<MSPropertyDecl>(R.getFoundDecl()); 2279 2280 if (MightBeImplicitMember) 2281 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2282 R, TemplateArgs); 2283 } 2284 2285 if (TemplateArgs || TemplateKWLoc.isValid()) { 2286 2287 // In C++1y, if this is a variable template id, then check it 2288 // in BuildTemplateIdExpr(). 2289 // The single lookup result must be a variable template declaration. 2290 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2291 Id.TemplateId->Kind == TNK_Var_template) { 2292 assert(R.getAsSingle<VarTemplateDecl>() && 2293 "There should only be one declaration found."); 2294 } 2295 2296 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2297 } 2298 2299 return BuildDeclarationNameExpr(SS, R, ADL); 2300 } 2301 2302 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2303 /// declaration name, generally during template instantiation. 2304 /// There's a large number of things which don't need to be done along 2305 /// this path. 2306 ExprResult 2307 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2308 const DeclarationNameInfo &NameInfo, 2309 bool IsAddressOfOperand, 2310 TypeSourceInfo **RecoveryTSI) { 2311 DeclContext *DC = computeDeclContext(SS, false); 2312 if (!DC) 2313 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2314 NameInfo, /*TemplateArgs=*/nullptr); 2315 2316 if (RequireCompleteDeclContext(SS, DC)) 2317 return ExprError(); 2318 2319 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2320 LookupQualifiedName(R, DC); 2321 2322 if (R.isAmbiguous()) 2323 return ExprError(); 2324 2325 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2326 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2327 NameInfo, /*TemplateArgs=*/nullptr); 2328 2329 if (R.empty()) { 2330 Diag(NameInfo.getLoc(), diag::err_no_member) 2331 << NameInfo.getName() << DC << SS.getRange(); 2332 return ExprError(); 2333 } 2334 2335 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2336 // Diagnose a missing typename if this resolved unambiguously to a type in 2337 // a dependent context. If we can recover with a type, downgrade this to 2338 // a warning in Microsoft compatibility mode. 2339 unsigned DiagID = diag::err_typename_missing; 2340 if (RecoveryTSI && getLangOpts().MSVCCompat) 2341 DiagID = diag::ext_typename_missing; 2342 SourceLocation Loc = SS.getBeginLoc(); 2343 auto D = Diag(Loc, DiagID); 2344 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2345 << SourceRange(Loc, NameInfo.getEndLoc()); 2346 2347 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2348 // context. 2349 if (!RecoveryTSI) 2350 return ExprError(); 2351 2352 // Only issue the fixit if we're prepared to recover. 2353 D << FixItHint::CreateInsertion(Loc, "typename "); 2354 2355 // Recover by pretending this was an elaborated type. 2356 QualType Ty = Context.getTypeDeclType(TD); 2357 TypeLocBuilder TLB; 2358 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2359 2360 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2361 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2362 QTL.setElaboratedKeywordLoc(SourceLocation()); 2363 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2364 2365 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2366 2367 return ExprEmpty(); 2368 } 2369 2370 // Defend against this resolving to an implicit member access. We usually 2371 // won't get here if this might be a legitimate a class member (we end up in 2372 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2373 // a pointer-to-member or in an unevaluated context in C++11. 2374 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2375 return BuildPossibleImplicitMemberExpr(SS, 2376 /*TemplateKWLoc=*/SourceLocation(), 2377 R, /*TemplateArgs=*/nullptr); 2378 2379 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2380 } 2381 2382 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2383 /// detected that we're currently inside an ObjC method. Perform some 2384 /// additional lookup. 2385 /// 2386 /// Ideally, most of this would be done by lookup, but there's 2387 /// actually quite a lot of extra work involved. 2388 /// 2389 /// Returns a null sentinel to indicate trivial success. 2390 ExprResult 2391 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2392 IdentifierInfo *II, bool AllowBuiltinCreation) { 2393 SourceLocation Loc = Lookup.getNameLoc(); 2394 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2395 2396 // Check for error condition which is already reported. 2397 if (!CurMethod) 2398 return ExprError(); 2399 2400 // There are two cases to handle here. 1) scoped lookup could have failed, 2401 // in which case we should look for an ivar. 2) scoped lookup could have 2402 // found a decl, but that decl is outside the current instance method (i.e. 2403 // a global variable). In these two cases, we do a lookup for an ivar with 2404 // this name, if the lookup sucedes, we replace it our current decl. 2405 2406 // If we're in a class method, we don't normally want to look for 2407 // ivars. But if we don't find anything else, and there's an 2408 // ivar, that's an error. 2409 bool IsClassMethod = CurMethod->isClassMethod(); 2410 2411 bool LookForIvars; 2412 if (Lookup.empty()) 2413 LookForIvars = true; 2414 else if (IsClassMethod) 2415 LookForIvars = false; 2416 else 2417 LookForIvars = (Lookup.isSingleResult() && 2418 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2419 ObjCInterfaceDecl *IFace = nullptr; 2420 if (LookForIvars) { 2421 IFace = CurMethod->getClassInterface(); 2422 ObjCInterfaceDecl *ClassDeclared; 2423 ObjCIvarDecl *IV = nullptr; 2424 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2425 // Diagnose using an ivar in a class method. 2426 if (IsClassMethod) 2427 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2428 << IV->getDeclName()); 2429 2430 // If we're referencing an invalid decl, just return this as a silent 2431 // error node. The error diagnostic was already emitted on the decl. 2432 if (IV->isInvalidDecl()) 2433 return ExprError(); 2434 2435 // Check if referencing a field with __attribute__((deprecated)). 2436 if (DiagnoseUseOfDecl(IV, Loc)) 2437 return ExprError(); 2438 2439 // Diagnose the use of an ivar outside of the declaring class. 2440 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2441 !declaresSameEntity(ClassDeclared, IFace) && 2442 !getLangOpts().DebuggerSupport) 2443 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2444 2445 // FIXME: This should use a new expr for a direct reference, don't 2446 // turn this into Self->ivar, just return a BareIVarExpr or something. 2447 IdentifierInfo &II = Context.Idents.get("self"); 2448 UnqualifiedId SelfName; 2449 SelfName.setIdentifier(&II, SourceLocation()); 2450 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2451 CXXScopeSpec SelfScopeSpec; 2452 SourceLocation TemplateKWLoc; 2453 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2454 SelfName, false, false); 2455 if (SelfExpr.isInvalid()) 2456 return ExprError(); 2457 2458 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2459 if (SelfExpr.isInvalid()) 2460 return ExprError(); 2461 2462 MarkAnyDeclReferenced(Loc, IV, true); 2463 2464 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2465 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2466 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2467 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2468 2469 ObjCIvarRefExpr *Result = new (Context) 2470 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2471 IV->getLocation(), SelfExpr.get(), true, true); 2472 2473 if (getLangOpts().ObjCAutoRefCount) { 2474 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2475 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2476 recordUseOfEvaluatedWeak(Result); 2477 } 2478 if (CurContext->isClosure()) 2479 Diag(Loc, diag::warn_implicitly_retains_self) 2480 << FixItHint::CreateInsertion(Loc, "self->"); 2481 } 2482 2483 return Result; 2484 } 2485 } else if (CurMethod->isInstanceMethod()) { 2486 // We should warn if a local variable hides an ivar. 2487 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2488 ObjCInterfaceDecl *ClassDeclared; 2489 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2490 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2491 declaresSameEntity(IFace, ClassDeclared)) 2492 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2493 } 2494 } 2495 } else if (Lookup.isSingleResult() && 2496 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2497 // If accessing a stand-alone ivar in a class method, this is an error. 2498 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2499 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2500 << IV->getDeclName()); 2501 } 2502 2503 if (Lookup.empty() && II && AllowBuiltinCreation) { 2504 // FIXME. Consolidate this with similar code in LookupName. 2505 if (unsigned BuiltinID = II->getBuiltinID()) { 2506 if (!(getLangOpts().CPlusPlus && 2507 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2508 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2509 S, Lookup.isForRedeclaration(), 2510 Lookup.getNameLoc()); 2511 if (D) Lookup.addDecl(D); 2512 } 2513 } 2514 } 2515 // Sentinel value saying that we didn't do anything special. 2516 return ExprResult((Expr *)nullptr); 2517 } 2518 2519 /// \brief Cast a base object to a member's actual type. 2520 /// 2521 /// Logically this happens in three phases: 2522 /// 2523 /// * First we cast from the base type to the naming class. 2524 /// The naming class is the class into which we were looking 2525 /// when we found the member; it's the qualifier type if a 2526 /// qualifier was provided, and otherwise it's the base type. 2527 /// 2528 /// * Next we cast from the naming class to the declaring class. 2529 /// If the member we found was brought into a class's scope by 2530 /// a using declaration, this is that class; otherwise it's 2531 /// the class declaring the member. 2532 /// 2533 /// * Finally we cast from the declaring class to the "true" 2534 /// declaring class of the member. This conversion does not 2535 /// obey access control. 2536 ExprResult 2537 Sema::PerformObjectMemberConversion(Expr *From, 2538 NestedNameSpecifier *Qualifier, 2539 NamedDecl *FoundDecl, 2540 NamedDecl *Member) { 2541 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2542 if (!RD) 2543 return From; 2544 2545 QualType DestRecordType; 2546 QualType DestType; 2547 QualType FromRecordType; 2548 QualType FromType = From->getType(); 2549 bool PointerConversions = false; 2550 if (isa<FieldDecl>(Member)) { 2551 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2552 2553 if (FromType->getAs<PointerType>()) { 2554 DestType = Context.getPointerType(DestRecordType); 2555 FromRecordType = FromType->getPointeeType(); 2556 PointerConversions = true; 2557 } else { 2558 DestType = DestRecordType; 2559 FromRecordType = FromType; 2560 } 2561 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2562 if (Method->isStatic()) 2563 return From; 2564 2565 DestType = Method->getThisType(Context); 2566 DestRecordType = DestType->getPointeeType(); 2567 2568 if (FromType->getAs<PointerType>()) { 2569 FromRecordType = FromType->getPointeeType(); 2570 PointerConversions = true; 2571 } else { 2572 FromRecordType = FromType; 2573 DestType = DestRecordType; 2574 } 2575 } else { 2576 // No conversion necessary. 2577 return From; 2578 } 2579 2580 if (DestType->isDependentType() || FromType->isDependentType()) 2581 return From; 2582 2583 // If the unqualified types are the same, no conversion is necessary. 2584 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2585 return From; 2586 2587 SourceRange FromRange = From->getSourceRange(); 2588 SourceLocation FromLoc = FromRange.getBegin(); 2589 2590 ExprValueKind VK = From->getValueKind(); 2591 2592 // C++ [class.member.lookup]p8: 2593 // [...] Ambiguities can often be resolved by qualifying a name with its 2594 // class name. 2595 // 2596 // If the member was a qualified name and the qualified referred to a 2597 // specific base subobject type, we'll cast to that intermediate type 2598 // first and then to the object in which the member is declared. That allows 2599 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2600 // 2601 // class Base { public: int x; }; 2602 // class Derived1 : public Base { }; 2603 // class Derived2 : public Base { }; 2604 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2605 // 2606 // void VeryDerived::f() { 2607 // x = 17; // error: ambiguous base subobjects 2608 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2609 // } 2610 if (Qualifier && Qualifier->getAsType()) { 2611 QualType QType = QualType(Qualifier->getAsType(), 0); 2612 assert(QType->isRecordType() && "lookup done with non-record type"); 2613 2614 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2615 2616 // In C++98, the qualifier type doesn't actually have to be a base 2617 // type of the object type, in which case we just ignore it. 2618 // Otherwise build the appropriate casts. 2619 if (IsDerivedFrom(FromRecordType, QRecordType)) { 2620 CXXCastPath BasePath; 2621 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2622 FromLoc, FromRange, &BasePath)) 2623 return ExprError(); 2624 2625 if (PointerConversions) 2626 QType = Context.getPointerType(QType); 2627 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2628 VK, &BasePath).get(); 2629 2630 FromType = QType; 2631 FromRecordType = QRecordType; 2632 2633 // If the qualifier type was the same as the destination type, 2634 // we're done. 2635 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2636 return From; 2637 } 2638 } 2639 2640 bool IgnoreAccess = false; 2641 2642 // If we actually found the member through a using declaration, cast 2643 // down to the using declaration's type. 2644 // 2645 // Pointer equality is fine here because only one declaration of a 2646 // class ever has member declarations. 2647 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2648 assert(isa<UsingShadowDecl>(FoundDecl)); 2649 QualType URecordType = Context.getTypeDeclType( 2650 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2651 2652 // We only need to do this if the naming-class to declaring-class 2653 // conversion is non-trivial. 2654 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2655 assert(IsDerivedFrom(FromRecordType, URecordType)); 2656 CXXCastPath BasePath; 2657 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2658 FromLoc, FromRange, &BasePath)) 2659 return ExprError(); 2660 2661 QualType UType = URecordType; 2662 if (PointerConversions) 2663 UType = Context.getPointerType(UType); 2664 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2665 VK, &BasePath).get(); 2666 FromType = UType; 2667 FromRecordType = URecordType; 2668 } 2669 2670 // We don't do access control for the conversion from the 2671 // declaring class to the true declaring class. 2672 IgnoreAccess = true; 2673 } 2674 2675 CXXCastPath BasePath; 2676 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2677 FromLoc, FromRange, &BasePath, 2678 IgnoreAccess)) 2679 return ExprError(); 2680 2681 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2682 VK, &BasePath); 2683 } 2684 2685 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2686 const LookupResult &R, 2687 bool HasTrailingLParen) { 2688 // Only when used directly as the postfix-expression of a call. 2689 if (!HasTrailingLParen) 2690 return false; 2691 2692 // Never if a scope specifier was provided. 2693 if (SS.isSet()) 2694 return false; 2695 2696 // Only in C++ or ObjC++. 2697 if (!getLangOpts().CPlusPlus) 2698 return false; 2699 2700 // Turn off ADL when we find certain kinds of declarations during 2701 // normal lookup: 2702 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 2703 NamedDecl *D = *I; 2704 2705 // C++0x [basic.lookup.argdep]p3: 2706 // -- a declaration of a class member 2707 // Since using decls preserve this property, we check this on the 2708 // original decl. 2709 if (D->isCXXClassMember()) 2710 return false; 2711 2712 // C++0x [basic.lookup.argdep]p3: 2713 // -- a block-scope function declaration that is not a 2714 // using-declaration 2715 // NOTE: we also trigger this for function templates (in fact, we 2716 // don't check the decl type at all, since all other decl types 2717 // turn off ADL anyway). 2718 if (isa<UsingShadowDecl>(D)) 2719 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2720 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2721 return false; 2722 2723 // C++0x [basic.lookup.argdep]p3: 2724 // -- a declaration that is neither a function or a function 2725 // template 2726 // And also for builtin functions. 2727 if (isa<FunctionDecl>(D)) { 2728 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2729 2730 // But also builtin functions. 2731 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2732 return false; 2733 } else if (!isa<FunctionTemplateDecl>(D)) 2734 return false; 2735 } 2736 2737 return true; 2738 } 2739 2740 2741 /// Diagnoses obvious problems with the use of the given declaration 2742 /// as an expression. This is only actually called for lookups that 2743 /// were not overloaded, and it doesn't promise that the declaration 2744 /// will in fact be used. 2745 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2746 if (isa<TypedefNameDecl>(D)) { 2747 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2748 return true; 2749 } 2750 2751 if (isa<ObjCInterfaceDecl>(D)) { 2752 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2753 return true; 2754 } 2755 2756 if (isa<NamespaceDecl>(D)) { 2757 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2758 return true; 2759 } 2760 2761 return false; 2762 } 2763 2764 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2765 LookupResult &R, bool NeedsADL, 2766 bool AcceptInvalidDecl) { 2767 // If this is a single, fully-resolved result and we don't need ADL, 2768 // just build an ordinary singleton decl ref. 2769 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2770 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2771 R.getRepresentativeDecl(), nullptr, 2772 AcceptInvalidDecl); 2773 2774 // We only need to check the declaration if there's exactly one 2775 // result, because in the overloaded case the results can only be 2776 // functions and function templates. 2777 if (R.isSingleResult() && 2778 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2779 return ExprError(); 2780 2781 // Otherwise, just build an unresolved lookup expression. Suppress 2782 // any lookup-related diagnostics; we'll hash these out later, when 2783 // we've picked a target. 2784 R.suppressDiagnostics(); 2785 2786 UnresolvedLookupExpr *ULE 2787 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2788 SS.getWithLocInContext(Context), 2789 R.getLookupNameInfo(), 2790 NeedsADL, R.isOverloadedResult(), 2791 R.begin(), R.end()); 2792 2793 return ULE; 2794 } 2795 2796 /// \brief Complete semantic analysis for a reference to the given declaration. 2797 ExprResult Sema::BuildDeclarationNameExpr( 2798 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2799 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2800 bool AcceptInvalidDecl) { 2801 assert(D && "Cannot refer to a NULL declaration"); 2802 assert(!isa<FunctionTemplateDecl>(D) && 2803 "Cannot refer unambiguously to a function template"); 2804 2805 SourceLocation Loc = NameInfo.getLoc(); 2806 if (CheckDeclInExpr(*this, Loc, D)) 2807 return ExprError(); 2808 2809 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2810 // Specifically diagnose references to class templates that are missing 2811 // a template argument list. 2812 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2813 << Template << SS.getRange(); 2814 Diag(Template->getLocation(), diag::note_template_decl_here); 2815 return ExprError(); 2816 } 2817 2818 // Make sure that we're referring to a value. 2819 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2820 if (!VD) { 2821 Diag(Loc, diag::err_ref_non_value) 2822 << D << SS.getRange(); 2823 Diag(D->getLocation(), diag::note_declared_at); 2824 return ExprError(); 2825 } 2826 2827 // Check whether this declaration can be used. Note that we suppress 2828 // this check when we're going to perform argument-dependent lookup 2829 // on this function name, because this might not be the function 2830 // that overload resolution actually selects. 2831 if (DiagnoseUseOfDecl(VD, Loc)) 2832 return ExprError(); 2833 2834 // Only create DeclRefExpr's for valid Decl's. 2835 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2836 return ExprError(); 2837 2838 // Handle members of anonymous structs and unions. If we got here, 2839 // and the reference is to a class member indirect field, then this 2840 // must be the subject of a pointer-to-member expression. 2841 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2842 if (!indirectField->isCXXClassMember()) 2843 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2844 indirectField); 2845 2846 { 2847 QualType type = VD->getType(); 2848 ExprValueKind valueKind = VK_RValue; 2849 2850 switch (D->getKind()) { 2851 // Ignore all the non-ValueDecl kinds. 2852 #define ABSTRACT_DECL(kind) 2853 #define VALUE(type, base) 2854 #define DECL(type, base) \ 2855 case Decl::type: 2856 #include "clang/AST/DeclNodes.inc" 2857 llvm_unreachable("invalid value decl kind"); 2858 2859 // These shouldn't make it here. 2860 case Decl::ObjCAtDefsField: 2861 case Decl::ObjCIvar: 2862 llvm_unreachable("forming non-member reference to ivar?"); 2863 2864 // Enum constants are always r-values and never references. 2865 // Unresolved using declarations are dependent. 2866 case Decl::EnumConstant: 2867 case Decl::UnresolvedUsingValue: 2868 valueKind = VK_RValue; 2869 break; 2870 2871 // Fields and indirect fields that got here must be for 2872 // pointer-to-member expressions; we just call them l-values for 2873 // internal consistency, because this subexpression doesn't really 2874 // exist in the high-level semantics. 2875 case Decl::Field: 2876 case Decl::IndirectField: 2877 assert(getLangOpts().CPlusPlus && 2878 "building reference to field in C?"); 2879 2880 // These can't have reference type in well-formed programs, but 2881 // for internal consistency we do this anyway. 2882 type = type.getNonReferenceType(); 2883 valueKind = VK_LValue; 2884 break; 2885 2886 // Non-type template parameters are either l-values or r-values 2887 // depending on the type. 2888 case Decl::NonTypeTemplateParm: { 2889 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2890 type = reftype->getPointeeType(); 2891 valueKind = VK_LValue; // even if the parameter is an r-value reference 2892 break; 2893 } 2894 2895 // For non-references, we need to strip qualifiers just in case 2896 // the template parameter was declared as 'const int' or whatever. 2897 valueKind = VK_RValue; 2898 type = type.getUnqualifiedType(); 2899 break; 2900 } 2901 2902 case Decl::Var: 2903 case Decl::VarTemplateSpecialization: 2904 case Decl::VarTemplatePartialSpecialization: 2905 // In C, "extern void blah;" is valid and is an r-value. 2906 if (!getLangOpts().CPlusPlus && 2907 !type.hasQualifiers() && 2908 type->isVoidType()) { 2909 valueKind = VK_RValue; 2910 break; 2911 } 2912 // fallthrough 2913 2914 case Decl::ImplicitParam: 2915 case Decl::ParmVar: { 2916 // These are always l-values. 2917 valueKind = VK_LValue; 2918 type = type.getNonReferenceType(); 2919 2920 // FIXME: Does the addition of const really only apply in 2921 // potentially-evaluated contexts? Since the variable isn't actually 2922 // captured in an unevaluated context, it seems that the answer is no. 2923 if (!isUnevaluatedContext()) { 2924 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2925 if (!CapturedType.isNull()) 2926 type = CapturedType; 2927 } 2928 2929 break; 2930 } 2931 2932 case Decl::Function: { 2933 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2934 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2935 type = Context.BuiltinFnTy; 2936 valueKind = VK_RValue; 2937 break; 2938 } 2939 } 2940 2941 const FunctionType *fty = type->castAs<FunctionType>(); 2942 2943 // If we're referring to a function with an __unknown_anytype 2944 // result type, make the entire expression __unknown_anytype. 2945 if (fty->getReturnType() == Context.UnknownAnyTy) { 2946 type = Context.UnknownAnyTy; 2947 valueKind = VK_RValue; 2948 break; 2949 } 2950 2951 // Functions are l-values in C++. 2952 if (getLangOpts().CPlusPlus) { 2953 valueKind = VK_LValue; 2954 break; 2955 } 2956 2957 // C99 DR 316 says that, if a function type comes from a 2958 // function definition (without a prototype), that type is only 2959 // used for checking compatibility. Therefore, when referencing 2960 // the function, we pretend that we don't have the full function 2961 // type. 2962 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2963 isa<FunctionProtoType>(fty)) 2964 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2965 fty->getExtInfo()); 2966 2967 // Functions are r-values in C. 2968 valueKind = VK_RValue; 2969 break; 2970 } 2971 2972 case Decl::MSProperty: 2973 valueKind = VK_LValue; 2974 break; 2975 2976 case Decl::CXXMethod: 2977 // If we're referring to a method with an __unknown_anytype 2978 // result type, make the entire expression __unknown_anytype. 2979 // This should only be possible with a type written directly. 2980 if (const FunctionProtoType *proto 2981 = dyn_cast<FunctionProtoType>(VD->getType())) 2982 if (proto->getReturnType() == Context.UnknownAnyTy) { 2983 type = Context.UnknownAnyTy; 2984 valueKind = VK_RValue; 2985 break; 2986 } 2987 2988 // C++ methods are l-values if static, r-values if non-static. 2989 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2990 valueKind = VK_LValue; 2991 break; 2992 } 2993 // fallthrough 2994 2995 case Decl::CXXConversion: 2996 case Decl::CXXDestructor: 2997 case Decl::CXXConstructor: 2998 valueKind = VK_RValue; 2999 break; 3000 } 3001 3002 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3003 TemplateArgs); 3004 } 3005 } 3006 3007 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3008 SmallString<32> &Target) { 3009 Target.resize(CharByteWidth * (Source.size() + 1)); 3010 char *ResultPtr = &Target[0]; 3011 const UTF8 *ErrorPtr; 3012 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3013 (void)success; 3014 assert(success); 3015 Target.resize(ResultPtr - &Target[0]); 3016 } 3017 3018 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3019 PredefinedExpr::IdentType IT) { 3020 // Pick the current block, lambda, captured statement or function. 3021 Decl *currentDecl = nullptr; 3022 if (const BlockScopeInfo *BSI = getCurBlock()) 3023 currentDecl = BSI->TheDecl; 3024 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3025 currentDecl = LSI->CallOperator; 3026 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3027 currentDecl = CSI->TheCapturedDecl; 3028 else 3029 currentDecl = getCurFunctionOrMethodDecl(); 3030 3031 if (!currentDecl) { 3032 Diag(Loc, diag::ext_predef_outside_function); 3033 currentDecl = Context.getTranslationUnitDecl(); 3034 } 3035 3036 QualType ResTy; 3037 StringLiteral *SL = nullptr; 3038 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3039 ResTy = Context.DependentTy; 3040 else { 3041 // Pre-defined identifiers are of type char[x], where x is the length of 3042 // the string. 3043 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3044 unsigned Length = Str.length(); 3045 3046 llvm::APInt LengthI(32, Length + 1); 3047 if (IT == PredefinedExpr::LFunction) { 3048 ResTy = Context.WideCharTy.withConst(); 3049 SmallString<32> RawChars; 3050 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3051 Str, RawChars); 3052 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3053 /*IndexTypeQuals*/ 0); 3054 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3055 /*Pascal*/ false, ResTy, Loc); 3056 } else { 3057 ResTy = Context.CharTy.withConst(); 3058 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3059 /*IndexTypeQuals*/ 0); 3060 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3061 /*Pascal*/ false, ResTy, Loc); 3062 } 3063 } 3064 3065 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3066 } 3067 3068 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3069 PredefinedExpr::IdentType IT; 3070 3071 switch (Kind) { 3072 default: llvm_unreachable("Unknown simple primary expr!"); 3073 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3074 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3075 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3076 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3077 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3078 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3079 } 3080 3081 return BuildPredefinedExpr(Loc, IT); 3082 } 3083 3084 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3085 SmallString<16> CharBuffer; 3086 bool Invalid = false; 3087 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3088 if (Invalid) 3089 return ExprError(); 3090 3091 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3092 PP, Tok.getKind()); 3093 if (Literal.hadError()) 3094 return ExprError(); 3095 3096 QualType Ty; 3097 if (Literal.isWide()) 3098 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3099 else if (Literal.isUTF16()) 3100 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3101 else if (Literal.isUTF32()) 3102 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3103 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3104 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3105 else 3106 Ty = Context.CharTy; // 'x' -> char in C++ 3107 3108 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3109 if (Literal.isWide()) 3110 Kind = CharacterLiteral::Wide; 3111 else if (Literal.isUTF16()) 3112 Kind = CharacterLiteral::UTF16; 3113 else if (Literal.isUTF32()) 3114 Kind = CharacterLiteral::UTF32; 3115 3116 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3117 Tok.getLocation()); 3118 3119 if (Literal.getUDSuffix().empty()) 3120 return Lit; 3121 3122 // We're building a user-defined literal. 3123 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3124 SourceLocation UDSuffixLoc = 3125 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3126 3127 // Make sure we're allowed user-defined literals here. 3128 if (!UDLScope) 3129 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3130 3131 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3132 // operator "" X (ch) 3133 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3134 Lit, Tok.getLocation()); 3135 } 3136 3137 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3138 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3139 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3140 Context.IntTy, Loc); 3141 } 3142 3143 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3144 QualType Ty, SourceLocation Loc) { 3145 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3146 3147 using llvm::APFloat; 3148 APFloat Val(Format); 3149 3150 APFloat::opStatus result = Literal.GetFloatValue(Val); 3151 3152 // Overflow is always an error, but underflow is only an error if 3153 // we underflowed to zero (APFloat reports denormals as underflow). 3154 if ((result & APFloat::opOverflow) || 3155 ((result & APFloat::opUnderflow) && Val.isZero())) { 3156 unsigned diagnostic; 3157 SmallString<20> buffer; 3158 if (result & APFloat::opOverflow) { 3159 diagnostic = diag::warn_float_overflow; 3160 APFloat::getLargest(Format).toString(buffer); 3161 } else { 3162 diagnostic = diag::warn_float_underflow; 3163 APFloat::getSmallest(Format).toString(buffer); 3164 } 3165 3166 S.Diag(Loc, diagnostic) 3167 << Ty 3168 << StringRef(buffer.data(), buffer.size()); 3169 } 3170 3171 bool isExact = (result == APFloat::opOK); 3172 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3173 } 3174 3175 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3176 assert(E && "Invalid expression"); 3177 3178 if (E->isValueDependent()) 3179 return false; 3180 3181 QualType QT = E->getType(); 3182 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3183 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3184 return true; 3185 } 3186 3187 llvm::APSInt ValueAPS; 3188 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3189 3190 if (R.isInvalid()) 3191 return true; 3192 3193 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3194 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3195 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3196 << ValueAPS.toString(10) << ValueIsPositive; 3197 return true; 3198 } 3199 3200 return false; 3201 } 3202 3203 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3204 // Fast path for a single digit (which is quite common). A single digit 3205 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3206 if (Tok.getLength() == 1) { 3207 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3208 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3209 } 3210 3211 SmallString<128> SpellingBuffer; 3212 // NumericLiteralParser wants to overread by one character. Add padding to 3213 // the buffer in case the token is copied to the buffer. If getSpelling() 3214 // returns a StringRef to the memory buffer, it should have a null char at 3215 // the EOF, so it is also safe. 3216 SpellingBuffer.resize(Tok.getLength() + 1); 3217 3218 // Get the spelling of the token, which eliminates trigraphs, etc. 3219 bool Invalid = false; 3220 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3221 if (Invalid) 3222 return ExprError(); 3223 3224 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3225 if (Literal.hadError) 3226 return ExprError(); 3227 3228 if (Literal.hasUDSuffix()) { 3229 // We're building a user-defined literal. 3230 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3231 SourceLocation UDSuffixLoc = 3232 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3233 3234 // Make sure we're allowed user-defined literals here. 3235 if (!UDLScope) 3236 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3237 3238 QualType CookedTy; 3239 if (Literal.isFloatingLiteral()) { 3240 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3241 // long double, the literal is treated as a call of the form 3242 // operator "" X (f L) 3243 CookedTy = Context.LongDoubleTy; 3244 } else { 3245 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3246 // unsigned long long, the literal is treated as a call of the form 3247 // operator "" X (n ULL) 3248 CookedTy = Context.UnsignedLongLongTy; 3249 } 3250 3251 DeclarationName OpName = 3252 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3253 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3254 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3255 3256 SourceLocation TokLoc = Tok.getLocation(); 3257 3258 // Perform literal operator lookup to determine if we're building a raw 3259 // literal or a cooked one. 3260 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3261 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3262 /*AllowRaw*/true, /*AllowTemplate*/true, 3263 /*AllowStringTemplate*/false)) { 3264 case LOLR_Error: 3265 return ExprError(); 3266 3267 case LOLR_Cooked: { 3268 Expr *Lit; 3269 if (Literal.isFloatingLiteral()) { 3270 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3271 } else { 3272 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3273 if (Literal.GetIntegerValue(ResultVal)) 3274 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3275 << /* Unsigned */ 1; 3276 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3277 Tok.getLocation()); 3278 } 3279 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3280 } 3281 3282 case LOLR_Raw: { 3283 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3284 // literal is treated as a call of the form 3285 // operator "" X ("n") 3286 unsigned Length = Literal.getUDSuffixOffset(); 3287 QualType StrTy = Context.getConstantArrayType( 3288 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3289 ArrayType::Normal, 0); 3290 Expr *Lit = StringLiteral::Create( 3291 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3292 /*Pascal*/false, StrTy, &TokLoc, 1); 3293 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3294 } 3295 3296 case LOLR_Template: { 3297 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3298 // template), L is treated as a call fo the form 3299 // operator "" X <'c1', 'c2', ... 'ck'>() 3300 // where n is the source character sequence c1 c2 ... ck. 3301 TemplateArgumentListInfo ExplicitArgs; 3302 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3303 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3304 llvm::APSInt Value(CharBits, CharIsUnsigned); 3305 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3306 Value = TokSpelling[I]; 3307 TemplateArgument Arg(Context, Value, Context.CharTy); 3308 TemplateArgumentLocInfo ArgInfo; 3309 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3310 } 3311 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3312 &ExplicitArgs); 3313 } 3314 case LOLR_StringTemplate: 3315 llvm_unreachable("unexpected literal operator lookup result"); 3316 } 3317 } 3318 3319 Expr *Res; 3320 3321 if (Literal.isFloatingLiteral()) { 3322 QualType Ty; 3323 if (Literal.isFloat) 3324 Ty = Context.FloatTy; 3325 else if (!Literal.isLong) 3326 Ty = Context.DoubleTy; 3327 else 3328 Ty = Context.LongDoubleTy; 3329 3330 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3331 3332 if (Ty == Context.DoubleTy) { 3333 if (getLangOpts().SinglePrecisionConstants) { 3334 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3335 } else if (getLangOpts().OpenCL && 3336 !((getLangOpts().OpenCLVersion >= 120) || 3337 getOpenCLOptions().cl_khr_fp64)) { 3338 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3339 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3340 } 3341 } 3342 } else if (!Literal.isIntegerLiteral()) { 3343 return ExprError(); 3344 } else { 3345 QualType Ty; 3346 3347 // 'long long' is a C99 or C++11 feature. 3348 if (!getLangOpts().C99 && Literal.isLongLong) { 3349 if (getLangOpts().CPlusPlus) 3350 Diag(Tok.getLocation(), 3351 getLangOpts().CPlusPlus11 ? 3352 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3353 else 3354 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3355 } 3356 3357 // Get the value in the widest-possible width. 3358 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3359 llvm::APInt ResultVal(MaxWidth, 0); 3360 3361 if (Literal.GetIntegerValue(ResultVal)) { 3362 // If this value didn't fit into uintmax_t, error and force to ull. 3363 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3364 << /* Unsigned */ 1; 3365 Ty = Context.UnsignedLongLongTy; 3366 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3367 "long long is not intmax_t?"); 3368 } else { 3369 // If this value fits into a ULL, try to figure out what else it fits into 3370 // according to the rules of C99 6.4.4.1p5. 3371 3372 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3373 // be an unsigned int. 3374 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3375 3376 // Check from smallest to largest, picking the smallest type we can. 3377 unsigned Width = 0; 3378 3379 // Microsoft specific integer suffixes are explicitly sized. 3380 if (Literal.MicrosoftInteger) { 3381 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3382 Width = 8; 3383 Ty = Context.CharTy; 3384 } else { 3385 Width = Literal.MicrosoftInteger; 3386 Ty = Context.getIntTypeForBitwidth(Width, 3387 /*Signed=*/!Literal.isUnsigned); 3388 } 3389 } 3390 3391 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3392 // Are int/unsigned possibilities? 3393 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3394 3395 // Does it fit in a unsigned int? 3396 if (ResultVal.isIntN(IntSize)) { 3397 // Does it fit in a signed int? 3398 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3399 Ty = Context.IntTy; 3400 else if (AllowUnsigned) 3401 Ty = Context.UnsignedIntTy; 3402 Width = IntSize; 3403 } 3404 } 3405 3406 // Are long/unsigned long possibilities? 3407 if (Ty.isNull() && !Literal.isLongLong) { 3408 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3409 3410 // Does it fit in a unsigned long? 3411 if (ResultVal.isIntN(LongSize)) { 3412 // Does it fit in a signed long? 3413 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3414 Ty = Context.LongTy; 3415 else if (AllowUnsigned) 3416 Ty = Context.UnsignedLongTy; 3417 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3418 // is compatible. 3419 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3420 const unsigned LongLongSize = 3421 Context.getTargetInfo().getLongLongWidth(); 3422 Diag(Tok.getLocation(), 3423 getLangOpts().CPlusPlus 3424 ? Literal.isLong 3425 ? diag::warn_old_implicitly_unsigned_long_cxx 3426 : /*C++98 UB*/ diag:: 3427 ext_old_implicitly_unsigned_long_cxx 3428 : diag::warn_old_implicitly_unsigned_long) 3429 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3430 : /*will be ill-formed*/ 1); 3431 Ty = Context.UnsignedLongTy; 3432 } 3433 Width = LongSize; 3434 } 3435 } 3436 3437 // Check long long if needed. 3438 if (Ty.isNull()) { 3439 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3440 3441 // Does it fit in a unsigned long long? 3442 if (ResultVal.isIntN(LongLongSize)) { 3443 // Does it fit in a signed long long? 3444 // To be compatible with MSVC, hex integer literals ending with the 3445 // LL or i64 suffix are always signed in Microsoft mode. 3446 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3447 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3448 Ty = Context.LongLongTy; 3449 else if (AllowUnsigned) 3450 Ty = Context.UnsignedLongLongTy; 3451 Width = LongLongSize; 3452 } 3453 } 3454 3455 // If we still couldn't decide a type, we probably have something that 3456 // does not fit in a signed long long, but has no U suffix. 3457 if (Ty.isNull()) { 3458 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3459 Ty = Context.UnsignedLongLongTy; 3460 Width = Context.getTargetInfo().getLongLongWidth(); 3461 } 3462 3463 if (ResultVal.getBitWidth() != Width) 3464 ResultVal = ResultVal.trunc(Width); 3465 } 3466 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3467 } 3468 3469 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3470 if (Literal.isImaginary) 3471 Res = new (Context) ImaginaryLiteral(Res, 3472 Context.getComplexType(Res->getType())); 3473 3474 return Res; 3475 } 3476 3477 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3478 assert(E && "ActOnParenExpr() missing expr"); 3479 return new (Context) ParenExpr(L, R, E); 3480 } 3481 3482 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3483 SourceLocation Loc, 3484 SourceRange ArgRange) { 3485 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3486 // scalar or vector data type argument..." 3487 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3488 // type (C99 6.2.5p18) or void. 3489 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3490 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3491 << T << ArgRange; 3492 return true; 3493 } 3494 3495 assert((T->isVoidType() || !T->isIncompleteType()) && 3496 "Scalar types should always be complete"); 3497 return false; 3498 } 3499 3500 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3501 SourceLocation Loc, 3502 SourceRange ArgRange, 3503 UnaryExprOrTypeTrait TraitKind) { 3504 // Invalid types must be hard errors for SFINAE in C++. 3505 if (S.LangOpts.CPlusPlus) 3506 return true; 3507 3508 // C99 6.5.3.4p1: 3509 if (T->isFunctionType() && 3510 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3511 // sizeof(function)/alignof(function) is allowed as an extension. 3512 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3513 << TraitKind << ArgRange; 3514 return false; 3515 } 3516 3517 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3518 // this is an error (OpenCL v1.1 s6.3.k) 3519 if (T->isVoidType()) { 3520 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3521 : diag::ext_sizeof_alignof_void_type; 3522 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3523 return false; 3524 } 3525 3526 return true; 3527 } 3528 3529 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3530 SourceLocation Loc, 3531 SourceRange ArgRange, 3532 UnaryExprOrTypeTrait TraitKind) { 3533 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3534 // runtime doesn't allow it. 3535 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3536 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3537 << T << (TraitKind == UETT_SizeOf) 3538 << ArgRange; 3539 return true; 3540 } 3541 3542 return false; 3543 } 3544 3545 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3546 /// pointer type is equal to T) and emit a warning if it is. 3547 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3548 Expr *E) { 3549 // Don't warn if the operation changed the type. 3550 if (T != E->getType()) 3551 return; 3552 3553 // Now look for array decays. 3554 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3555 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3556 return; 3557 3558 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3559 << ICE->getType() 3560 << ICE->getSubExpr()->getType(); 3561 } 3562 3563 /// \brief Check the constraints on expression operands to unary type expression 3564 /// and type traits. 3565 /// 3566 /// Completes any types necessary and validates the constraints on the operand 3567 /// expression. The logic mostly mirrors the type-based overload, but may modify 3568 /// the expression as it completes the type for that expression through template 3569 /// instantiation, etc. 3570 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3571 UnaryExprOrTypeTrait ExprKind) { 3572 QualType ExprTy = E->getType(); 3573 assert(!ExprTy->isReferenceType()); 3574 3575 if (ExprKind == UETT_VecStep) 3576 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3577 E->getSourceRange()); 3578 3579 // Whitelist some types as extensions 3580 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3581 E->getSourceRange(), ExprKind)) 3582 return false; 3583 3584 // 'alignof' applied to an expression only requires the base element type of 3585 // the expression to be complete. 'sizeof' requires the expression's type to 3586 // be complete (and will attempt to complete it if it's an array of unknown 3587 // bound). 3588 if (ExprKind == UETT_AlignOf) { 3589 if (RequireCompleteType(E->getExprLoc(), 3590 Context.getBaseElementType(E->getType()), 3591 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3592 E->getSourceRange())) 3593 return true; 3594 } else { 3595 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3596 ExprKind, E->getSourceRange())) 3597 return true; 3598 } 3599 3600 // Completing the expression's type may have changed it. 3601 ExprTy = E->getType(); 3602 assert(!ExprTy->isReferenceType()); 3603 3604 if (ExprTy->isFunctionType()) { 3605 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3606 << ExprKind << E->getSourceRange(); 3607 return true; 3608 } 3609 3610 // The operand for sizeof and alignof is in an unevaluated expression context, 3611 // so side effects could result in unintended consequences. 3612 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3613 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3614 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3615 3616 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3617 E->getSourceRange(), ExprKind)) 3618 return true; 3619 3620 if (ExprKind == UETT_SizeOf) { 3621 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3622 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3623 QualType OType = PVD->getOriginalType(); 3624 QualType Type = PVD->getType(); 3625 if (Type->isPointerType() && OType->isArrayType()) { 3626 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3627 << Type << OType; 3628 Diag(PVD->getLocation(), diag::note_declared_at); 3629 } 3630 } 3631 } 3632 3633 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3634 // decays into a pointer and returns an unintended result. This is most 3635 // likely a typo for "sizeof(array) op x". 3636 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3637 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3638 BO->getLHS()); 3639 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3640 BO->getRHS()); 3641 } 3642 } 3643 3644 return false; 3645 } 3646 3647 /// \brief Check the constraints on operands to unary expression and type 3648 /// traits. 3649 /// 3650 /// This will complete any types necessary, and validate the various constraints 3651 /// on those operands. 3652 /// 3653 /// The UsualUnaryConversions() function is *not* called by this routine. 3654 /// C99 6.3.2.1p[2-4] all state: 3655 /// Except when it is the operand of the sizeof operator ... 3656 /// 3657 /// C++ [expr.sizeof]p4 3658 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3659 /// standard conversions are not applied to the operand of sizeof. 3660 /// 3661 /// This policy is followed for all of the unary trait expressions. 3662 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3663 SourceLocation OpLoc, 3664 SourceRange ExprRange, 3665 UnaryExprOrTypeTrait ExprKind) { 3666 if (ExprType->isDependentType()) 3667 return false; 3668 3669 // C++ [expr.sizeof]p2: 3670 // When applied to a reference or a reference type, the result 3671 // is the size of the referenced type. 3672 // C++11 [expr.alignof]p3: 3673 // When alignof is applied to a reference type, the result 3674 // shall be the alignment of the referenced type. 3675 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3676 ExprType = Ref->getPointeeType(); 3677 3678 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3679 // When alignof or _Alignof is applied to an array type, the result 3680 // is the alignment of the element type. 3681 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3682 ExprType = Context.getBaseElementType(ExprType); 3683 3684 if (ExprKind == UETT_VecStep) 3685 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3686 3687 // Whitelist some types as extensions 3688 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3689 ExprKind)) 3690 return false; 3691 3692 if (RequireCompleteType(OpLoc, ExprType, 3693 diag::err_sizeof_alignof_incomplete_type, 3694 ExprKind, ExprRange)) 3695 return true; 3696 3697 if (ExprType->isFunctionType()) { 3698 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3699 << ExprKind << ExprRange; 3700 return true; 3701 } 3702 3703 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3704 ExprKind)) 3705 return true; 3706 3707 return false; 3708 } 3709 3710 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3711 E = E->IgnoreParens(); 3712 3713 // Cannot know anything else if the expression is dependent. 3714 if (E->isTypeDependent()) 3715 return false; 3716 3717 if (E->getObjectKind() == OK_BitField) { 3718 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) 3719 << 1 << E->getSourceRange(); 3720 return true; 3721 } 3722 3723 ValueDecl *D = nullptr; 3724 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3725 D = DRE->getDecl(); 3726 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3727 D = ME->getMemberDecl(); 3728 } 3729 3730 // If it's a field, require the containing struct to have a 3731 // complete definition so that we can compute the layout. 3732 // 3733 // This can happen in C++11 onwards, either by naming the member 3734 // in a way that is not transformed into a member access expression 3735 // (in an unevaluated operand, for instance), or by naming the member 3736 // in a trailing-return-type. 3737 // 3738 // For the record, since __alignof__ on expressions is a GCC 3739 // extension, GCC seems to permit this but always gives the 3740 // nonsensical answer 0. 3741 // 3742 // We don't really need the layout here --- we could instead just 3743 // directly check for all the appropriate alignment-lowing 3744 // attributes --- but that would require duplicating a lot of 3745 // logic that just isn't worth duplicating for such a marginal 3746 // use-case. 3747 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3748 // Fast path this check, since we at least know the record has a 3749 // definition if we can find a member of it. 3750 if (!FD->getParent()->isCompleteDefinition()) { 3751 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3752 << E->getSourceRange(); 3753 return true; 3754 } 3755 3756 // Otherwise, if it's a field, and the field doesn't have 3757 // reference type, then it must have a complete type (or be a 3758 // flexible array member, which we explicitly want to 3759 // white-list anyway), which makes the following checks trivial. 3760 if (!FD->getType()->isReferenceType()) 3761 return false; 3762 } 3763 3764 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3765 } 3766 3767 bool Sema::CheckVecStepExpr(Expr *E) { 3768 E = E->IgnoreParens(); 3769 3770 // Cannot know anything else if the expression is dependent. 3771 if (E->isTypeDependent()) 3772 return false; 3773 3774 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3775 } 3776 3777 /// \brief Build a sizeof or alignof expression given a type operand. 3778 ExprResult 3779 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3780 SourceLocation OpLoc, 3781 UnaryExprOrTypeTrait ExprKind, 3782 SourceRange R) { 3783 if (!TInfo) 3784 return ExprError(); 3785 3786 QualType T = TInfo->getType(); 3787 3788 if (!T->isDependentType() && 3789 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3790 return ExprError(); 3791 3792 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3793 return new (Context) UnaryExprOrTypeTraitExpr( 3794 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3795 } 3796 3797 /// \brief Build a sizeof or alignof expression given an expression 3798 /// operand. 3799 ExprResult 3800 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3801 UnaryExprOrTypeTrait ExprKind) { 3802 ExprResult PE = CheckPlaceholderExpr(E); 3803 if (PE.isInvalid()) 3804 return ExprError(); 3805 3806 E = PE.get(); 3807 3808 // Verify that the operand is valid. 3809 bool isInvalid = false; 3810 if (E->isTypeDependent()) { 3811 // Delay type-checking for type-dependent expressions. 3812 } else if (ExprKind == UETT_AlignOf) { 3813 isInvalid = CheckAlignOfExpr(*this, E); 3814 } else if (ExprKind == UETT_VecStep) { 3815 isInvalid = CheckVecStepExpr(E); 3816 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 3817 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 3818 isInvalid = true; 3819 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3820 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0; 3821 isInvalid = true; 3822 } else { 3823 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3824 } 3825 3826 if (isInvalid) 3827 return ExprError(); 3828 3829 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3830 PE = TransformToPotentiallyEvaluated(E); 3831 if (PE.isInvalid()) return ExprError(); 3832 E = PE.get(); 3833 } 3834 3835 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3836 return new (Context) UnaryExprOrTypeTraitExpr( 3837 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 3838 } 3839 3840 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3841 /// expr and the same for @c alignof and @c __alignof 3842 /// Note that the ArgRange is invalid if isType is false. 3843 ExprResult 3844 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3845 UnaryExprOrTypeTrait ExprKind, bool IsType, 3846 void *TyOrEx, const SourceRange &ArgRange) { 3847 // If error parsing type, ignore. 3848 if (!TyOrEx) return ExprError(); 3849 3850 if (IsType) { 3851 TypeSourceInfo *TInfo; 3852 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3853 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3854 } 3855 3856 Expr *ArgEx = (Expr *)TyOrEx; 3857 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3858 return Result; 3859 } 3860 3861 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3862 bool IsReal) { 3863 if (V.get()->isTypeDependent()) 3864 return S.Context.DependentTy; 3865 3866 // _Real and _Imag are only l-values for normal l-values. 3867 if (V.get()->getObjectKind() != OK_Ordinary) { 3868 V = S.DefaultLvalueConversion(V.get()); 3869 if (V.isInvalid()) 3870 return QualType(); 3871 } 3872 3873 // These operators return the element type of a complex type. 3874 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3875 return CT->getElementType(); 3876 3877 // Otherwise they pass through real integer and floating point types here. 3878 if (V.get()->getType()->isArithmeticType()) 3879 return V.get()->getType(); 3880 3881 // Test for placeholders. 3882 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3883 if (PR.isInvalid()) return QualType(); 3884 if (PR.get() != V.get()) { 3885 V = PR; 3886 return CheckRealImagOperand(S, V, Loc, IsReal); 3887 } 3888 3889 // Reject anything else. 3890 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3891 << (IsReal ? "__real" : "__imag"); 3892 return QualType(); 3893 } 3894 3895 3896 3897 ExprResult 3898 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3899 tok::TokenKind Kind, Expr *Input) { 3900 UnaryOperatorKind Opc; 3901 switch (Kind) { 3902 default: llvm_unreachable("Unknown unary op!"); 3903 case tok::plusplus: Opc = UO_PostInc; break; 3904 case tok::minusminus: Opc = UO_PostDec; break; 3905 } 3906 3907 // Since this might is a postfix expression, get rid of ParenListExprs. 3908 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3909 if (Result.isInvalid()) return ExprError(); 3910 Input = Result.get(); 3911 3912 return BuildUnaryOp(S, OpLoc, Opc, Input); 3913 } 3914 3915 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3916 /// 3917 /// \return true on error 3918 static bool checkArithmeticOnObjCPointer(Sema &S, 3919 SourceLocation opLoc, 3920 Expr *op) { 3921 assert(op->getType()->isObjCObjectPointerType()); 3922 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 3923 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 3924 return false; 3925 3926 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3927 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3928 << op->getSourceRange(); 3929 return true; 3930 } 3931 3932 ExprResult 3933 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3934 Expr *idx, SourceLocation rbLoc) { 3935 if (base && !base->getType().isNull() && 3936 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 3937 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 3938 /*Length=*/nullptr, rbLoc); 3939 3940 // Since this might be a postfix expression, get rid of ParenListExprs. 3941 if (isa<ParenListExpr>(base)) { 3942 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3943 if (result.isInvalid()) return ExprError(); 3944 base = result.get(); 3945 } 3946 3947 // Handle any non-overload placeholder types in the base and index 3948 // expressions. We can't handle overloads here because the other 3949 // operand might be an overloadable type, in which case the overload 3950 // resolution for the operator overload should get the first crack 3951 // at the overload. 3952 if (base->getType()->isNonOverloadPlaceholderType()) { 3953 ExprResult result = CheckPlaceholderExpr(base); 3954 if (result.isInvalid()) return ExprError(); 3955 base = result.get(); 3956 } 3957 if (idx->getType()->isNonOverloadPlaceholderType()) { 3958 ExprResult result = CheckPlaceholderExpr(idx); 3959 if (result.isInvalid()) return ExprError(); 3960 idx = result.get(); 3961 } 3962 3963 // Build an unanalyzed expression if either operand is type-dependent. 3964 if (getLangOpts().CPlusPlus && 3965 (base->isTypeDependent() || idx->isTypeDependent())) { 3966 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 3967 VK_LValue, OK_Ordinary, rbLoc); 3968 } 3969 3970 // Use C++ overloaded-operator rules if either operand has record 3971 // type. The spec says to do this if either type is *overloadable*, 3972 // but enum types can't declare subscript operators or conversion 3973 // operators, so there's nothing interesting for overload resolution 3974 // to do if there aren't any record types involved. 3975 // 3976 // ObjC pointers have their own subscripting logic that is not tied 3977 // to overload resolution and so should not take this path. 3978 if (getLangOpts().CPlusPlus && 3979 (base->getType()->isRecordType() || 3980 (!base->getType()->isObjCObjectPointerType() && 3981 idx->getType()->isRecordType()))) { 3982 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3983 } 3984 3985 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3986 } 3987 3988 static QualType getNonOMPArraySectionType(Expr *Base) { 3989 unsigned ArraySectionCount = 0; 3990 while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) { 3991 Base = OASE->getBase(); 3992 ++ArraySectionCount; 3993 } 3994 auto OriginalTy = Base->getType(); 3995 if (auto *DRE = dyn_cast<DeclRefExpr>(Base)) 3996 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 3997 OriginalTy = PVD->getOriginalType().getNonReferenceType(); 3998 3999 for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) { 4000 if (OriginalTy->isAnyPointerType()) 4001 OriginalTy = OriginalTy->getPointeeType(); 4002 else { 4003 assert (OriginalTy->isArrayType()); 4004 OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType(); 4005 } 4006 } 4007 return OriginalTy; 4008 } 4009 4010 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4011 Expr *LowerBound, 4012 SourceLocation ColonLoc, Expr *Length, 4013 SourceLocation RBLoc) { 4014 if (Base->getType()->isPlaceholderType() && 4015 !Base->getType()->isSpecificPlaceholderType( 4016 BuiltinType::OMPArraySection)) { 4017 ExprResult Result = CheckPlaceholderExpr(Base); 4018 if (Result.isInvalid()) 4019 return ExprError(); 4020 Base = Result.get(); 4021 } 4022 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4023 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4024 if (Result.isInvalid()) 4025 return ExprError(); 4026 LowerBound = Result.get(); 4027 } 4028 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4029 ExprResult Result = CheckPlaceholderExpr(Length); 4030 if (Result.isInvalid()) 4031 return ExprError(); 4032 Length = Result.get(); 4033 } 4034 4035 // Build an unanalyzed expression if either operand is type-dependent. 4036 if (Base->isTypeDependent() || 4037 (LowerBound && 4038 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4039 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4040 return new (Context) 4041 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4042 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4043 } 4044 4045 // Perform default conversions. 4046 QualType OriginalTy = getNonOMPArraySectionType(Base); 4047 QualType ResultTy; 4048 if (OriginalTy->isAnyPointerType()) { 4049 ResultTy = OriginalTy->getPointeeType(); 4050 } else if (OriginalTy->isArrayType()) { 4051 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4052 } else { 4053 return ExprError( 4054 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4055 << Base->getSourceRange()); 4056 } 4057 // C99 6.5.2.1p1 4058 if (LowerBound) { 4059 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4060 LowerBound); 4061 if (Res.isInvalid()) 4062 return ExprError(Diag(LowerBound->getExprLoc(), 4063 diag::err_omp_typecheck_section_not_integer) 4064 << 0 << LowerBound->getSourceRange()); 4065 LowerBound = Res.get(); 4066 4067 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4068 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4069 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4070 << 0 << LowerBound->getSourceRange(); 4071 } 4072 if (Length) { 4073 auto Res = 4074 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4075 if (Res.isInvalid()) 4076 return ExprError(Diag(Length->getExprLoc(), 4077 diag::err_omp_typecheck_section_not_integer) 4078 << 1 << Length->getSourceRange()); 4079 Length = Res.get(); 4080 4081 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4082 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4083 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4084 << 1 << Length->getSourceRange(); 4085 } 4086 4087 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4088 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4089 // type. Note that functions are not objects, and that (in C99 parlance) 4090 // incomplete types are not object types. 4091 if (ResultTy->isFunctionType()) { 4092 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4093 << ResultTy << Base->getSourceRange(); 4094 return ExprError(); 4095 } 4096 4097 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4098 diag::err_omp_section_incomplete_type, Base)) 4099 return ExprError(); 4100 4101 if (LowerBound) { 4102 llvm::APSInt LowerBoundValue; 4103 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4104 // OpenMP 4.0, [2.4 Array Sections] 4105 // The lower-bound and length must evaluate to non-negative integers. 4106 if (LowerBoundValue.isNegative()) { 4107 Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative) 4108 << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true) 4109 << LowerBound->getSourceRange(); 4110 return ExprError(); 4111 } 4112 } 4113 } 4114 4115 if (Length) { 4116 llvm::APSInt LengthValue; 4117 if (Length->EvaluateAsInt(LengthValue, Context)) { 4118 // OpenMP 4.0, [2.4 Array Sections] 4119 // The lower-bound and length must evaluate to non-negative integers. 4120 if (LengthValue.isNegative()) { 4121 Diag(Length->getExprLoc(), diag::err_omp_section_negative) 4122 << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4123 << Length->getSourceRange(); 4124 return ExprError(); 4125 } 4126 } 4127 } else if (ColonLoc.isValid() && 4128 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4129 !OriginalTy->isVariableArrayType()))) { 4130 // OpenMP 4.0, [2.4 Array Sections] 4131 // When the size of the array dimension is not known, the length must be 4132 // specified explicitly. 4133 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4134 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4135 return ExprError(); 4136 } 4137 4138 return new (Context) 4139 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4140 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4141 } 4142 4143 ExprResult 4144 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4145 Expr *Idx, SourceLocation RLoc) { 4146 Expr *LHSExp = Base; 4147 Expr *RHSExp = Idx; 4148 4149 // Perform default conversions. 4150 if (!LHSExp->getType()->getAs<VectorType>()) { 4151 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4152 if (Result.isInvalid()) 4153 return ExprError(); 4154 LHSExp = Result.get(); 4155 } 4156 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4157 if (Result.isInvalid()) 4158 return ExprError(); 4159 RHSExp = Result.get(); 4160 4161 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4162 ExprValueKind VK = VK_LValue; 4163 ExprObjectKind OK = OK_Ordinary; 4164 4165 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4166 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4167 // in the subscript position. As a result, we need to derive the array base 4168 // and index from the expression types. 4169 Expr *BaseExpr, *IndexExpr; 4170 QualType ResultType; 4171 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4172 BaseExpr = LHSExp; 4173 IndexExpr = RHSExp; 4174 ResultType = Context.DependentTy; 4175 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4176 BaseExpr = LHSExp; 4177 IndexExpr = RHSExp; 4178 ResultType = PTy->getPointeeType(); 4179 } else if (const ObjCObjectPointerType *PTy = 4180 LHSTy->getAs<ObjCObjectPointerType>()) { 4181 BaseExpr = LHSExp; 4182 IndexExpr = RHSExp; 4183 4184 // Use custom logic if this should be the pseudo-object subscript 4185 // expression. 4186 if (!LangOpts.isSubscriptPointerArithmetic()) 4187 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4188 nullptr); 4189 4190 ResultType = PTy->getPointeeType(); 4191 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4192 // Handle the uncommon case of "123[Ptr]". 4193 BaseExpr = RHSExp; 4194 IndexExpr = LHSExp; 4195 ResultType = PTy->getPointeeType(); 4196 } else if (const ObjCObjectPointerType *PTy = 4197 RHSTy->getAs<ObjCObjectPointerType>()) { 4198 // Handle the uncommon case of "123[Ptr]". 4199 BaseExpr = RHSExp; 4200 IndexExpr = LHSExp; 4201 ResultType = PTy->getPointeeType(); 4202 if (!LangOpts.isSubscriptPointerArithmetic()) { 4203 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4204 << ResultType << BaseExpr->getSourceRange(); 4205 return ExprError(); 4206 } 4207 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4208 BaseExpr = LHSExp; // vectors: V[123] 4209 IndexExpr = RHSExp; 4210 VK = LHSExp->getValueKind(); 4211 if (VK != VK_RValue) 4212 OK = OK_VectorComponent; 4213 4214 // FIXME: need to deal with const... 4215 ResultType = VTy->getElementType(); 4216 } else if (LHSTy->isArrayType()) { 4217 // If we see an array that wasn't promoted by 4218 // DefaultFunctionArrayLvalueConversion, it must be an array that 4219 // wasn't promoted because of the C90 rule that doesn't 4220 // allow promoting non-lvalue arrays. Warn, then 4221 // force the promotion here. 4222 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4223 LHSExp->getSourceRange(); 4224 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4225 CK_ArrayToPointerDecay).get(); 4226 LHSTy = LHSExp->getType(); 4227 4228 BaseExpr = LHSExp; 4229 IndexExpr = RHSExp; 4230 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4231 } else if (RHSTy->isArrayType()) { 4232 // Same as previous, except for 123[f().a] case 4233 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4234 RHSExp->getSourceRange(); 4235 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4236 CK_ArrayToPointerDecay).get(); 4237 RHSTy = RHSExp->getType(); 4238 4239 BaseExpr = RHSExp; 4240 IndexExpr = LHSExp; 4241 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4242 } else { 4243 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4244 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4245 } 4246 // C99 6.5.2.1p1 4247 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4248 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4249 << IndexExpr->getSourceRange()); 4250 4251 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4252 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4253 && !IndexExpr->isTypeDependent()) 4254 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4255 4256 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4257 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4258 // type. Note that Functions are not objects, and that (in C99 parlance) 4259 // incomplete types are not object types. 4260 if (ResultType->isFunctionType()) { 4261 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4262 << ResultType << BaseExpr->getSourceRange(); 4263 return ExprError(); 4264 } 4265 4266 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4267 // GNU extension: subscripting on pointer to void 4268 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4269 << BaseExpr->getSourceRange(); 4270 4271 // C forbids expressions of unqualified void type from being l-values. 4272 // See IsCForbiddenLValueType. 4273 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4274 } else if (!ResultType->isDependentType() && 4275 RequireCompleteType(LLoc, ResultType, 4276 diag::err_subscript_incomplete_type, BaseExpr)) 4277 return ExprError(); 4278 4279 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4280 !ResultType.isCForbiddenLValueType()); 4281 4282 return new (Context) 4283 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4284 } 4285 4286 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4287 FunctionDecl *FD, 4288 ParmVarDecl *Param) { 4289 if (Param->hasUnparsedDefaultArg()) { 4290 Diag(CallLoc, 4291 diag::err_use_of_default_argument_to_function_declared_later) << 4292 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4293 Diag(UnparsedDefaultArgLocs[Param], 4294 diag::note_default_argument_declared_here); 4295 return ExprError(); 4296 } 4297 4298 if (Param->hasUninstantiatedDefaultArg()) { 4299 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4300 4301 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4302 Param); 4303 4304 // Instantiate the expression. 4305 MultiLevelTemplateArgumentList MutiLevelArgList 4306 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4307 4308 InstantiatingTemplate Inst(*this, CallLoc, Param, 4309 MutiLevelArgList.getInnermost()); 4310 if (Inst.isInvalid()) 4311 return ExprError(); 4312 4313 ExprResult Result; 4314 { 4315 // C++ [dcl.fct.default]p5: 4316 // The names in the [default argument] expression are bound, and 4317 // the semantic constraints are checked, at the point where the 4318 // default argument expression appears. 4319 ContextRAII SavedContext(*this, FD); 4320 LocalInstantiationScope Local(*this); 4321 Result = SubstExpr(UninstExpr, MutiLevelArgList); 4322 } 4323 if (Result.isInvalid()) 4324 return ExprError(); 4325 4326 // Check the expression as an initializer for the parameter. 4327 InitializedEntity Entity 4328 = InitializedEntity::InitializeParameter(Context, Param); 4329 InitializationKind Kind 4330 = InitializationKind::CreateCopy(Param->getLocation(), 4331 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4332 Expr *ResultE = Result.getAs<Expr>(); 4333 4334 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4335 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4336 if (Result.isInvalid()) 4337 return ExprError(); 4338 4339 Expr *Arg = Result.getAs<Expr>(); 4340 CheckCompletedExpr(Arg, Param->getOuterLocStart()); 4341 // Build the default argument expression. 4342 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg); 4343 } 4344 4345 // If the default expression creates temporaries, we need to 4346 // push them to the current stack of expression temporaries so they'll 4347 // be properly destroyed. 4348 // FIXME: We should really be rebuilding the default argument with new 4349 // bound temporaries; see the comment in PR5810. 4350 // We don't need to do that with block decls, though, because 4351 // blocks in default argument expression can never capture anything. 4352 if (isa<ExprWithCleanups>(Param->getInit())) { 4353 // Set the "needs cleanups" bit regardless of whether there are 4354 // any explicit objects. 4355 ExprNeedsCleanups = true; 4356 4357 // Append all the objects to the cleanup list. Right now, this 4358 // should always be a no-op, because blocks in default argument 4359 // expressions should never be able to capture anything. 4360 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 4361 "default argument expression has capturing blocks?"); 4362 } 4363 4364 // We already type-checked the argument, so we know it works. 4365 // Just mark all of the declarations in this potentially-evaluated expression 4366 // as being "referenced". 4367 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4368 /*SkipLocalVariables=*/true); 4369 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4370 } 4371 4372 4373 Sema::VariadicCallType 4374 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4375 Expr *Fn) { 4376 if (Proto && Proto->isVariadic()) { 4377 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4378 return VariadicConstructor; 4379 else if (Fn && Fn->getType()->isBlockPointerType()) 4380 return VariadicBlock; 4381 else if (FDecl) { 4382 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4383 if (Method->isInstance()) 4384 return VariadicMethod; 4385 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4386 return VariadicMethod; 4387 return VariadicFunction; 4388 } 4389 return VariadicDoesNotApply; 4390 } 4391 4392 namespace { 4393 class FunctionCallCCC : public FunctionCallFilterCCC { 4394 public: 4395 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4396 unsigned NumArgs, MemberExpr *ME) 4397 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4398 FunctionName(FuncName) {} 4399 4400 bool ValidateCandidate(const TypoCorrection &candidate) override { 4401 if (!candidate.getCorrectionSpecifier() || 4402 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4403 return false; 4404 } 4405 4406 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4407 } 4408 4409 private: 4410 const IdentifierInfo *const FunctionName; 4411 }; 4412 } 4413 4414 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4415 FunctionDecl *FDecl, 4416 ArrayRef<Expr *> Args) { 4417 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4418 DeclarationName FuncName = FDecl->getDeclName(); 4419 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4420 4421 if (TypoCorrection Corrected = S.CorrectTypo( 4422 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4423 S.getScopeForContext(S.CurContext), nullptr, 4424 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4425 Args.size(), ME), 4426 Sema::CTK_ErrorRecovery)) { 4427 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 4428 if (Corrected.isOverloaded()) { 4429 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4430 OverloadCandidateSet::iterator Best; 4431 for (TypoCorrection::decl_iterator CD = Corrected.begin(), 4432 CDEnd = Corrected.end(); 4433 CD != CDEnd; ++CD) { 4434 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD)) 4435 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4436 OCS); 4437 } 4438 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4439 case OR_Success: 4440 ND = Best->Function; 4441 Corrected.setCorrectionDecl(ND); 4442 break; 4443 default: 4444 break; 4445 } 4446 } 4447 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 4448 return Corrected; 4449 } 4450 } 4451 } 4452 return TypoCorrection(); 4453 } 4454 4455 /// ConvertArgumentsForCall - Converts the arguments specified in 4456 /// Args/NumArgs to the parameter types of the function FDecl with 4457 /// function prototype Proto. Call is the call expression itself, and 4458 /// Fn is the function expression. For a C++ member function, this 4459 /// routine does not attempt to convert the object argument. Returns 4460 /// true if the call is ill-formed. 4461 bool 4462 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4463 FunctionDecl *FDecl, 4464 const FunctionProtoType *Proto, 4465 ArrayRef<Expr *> Args, 4466 SourceLocation RParenLoc, 4467 bool IsExecConfig) { 4468 // Bail out early if calling a builtin with custom typechecking. 4469 if (FDecl) 4470 if (unsigned ID = FDecl->getBuiltinID()) 4471 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4472 return false; 4473 4474 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4475 // assignment, to the types of the corresponding parameter, ... 4476 unsigned NumParams = Proto->getNumParams(); 4477 bool Invalid = false; 4478 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4479 unsigned FnKind = Fn->getType()->isBlockPointerType() 4480 ? 1 /* block */ 4481 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4482 : 0 /* function */); 4483 4484 // If too few arguments are available (and we don't have default 4485 // arguments for the remaining parameters), don't make the call. 4486 if (Args.size() < NumParams) { 4487 if (Args.size() < MinArgs) { 4488 TypoCorrection TC; 4489 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4490 unsigned diag_id = 4491 MinArgs == NumParams && !Proto->isVariadic() 4492 ? diag::err_typecheck_call_too_few_args_suggest 4493 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4494 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4495 << static_cast<unsigned>(Args.size()) 4496 << TC.getCorrectionRange()); 4497 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4498 Diag(RParenLoc, 4499 MinArgs == NumParams && !Proto->isVariadic() 4500 ? diag::err_typecheck_call_too_few_args_one 4501 : diag::err_typecheck_call_too_few_args_at_least_one) 4502 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4503 else 4504 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4505 ? diag::err_typecheck_call_too_few_args 4506 : diag::err_typecheck_call_too_few_args_at_least) 4507 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4508 << Fn->getSourceRange(); 4509 4510 // Emit the location of the prototype. 4511 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4512 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4513 << FDecl; 4514 4515 return true; 4516 } 4517 Call->setNumArgs(Context, NumParams); 4518 } 4519 4520 // If too many are passed and not variadic, error on the extras and drop 4521 // them. 4522 if (Args.size() > NumParams) { 4523 if (!Proto->isVariadic()) { 4524 TypoCorrection TC; 4525 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4526 unsigned diag_id = 4527 MinArgs == NumParams && !Proto->isVariadic() 4528 ? diag::err_typecheck_call_too_many_args_suggest 4529 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4530 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4531 << static_cast<unsigned>(Args.size()) 4532 << TC.getCorrectionRange()); 4533 } else if (NumParams == 1 && FDecl && 4534 FDecl->getParamDecl(0)->getDeclName()) 4535 Diag(Args[NumParams]->getLocStart(), 4536 MinArgs == NumParams 4537 ? diag::err_typecheck_call_too_many_args_one 4538 : diag::err_typecheck_call_too_many_args_at_most_one) 4539 << FnKind << FDecl->getParamDecl(0) 4540 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4541 << SourceRange(Args[NumParams]->getLocStart(), 4542 Args.back()->getLocEnd()); 4543 else 4544 Diag(Args[NumParams]->getLocStart(), 4545 MinArgs == NumParams 4546 ? diag::err_typecheck_call_too_many_args 4547 : diag::err_typecheck_call_too_many_args_at_most) 4548 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4549 << Fn->getSourceRange() 4550 << SourceRange(Args[NumParams]->getLocStart(), 4551 Args.back()->getLocEnd()); 4552 4553 // Emit the location of the prototype. 4554 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4555 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4556 << FDecl; 4557 4558 // This deletes the extra arguments. 4559 Call->setNumArgs(Context, NumParams); 4560 return true; 4561 } 4562 } 4563 SmallVector<Expr *, 8> AllArgs; 4564 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4565 4566 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4567 Proto, 0, Args, AllArgs, CallType); 4568 if (Invalid) 4569 return true; 4570 unsigned TotalNumArgs = AllArgs.size(); 4571 for (unsigned i = 0; i < TotalNumArgs; ++i) 4572 Call->setArg(i, AllArgs[i]); 4573 4574 return false; 4575 } 4576 4577 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4578 const FunctionProtoType *Proto, 4579 unsigned FirstParam, ArrayRef<Expr *> Args, 4580 SmallVectorImpl<Expr *> &AllArgs, 4581 VariadicCallType CallType, bool AllowExplicit, 4582 bool IsListInitialization) { 4583 unsigned NumParams = Proto->getNumParams(); 4584 bool Invalid = false; 4585 unsigned ArgIx = 0; 4586 // Continue to check argument types (even if we have too few/many args). 4587 for (unsigned i = FirstParam; i < NumParams; i++) { 4588 QualType ProtoArgType = Proto->getParamType(i); 4589 4590 Expr *Arg; 4591 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4592 if (ArgIx < Args.size()) { 4593 Arg = Args[ArgIx++]; 4594 4595 if (RequireCompleteType(Arg->getLocStart(), 4596 ProtoArgType, 4597 diag::err_call_incomplete_argument, Arg)) 4598 return true; 4599 4600 // Strip the unbridged-cast placeholder expression off, if applicable. 4601 bool CFAudited = false; 4602 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4603 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4604 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4605 Arg = stripARCUnbridgedCast(Arg); 4606 else if (getLangOpts().ObjCAutoRefCount && 4607 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4608 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4609 CFAudited = true; 4610 4611 InitializedEntity Entity = 4612 Param ? InitializedEntity::InitializeParameter(Context, Param, 4613 ProtoArgType) 4614 : InitializedEntity::InitializeParameter( 4615 Context, ProtoArgType, Proto->isParamConsumed(i)); 4616 4617 // Remember that parameter belongs to a CF audited API. 4618 if (CFAudited) 4619 Entity.setParameterCFAudited(); 4620 4621 ExprResult ArgE = PerformCopyInitialization( 4622 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4623 if (ArgE.isInvalid()) 4624 return true; 4625 4626 Arg = ArgE.getAs<Expr>(); 4627 } else { 4628 assert(Param && "can't use default arguments without a known callee"); 4629 4630 ExprResult ArgExpr = 4631 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4632 if (ArgExpr.isInvalid()) 4633 return true; 4634 4635 Arg = ArgExpr.getAs<Expr>(); 4636 } 4637 4638 // Check for array bounds violations for each argument to the call. This 4639 // check only triggers warnings when the argument isn't a more complex Expr 4640 // with its own checking, such as a BinaryOperator. 4641 CheckArrayAccess(Arg); 4642 4643 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4644 CheckStaticArrayArgument(CallLoc, Param, Arg); 4645 4646 AllArgs.push_back(Arg); 4647 } 4648 4649 // If this is a variadic call, handle args passed through "...". 4650 if (CallType != VariadicDoesNotApply) { 4651 // Assume that extern "C" functions with variadic arguments that 4652 // return __unknown_anytype aren't *really* variadic. 4653 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4654 FDecl->isExternC()) { 4655 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4656 QualType paramType; // ignored 4657 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType); 4658 Invalid |= arg.isInvalid(); 4659 AllArgs.push_back(arg.get()); 4660 } 4661 4662 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4663 } else { 4664 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) { 4665 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType, 4666 FDecl); 4667 Invalid |= Arg.isInvalid(); 4668 AllArgs.push_back(Arg.get()); 4669 } 4670 } 4671 4672 // Check for array bounds violations. 4673 for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) 4674 CheckArrayAccess(Args[i]); 4675 } 4676 return Invalid; 4677 } 4678 4679 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4680 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4681 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4682 TL = DTL.getOriginalLoc(); 4683 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4684 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4685 << ATL.getLocalSourceRange(); 4686 } 4687 4688 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4689 /// array parameter, check that it is non-null, and that if it is formed by 4690 /// array-to-pointer decay, the underlying array is sufficiently large. 4691 /// 4692 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4693 /// array type derivation, then for each call to the function, the value of the 4694 /// corresponding actual argument shall provide access to the first element of 4695 /// an array with at least as many elements as specified by the size expression. 4696 void 4697 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4698 ParmVarDecl *Param, 4699 const Expr *ArgExpr) { 4700 // Static array parameters are not supported in C++. 4701 if (!Param || getLangOpts().CPlusPlus) 4702 return; 4703 4704 QualType OrigTy = Param->getOriginalType(); 4705 4706 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4707 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4708 return; 4709 4710 if (ArgExpr->isNullPointerConstant(Context, 4711 Expr::NPC_NeverValueDependent)) { 4712 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4713 DiagnoseCalleeStaticArrayParam(*this, Param); 4714 return; 4715 } 4716 4717 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4718 if (!CAT) 4719 return; 4720 4721 const ConstantArrayType *ArgCAT = 4722 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4723 if (!ArgCAT) 4724 return; 4725 4726 if (ArgCAT->getSize().ult(CAT->getSize())) { 4727 Diag(CallLoc, diag::warn_static_array_too_small) 4728 << ArgExpr->getSourceRange() 4729 << (unsigned) ArgCAT->getSize().getZExtValue() 4730 << (unsigned) CAT->getSize().getZExtValue(); 4731 DiagnoseCalleeStaticArrayParam(*this, Param); 4732 } 4733 } 4734 4735 /// Given a function expression of unknown-any type, try to rebuild it 4736 /// to have a function type. 4737 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4738 4739 /// Is the given type a placeholder that we need to lower out 4740 /// immediately during argument processing? 4741 static bool isPlaceholderToRemoveAsArg(QualType type) { 4742 // Placeholders are never sugared. 4743 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4744 if (!placeholder) return false; 4745 4746 switch (placeholder->getKind()) { 4747 // Ignore all the non-placeholder types. 4748 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4749 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4750 #include "clang/AST/BuiltinTypes.def" 4751 return false; 4752 4753 // We cannot lower out overload sets; they might validly be resolved 4754 // by the call machinery. 4755 case BuiltinType::Overload: 4756 return false; 4757 4758 // Unbridged casts in ARC can be handled in some call positions and 4759 // should be left in place. 4760 case BuiltinType::ARCUnbridgedCast: 4761 return false; 4762 4763 // Pseudo-objects should be converted as soon as possible. 4764 case BuiltinType::PseudoObject: 4765 return true; 4766 4767 // The debugger mode could theoretically but currently does not try 4768 // to resolve unknown-typed arguments based on known parameter types. 4769 case BuiltinType::UnknownAny: 4770 return true; 4771 4772 // These are always invalid as call arguments and should be reported. 4773 case BuiltinType::BoundMember: 4774 case BuiltinType::BuiltinFn: 4775 case BuiltinType::OMPArraySection: 4776 return true; 4777 4778 } 4779 llvm_unreachable("bad builtin type kind"); 4780 } 4781 4782 /// Check an argument list for placeholders that we won't try to 4783 /// handle later. 4784 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4785 // Apply this processing to all the arguments at once instead of 4786 // dying at the first failure. 4787 bool hasInvalid = false; 4788 for (size_t i = 0, e = args.size(); i != e; i++) { 4789 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4790 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4791 if (result.isInvalid()) hasInvalid = true; 4792 else args[i] = result.get(); 4793 } else if (hasInvalid) { 4794 (void)S.CorrectDelayedTyposInExpr(args[i]); 4795 } 4796 } 4797 return hasInvalid; 4798 } 4799 4800 /// If a builtin function has a pointer argument with no explicit address 4801 /// space, than it should be able to accept a pointer to any address 4802 /// space as input. In order to do this, we need to replace the 4803 /// standard builtin declaration with one that uses the same address space 4804 /// as the call. 4805 /// 4806 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 4807 /// it does not contain any pointer arguments without 4808 /// an address space qualifer. Otherwise the rewritten 4809 /// FunctionDecl is returned. 4810 /// TODO: Handle pointer return types. 4811 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 4812 const FunctionDecl *FDecl, 4813 MultiExprArg ArgExprs) { 4814 4815 QualType DeclType = FDecl->getType(); 4816 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 4817 4818 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 4819 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 4820 return nullptr; 4821 4822 bool NeedsNewDecl = false; 4823 unsigned i = 0; 4824 SmallVector<QualType, 8> OverloadParams; 4825 4826 for (QualType ParamType : FT->param_types()) { 4827 4828 // Convert array arguments to pointer to simplify type lookup. 4829 Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get(); 4830 QualType ArgType = Arg->getType(); 4831 if (!ParamType->isPointerType() || 4832 ParamType.getQualifiers().hasAddressSpace() || 4833 !ArgType->isPointerType() || 4834 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 4835 OverloadParams.push_back(ParamType); 4836 continue; 4837 } 4838 4839 NeedsNewDecl = true; 4840 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 4841 4842 QualType PointeeType = ParamType->getPointeeType(); 4843 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 4844 OverloadParams.push_back(Context.getPointerType(PointeeType)); 4845 } 4846 4847 if (!NeedsNewDecl) 4848 return nullptr; 4849 4850 FunctionProtoType::ExtProtoInfo EPI; 4851 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 4852 OverloadParams, EPI); 4853 DeclContext *Parent = Context.getTranslationUnitDecl(); 4854 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 4855 FDecl->getLocation(), 4856 FDecl->getLocation(), 4857 FDecl->getIdentifier(), 4858 OverloadTy, 4859 /*TInfo=*/nullptr, 4860 SC_Extern, false, 4861 /*hasPrototype=*/true); 4862 SmallVector<ParmVarDecl*, 16> Params; 4863 FT = cast<FunctionProtoType>(OverloadTy); 4864 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 4865 QualType ParamType = FT->getParamType(i); 4866 ParmVarDecl *Parm = 4867 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 4868 SourceLocation(), nullptr, ParamType, 4869 /*TInfo=*/nullptr, SC_None, nullptr); 4870 Parm->setScopeInfo(0, i); 4871 Params.push_back(Parm); 4872 } 4873 OverloadDecl->setParams(Params); 4874 return OverloadDecl; 4875 } 4876 4877 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4878 /// This provides the location of the left/right parens and a list of comma 4879 /// locations. 4880 ExprResult 4881 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4882 MultiExprArg ArgExprs, SourceLocation RParenLoc, 4883 Expr *ExecConfig, bool IsExecConfig) { 4884 // Since this might be a postfix expression, get rid of ParenListExprs. 4885 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4886 if (Result.isInvalid()) return ExprError(); 4887 Fn = Result.get(); 4888 4889 if (checkArgsForPlaceholders(*this, ArgExprs)) 4890 return ExprError(); 4891 4892 if (getLangOpts().CPlusPlus) { 4893 // If this is a pseudo-destructor expression, build the call immediately. 4894 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4895 if (!ArgExprs.empty()) { 4896 // Pseudo-destructor calls should not have any arguments. 4897 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4898 << FixItHint::CreateRemoval( 4899 SourceRange(ArgExprs[0]->getLocStart(), 4900 ArgExprs.back()->getLocEnd())); 4901 } 4902 4903 return new (Context) 4904 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 4905 } 4906 if (Fn->getType() == Context.PseudoObjectTy) { 4907 ExprResult result = CheckPlaceholderExpr(Fn); 4908 if (result.isInvalid()) return ExprError(); 4909 Fn = result.get(); 4910 } 4911 4912 // Determine whether this is a dependent call inside a C++ template, 4913 // in which case we won't do any semantic analysis now. 4914 // FIXME: Will need to cache the results of name lookup (including ADL) in 4915 // Fn. 4916 bool Dependent = false; 4917 if (Fn->isTypeDependent()) 4918 Dependent = true; 4919 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 4920 Dependent = true; 4921 4922 if (Dependent) { 4923 if (ExecConfig) { 4924 return new (Context) CUDAKernelCallExpr( 4925 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 4926 Context.DependentTy, VK_RValue, RParenLoc); 4927 } else { 4928 return new (Context) CallExpr( 4929 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 4930 } 4931 } 4932 4933 // Determine whether this is a call to an object (C++ [over.call.object]). 4934 if (Fn->getType()->isRecordType()) 4935 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs, 4936 RParenLoc); 4937 4938 if (Fn->getType() == Context.UnknownAnyTy) { 4939 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4940 if (result.isInvalid()) return ExprError(); 4941 Fn = result.get(); 4942 } 4943 4944 if (Fn->getType() == Context.BoundMemberTy) { 4945 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 4946 } 4947 } 4948 4949 // Check for overloaded calls. This can happen even in C due to extensions. 4950 if (Fn->getType() == Context.OverloadTy) { 4951 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 4952 4953 // We aren't supposed to apply this logic for if there's an '&' involved. 4954 if (!find.HasFormOfMemberPointer) { 4955 OverloadExpr *ovl = find.Expression; 4956 if (isa<UnresolvedLookupExpr>(ovl)) { 4957 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl); 4958 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 4959 RParenLoc, ExecConfig); 4960 } else { 4961 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, 4962 RParenLoc); 4963 } 4964 } 4965 } 4966 4967 // If we're directly calling a function, get the appropriate declaration. 4968 if (Fn->getType() == Context.UnknownAnyTy) { 4969 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4970 if (result.isInvalid()) return ExprError(); 4971 Fn = result.get(); 4972 } 4973 4974 Expr *NakedFn = Fn->IgnoreParens(); 4975 4976 NamedDecl *NDecl = nullptr; 4977 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) 4978 if (UnOp->getOpcode() == UO_AddrOf) 4979 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4980 4981 if (isa<DeclRefExpr>(NakedFn)) { 4982 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4983 4984 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 4985 if (FDecl && FDecl->getBuiltinID()) { 4986 // Rewrite the function decl for this builtin by replacing paramaters 4987 // with no explicit address space with the address space of the arguments 4988 // in ArgExprs. 4989 if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 4990 NDecl = FDecl; 4991 Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(), 4992 SourceLocation(), FDecl, false, 4993 SourceLocation(), FDecl->getType(), 4994 Fn->getValueKind(), FDecl); 4995 } 4996 } 4997 } else if (isa<MemberExpr>(NakedFn)) 4998 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 4999 5000 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5001 if (FD->hasAttr<EnableIfAttr>()) { 5002 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 5003 Diag(Fn->getLocStart(), 5004 isa<CXXMethodDecl>(FD) ? 5005 diag::err_ovl_no_viable_member_function_in_call : 5006 diag::err_ovl_no_viable_function_in_call) 5007 << FD << FD->getSourceRange(); 5008 Diag(FD->getLocation(), 5009 diag::note_ovl_candidate_disabled_by_enable_if_attr) 5010 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5011 } 5012 } 5013 } 5014 5015 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5016 ExecConfig, IsExecConfig); 5017 } 5018 5019 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5020 /// 5021 /// __builtin_astype( value, dst type ) 5022 /// 5023 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5024 SourceLocation BuiltinLoc, 5025 SourceLocation RParenLoc) { 5026 ExprValueKind VK = VK_RValue; 5027 ExprObjectKind OK = OK_Ordinary; 5028 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5029 QualType SrcTy = E->getType(); 5030 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5031 return ExprError(Diag(BuiltinLoc, 5032 diag::err_invalid_astype_of_different_size) 5033 << DstTy 5034 << SrcTy 5035 << E->getSourceRange()); 5036 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5037 } 5038 5039 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5040 /// provided arguments. 5041 /// 5042 /// __builtin_convertvector( value, dst type ) 5043 /// 5044 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5045 SourceLocation BuiltinLoc, 5046 SourceLocation RParenLoc) { 5047 TypeSourceInfo *TInfo; 5048 GetTypeFromParser(ParsedDestTy, &TInfo); 5049 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5050 } 5051 5052 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5053 /// i.e. an expression not of \p OverloadTy. The expression should 5054 /// unary-convert to an expression of function-pointer or 5055 /// block-pointer type. 5056 /// 5057 /// \param NDecl the declaration being called, if available 5058 ExprResult 5059 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5060 SourceLocation LParenLoc, 5061 ArrayRef<Expr *> Args, 5062 SourceLocation RParenLoc, 5063 Expr *Config, bool IsExecConfig) { 5064 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5065 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5066 5067 // Promote the function operand. 5068 // We special-case function promotion here because we only allow promoting 5069 // builtin functions to function pointers in the callee of a call. 5070 ExprResult Result; 5071 if (BuiltinID && 5072 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5073 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5074 CK_BuiltinFnToFnPtr).get(); 5075 } else { 5076 Result = CallExprUnaryConversions(Fn); 5077 } 5078 if (Result.isInvalid()) 5079 return ExprError(); 5080 Fn = Result.get(); 5081 5082 // Make the call expr early, before semantic checks. This guarantees cleanup 5083 // of arguments and function on error. 5084 CallExpr *TheCall; 5085 if (Config) 5086 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5087 cast<CallExpr>(Config), Args, 5088 Context.BoolTy, VK_RValue, 5089 RParenLoc); 5090 else 5091 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5092 VK_RValue, RParenLoc); 5093 5094 if (!getLangOpts().CPlusPlus) { 5095 // C cannot always handle TypoExpr nodes in builtin calls and direct 5096 // function calls as their argument checking don't necessarily handle 5097 // dependent types properly, so make sure any TypoExprs have been 5098 // dealt with. 5099 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5100 if (!Result.isUsable()) return ExprError(); 5101 TheCall = dyn_cast<CallExpr>(Result.get()); 5102 if (!TheCall) return Result; 5103 Args = ArrayRef<Expr *>(TheCall->getArgs(), TheCall->getNumArgs()); 5104 } 5105 5106 // Bail out early if calling a builtin with custom typechecking. 5107 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5108 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5109 5110 retry: 5111 const FunctionType *FuncT; 5112 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5113 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5114 // have type pointer to function". 5115 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5116 if (!FuncT) 5117 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5118 << Fn->getType() << Fn->getSourceRange()); 5119 } else if (const BlockPointerType *BPT = 5120 Fn->getType()->getAs<BlockPointerType>()) { 5121 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5122 } else { 5123 // Handle calls to expressions of unknown-any type. 5124 if (Fn->getType() == Context.UnknownAnyTy) { 5125 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5126 if (rewrite.isInvalid()) return ExprError(); 5127 Fn = rewrite.get(); 5128 TheCall->setCallee(Fn); 5129 goto retry; 5130 } 5131 5132 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5133 << Fn->getType() << Fn->getSourceRange()); 5134 } 5135 5136 if (getLangOpts().CUDA) { 5137 if (Config) { 5138 // CUDA: Kernel calls must be to global functions 5139 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5140 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5141 << FDecl->getName() << Fn->getSourceRange()); 5142 5143 // CUDA: Kernel function must have 'void' return type 5144 if (!FuncT->getReturnType()->isVoidType()) 5145 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5146 << Fn->getType() << Fn->getSourceRange()); 5147 } else { 5148 // CUDA: Calls to global functions must be configured 5149 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5150 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5151 << FDecl->getName() << Fn->getSourceRange()); 5152 } 5153 } 5154 5155 // Check for a valid return type 5156 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5157 FDecl)) 5158 return ExprError(); 5159 5160 // We know the result type of the call, set it. 5161 TheCall->setType(FuncT->getCallResultType(Context)); 5162 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5163 5164 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5165 if (Proto) { 5166 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5167 IsExecConfig)) 5168 return ExprError(); 5169 } else { 5170 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5171 5172 if (FDecl) { 5173 // Check if we have too few/too many template arguments, based 5174 // on our knowledge of the function definition. 5175 const FunctionDecl *Def = nullptr; 5176 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5177 Proto = Def->getType()->getAs<FunctionProtoType>(); 5178 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5179 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5180 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5181 } 5182 5183 // If the function we're calling isn't a function prototype, but we have 5184 // a function prototype from a prior declaratiom, use that prototype. 5185 if (!FDecl->hasPrototype()) 5186 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5187 } 5188 5189 // Promote the arguments (C99 6.5.2.2p6). 5190 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5191 Expr *Arg = Args[i]; 5192 5193 if (Proto && i < Proto->getNumParams()) { 5194 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5195 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5196 ExprResult ArgE = 5197 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5198 if (ArgE.isInvalid()) 5199 return true; 5200 5201 Arg = ArgE.getAs<Expr>(); 5202 5203 } else { 5204 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5205 5206 if (ArgE.isInvalid()) 5207 return true; 5208 5209 Arg = ArgE.getAs<Expr>(); 5210 } 5211 5212 if (RequireCompleteType(Arg->getLocStart(), 5213 Arg->getType(), 5214 diag::err_call_incomplete_argument, Arg)) 5215 return ExprError(); 5216 5217 TheCall->setArg(i, Arg); 5218 } 5219 } 5220 5221 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5222 if (!Method->isStatic()) 5223 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5224 << Fn->getSourceRange()); 5225 5226 // Check for sentinels 5227 if (NDecl) 5228 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5229 5230 // Do special checking on direct calls to functions. 5231 if (FDecl) { 5232 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5233 return ExprError(); 5234 5235 if (BuiltinID) 5236 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5237 } else if (NDecl) { 5238 if (CheckPointerCall(NDecl, TheCall, Proto)) 5239 return ExprError(); 5240 } else { 5241 if (CheckOtherCall(TheCall, Proto)) 5242 return ExprError(); 5243 } 5244 5245 return MaybeBindToTemporary(TheCall); 5246 } 5247 5248 ExprResult 5249 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5250 SourceLocation RParenLoc, Expr *InitExpr) { 5251 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5252 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5253 5254 TypeSourceInfo *TInfo; 5255 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5256 if (!TInfo) 5257 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5258 5259 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5260 } 5261 5262 ExprResult 5263 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5264 SourceLocation RParenLoc, Expr *LiteralExpr) { 5265 QualType literalType = TInfo->getType(); 5266 5267 if (literalType->isArrayType()) { 5268 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5269 diag::err_illegal_decl_array_incomplete_type, 5270 SourceRange(LParenLoc, 5271 LiteralExpr->getSourceRange().getEnd()))) 5272 return ExprError(); 5273 if (literalType->isVariableArrayType()) 5274 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5275 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5276 } else if (!literalType->isDependentType() && 5277 RequireCompleteType(LParenLoc, literalType, 5278 diag::err_typecheck_decl_incomplete_type, 5279 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5280 return ExprError(); 5281 5282 InitializedEntity Entity 5283 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5284 InitializationKind Kind 5285 = InitializationKind::CreateCStyleCast(LParenLoc, 5286 SourceRange(LParenLoc, RParenLoc), 5287 /*InitList=*/true); 5288 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5289 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5290 &literalType); 5291 if (Result.isInvalid()) 5292 return ExprError(); 5293 LiteralExpr = Result.get(); 5294 5295 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 5296 if (isFileScope && 5297 !LiteralExpr->isTypeDependent() && 5298 !LiteralExpr->isValueDependent() && 5299 !literalType->isDependentType()) { // 6.5.2.5p3 5300 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5301 return ExprError(); 5302 } 5303 5304 // In C, compound literals are l-values for some reason. 5305 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 5306 5307 return MaybeBindToTemporary( 5308 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5309 VK, LiteralExpr, isFileScope)); 5310 } 5311 5312 ExprResult 5313 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5314 SourceLocation RBraceLoc) { 5315 // Immediately handle non-overload placeholders. Overloads can be 5316 // resolved contextually, but everything else here can't. 5317 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5318 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5319 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5320 5321 // Ignore failures; dropping the entire initializer list because 5322 // of one failure would be terrible for indexing/etc. 5323 if (result.isInvalid()) continue; 5324 5325 InitArgList[I] = result.get(); 5326 } 5327 } 5328 5329 // Semantic analysis for initializers is done by ActOnDeclarator() and 5330 // CheckInitializer() - it requires knowledge of the object being intialized. 5331 5332 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5333 RBraceLoc); 5334 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5335 return E; 5336 } 5337 5338 /// Do an explicit extend of the given block pointer if we're in ARC. 5339 void Sema::maybeExtendBlockObject(ExprResult &E) { 5340 assert(E.get()->getType()->isBlockPointerType()); 5341 assert(E.get()->isRValue()); 5342 5343 // Only do this in an r-value context. 5344 if (!getLangOpts().ObjCAutoRefCount) return; 5345 5346 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5347 CK_ARCExtendBlockObject, E.get(), 5348 /*base path*/ nullptr, VK_RValue); 5349 ExprNeedsCleanups = true; 5350 } 5351 5352 /// Prepare a conversion of the given expression to an ObjC object 5353 /// pointer type. 5354 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5355 QualType type = E.get()->getType(); 5356 if (type->isObjCObjectPointerType()) { 5357 return CK_BitCast; 5358 } else if (type->isBlockPointerType()) { 5359 maybeExtendBlockObject(E); 5360 return CK_BlockPointerToObjCPointerCast; 5361 } else { 5362 assert(type->isPointerType()); 5363 return CK_CPointerToObjCPointerCast; 5364 } 5365 } 5366 5367 /// Prepares for a scalar cast, performing all the necessary stages 5368 /// except the final cast and returning the kind required. 5369 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5370 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5371 // Also, callers should have filtered out the invalid cases with 5372 // pointers. Everything else should be possible. 5373 5374 QualType SrcTy = Src.get()->getType(); 5375 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5376 return CK_NoOp; 5377 5378 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5379 case Type::STK_MemberPointer: 5380 llvm_unreachable("member pointer type in C"); 5381 5382 case Type::STK_CPointer: 5383 case Type::STK_BlockPointer: 5384 case Type::STK_ObjCObjectPointer: 5385 switch (DestTy->getScalarTypeKind()) { 5386 case Type::STK_CPointer: { 5387 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5388 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5389 if (SrcAS != DestAS) 5390 return CK_AddressSpaceConversion; 5391 return CK_BitCast; 5392 } 5393 case Type::STK_BlockPointer: 5394 return (SrcKind == Type::STK_BlockPointer 5395 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5396 case Type::STK_ObjCObjectPointer: 5397 if (SrcKind == Type::STK_ObjCObjectPointer) 5398 return CK_BitCast; 5399 if (SrcKind == Type::STK_CPointer) 5400 return CK_CPointerToObjCPointerCast; 5401 maybeExtendBlockObject(Src); 5402 return CK_BlockPointerToObjCPointerCast; 5403 case Type::STK_Bool: 5404 return CK_PointerToBoolean; 5405 case Type::STK_Integral: 5406 return CK_PointerToIntegral; 5407 case Type::STK_Floating: 5408 case Type::STK_FloatingComplex: 5409 case Type::STK_IntegralComplex: 5410 case Type::STK_MemberPointer: 5411 llvm_unreachable("illegal cast from pointer"); 5412 } 5413 llvm_unreachable("Should have returned before this"); 5414 5415 case Type::STK_Bool: // casting from bool is like casting from an integer 5416 case Type::STK_Integral: 5417 switch (DestTy->getScalarTypeKind()) { 5418 case Type::STK_CPointer: 5419 case Type::STK_ObjCObjectPointer: 5420 case Type::STK_BlockPointer: 5421 if (Src.get()->isNullPointerConstant(Context, 5422 Expr::NPC_ValueDependentIsNull)) 5423 return CK_NullToPointer; 5424 return CK_IntegralToPointer; 5425 case Type::STK_Bool: 5426 return CK_IntegralToBoolean; 5427 case Type::STK_Integral: 5428 return CK_IntegralCast; 5429 case Type::STK_Floating: 5430 return CK_IntegralToFloating; 5431 case Type::STK_IntegralComplex: 5432 Src = ImpCastExprToType(Src.get(), 5433 DestTy->castAs<ComplexType>()->getElementType(), 5434 CK_IntegralCast); 5435 return CK_IntegralRealToComplex; 5436 case Type::STK_FloatingComplex: 5437 Src = ImpCastExprToType(Src.get(), 5438 DestTy->castAs<ComplexType>()->getElementType(), 5439 CK_IntegralToFloating); 5440 return CK_FloatingRealToComplex; 5441 case Type::STK_MemberPointer: 5442 llvm_unreachable("member pointer type in C"); 5443 } 5444 llvm_unreachable("Should have returned before this"); 5445 5446 case Type::STK_Floating: 5447 switch (DestTy->getScalarTypeKind()) { 5448 case Type::STK_Floating: 5449 return CK_FloatingCast; 5450 case Type::STK_Bool: 5451 return CK_FloatingToBoolean; 5452 case Type::STK_Integral: 5453 return CK_FloatingToIntegral; 5454 case Type::STK_FloatingComplex: 5455 Src = ImpCastExprToType(Src.get(), 5456 DestTy->castAs<ComplexType>()->getElementType(), 5457 CK_FloatingCast); 5458 return CK_FloatingRealToComplex; 5459 case Type::STK_IntegralComplex: 5460 Src = ImpCastExprToType(Src.get(), 5461 DestTy->castAs<ComplexType>()->getElementType(), 5462 CK_FloatingToIntegral); 5463 return CK_IntegralRealToComplex; 5464 case Type::STK_CPointer: 5465 case Type::STK_ObjCObjectPointer: 5466 case Type::STK_BlockPointer: 5467 llvm_unreachable("valid float->pointer cast?"); 5468 case Type::STK_MemberPointer: 5469 llvm_unreachable("member pointer type in C"); 5470 } 5471 llvm_unreachable("Should have returned before this"); 5472 5473 case Type::STK_FloatingComplex: 5474 switch (DestTy->getScalarTypeKind()) { 5475 case Type::STK_FloatingComplex: 5476 return CK_FloatingComplexCast; 5477 case Type::STK_IntegralComplex: 5478 return CK_FloatingComplexToIntegralComplex; 5479 case Type::STK_Floating: { 5480 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5481 if (Context.hasSameType(ET, DestTy)) 5482 return CK_FloatingComplexToReal; 5483 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5484 return CK_FloatingCast; 5485 } 5486 case Type::STK_Bool: 5487 return CK_FloatingComplexToBoolean; 5488 case Type::STK_Integral: 5489 Src = ImpCastExprToType(Src.get(), 5490 SrcTy->castAs<ComplexType>()->getElementType(), 5491 CK_FloatingComplexToReal); 5492 return CK_FloatingToIntegral; 5493 case Type::STK_CPointer: 5494 case Type::STK_ObjCObjectPointer: 5495 case Type::STK_BlockPointer: 5496 llvm_unreachable("valid complex float->pointer cast?"); 5497 case Type::STK_MemberPointer: 5498 llvm_unreachable("member pointer type in C"); 5499 } 5500 llvm_unreachable("Should have returned before this"); 5501 5502 case Type::STK_IntegralComplex: 5503 switch (DestTy->getScalarTypeKind()) { 5504 case Type::STK_FloatingComplex: 5505 return CK_IntegralComplexToFloatingComplex; 5506 case Type::STK_IntegralComplex: 5507 return CK_IntegralComplexCast; 5508 case Type::STK_Integral: { 5509 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5510 if (Context.hasSameType(ET, DestTy)) 5511 return CK_IntegralComplexToReal; 5512 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5513 return CK_IntegralCast; 5514 } 5515 case Type::STK_Bool: 5516 return CK_IntegralComplexToBoolean; 5517 case Type::STK_Floating: 5518 Src = ImpCastExprToType(Src.get(), 5519 SrcTy->castAs<ComplexType>()->getElementType(), 5520 CK_IntegralComplexToReal); 5521 return CK_IntegralToFloating; 5522 case Type::STK_CPointer: 5523 case Type::STK_ObjCObjectPointer: 5524 case Type::STK_BlockPointer: 5525 llvm_unreachable("valid complex int->pointer cast?"); 5526 case Type::STK_MemberPointer: 5527 llvm_unreachable("member pointer type in C"); 5528 } 5529 llvm_unreachable("Should have returned before this"); 5530 } 5531 5532 llvm_unreachable("Unhandled scalar cast"); 5533 } 5534 5535 static bool breakDownVectorType(QualType type, uint64_t &len, 5536 QualType &eltType) { 5537 // Vectors are simple. 5538 if (const VectorType *vecType = type->getAs<VectorType>()) { 5539 len = vecType->getNumElements(); 5540 eltType = vecType->getElementType(); 5541 assert(eltType->isScalarType()); 5542 return true; 5543 } 5544 5545 // We allow lax conversion to and from non-vector types, but only if 5546 // they're real types (i.e. non-complex, non-pointer scalar types). 5547 if (!type->isRealType()) return false; 5548 5549 len = 1; 5550 eltType = type; 5551 return true; 5552 } 5553 5554 /// Are the two types lax-compatible vector types? That is, given 5555 /// that one of them is a vector, do they have equal storage sizes, 5556 /// where the storage size is the number of elements times the element 5557 /// size? 5558 /// 5559 /// This will also return false if either of the types is neither a 5560 /// vector nor a real type. 5561 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5562 assert(destTy->isVectorType() || srcTy->isVectorType()); 5563 5564 uint64_t srcLen, destLen; 5565 QualType srcElt, destElt; 5566 if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false; 5567 if (!breakDownVectorType(destTy, destLen, destElt)) return false; 5568 5569 // ASTContext::getTypeSize will return the size rounded up to a 5570 // power of 2, so instead of using that, we need to use the raw 5571 // element size multiplied by the element count. 5572 uint64_t srcEltSize = Context.getTypeSize(srcElt); 5573 uint64_t destEltSize = Context.getTypeSize(destElt); 5574 5575 return (srcLen * srcEltSize == destLen * destEltSize); 5576 } 5577 5578 /// Is this a legal conversion between two types, one of which is 5579 /// known to be a vector type? 5580 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5581 assert(destTy->isVectorType() || srcTy->isVectorType()); 5582 5583 if (!Context.getLangOpts().LaxVectorConversions) 5584 return false; 5585 return areLaxCompatibleVectorTypes(srcTy, destTy); 5586 } 5587 5588 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5589 CastKind &Kind) { 5590 assert(VectorTy->isVectorType() && "Not a vector type!"); 5591 5592 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5593 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5594 return Diag(R.getBegin(), 5595 Ty->isVectorType() ? 5596 diag::err_invalid_conversion_between_vectors : 5597 diag::err_invalid_conversion_between_vector_and_integer) 5598 << VectorTy << Ty << R; 5599 } else 5600 return Diag(R.getBegin(), 5601 diag::err_invalid_conversion_between_vector_and_scalar) 5602 << VectorTy << Ty << R; 5603 5604 Kind = CK_BitCast; 5605 return false; 5606 } 5607 5608 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5609 Expr *CastExpr, CastKind &Kind) { 5610 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5611 5612 QualType SrcTy = CastExpr->getType(); 5613 5614 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5615 // an ExtVectorType. 5616 // In OpenCL, casts between vectors of different types are not allowed. 5617 // (See OpenCL 6.2). 5618 if (SrcTy->isVectorType()) { 5619 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 5620 || (getLangOpts().OpenCL && 5621 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5622 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5623 << DestTy << SrcTy << R; 5624 return ExprError(); 5625 } 5626 Kind = CK_BitCast; 5627 return CastExpr; 5628 } 5629 5630 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5631 // conversion will take place first from scalar to elt type, and then 5632 // splat from elt type to vector. 5633 if (SrcTy->isPointerType()) 5634 return Diag(R.getBegin(), 5635 diag::err_invalid_conversion_between_vector_and_scalar) 5636 << DestTy << SrcTy << R; 5637 5638 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 5639 ExprResult CastExprRes = CastExpr; 5640 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 5641 if (CastExprRes.isInvalid()) 5642 return ExprError(); 5643 CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get(); 5644 5645 Kind = CK_VectorSplat; 5646 return CastExpr; 5647 } 5648 5649 ExprResult 5650 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5651 Declarator &D, ParsedType &Ty, 5652 SourceLocation RParenLoc, Expr *CastExpr) { 5653 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5654 "ActOnCastExpr(): missing type or expr"); 5655 5656 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5657 if (D.isInvalidType()) 5658 return ExprError(); 5659 5660 if (getLangOpts().CPlusPlus) { 5661 // Check that there are no default arguments (C++ only). 5662 CheckExtraCXXDefaultArguments(D); 5663 } else { 5664 // Make sure any TypoExprs have been dealt with. 5665 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 5666 if (!Res.isUsable()) 5667 return ExprError(); 5668 CastExpr = Res.get(); 5669 } 5670 5671 checkUnusedDeclAttributes(D); 5672 5673 QualType castType = castTInfo->getType(); 5674 Ty = CreateParsedType(castType, castTInfo); 5675 5676 bool isVectorLiteral = false; 5677 5678 // Check for an altivec or OpenCL literal, 5679 // i.e. all the elements are integer constants. 5680 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5681 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5682 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 5683 && castType->isVectorType() && (PE || PLE)) { 5684 if (PLE && PLE->getNumExprs() == 0) { 5685 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5686 return ExprError(); 5687 } 5688 if (PE || PLE->getNumExprs() == 1) { 5689 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5690 if (!E->getType()->isVectorType()) 5691 isVectorLiteral = true; 5692 } 5693 else 5694 isVectorLiteral = true; 5695 } 5696 5697 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5698 // then handle it as such. 5699 if (isVectorLiteral) 5700 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5701 5702 // If the Expr being casted is a ParenListExpr, handle it specially. 5703 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5704 // sequence of BinOp comma operators. 5705 if (isa<ParenListExpr>(CastExpr)) { 5706 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5707 if (Result.isInvalid()) return ExprError(); 5708 CastExpr = Result.get(); 5709 } 5710 5711 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 5712 !getSourceManager().isInSystemMacro(LParenLoc)) 5713 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 5714 5715 CheckTollFreeBridgeCast(castType, CastExpr); 5716 5717 CheckObjCBridgeRelatedCast(castType, CastExpr); 5718 5719 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 5720 } 5721 5722 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 5723 SourceLocation RParenLoc, Expr *E, 5724 TypeSourceInfo *TInfo) { 5725 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 5726 "Expected paren or paren list expression"); 5727 5728 Expr **exprs; 5729 unsigned numExprs; 5730 Expr *subExpr; 5731 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 5732 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 5733 LiteralLParenLoc = PE->getLParenLoc(); 5734 LiteralRParenLoc = PE->getRParenLoc(); 5735 exprs = PE->getExprs(); 5736 numExprs = PE->getNumExprs(); 5737 } else { // isa<ParenExpr> by assertion at function entrance 5738 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 5739 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 5740 subExpr = cast<ParenExpr>(E)->getSubExpr(); 5741 exprs = &subExpr; 5742 numExprs = 1; 5743 } 5744 5745 QualType Ty = TInfo->getType(); 5746 assert(Ty->isVectorType() && "Expected vector type"); 5747 5748 SmallVector<Expr *, 8> initExprs; 5749 const VectorType *VTy = Ty->getAs<VectorType>(); 5750 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 5751 5752 // '(...)' form of vector initialization in AltiVec: the number of 5753 // initializers must be one or must match the size of the vector. 5754 // If a single value is specified in the initializer then it will be 5755 // replicated to all the components of the vector 5756 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 5757 // The number of initializers must be one or must match the size of the 5758 // vector. If a single value is specified in the initializer then it will 5759 // be replicated to all the components of the vector 5760 if (numExprs == 1) { 5761 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5762 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5763 if (Literal.isInvalid()) 5764 return ExprError(); 5765 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5766 PrepareScalarCast(Literal, ElemTy)); 5767 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5768 } 5769 else if (numExprs < numElems) { 5770 Diag(E->getExprLoc(), 5771 diag::err_incorrect_number_of_vector_initializers); 5772 return ExprError(); 5773 } 5774 else 5775 initExprs.append(exprs, exprs + numExprs); 5776 } 5777 else { 5778 // For OpenCL, when the number of initializers is a single value, 5779 // it will be replicated to all components of the vector. 5780 if (getLangOpts().OpenCL && 5781 VTy->getVectorKind() == VectorType::GenericVector && 5782 numExprs == 1) { 5783 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5784 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5785 if (Literal.isInvalid()) 5786 return ExprError(); 5787 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5788 PrepareScalarCast(Literal, ElemTy)); 5789 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5790 } 5791 5792 initExprs.append(exprs, exprs + numExprs); 5793 } 5794 // FIXME: This means that pretty-printing the final AST will produce curly 5795 // braces instead of the original commas. 5796 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 5797 initExprs, LiteralRParenLoc); 5798 initE->setType(Ty); 5799 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 5800 } 5801 5802 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 5803 /// the ParenListExpr into a sequence of comma binary operators. 5804 ExprResult 5805 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 5806 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 5807 if (!E) 5808 return OrigExpr; 5809 5810 ExprResult Result(E->getExpr(0)); 5811 5812 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 5813 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 5814 E->getExpr(i)); 5815 5816 if (Result.isInvalid()) return ExprError(); 5817 5818 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 5819 } 5820 5821 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 5822 SourceLocation R, 5823 MultiExprArg Val) { 5824 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 5825 return expr; 5826 } 5827 5828 /// \brief Emit a specialized diagnostic when one expression is a null pointer 5829 /// constant and the other is not a pointer. Returns true if a diagnostic is 5830 /// emitted. 5831 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 5832 SourceLocation QuestionLoc) { 5833 Expr *NullExpr = LHSExpr; 5834 Expr *NonPointerExpr = RHSExpr; 5835 Expr::NullPointerConstantKind NullKind = 5836 NullExpr->isNullPointerConstant(Context, 5837 Expr::NPC_ValueDependentIsNotNull); 5838 5839 if (NullKind == Expr::NPCK_NotNull) { 5840 NullExpr = RHSExpr; 5841 NonPointerExpr = LHSExpr; 5842 NullKind = 5843 NullExpr->isNullPointerConstant(Context, 5844 Expr::NPC_ValueDependentIsNotNull); 5845 } 5846 5847 if (NullKind == Expr::NPCK_NotNull) 5848 return false; 5849 5850 if (NullKind == Expr::NPCK_ZeroExpression) 5851 return false; 5852 5853 if (NullKind == Expr::NPCK_ZeroLiteral) { 5854 // In this case, check to make sure that we got here from a "NULL" 5855 // string in the source code. 5856 NullExpr = NullExpr->IgnoreParenImpCasts(); 5857 SourceLocation loc = NullExpr->getExprLoc(); 5858 if (!findMacroSpelling(loc, "NULL")) 5859 return false; 5860 } 5861 5862 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 5863 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 5864 << NonPointerExpr->getType() << DiagType 5865 << NonPointerExpr->getSourceRange(); 5866 return true; 5867 } 5868 5869 /// \brief Return false if the condition expression is valid, true otherwise. 5870 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 5871 QualType CondTy = Cond->getType(); 5872 5873 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 5874 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 5875 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 5876 << CondTy << Cond->getSourceRange(); 5877 return true; 5878 } 5879 5880 // C99 6.5.15p2 5881 if (CondTy->isScalarType()) return false; 5882 5883 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 5884 << CondTy << Cond->getSourceRange(); 5885 return true; 5886 } 5887 5888 /// \brief Handle when one or both operands are void type. 5889 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 5890 ExprResult &RHS) { 5891 Expr *LHSExpr = LHS.get(); 5892 Expr *RHSExpr = RHS.get(); 5893 5894 if (!LHSExpr->getType()->isVoidType()) 5895 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5896 << RHSExpr->getSourceRange(); 5897 if (!RHSExpr->getType()->isVoidType()) 5898 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5899 << LHSExpr->getSourceRange(); 5900 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 5901 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 5902 return S.Context.VoidTy; 5903 } 5904 5905 /// \brief Return false if the NullExpr can be promoted to PointerTy, 5906 /// true otherwise. 5907 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 5908 QualType PointerTy) { 5909 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 5910 !NullExpr.get()->isNullPointerConstant(S.Context, 5911 Expr::NPC_ValueDependentIsNull)) 5912 return true; 5913 5914 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 5915 return false; 5916 } 5917 5918 /// \brief Checks compatibility between two pointers and return the resulting 5919 /// type. 5920 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 5921 ExprResult &RHS, 5922 SourceLocation Loc) { 5923 QualType LHSTy = LHS.get()->getType(); 5924 QualType RHSTy = RHS.get()->getType(); 5925 5926 if (S.Context.hasSameType(LHSTy, RHSTy)) { 5927 // Two identical pointers types are always compatible. 5928 return LHSTy; 5929 } 5930 5931 QualType lhptee, rhptee; 5932 5933 // Get the pointee types. 5934 bool IsBlockPointer = false; 5935 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 5936 lhptee = LHSBTy->getPointeeType(); 5937 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 5938 IsBlockPointer = true; 5939 } else { 5940 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 5941 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 5942 } 5943 5944 // C99 6.5.15p6: If both operands are pointers to compatible types or to 5945 // differently qualified versions of compatible types, the result type is 5946 // a pointer to an appropriately qualified version of the composite 5947 // type. 5948 5949 // Only CVR-qualifiers exist in the standard, and the differently-qualified 5950 // clause doesn't make sense for our extensions. E.g. address space 2 should 5951 // be incompatible with address space 3: they may live on different devices or 5952 // anything. 5953 Qualifiers lhQual = lhptee.getQualifiers(); 5954 Qualifiers rhQual = rhptee.getQualifiers(); 5955 5956 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 5957 lhQual.removeCVRQualifiers(); 5958 rhQual.removeCVRQualifiers(); 5959 5960 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 5961 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 5962 5963 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 5964 5965 if (CompositeTy.isNull()) { 5966 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 5967 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5968 << RHS.get()->getSourceRange(); 5969 // In this situation, we assume void* type. No especially good 5970 // reason, but this is what gcc does, and we do have to pick 5971 // to get a consistent AST. 5972 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 5973 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 5974 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 5975 return incompatTy; 5976 } 5977 5978 // The pointer types are compatible. 5979 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 5980 if (IsBlockPointer) 5981 ResultTy = S.Context.getBlockPointerType(ResultTy); 5982 else 5983 ResultTy = S.Context.getPointerType(ResultTy); 5984 5985 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast); 5986 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast); 5987 return ResultTy; 5988 } 5989 5990 /// \brief Return the resulting type when the operands are both block pointers. 5991 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 5992 ExprResult &LHS, 5993 ExprResult &RHS, 5994 SourceLocation Loc) { 5995 QualType LHSTy = LHS.get()->getType(); 5996 QualType RHSTy = RHS.get()->getType(); 5997 5998 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 5999 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6000 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6001 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6002 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6003 return destType; 6004 } 6005 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6006 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6007 << RHS.get()->getSourceRange(); 6008 return QualType(); 6009 } 6010 6011 // We have 2 block pointer types. 6012 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6013 } 6014 6015 /// \brief Return the resulting type when the operands are both pointers. 6016 static QualType 6017 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6018 ExprResult &RHS, 6019 SourceLocation Loc) { 6020 // get the pointer types 6021 QualType LHSTy = LHS.get()->getType(); 6022 QualType RHSTy = RHS.get()->getType(); 6023 6024 // get the "pointed to" types 6025 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6026 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6027 6028 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6029 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6030 // Figure out necessary qualifiers (C99 6.5.15p6) 6031 QualType destPointee 6032 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6033 QualType destType = S.Context.getPointerType(destPointee); 6034 // Add qualifiers if necessary. 6035 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6036 // Promote to void*. 6037 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6038 return destType; 6039 } 6040 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6041 QualType destPointee 6042 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6043 QualType destType = S.Context.getPointerType(destPointee); 6044 // Add qualifiers if necessary. 6045 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6046 // Promote to void*. 6047 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6048 return destType; 6049 } 6050 6051 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6052 } 6053 6054 /// \brief Return false if the first expression is not an integer and the second 6055 /// expression is not a pointer, true otherwise. 6056 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6057 Expr* PointerExpr, SourceLocation Loc, 6058 bool IsIntFirstExpr) { 6059 if (!PointerExpr->getType()->isPointerType() || 6060 !Int.get()->getType()->isIntegerType()) 6061 return false; 6062 6063 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6064 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6065 6066 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6067 << Expr1->getType() << Expr2->getType() 6068 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6069 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6070 CK_IntegralToPointer); 6071 return true; 6072 } 6073 6074 /// \brief Simple conversion between integer and floating point types. 6075 /// 6076 /// Used when handling the OpenCL conditional operator where the 6077 /// condition is a vector while the other operands are scalar. 6078 /// 6079 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6080 /// types are either integer or floating type. Between the two 6081 /// operands, the type with the higher rank is defined as the "result 6082 /// type". The other operand needs to be promoted to the same type. No 6083 /// other type promotion is allowed. We cannot use 6084 /// UsualArithmeticConversions() for this purpose, since it always 6085 /// promotes promotable types. 6086 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6087 ExprResult &RHS, 6088 SourceLocation QuestionLoc) { 6089 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6090 if (LHS.isInvalid()) 6091 return QualType(); 6092 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6093 if (RHS.isInvalid()) 6094 return QualType(); 6095 6096 // For conversion purposes, we ignore any qualifiers. 6097 // For example, "const float" and "float" are equivalent. 6098 QualType LHSType = 6099 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6100 QualType RHSType = 6101 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6102 6103 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6104 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6105 << LHSType << LHS.get()->getSourceRange(); 6106 return QualType(); 6107 } 6108 6109 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6110 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6111 << RHSType << RHS.get()->getSourceRange(); 6112 return QualType(); 6113 } 6114 6115 // If both types are identical, no conversion is needed. 6116 if (LHSType == RHSType) 6117 return LHSType; 6118 6119 // Now handle "real" floating types (i.e. float, double, long double). 6120 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6121 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6122 /*IsCompAssign = */ false); 6123 6124 // Finally, we have two differing integer types. 6125 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6126 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6127 } 6128 6129 /// \brief Convert scalar operands to a vector that matches the 6130 /// condition in length. 6131 /// 6132 /// Used when handling the OpenCL conditional operator where the 6133 /// condition is a vector while the other operands are scalar. 6134 /// 6135 /// We first compute the "result type" for the scalar operands 6136 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6137 /// into a vector of that type where the length matches the condition 6138 /// vector type. s6.11.6 requires that the element types of the result 6139 /// and the condition must have the same number of bits. 6140 static QualType 6141 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6142 QualType CondTy, SourceLocation QuestionLoc) { 6143 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6144 if (ResTy.isNull()) return QualType(); 6145 6146 const VectorType *CV = CondTy->getAs<VectorType>(); 6147 assert(CV); 6148 6149 // Determine the vector result type 6150 unsigned NumElements = CV->getNumElements(); 6151 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6152 6153 // Ensure that all types have the same number of bits 6154 if (S.Context.getTypeSize(CV->getElementType()) 6155 != S.Context.getTypeSize(ResTy)) { 6156 // Since VectorTy is created internally, it does not pretty print 6157 // with an OpenCL name. Instead, we just print a description. 6158 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6159 SmallString<64> Str; 6160 llvm::raw_svector_ostream OS(Str); 6161 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6162 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6163 << CondTy << OS.str(); 6164 return QualType(); 6165 } 6166 6167 // Convert operands to the vector result type 6168 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6169 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6170 6171 return VectorTy; 6172 } 6173 6174 /// \brief Return false if this is a valid OpenCL condition vector 6175 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6176 SourceLocation QuestionLoc) { 6177 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6178 // integral type. 6179 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6180 assert(CondTy); 6181 QualType EleTy = CondTy->getElementType(); 6182 if (EleTy->isIntegerType()) return false; 6183 6184 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6185 << Cond->getType() << Cond->getSourceRange(); 6186 return true; 6187 } 6188 6189 /// \brief Return false if the vector condition type and the vector 6190 /// result type are compatible. 6191 /// 6192 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6193 /// number of elements, and their element types have the same number 6194 /// of bits. 6195 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6196 SourceLocation QuestionLoc) { 6197 const VectorType *CV = CondTy->getAs<VectorType>(); 6198 const VectorType *RV = VecResTy->getAs<VectorType>(); 6199 assert(CV && RV); 6200 6201 if (CV->getNumElements() != RV->getNumElements()) { 6202 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6203 << CondTy << VecResTy; 6204 return true; 6205 } 6206 6207 QualType CVE = CV->getElementType(); 6208 QualType RVE = RV->getElementType(); 6209 6210 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6211 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6212 << CondTy << VecResTy; 6213 return true; 6214 } 6215 6216 return false; 6217 } 6218 6219 /// \brief Return the resulting type for the conditional operator in 6220 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6221 /// s6.3.i) when the condition is a vector type. 6222 static QualType 6223 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6224 ExprResult &LHS, ExprResult &RHS, 6225 SourceLocation QuestionLoc) { 6226 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6227 if (Cond.isInvalid()) 6228 return QualType(); 6229 QualType CondTy = Cond.get()->getType(); 6230 6231 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6232 return QualType(); 6233 6234 // If either operand is a vector then find the vector type of the 6235 // result as specified in OpenCL v1.1 s6.3.i. 6236 if (LHS.get()->getType()->isVectorType() || 6237 RHS.get()->getType()->isVectorType()) { 6238 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6239 /*isCompAssign*/false, 6240 /*AllowBothBool*/true, 6241 /*AllowBoolConversions*/false); 6242 if (VecResTy.isNull()) return QualType(); 6243 // The result type must match the condition type as specified in 6244 // OpenCL v1.1 s6.11.6. 6245 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6246 return QualType(); 6247 return VecResTy; 6248 } 6249 6250 // Both operands are scalar. 6251 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6252 } 6253 6254 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6255 /// In that case, LHS = cond. 6256 /// C99 6.5.15 6257 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6258 ExprResult &RHS, ExprValueKind &VK, 6259 ExprObjectKind &OK, 6260 SourceLocation QuestionLoc) { 6261 6262 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6263 if (!LHSResult.isUsable()) return QualType(); 6264 LHS = LHSResult; 6265 6266 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6267 if (!RHSResult.isUsable()) return QualType(); 6268 RHS = RHSResult; 6269 6270 // C++ is sufficiently different to merit its own checker. 6271 if (getLangOpts().CPlusPlus) 6272 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6273 6274 VK = VK_RValue; 6275 OK = OK_Ordinary; 6276 6277 // The OpenCL operator with a vector condition is sufficiently 6278 // different to merit its own checker. 6279 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6280 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6281 6282 // First, check the condition. 6283 Cond = UsualUnaryConversions(Cond.get()); 6284 if (Cond.isInvalid()) 6285 return QualType(); 6286 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6287 return QualType(); 6288 6289 // Now check the two expressions. 6290 if (LHS.get()->getType()->isVectorType() || 6291 RHS.get()->getType()->isVectorType()) 6292 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6293 /*AllowBothBool*/true, 6294 /*AllowBoolConversions*/false); 6295 6296 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6297 if (LHS.isInvalid() || RHS.isInvalid()) 6298 return QualType(); 6299 6300 QualType LHSTy = LHS.get()->getType(); 6301 QualType RHSTy = RHS.get()->getType(); 6302 6303 // If both operands have arithmetic type, do the usual arithmetic conversions 6304 // to find a common type: C99 6.5.15p3,5. 6305 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6306 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6307 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6308 6309 return ResTy; 6310 } 6311 6312 // If both operands are the same structure or union type, the result is that 6313 // type. 6314 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6315 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6316 if (LHSRT->getDecl() == RHSRT->getDecl()) 6317 // "If both the operands have structure or union type, the result has 6318 // that type." This implies that CV qualifiers are dropped. 6319 return LHSTy.getUnqualifiedType(); 6320 // FIXME: Type of conditional expression must be complete in C mode. 6321 } 6322 6323 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6324 // The following || allows only one side to be void (a GCC-ism). 6325 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6326 return checkConditionalVoidType(*this, LHS, RHS); 6327 } 6328 6329 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6330 // the type of the other operand." 6331 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6332 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6333 6334 // All objective-c pointer type analysis is done here. 6335 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6336 QuestionLoc); 6337 if (LHS.isInvalid() || RHS.isInvalid()) 6338 return QualType(); 6339 if (!compositeType.isNull()) 6340 return compositeType; 6341 6342 6343 // Handle block pointer types. 6344 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6345 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6346 QuestionLoc); 6347 6348 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6349 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6350 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6351 QuestionLoc); 6352 6353 // GCC compatibility: soften pointer/integer mismatch. Note that 6354 // null pointers have been filtered out by this point. 6355 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6356 /*isIntFirstExpr=*/true)) 6357 return RHSTy; 6358 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6359 /*isIntFirstExpr=*/false)) 6360 return LHSTy; 6361 6362 // Emit a better diagnostic if one of the expressions is a null pointer 6363 // constant and the other is not a pointer type. In this case, the user most 6364 // likely forgot to take the address of the other expression. 6365 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6366 return QualType(); 6367 6368 // Otherwise, the operands are not compatible. 6369 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6370 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6371 << RHS.get()->getSourceRange(); 6372 return QualType(); 6373 } 6374 6375 /// FindCompositeObjCPointerType - Helper method to find composite type of 6376 /// two objective-c pointer types of the two input expressions. 6377 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6378 SourceLocation QuestionLoc) { 6379 QualType LHSTy = LHS.get()->getType(); 6380 QualType RHSTy = RHS.get()->getType(); 6381 6382 // Handle things like Class and struct objc_class*. Here we case the result 6383 // to the pseudo-builtin, because that will be implicitly cast back to the 6384 // redefinition type if an attempt is made to access its fields. 6385 if (LHSTy->isObjCClassType() && 6386 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6387 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6388 return LHSTy; 6389 } 6390 if (RHSTy->isObjCClassType() && 6391 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6392 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6393 return RHSTy; 6394 } 6395 // And the same for struct objc_object* / id 6396 if (LHSTy->isObjCIdType() && 6397 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6398 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6399 return LHSTy; 6400 } 6401 if (RHSTy->isObjCIdType() && 6402 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6403 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6404 return RHSTy; 6405 } 6406 // And the same for struct objc_selector* / SEL 6407 if (Context.isObjCSelType(LHSTy) && 6408 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6409 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6410 return LHSTy; 6411 } 6412 if (Context.isObjCSelType(RHSTy) && 6413 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6414 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6415 return RHSTy; 6416 } 6417 // Check constraints for Objective-C object pointers types. 6418 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6419 6420 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6421 // Two identical object pointer types are always compatible. 6422 return LHSTy; 6423 } 6424 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6425 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6426 QualType compositeType = LHSTy; 6427 6428 // If both operands are interfaces and either operand can be 6429 // assigned to the other, use that type as the composite 6430 // type. This allows 6431 // xxx ? (A*) a : (B*) b 6432 // where B is a subclass of A. 6433 // 6434 // Additionally, as for assignment, if either type is 'id' 6435 // allow silent coercion. Finally, if the types are 6436 // incompatible then make sure to use 'id' as the composite 6437 // type so the result is acceptable for sending messages to. 6438 6439 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6440 // It could return the composite type. 6441 if (!(compositeType = 6442 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6443 // Nothing more to do. 6444 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6445 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6446 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6447 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6448 } else if ((LHSTy->isObjCQualifiedIdType() || 6449 RHSTy->isObjCQualifiedIdType()) && 6450 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6451 // Need to handle "id<xx>" explicitly. 6452 // GCC allows qualified id and any Objective-C type to devolve to 6453 // id. Currently localizing to here until clear this should be 6454 // part of ObjCQualifiedIdTypesAreCompatible. 6455 compositeType = Context.getObjCIdType(); 6456 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6457 compositeType = Context.getObjCIdType(); 6458 } else { 6459 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6460 << LHSTy << RHSTy 6461 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6462 QualType incompatTy = Context.getObjCIdType(); 6463 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6464 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6465 return incompatTy; 6466 } 6467 // The object pointer types are compatible. 6468 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6469 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6470 return compositeType; 6471 } 6472 // Check Objective-C object pointer types and 'void *' 6473 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6474 if (getLangOpts().ObjCAutoRefCount) { 6475 // ARC forbids the implicit conversion of object pointers to 'void *', 6476 // so these types are not compatible. 6477 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6478 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6479 LHS = RHS = true; 6480 return QualType(); 6481 } 6482 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6483 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6484 QualType destPointee 6485 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6486 QualType destType = Context.getPointerType(destPointee); 6487 // Add qualifiers if necessary. 6488 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6489 // Promote to void*. 6490 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6491 return destType; 6492 } 6493 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6494 if (getLangOpts().ObjCAutoRefCount) { 6495 // ARC forbids the implicit conversion of object pointers to 'void *', 6496 // so these types are not compatible. 6497 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6498 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6499 LHS = RHS = true; 6500 return QualType(); 6501 } 6502 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6503 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6504 QualType destPointee 6505 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6506 QualType destType = Context.getPointerType(destPointee); 6507 // Add qualifiers if necessary. 6508 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6509 // Promote to void*. 6510 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6511 return destType; 6512 } 6513 return QualType(); 6514 } 6515 6516 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6517 /// ParenRange in parentheses. 6518 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6519 const PartialDiagnostic &Note, 6520 SourceRange ParenRange) { 6521 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd()); 6522 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6523 EndLoc.isValid()) { 6524 Self.Diag(Loc, Note) 6525 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6526 << FixItHint::CreateInsertion(EndLoc, ")"); 6527 } else { 6528 // We can't display the parentheses, so just show the bare note. 6529 Self.Diag(Loc, Note) << ParenRange; 6530 } 6531 } 6532 6533 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6534 return Opc >= BO_Mul && Opc <= BO_Shr; 6535 } 6536 6537 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6538 /// expression, either using a built-in or overloaded operator, 6539 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6540 /// expression. 6541 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6542 Expr **RHSExprs) { 6543 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6544 E = E->IgnoreImpCasts(); 6545 E = E->IgnoreConversionOperator(); 6546 E = E->IgnoreImpCasts(); 6547 6548 // Built-in binary operator. 6549 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 6550 if (IsArithmeticOp(OP->getOpcode())) { 6551 *Opcode = OP->getOpcode(); 6552 *RHSExprs = OP->getRHS(); 6553 return true; 6554 } 6555 } 6556 6557 // Overloaded operator. 6558 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 6559 if (Call->getNumArgs() != 2) 6560 return false; 6561 6562 // Make sure this is really a binary operator that is safe to pass into 6563 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 6564 OverloadedOperatorKind OO = Call->getOperator(); 6565 if (OO < OO_Plus || OO > OO_Arrow || 6566 OO == OO_PlusPlus || OO == OO_MinusMinus) 6567 return false; 6568 6569 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 6570 if (IsArithmeticOp(OpKind)) { 6571 *Opcode = OpKind; 6572 *RHSExprs = Call->getArg(1); 6573 return true; 6574 } 6575 } 6576 6577 return false; 6578 } 6579 6580 static bool IsLogicOp(BinaryOperatorKind Opc) { 6581 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr); 6582 } 6583 6584 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 6585 /// or is a logical expression such as (x==y) which has int type, but is 6586 /// commonly interpreted as boolean. 6587 static bool ExprLooksBoolean(Expr *E) { 6588 E = E->IgnoreParenImpCasts(); 6589 6590 if (E->getType()->isBooleanType()) 6591 return true; 6592 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 6593 return IsLogicOp(OP->getOpcode()); 6594 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 6595 return OP->getOpcode() == UO_LNot; 6596 if (E->getType()->isPointerType()) 6597 return true; 6598 6599 return false; 6600 } 6601 6602 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 6603 /// and binary operator are mixed in a way that suggests the programmer assumed 6604 /// the conditional operator has higher precedence, for example: 6605 /// "int x = a + someBinaryCondition ? 1 : 2". 6606 static void DiagnoseConditionalPrecedence(Sema &Self, 6607 SourceLocation OpLoc, 6608 Expr *Condition, 6609 Expr *LHSExpr, 6610 Expr *RHSExpr) { 6611 BinaryOperatorKind CondOpcode; 6612 Expr *CondRHS; 6613 6614 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 6615 return; 6616 if (!ExprLooksBoolean(CondRHS)) 6617 return; 6618 6619 // The condition is an arithmetic binary expression, with a right- 6620 // hand side that looks boolean, so warn. 6621 6622 Self.Diag(OpLoc, diag::warn_precedence_conditional) 6623 << Condition->getSourceRange() 6624 << BinaryOperator::getOpcodeStr(CondOpcode); 6625 6626 SuggestParentheses(Self, OpLoc, 6627 Self.PDiag(diag::note_precedence_silence) 6628 << BinaryOperator::getOpcodeStr(CondOpcode), 6629 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 6630 6631 SuggestParentheses(Self, OpLoc, 6632 Self.PDiag(diag::note_precedence_conditional_first), 6633 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 6634 } 6635 6636 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 6637 /// in the case of a the GNU conditional expr extension. 6638 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 6639 SourceLocation ColonLoc, 6640 Expr *CondExpr, Expr *LHSExpr, 6641 Expr *RHSExpr) { 6642 if (!getLangOpts().CPlusPlus) { 6643 // C cannot handle TypoExpr nodes in the condition because it 6644 // doesn't handle dependent types properly, so make sure any TypoExprs have 6645 // been dealt with before checking the operands. 6646 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 6647 if (!CondResult.isUsable()) return ExprError(); 6648 CondExpr = CondResult.get(); 6649 } 6650 6651 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 6652 // was the condition. 6653 OpaqueValueExpr *opaqueValue = nullptr; 6654 Expr *commonExpr = nullptr; 6655 if (!LHSExpr) { 6656 commonExpr = CondExpr; 6657 // Lower out placeholder types first. This is important so that we don't 6658 // try to capture a placeholder. This happens in few cases in C++; such 6659 // as Objective-C++'s dictionary subscripting syntax. 6660 if (commonExpr->hasPlaceholderType()) { 6661 ExprResult result = CheckPlaceholderExpr(commonExpr); 6662 if (!result.isUsable()) return ExprError(); 6663 commonExpr = result.get(); 6664 } 6665 // We usually want to apply unary conversions *before* saving, except 6666 // in the special case of a C++ l-value conditional. 6667 if (!(getLangOpts().CPlusPlus 6668 && !commonExpr->isTypeDependent() 6669 && commonExpr->getValueKind() == RHSExpr->getValueKind() 6670 && commonExpr->isGLValue() 6671 && commonExpr->isOrdinaryOrBitFieldObject() 6672 && RHSExpr->isOrdinaryOrBitFieldObject() 6673 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 6674 ExprResult commonRes = UsualUnaryConversions(commonExpr); 6675 if (commonRes.isInvalid()) 6676 return ExprError(); 6677 commonExpr = commonRes.get(); 6678 } 6679 6680 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 6681 commonExpr->getType(), 6682 commonExpr->getValueKind(), 6683 commonExpr->getObjectKind(), 6684 commonExpr); 6685 LHSExpr = CondExpr = opaqueValue; 6686 } 6687 6688 ExprValueKind VK = VK_RValue; 6689 ExprObjectKind OK = OK_Ordinary; 6690 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 6691 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 6692 VK, OK, QuestionLoc); 6693 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 6694 RHS.isInvalid()) 6695 return ExprError(); 6696 6697 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 6698 RHS.get()); 6699 6700 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 6701 6702 if (!commonExpr) 6703 return new (Context) 6704 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 6705 RHS.get(), result, VK, OK); 6706 6707 return new (Context) BinaryConditionalOperator( 6708 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 6709 ColonLoc, result, VK, OK); 6710 } 6711 6712 // checkPointerTypesForAssignment - This is a very tricky routine (despite 6713 // being closely modeled after the C99 spec:-). The odd characteristic of this 6714 // routine is it effectively iqnores the qualifiers on the top level pointee. 6715 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 6716 // FIXME: add a couple examples in this comment. 6717 static Sema::AssignConvertType 6718 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 6719 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6720 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6721 6722 // get the "pointed to" type (ignoring qualifiers at the top level) 6723 const Type *lhptee, *rhptee; 6724 Qualifiers lhq, rhq; 6725 std::tie(lhptee, lhq) = 6726 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 6727 std::tie(rhptee, rhq) = 6728 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 6729 6730 Sema::AssignConvertType ConvTy = Sema::Compatible; 6731 6732 // C99 6.5.16.1p1: This following citation is common to constraints 6733 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 6734 // qualifiers of the type *pointed to* by the right; 6735 6736 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 6737 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 6738 lhq.compatiblyIncludesObjCLifetime(rhq)) { 6739 // Ignore lifetime for further calculation. 6740 lhq.removeObjCLifetime(); 6741 rhq.removeObjCLifetime(); 6742 } 6743 6744 if (!lhq.compatiblyIncludes(rhq)) { 6745 // Treat address-space mismatches as fatal. TODO: address subspaces 6746 if (!lhq.isAddressSpaceSupersetOf(rhq)) 6747 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6748 6749 // It's okay to add or remove GC or lifetime qualifiers when converting to 6750 // and from void*. 6751 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 6752 .compatiblyIncludes( 6753 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 6754 && (lhptee->isVoidType() || rhptee->isVoidType())) 6755 ; // keep old 6756 6757 // Treat lifetime mismatches as fatal. 6758 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 6759 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6760 6761 // For GCC compatibility, other qualifier mismatches are treated 6762 // as still compatible in C. 6763 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6764 } 6765 6766 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 6767 // incomplete type and the other is a pointer to a qualified or unqualified 6768 // version of void... 6769 if (lhptee->isVoidType()) { 6770 if (rhptee->isIncompleteOrObjectType()) 6771 return ConvTy; 6772 6773 // As an extension, we allow cast to/from void* to function pointer. 6774 assert(rhptee->isFunctionType()); 6775 return Sema::FunctionVoidPointer; 6776 } 6777 6778 if (rhptee->isVoidType()) { 6779 if (lhptee->isIncompleteOrObjectType()) 6780 return ConvTy; 6781 6782 // As an extension, we allow cast to/from void* to function pointer. 6783 assert(lhptee->isFunctionType()); 6784 return Sema::FunctionVoidPointer; 6785 } 6786 6787 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 6788 // unqualified versions of compatible types, ... 6789 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 6790 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 6791 // Check if the pointee types are compatible ignoring the sign. 6792 // We explicitly check for char so that we catch "char" vs 6793 // "unsigned char" on systems where "char" is unsigned. 6794 if (lhptee->isCharType()) 6795 ltrans = S.Context.UnsignedCharTy; 6796 else if (lhptee->hasSignedIntegerRepresentation()) 6797 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 6798 6799 if (rhptee->isCharType()) 6800 rtrans = S.Context.UnsignedCharTy; 6801 else if (rhptee->hasSignedIntegerRepresentation()) 6802 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 6803 6804 if (ltrans == rtrans) { 6805 // Types are compatible ignoring the sign. Qualifier incompatibility 6806 // takes priority over sign incompatibility because the sign 6807 // warning can be disabled. 6808 if (ConvTy != Sema::Compatible) 6809 return ConvTy; 6810 6811 return Sema::IncompatiblePointerSign; 6812 } 6813 6814 // If we are a multi-level pointer, it's possible that our issue is simply 6815 // one of qualification - e.g. char ** -> const char ** is not allowed. If 6816 // the eventual target type is the same and the pointers have the same 6817 // level of indirection, this must be the issue. 6818 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 6819 do { 6820 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 6821 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 6822 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 6823 6824 if (lhptee == rhptee) 6825 return Sema::IncompatibleNestedPointerQualifiers; 6826 } 6827 6828 // General pointer incompatibility takes priority over qualifiers. 6829 return Sema::IncompatiblePointer; 6830 } 6831 if (!S.getLangOpts().CPlusPlus && 6832 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 6833 return Sema::IncompatiblePointer; 6834 return ConvTy; 6835 } 6836 6837 /// checkBlockPointerTypesForAssignment - This routine determines whether two 6838 /// block pointer types are compatible or whether a block and normal pointer 6839 /// are compatible. It is more restrict than comparing two function pointer 6840 // types. 6841 static Sema::AssignConvertType 6842 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 6843 QualType RHSType) { 6844 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6845 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6846 6847 QualType lhptee, rhptee; 6848 6849 // get the "pointed to" type (ignoring qualifiers at the top level) 6850 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 6851 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 6852 6853 // In C++, the types have to match exactly. 6854 if (S.getLangOpts().CPlusPlus) 6855 return Sema::IncompatibleBlockPointer; 6856 6857 Sema::AssignConvertType ConvTy = Sema::Compatible; 6858 6859 // For blocks we enforce that qualifiers are identical. 6860 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 6861 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6862 6863 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 6864 return Sema::IncompatibleBlockPointer; 6865 6866 return ConvTy; 6867 } 6868 6869 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 6870 /// for assignment compatibility. 6871 static Sema::AssignConvertType 6872 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 6873 QualType RHSType) { 6874 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 6875 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 6876 6877 if (LHSType->isObjCBuiltinType()) { 6878 // Class is not compatible with ObjC object pointers. 6879 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 6880 !RHSType->isObjCQualifiedClassType()) 6881 return Sema::IncompatiblePointer; 6882 return Sema::Compatible; 6883 } 6884 if (RHSType->isObjCBuiltinType()) { 6885 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 6886 !LHSType->isObjCQualifiedClassType()) 6887 return Sema::IncompatiblePointer; 6888 return Sema::Compatible; 6889 } 6890 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6891 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6892 6893 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 6894 // make an exception for id<P> 6895 !LHSType->isObjCQualifiedIdType()) 6896 return Sema::CompatiblePointerDiscardsQualifiers; 6897 6898 if (S.Context.typesAreCompatible(LHSType, RHSType)) 6899 return Sema::Compatible; 6900 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 6901 return Sema::IncompatibleObjCQualifiedId; 6902 return Sema::IncompatiblePointer; 6903 } 6904 6905 Sema::AssignConvertType 6906 Sema::CheckAssignmentConstraints(SourceLocation Loc, 6907 QualType LHSType, QualType RHSType) { 6908 // Fake up an opaque expression. We don't actually care about what 6909 // cast operations are required, so if CheckAssignmentConstraints 6910 // adds casts to this they'll be wasted, but fortunately that doesn't 6911 // usually happen on valid code. 6912 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 6913 ExprResult RHSPtr = &RHSExpr; 6914 CastKind K = CK_Invalid; 6915 6916 return CheckAssignmentConstraints(LHSType, RHSPtr, K); 6917 } 6918 6919 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 6920 /// has code to accommodate several GCC extensions when type checking 6921 /// pointers. Here are some objectionable examples that GCC considers warnings: 6922 /// 6923 /// int a, *pint; 6924 /// short *pshort; 6925 /// struct foo *pfoo; 6926 /// 6927 /// pint = pshort; // warning: assignment from incompatible pointer type 6928 /// a = pint; // warning: assignment makes integer from pointer without a cast 6929 /// pint = a; // warning: assignment makes pointer from integer without a cast 6930 /// pint = pfoo; // warning: assignment from incompatible pointer type 6931 /// 6932 /// As a result, the code for dealing with pointers is more complex than the 6933 /// C99 spec dictates. 6934 /// 6935 /// Sets 'Kind' for any result kind except Incompatible. 6936 Sema::AssignConvertType 6937 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6938 CastKind &Kind) { 6939 QualType RHSType = RHS.get()->getType(); 6940 QualType OrigLHSType = LHSType; 6941 6942 // Get canonical types. We're not formatting these types, just comparing 6943 // them. 6944 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 6945 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 6946 6947 // Common case: no conversion required. 6948 if (LHSType == RHSType) { 6949 Kind = CK_NoOp; 6950 return Compatible; 6951 } 6952 6953 // If we have an atomic type, try a non-atomic assignment, then just add an 6954 // atomic qualification step. 6955 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 6956 Sema::AssignConvertType result = 6957 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 6958 if (result != Compatible) 6959 return result; 6960 if (Kind != CK_NoOp) 6961 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 6962 Kind = CK_NonAtomicToAtomic; 6963 return Compatible; 6964 } 6965 6966 // If the left-hand side is a reference type, then we are in a 6967 // (rare!) case where we've allowed the use of references in C, 6968 // e.g., as a parameter type in a built-in function. In this case, 6969 // just make sure that the type referenced is compatible with the 6970 // right-hand side type. The caller is responsible for adjusting 6971 // LHSType so that the resulting expression does not have reference 6972 // type. 6973 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 6974 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 6975 Kind = CK_LValueBitCast; 6976 return Compatible; 6977 } 6978 return Incompatible; 6979 } 6980 6981 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 6982 // to the same ExtVector type. 6983 if (LHSType->isExtVectorType()) { 6984 if (RHSType->isExtVectorType()) 6985 return Incompatible; 6986 if (RHSType->isArithmeticType()) { 6987 // CK_VectorSplat does T -> vector T, so first cast to the 6988 // element type. 6989 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 6990 if (elType != RHSType) { 6991 Kind = PrepareScalarCast(RHS, elType); 6992 RHS = ImpCastExprToType(RHS.get(), elType, Kind); 6993 } 6994 Kind = CK_VectorSplat; 6995 return Compatible; 6996 } 6997 } 6998 6999 // Conversions to or from vector type. 7000 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7001 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7002 // Allow assignments of an AltiVec vector type to an equivalent GCC 7003 // vector type and vice versa 7004 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7005 Kind = CK_BitCast; 7006 return Compatible; 7007 } 7008 7009 // If we are allowing lax vector conversions, and LHS and RHS are both 7010 // vectors, the total size only needs to be the same. This is a bitcast; 7011 // no bits are changed but the result type is different. 7012 if (isLaxVectorConversion(RHSType, LHSType)) { 7013 Kind = CK_BitCast; 7014 return IncompatibleVectors; 7015 } 7016 } 7017 return Incompatible; 7018 } 7019 7020 // Arithmetic conversions. 7021 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7022 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7023 Kind = PrepareScalarCast(RHS, LHSType); 7024 return Compatible; 7025 } 7026 7027 // Conversions to normal pointers. 7028 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7029 // U* -> T* 7030 if (isa<PointerType>(RHSType)) { 7031 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7032 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7033 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7034 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7035 } 7036 7037 // int -> T* 7038 if (RHSType->isIntegerType()) { 7039 Kind = CK_IntegralToPointer; // FIXME: null? 7040 return IntToPointer; 7041 } 7042 7043 // C pointers are not compatible with ObjC object pointers, 7044 // with two exceptions: 7045 if (isa<ObjCObjectPointerType>(RHSType)) { 7046 // - conversions to void* 7047 if (LHSPointer->getPointeeType()->isVoidType()) { 7048 Kind = CK_BitCast; 7049 return Compatible; 7050 } 7051 7052 // - conversions from 'Class' to the redefinition type 7053 if (RHSType->isObjCClassType() && 7054 Context.hasSameType(LHSType, 7055 Context.getObjCClassRedefinitionType())) { 7056 Kind = CK_BitCast; 7057 return Compatible; 7058 } 7059 7060 Kind = CK_BitCast; 7061 return IncompatiblePointer; 7062 } 7063 7064 // U^ -> void* 7065 if (RHSType->getAs<BlockPointerType>()) { 7066 if (LHSPointer->getPointeeType()->isVoidType()) { 7067 Kind = CK_BitCast; 7068 return Compatible; 7069 } 7070 } 7071 7072 return Incompatible; 7073 } 7074 7075 // Conversions to block pointers. 7076 if (isa<BlockPointerType>(LHSType)) { 7077 // U^ -> T^ 7078 if (RHSType->isBlockPointerType()) { 7079 Kind = CK_BitCast; 7080 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7081 } 7082 7083 // int or null -> T^ 7084 if (RHSType->isIntegerType()) { 7085 Kind = CK_IntegralToPointer; // FIXME: null 7086 return IntToBlockPointer; 7087 } 7088 7089 // id -> T^ 7090 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7091 Kind = CK_AnyPointerToBlockPointerCast; 7092 return Compatible; 7093 } 7094 7095 // void* -> T^ 7096 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7097 if (RHSPT->getPointeeType()->isVoidType()) { 7098 Kind = CK_AnyPointerToBlockPointerCast; 7099 return Compatible; 7100 } 7101 7102 return Incompatible; 7103 } 7104 7105 // Conversions to Objective-C pointers. 7106 if (isa<ObjCObjectPointerType>(LHSType)) { 7107 // A* -> B* 7108 if (RHSType->isObjCObjectPointerType()) { 7109 Kind = CK_BitCast; 7110 Sema::AssignConvertType result = 7111 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7112 if (getLangOpts().ObjCAutoRefCount && 7113 result == Compatible && 7114 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7115 result = IncompatibleObjCWeakRef; 7116 return result; 7117 } 7118 7119 // int or null -> A* 7120 if (RHSType->isIntegerType()) { 7121 Kind = CK_IntegralToPointer; // FIXME: null 7122 return IntToPointer; 7123 } 7124 7125 // In general, C pointers are not compatible with ObjC object pointers, 7126 // with two exceptions: 7127 if (isa<PointerType>(RHSType)) { 7128 Kind = CK_CPointerToObjCPointerCast; 7129 7130 // - conversions from 'void*' 7131 if (RHSType->isVoidPointerType()) { 7132 return Compatible; 7133 } 7134 7135 // - conversions to 'Class' from its redefinition type 7136 if (LHSType->isObjCClassType() && 7137 Context.hasSameType(RHSType, 7138 Context.getObjCClassRedefinitionType())) { 7139 return Compatible; 7140 } 7141 7142 return IncompatiblePointer; 7143 } 7144 7145 // Only under strict condition T^ is compatible with an Objective-C pointer. 7146 if (RHSType->isBlockPointerType() && 7147 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7148 maybeExtendBlockObject(RHS); 7149 Kind = CK_BlockPointerToObjCPointerCast; 7150 return Compatible; 7151 } 7152 7153 return Incompatible; 7154 } 7155 7156 // Conversions from pointers that are not covered by the above. 7157 if (isa<PointerType>(RHSType)) { 7158 // T* -> _Bool 7159 if (LHSType == Context.BoolTy) { 7160 Kind = CK_PointerToBoolean; 7161 return Compatible; 7162 } 7163 7164 // T* -> int 7165 if (LHSType->isIntegerType()) { 7166 Kind = CK_PointerToIntegral; 7167 return PointerToInt; 7168 } 7169 7170 return Incompatible; 7171 } 7172 7173 // Conversions from Objective-C pointers that are not covered by the above. 7174 if (isa<ObjCObjectPointerType>(RHSType)) { 7175 // T* -> _Bool 7176 if (LHSType == Context.BoolTy) { 7177 Kind = CK_PointerToBoolean; 7178 return Compatible; 7179 } 7180 7181 // T* -> int 7182 if (LHSType->isIntegerType()) { 7183 Kind = CK_PointerToIntegral; 7184 return PointerToInt; 7185 } 7186 7187 return Incompatible; 7188 } 7189 7190 // struct A -> struct B 7191 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7192 if (Context.typesAreCompatible(LHSType, RHSType)) { 7193 Kind = CK_NoOp; 7194 return Compatible; 7195 } 7196 } 7197 7198 return Incompatible; 7199 } 7200 7201 /// \brief Constructs a transparent union from an expression that is 7202 /// used to initialize the transparent union. 7203 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7204 ExprResult &EResult, QualType UnionType, 7205 FieldDecl *Field) { 7206 // Build an initializer list that designates the appropriate member 7207 // of the transparent union. 7208 Expr *E = EResult.get(); 7209 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7210 E, SourceLocation()); 7211 Initializer->setType(UnionType); 7212 Initializer->setInitializedFieldInUnion(Field); 7213 7214 // Build a compound literal constructing a value of the transparent 7215 // union type from this initializer list. 7216 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7217 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7218 VK_RValue, Initializer, false); 7219 } 7220 7221 Sema::AssignConvertType 7222 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7223 ExprResult &RHS) { 7224 QualType RHSType = RHS.get()->getType(); 7225 7226 // If the ArgType is a Union type, we want to handle a potential 7227 // transparent_union GCC extension. 7228 const RecordType *UT = ArgType->getAsUnionType(); 7229 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7230 return Incompatible; 7231 7232 // The field to initialize within the transparent union. 7233 RecordDecl *UD = UT->getDecl(); 7234 FieldDecl *InitField = nullptr; 7235 // It's compatible if the expression matches any of the fields. 7236 for (auto *it : UD->fields()) { 7237 if (it->getType()->isPointerType()) { 7238 // If the transparent union contains a pointer type, we allow: 7239 // 1) void pointer 7240 // 2) null pointer constant 7241 if (RHSType->isPointerType()) 7242 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7243 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7244 InitField = it; 7245 break; 7246 } 7247 7248 if (RHS.get()->isNullPointerConstant(Context, 7249 Expr::NPC_ValueDependentIsNull)) { 7250 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7251 CK_NullToPointer); 7252 InitField = it; 7253 break; 7254 } 7255 } 7256 7257 CastKind Kind = CK_Invalid; 7258 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7259 == Compatible) { 7260 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7261 InitField = it; 7262 break; 7263 } 7264 } 7265 7266 if (!InitField) 7267 return Incompatible; 7268 7269 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7270 return Compatible; 7271 } 7272 7273 Sema::AssignConvertType 7274 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7275 bool Diagnose, 7276 bool DiagnoseCFAudited) { 7277 if (getLangOpts().CPlusPlus) { 7278 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7279 // C++ 5.17p3: If the left operand is not of class type, the 7280 // expression is implicitly converted (C++ 4) to the 7281 // cv-unqualified type of the left operand. 7282 ExprResult Res; 7283 if (Diagnose) { 7284 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7285 AA_Assigning); 7286 } else { 7287 ImplicitConversionSequence ICS = 7288 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7289 /*SuppressUserConversions=*/false, 7290 /*AllowExplicit=*/false, 7291 /*InOverloadResolution=*/false, 7292 /*CStyle=*/false, 7293 /*AllowObjCWritebackConversion=*/false); 7294 if (ICS.isFailure()) 7295 return Incompatible; 7296 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7297 ICS, AA_Assigning); 7298 } 7299 if (Res.isInvalid()) 7300 return Incompatible; 7301 Sema::AssignConvertType result = Compatible; 7302 if (getLangOpts().ObjCAutoRefCount && 7303 !CheckObjCARCUnavailableWeakConversion(LHSType, 7304 RHS.get()->getType())) 7305 result = IncompatibleObjCWeakRef; 7306 RHS = Res; 7307 return result; 7308 } 7309 7310 // FIXME: Currently, we fall through and treat C++ classes like C 7311 // structures. 7312 // FIXME: We also fall through for atomics; not sure what should 7313 // happen there, though. 7314 } 7315 7316 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7317 // a null pointer constant. 7318 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7319 LHSType->isBlockPointerType()) && 7320 RHS.get()->isNullPointerConstant(Context, 7321 Expr::NPC_ValueDependentIsNull)) { 7322 CastKind Kind; 7323 CXXCastPath Path; 7324 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false); 7325 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7326 return Compatible; 7327 } 7328 7329 // This check seems unnatural, however it is necessary to ensure the proper 7330 // conversion of functions/arrays. If the conversion were done for all 7331 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7332 // expressions that suppress this implicit conversion (&, sizeof). 7333 // 7334 // Suppress this for references: C++ 8.5.3p5. 7335 if (!LHSType->isReferenceType()) { 7336 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7337 if (RHS.isInvalid()) 7338 return Incompatible; 7339 } 7340 7341 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7342 if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) { 7343 ObjCProtocolDecl *PDecl = OPE->getProtocol(); 7344 if (PDecl && !PDecl->hasDefinition()) { 7345 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7346 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7347 } 7348 } 7349 7350 CastKind Kind = CK_Invalid; 7351 Sema::AssignConvertType result = 7352 CheckAssignmentConstraints(LHSType, RHS, Kind); 7353 7354 // C99 6.5.16.1p2: The value of the right operand is converted to the 7355 // type of the assignment expression. 7356 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7357 // so that we can use references in built-in functions even in C. 7358 // The getNonReferenceType() call makes sure that the resulting expression 7359 // does not have reference type. 7360 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7361 QualType Ty = LHSType.getNonLValueExprType(Context); 7362 Expr *E = RHS.get(); 7363 if (getLangOpts().ObjCAutoRefCount) 7364 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7365 DiagnoseCFAudited); 7366 if (getLangOpts().ObjC1 && 7367 (CheckObjCBridgeRelatedConversions(E->getLocStart(), 7368 LHSType, E->getType(), E) || 7369 ConversionToObjCStringLiteralCheck(LHSType, E))) { 7370 RHS = E; 7371 return Compatible; 7372 } 7373 7374 RHS = ImpCastExprToType(E, Ty, Kind); 7375 } 7376 return result; 7377 } 7378 7379 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7380 ExprResult &RHS) { 7381 Diag(Loc, diag::err_typecheck_invalid_operands) 7382 << LHS.get()->getType() << RHS.get()->getType() 7383 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7384 return QualType(); 7385 } 7386 7387 /// Try to convert a value of non-vector type to a vector type by converting 7388 /// the type to the element type of the vector and then performing a splat. 7389 /// If the language is OpenCL, we only use conversions that promote scalar 7390 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7391 /// for float->int. 7392 /// 7393 /// \param scalar - if non-null, actually perform the conversions 7394 /// \return true if the operation fails (but without diagnosing the failure) 7395 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 7396 QualType scalarTy, 7397 QualType vectorEltTy, 7398 QualType vectorTy) { 7399 // The conversion to apply to the scalar before splatting it, 7400 // if necessary. 7401 CastKind scalarCast = CK_Invalid; 7402 7403 if (vectorEltTy->isIntegralType(S.Context)) { 7404 if (!scalarTy->isIntegralType(S.Context)) 7405 return true; 7406 if (S.getLangOpts().OpenCL && 7407 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 7408 return true; 7409 scalarCast = CK_IntegralCast; 7410 } else if (vectorEltTy->isRealFloatingType()) { 7411 if (scalarTy->isRealFloatingType()) { 7412 if (S.getLangOpts().OpenCL && 7413 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 7414 return true; 7415 scalarCast = CK_FloatingCast; 7416 } 7417 else if (scalarTy->isIntegralType(S.Context)) 7418 scalarCast = CK_IntegralToFloating; 7419 else 7420 return true; 7421 } else { 7422 return true; 7423 } 7424 7425 // Adjust scalar if desired. 7426 if (scalar) { 7427 if (scalarCast != CK_Invalid) 7428 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 7429 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 7430 } 7431 return false; 7432 } 7433 7434 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7435 SourceLocation Loc, bool IsCompAssign, 7436 bool AllowBothBool, 7437 bool AllowBoolConversions) { 7438 if (!IsCompAssign) { 7439 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 7440 if (LHS.isInvalid()) 7441 return QualType(); 7442 } 7443 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7444 if (RHS.isInvalid()) 7445 return QualType(); 7446 7447 // For conversion purposes, we ignore any qualifiers. 7448 // For example, "const float" and "float" are equivalent. 7449 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 7450 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 7451 7452 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 7453 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 7454 assert(LHSVecType || RHSVecType); 7455 7456 // AltiVec-style "vector bool op vector bool" combinations are allowed 7457 // for some operators but not others. 7458 if (!AllowBothBool && 7459 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7460 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 7461 return InvalidOperands(Loc, LHS, RHS); 7462 7463 // If the vector types are identical, return. 7464 if (Context.hasSameType(LHSType, RHSType)) 7465 return LHSType; 7466 7467 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 7468 if (LHSVecType && RHSVecType && 7469 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7470 if (isa<ExtVectorType>(LHSVecType)) { 7471 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7472 return LHSType; 7473 } 7474 7475 if (!IsCompAssign) 7476 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7477 return RHSType; 7478 } 7479 7480 // AllowBoolConversions says that bool and non-bool AltiVec vectors 7481 // can be mixed, with the result being the non-bool type. The non-bool 7482 // operand must have integer element type. 7483 if (AllowBoolConversions && LHSVecType && RHSVecType && 7484 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 7485 (Context.getTypeSize(LHSVecType->getElementType()) == 7486 Context.getTypeSize(RHSVecType->getElementType()))) { 7487 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 7488 LHSVecType->getElementType()->isIntegerType() && 7489 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 7490 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7491 return LHSType; 7492 } 7493 if (!IsCompAssign && 7494 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7495 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 7496 RHSVecType->getElementType()->isIntegerType()) { 7497 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7498 return RHSType; 7499 } 7500 } 7501 7502 // If there's an ext-vector type and a scalar, try to convert the scalar to 7503 // the vector element type and splat. 7504 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 7505 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 7506 LHSVecType->getElementType(), LHSType)) 7507 return LHSType; 7508 } 7509 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 7510 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 7511 LHSType, RHSVecType->getElementType(), 7512 RHSType)) 7513 return RHSType; 7514 } 7515 7516 // If we're allowing lax vector conversions, only the total (data) size 7517 // needs to be the same. 7518 // FIXME: Should we really be allowing this? 7519 // FIXME: We really just pick the LHS type arbitrarily? 7520 if (isLaxVectorConversion(RHSType, LHSType)) { 7521 QualType resultType = LHSType; 7522 RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast); 7523 return resultType; 7524 } 7525 7526 // Okay, the expression is invalid. 7527 7528 // If there's a non-vector, non-real operand, diagnose that. 7529 if ((!RHSVecType && !RHSType->isRealType()) || 7530 (!LHSVecType && !LHSType->isRealType())) { 7531 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 7532 << LHSType << RHSType 7533 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7534 return QualType(); 7535 } 7536 7537 // OpenCL V1.1 6.2.6.p1: 7538 // If the operands are of more than one vector type, then an error shall 7539 // occur. Implicit conversions between vector types are not permitted, per 7540 // section 6.2.1. 7541 if (getLangOpts().OpenCL && 7542 RHSVecType && isa<ExtVectorType>(RHSVecType) && 7543 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 7544 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 7545 << RHSType; 7546 return QualType(); 7547 } 7548 7549 // Otherwise, use the generic diagnostic. 7550 Diag(Loc, diag::err_typecheck_vector_not_convertable) 7551 << LHSType << RHSType 7552 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7553 return QualType(); 7554 } 7555 7556 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 7557 // expression. These are mainly cases where the null pointer is used as an 7558 // integer instead of a pointer. 7559 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 7560 SourceLocation Loc, bool IsCompare) { 7561 // The canonical way to check for a GNU null is with isNullPointerConstant, 7562 // but we use a bit of a hack here for speed; this is a relatively 7563 // hot path, and isNullPointerConstant is slow. 7564 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 7565 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 7566 7567 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 7568 7569 // Avoid analyzing cases where the result will either be invalid (and 7570 // diagnosed as such) or entirely valid and not something to warn about. 7571 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 7572 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 7573 return; 7574 7575 // Comparison operations would not make sense with a null pointer no matter 7576 // what the other expression is. 7577 if (!IsCompare) { 7578 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 7579 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 7580 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 7581 return; 7582 } 7583 7584 // The rest of the operations only make sense with a null pointer 7585 // if the other expression is a pointer. 7586 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 7587 NonNullType->canDecayToPointerType()) 7588 return; 7589 7590 S.Diag(Loc, diag::warn_null_in_comparison_operation) 7591 << LHSNull /* LHS is NULL */ << NonNullType 7592 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7593 } 7594 7595 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 7596 ExprResult &RHS, 7597 SourceLocation Loc, bool IsDiv) { 7598 // Check for division/remainder by zero. 7599 unsigned Diag = (IsDiv) ? diag::warn_division_by_zero : 7600 diag::warn_remainder_by_zero; 7601 llvm::APSInt RHSValue; 7602 if (!RHS.get()->isValueDependent() && 7603 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 7604 S.DiagRuntimeBehavior(Loc, RHS.get(), 7605 S.PDiag(Diag) << RHS.get()->getSourceRange()); 7606 } 7607 7608 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 7609 SourceLocation Loc, 7610 bool IsCompAssign, bool IsDiv) { 7611 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7612 7613 if (LHS.get()->getType()->isVectorType() || 7614 RHS.get()->getType()->isVectorType()) 7615 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 7616 /*AllowBothBool*/getLangOpts().AltiVec, 7617 /*AllowBoolConversions*/false); 7618 7619 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 7620 if (LHS.isInvalid() || RHS.isInvalid()) 7621 return QualType(); 7622 7623 7624 if (compType.isNull() || !compType->isArithmeticType()) 7625 return InvalidOperands(Loc, LHS, RHS); 7626 if (IsDiv) 7627 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 7628 return compType; 7629 } 7630 7631 QualType Sema::CheckRemainderOperands( 7632 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 7633 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7634 7635 if (LHS.get()->getType()->isVectorType() || 7636 RHS.get()->getType()->isVectorType()) { 7637 if (LHS.get()->getType()->hasIntegerRepresentation() && 7638 RHS.get()->getType()->hasIntegerRepresentation()) 7639 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 7640 /*AllowBothBool*/getLangOpts().AltiVec, 7641 /*AllowBoolConversions*/false); 7642 return InvalidOperands(Loc, LHS, RHS); 7643 } 7644 7645 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 7646 if (LHS.isInvalid() || RHS.isInvalid()) 7647 return QualType(); 7648 7649 if (compType.isNull() || !compType->isIntegerType()) 7650 return InvalidOperands(Loc, LHS, RHS); 7651 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 7652 return compType; 7653 } 7654 7655 /// \brief Diagnose invalid arithmetic on two void pointers. 7656 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 7657 Expr *LHSExpr, Expr *RHSExpr) { 7658 S.Diag(Loc, S.getLangOpts().CPlusPlus 7659 ? diag::err_typecheck_pointer_arith_void_type 7660 : diag::ext_gnu_void_ptr) 7661 << 1 /* two pointers */ << LHSExpr->getSourceRange() 7662 << RHSExpr->getSourceRange(); 7663 } 7664 7665 /// \brief Diagnose invalid arithmetic on a void pointer. 7666 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 7667 Expr *Pointer) { 7668 S.Diag(Loc, S.getLangOpts().CPlusPlus 7669 ? diag::err_typecheck_pointer_arith_void_type 7670 : diag::ext_gnu_void_ptr) 7671 << 0 /* one pointer */ << Pointer->getSourceRange(); 7672 } 7673 7674 /// \brief Diagnose invalid arithmetic on two function pointers. 7675 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 7676 Expr *LHS, Expr *RHS) { 7677 assert(LHS->getType()->isAnyPointerType()); 7678 assert(RHS->getType()->isAnyPointerType()); 7679 S.Diag(Loc, S.getLangOpts().CPlusPlus 7680 ? diag::err_typecheck_pointer_arith_function_type 7681 : diag::ext_gnu_ptr_func_arith) 7682 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 7683 // We only show the second type if it differs from the first. 7684 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 7685 RHS->getType()) 7686 << RHS->getType()->getPointeeType() 7687 << LHS->getSourceRange() << RHS->getSourceRange(); 7688 } 7689 7690 /// \brief Diagnose invalid arithmetic on a function pointer. 7691 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 7692 Expr *Pointer) { 7693 assert(Pointer->getType()->isAnyPointerType()); 7694 S.Diag(Loc, S.getLangOpts().CPlusPlus 7695 ? diag::err_typecheck_pointer_arith_function_type 7696 : diag::ext_gnu_ptr_func_arith) 7697 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 7698 << 0 /* one pointer, so only one type */ 7699 << Pointer->getSourceRange(); 7700 } 7701 7702 /// \brief Emit error if Operand is incomplete pointer type 7703 /// 7704 /// \returns True if pointer has incomplete type 7705 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 7706 Expr *Operand) { 7707 QualType ResType = Operand->getType(); 7708 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7709 ResType = ResAtomicType->getValueType(); 7710 7711 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 7712 QualType PointeeTy = ResType->getPointeeType(); 7713 return S.RequireCompleteType(Loc, PointeeTy, 7714 diag::err_typecheck_arithmetic_incomplete_type, 7715 PointeeTy, Operand->getSourceRange()); 7716 } 7717 7718 /// \brief Check the validity of an arithmetic pointer operand. 7719 /// 7720 /// If the operand has pointer type, this code will check for pointer types 7721 /// which are invalid in arithmetic operations. These will be diagnosed 7722 /// appropriately, including whether or not the use is supported as an 7723 /// extension. 7724 /// 7725 /// \returns True when the operand is valid to use (even if as an extension). 7726 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 7727 Expr *Operand) { 7728 QualType ResType = Operand->getType(); 7729 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7730 ResType = ResAtomicType->getValueType(); 7731 7732 if (!ResType->isAnyPointerType()) return true; 7733 7734 QualType PointeeTy = ResType->getPointeeType(); 7735 if (PointeeTy->isVoidType()) { 7736 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 7737 return !S.getLangOpts().CPlusPlus; 7738 } 7739 if (PointeeTy->isFunctionType()) { 7740 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 7741 return !S.getLangOpts().CPlusPlus; 7742 } 7743 7744 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 7745 7746 return true; 7747 } 7748 7749 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 7750 /// operands. 7751 /// 7752 /// This routine will diagnose any invalid arithmetic on pointer operands much 7753 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 7754 /// for emitting a single diagnostic even for operations where both LHS and RHS 7755 /// are (potentially problematic) pointers. 7756 /// 7757 /// \returns True when the operand is valid to use (even if as an extension). 7758 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 7759 Expr *LHSExpr, Expr *RHSExpr) { 7760 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 7761 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 7762 if (!isLHSPointer && !isRHSPointer) return true; 7763 7764 QualType LHSPointeeTy, RHSPointeeTy; 7765 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 7766 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 7767 7768 // if both are pointers check if operation is valid wrt address spaces 7769 if (isLHSPointer && isRHSPointer) { 7770 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 7771 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 7772 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 7773 S.Diag(Loc, 7774 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7775 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 7776 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 7777 return false; 7778 } 7779 } 7780 7781 // Check for arithmetic on pointers to incomplete types. 7782 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 7783 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 7784 if (isLHSVoidPtr || isRHSVoidPtr) { 7785 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 7786 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 7787 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 7788 7789 return !S.getLangOpts().CPlusPlus; 7790 } 7791 7792 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 7793 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 7794 if (isLHSFuncPtr || isRHSFuncPtr) { 7795 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 7796 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 7797 RHSExpr); 7798 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 7799 7800 return !S.getLangOpts().CPlusPlus; 7801 } 7802 7803 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 7804 return false; 7805 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 7806 return false; 7807 7808 return true; 7809 } 7810 7811 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 7812 /// literal. 7813 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 7814 Expr *LHSExpr, Expr *RHSExpr) { 7815 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 7816 Expr* IndexExpr = RHSExpr; 7817 if (!StrExpr) { 7818 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 7819 IndexExpr = LHSExpr; 7820 } 7821 7822 bool IsStringPlusInt = StrExpr && 7823 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 7824 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 7825 return; 7826 7827 llvm::APSInt index; 7828 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 7829 unsigned StrLenWithNull = StrExpr->getLength() + 1; 7830 if (index.isNonNegative() && 7831 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 7832 index.isUnsigned())) 7833 return; 7834 } 7835 7836 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7837 Self.Diag(OpLoc, diag::warn_string_plus_int) 7838 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 7839 7840 // Only print a fixit for "str" + int, not for int + "str". 7841 if (IndexExpr == RHSExpr) { 7842 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7843 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7844 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7845 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7846 << FixItHint::CreateInsertion(EndLoc, "]"); 7847 } else 7848 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7849 } 7850 7851 /// \brief Emit a warning when adding a char literal to a string. 7852 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 7853 Expr *LHSExpr, Expr *RHSExpr) { 7854 const Expr *StringRefExpr = LHSExpr; 7855 const CharacterLiteral *CharExpr = 7856 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 7857 7858 if (!CharExpr) { 7859 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 7860 StringRefExpr = RHSExpr; 7861 } 7862 7863 if (!CharExpr || !StringRefExpr) 7864 return; 7865 7866 const QualType StringType = StringRefExpr->getType(); 7867 7868 // Return if not a PointerType. 7869 if (!StringType->isAnyPointerType()) 7870 return; 7871 7872 // Return if not a CharacterType. 7873 if (!StringType->getPointeeType()->isAnyCharacterType()) 7874 return; 7875 7876 ASTContext &Ctx = Self.getASTContext(); 7877 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7878 7879 const QualType CharType = CharExpr->getType(); 7880 if (!CharType->isAnyCharacterType() && 7881 CharType->isIntegerType() && 7882 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 7883 Self.Diag(OpLoc, diag::warn_string_plus_char) 7884 << DiagRange << Ctx.CharTy; 7885 } else { 7886 Self.Diag(OpLoc, diag::warn_string_plus_char) 7887 << DiagRange << CharExpr->getType(); 7888 } 7889 7890 // Only print a fixit for str + char, not for char + str. 7891 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 7892 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd()); 7893 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7894 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7895 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7896 << FixItHint::CreateInsertion(EndLoc, "]"); 7897 } else { 7898 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7899 } 7900 } 7901 7902 /// \brief Emit error when two pointers are incompatible. 7903 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 7904 Expr *LHSExpr, Expr *RHSExpr) { 7905 assert(LHSExpr->getType()->isAnyPointerType()); 7906 assert(RHSExpr->getType()->isAnyPointerType()); 7907 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 7908 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 7909 << RHSExpr->getSourceRange(); 7910 } 7911 7912 QualType Sema::CheckAdditionOperands( // C99 6.5.6 7913 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 7914 QualType* CompLHSTy) { 7915 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7916 7917 if (LHS.get()->getType()->isVectorType() || 7918 RHS.get()->getType()->isVectorType()) { 7919 QualType compType = CheckVectorOperands( 7920 LHS, RHS, Loc, CompLHSTy, 7921 /*AllowBothBool*/getLangOpts().AltiVec, 7922 /*AllowBoolConversions*/getLangOpts().ZVector); 7923 if (CompLHSTy) *CompLHSTy = compType; 7924 return compType; 7925 } 7926 7927 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7928 if (LHS.isInvalid() || RHS.isInvalid()) 7929 return QualType(); 7930 7931 // Diagnose "string literal" '+' int and string '+' "char literal". 7932 if (Opc == BO_Add) { 7933 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 7934 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 7935 } 7936 7937 // handle the common case first (both operands are arithmetic). 7938 if (!compType.isNull() && compType->isArithmeticType()) { 7939 if (CompLHSTy) *CompLHSTy = compType; 7940 return compType; 7941 } 7942 7943 // Type-checking. Ultimately the pointer's going to be in PExp; 7944 // note that we bias towards the LHS being the pointer. 7945 Expr *PExp = LHS.get(), *IExp = RHS.get(); 7946 7947 bool isObjCPointer; 7948 if (PExp->getType()->isPointerType()) { 7949 isObjCPointer = false; 7950 } else if (PExp->getType()->isObjCObjectPointerType()) { 7951 isObjCPointer = true; 7952 } else { 7953 std::swap(PExp, IExp); 7954 if (PExp->getType()->isPointerType()) { 7955 isObjCPointer = false; 7956 } else if (PExp->getType()->isObjCObjectPointerType()) { 7957 isObjCPointer = true; 7958 } else { 7959 return InvalidOperands(Loc, LHS, RHS); 7960 } 7961 } 7962 assert(PExp->getType()->isAnyPointerType()); 7963 7964 if (!IExp->getType()->isIntegerType()) 7965 return InvalidOperands(Loc, LHS, RHS); 7966 7967 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 7968 return QualType(); 7969 7970 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 7971 return QualType(); 7972 7973 // Check array bounds for pointer arithemtic 7974 CheckArrayAccess(PExp, IExp); 7975 7976 if (CompLHSTy) { 7977 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 7978 if (LHSTy.isNull()) { 7979 LHSTy = LHS.get()->getType(); 7980 if (LHSTy->isPromotableIntegerType()) 7981 LHSTy = Context.getPromotedIntegerType(LHSTy); 7982 } 7983 *CompLHSTy = LHSTy; 7984 } 7985 7986 return PExp->getType(); 7987 } 7988 7989 // C99 6.5.6 7990 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 7991 SourceLocation Loc, 7992 QualType* CompLHSTy) { 7993 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7994 7995 if (LHS.get()->getType()->isVectorType() || 7996 RHS.get()->getType()->isVectorType()) { 7997 QualType compType = CheckVectorOperands( 7998 LHS, RHS, Loc, CompLHSTy, 7999 /*AllowBothBool*/getLangOpts().AltiVec, 8000 /*AllowBoolConversions*/getLangOpts().ZVector); 8001 if (CompLHSTy) *CompLHSTy = compType; 8002 return compType; 8003 } 8004 8005 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8006 if (LHS.isInvalid() || RHS.isInvalid()) 8007 return QualType(); 8008 8009 // Enforce type constraints: C99 6.5.6p3. 8010 8011 // Handle the common case first (both operands are arithmetic). 8012 if (!compType.isNull() && compType->isArithmeticType()) { 8013 if (CompLHSTy) *CompLHSTy = compType; 8014 return compType; 8015 } 8016 8017 // Either ptr - int or ptr - ptr. 8018 if (LHS.get()->getType()->isAnyPointerType()) { 8019 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8020 8021 // Diagnose bad cases where we step over interface counts. 8022 if (LHS.get()->getType()->isObjCObjectPointerType() && 8023 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8024 return QualType(); 8025 8026 // The result type of a pointer-int computation is the pointer type. 8027 if (RHS.get()->getType()->isIntegerType()) { 8028 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8029 return QualType(); 8030 8031 // Check array bounds for pointer arithemtic 8032 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8033 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8034 8035 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8036 return LHS.get()->getType(); 8037 } 8038 8039 // Handle pointer-pointer subtractions. 8040 if (const PointerType *RHSPTy 8041 = RHS.get()->getType()->getAs<PointerType>()) { 8042 QualType rpointee = RHSPTy->getPointeeType(); 8043 8044 if (getLangOpts().CPlusPlus) { 8045 // Pointee types must be the same: C++ [expr.add] 8046 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8047 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8048 } 8049 } else { 8050 // Pointee types must be compatible C99 6.5.6p3 8051 if (!Context.typesAreCompatible( 8052 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8053 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8054 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8055 return QualType(); 8056 } 8057 } 8058 8059 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8060 LHS.get(), RHS.get())) 8061 return QualType(); 8062 8063 // The pointee type may have zero size. As an extension, a structure or 8064 // union may have zero size or an array may have zero length. In this 8065 // case subtraction does not make sense. 8066 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8067 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8068 if (ElementSize.isZero()) { 8069 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8070 << rpointee.getUnqualifiedType() 8071 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8072 } 8073 } 8074 8075 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8076 return Context.getPointerDiffType(); 8077 } 8078 } 8079 8080 return InvalidOperands(Loc, LHS, RHS); 8081 } 8082 8083 static bool isScopedEnumerationType(QualType T) { 8084 if (const EnumType *ET = T->getAs<EnumType>()) 8085 return ET->getDecl()->isScoped(); 8086 return false; 8087 } 8088 8089 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8090 SourceLocation Loc, unsigned Opc, 8091 QualType LHSType) { 8092 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8093 // so skip remaining warnings as we don't want to modify values within Sema. 8094 if (S.getLangOpts().OpenCL) 8095 return; 8096 8097 llvm::APSInt Right; 8098 // Check right/shifter operand 8099 if (RHS.get()->isValueDependent() || 8100 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8101 return; 8102 8103 if (Right.isNegative()) { 8104 S.DiagRuntimeBehavior(Loc, RHS.get(), 8105 S.PDiag(diag::warn_shift_negative) 8106 << RHS.get()->getSourceRange()); 8107 return; 8108 } 8109 llvm::APInt LeftBits(Right.getBitWidth(), 8110 S.Context.getTypeSize(LHS.get()->getType())); 8111 if (Right.uge(LeftBits)) { 8112 S.DiagRuntimeBehavior(Loc, RHS.get(), 8113 S.PDiag(diag::warn_shift_gt_typewidth) 8114 << RHS.get()->getSourceRange()); 8115 return; 8116 } 8117 if (Opc != BO_Shl) 8118 return; 8119 8120 // When left shifting an ICE which is signed, we can check for overflow which 8121 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8122 // integers have defined behavior modulo one more than the maximum value 8123 // representable in the result type, so never warn for those. 8124 llvm::APSInt Left; 8125 if (LHS.get()->isValueDependent() || 8126 LHSType->hasUnsignedIntegerRepresentation() || 8127 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8128 return; 8129 8130 // If LHS does not have a signed type and non-negative value 8131 // then, the behavior is undefined. Warn about it. 8132 if (Left.isNegative()) { 8133 S.DiagRuntimeBehavior(Loc, LHS.get(), 8134 S.PDiag(diag::warn_shift_lhs_negative) 8135 << LHS.get()->getSourceRange()); 8136 return; 8137 } 8138 8139 llvm::APInt ResultBits = 8140 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8141 if (LeftBits.uge(ResultBits)) 8142 return; 8143 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8144 Result = Result.shl(Right); 8145 8146 // Print the bit representation of the signed integer as an unsigned 8147 // hexadecimal number. 8148 SmallString<40> HexResult; 8149 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8150 8151 // If we are only missing a sign bit, this is less likely to result in actual 8152 // bugs -- if the result is cast back to an unsigned type, it will have the 8153 // expected value. Thus we place this behind a different warning that can be 8154 // turned off separately if needed. 8155 if (LeftBits == ResultBits - 1) { 8156 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8157 << HexResult << LHSType 8158 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8159 return; 8160 } 8161 8162 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8163 << HexResult.str() << Result.getMinSignedBits() << LHSType 8164 << Left.getBitWidth() << LHS.get()->getSourceRange() 8165 << RHS.get()->getSourceRange(); 8166 } 8167 8168 /// \brief Return the resulting type when an OpenCL vector is shifted 8169 /// by a scalar or vector shift amount. 8170 static QualType checkOpenCLVectorShift(Sema &S, 8171 ExprResult &LHS, ExprResult &RHS, 8172 SourceLocation Loc, bool IsCompAssign) { 8173 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8174 if (!LHS.get()->getType()->isVectorType()) { 8175 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8176 << RHS.get()->getType() << LHS.get()->getType() 8177 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8178 return QualType(); 8179 } 8180 8181 if (!IsCompAssign) { 8182 LHS = S.UsualUnaryConversions(LHS.get()); 8183 if (LHS.isInvalid()) return QualType(); 8184 } 8185 8186 RHS = S.UsualUnaryConversions(RHS.get()); 8187 if (RHS.isInvalid()) return QualType(); 8188 8189 QualType LHSType = LHS.get()->getType(); 8190 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 8191 QualType LHSEleType = LHSVecTy->getElementType(); 8192 8193 // Note that RHS might not be a vector. 8194 QualType RHSType = RHS.get()->getType(); 8195 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8196 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8197 8198 // OpenCL v1.1 s6.3.j says that the operands need to be integers. 8199 if (!LHSEleType->isIntegerType()) { 8200 S.Diag(Loc, diag::err_typecheck_expect_int) 8201 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8202 return QualType(); 8203 } 8204 8205 if (!RHSEleType->isIntegerType()) { 8206 S.Diag(Loc, diag::err_typecheck_expect_int) 8207 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8208 return QualType(); 8209 } 8210 8211 if (RHSVecTy) { 8212 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8213 // are applied component-wise. So if RHS is a vector, then ensure 8214 // that the number of elements is the same as LHS... 8215 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8216 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8217 << LHS.get()->getType() << RHS.get()->getType() 8218 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8219 return QualType(); 8220 } 8221 } else { 8222 // ...else expand RHS to match the number of elements in LHS. 8223 QualType VecTy = 8224 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8225 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8226 } 8227 8228 return LHSType; 8229 } 8230 8231 // C99 6.5.7 8232 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8233 SourceLocation Loc, unsigned Opc, 8234 bool IsCompAssign) { 8235 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8236 8237 // Vector shifts promote their scalar inputs to vector type. 8238 if (LHS.get()->getType()->isVectorType() || 8239 RHS.get()->getType()->isVectorType()) { 8240 if (LangOpts.OpenCL) 8241 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8242 if (LangOpts.ZVector) { 8243 // The shift operators for the z vector extensions work basically 8244 // like OpenCL shifts, except that neither the LHS nor the RHS is 8245 // allowed to be a "vector bool". 8246 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8247 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8248 return InvalidOperands(Loc, LHS, RHS); 8249 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8250 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8251 return InvalidOperands(Loc, LHS, RHS); 8252 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8253 } 8254 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8255 /*AllowBothBool*/true, 8256 /*AllowBoolConversions*/false); 8257 } 8258 8259 // Shifts don't perform usual arithmetic conversions, they just do integer 8260 // promotions on each operand. C99 6.5.7p3 8261 8262 // For the LHS, do usual unary conversions, but then reset them away 8263 // if this is a compound assignment. 8264 ExprResult OldLHS = LHS; 8265 LHS = UsualUnaryConversions(LHS.get()); 8266 if (LHS.isInvalid()) 8267 return QualType(); 8268 QualType LHSType = LHS.get()->getType(); 8269 if (IsCompAssign) LHS = OldLHS; 8270 8271 // The RHS is simpler. 8272 RHS = UsualUnaryConversions(RHS.get()); 8273 if (RHS.isInvalid()) 8274 return QualType(); 8275 QualType RHSType = RHS.get()->getType(); 8276 8277 // C99 6.5.7p2: Each of the operands shall have integer type. 8278 if (!LHSType->hasIntegerRepresentation() || 8279 !RHSType->hasIntegerRepresentation()) 8280 return InvalidOperands(Loc, LHS, RHS); 8281 8282 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8283 // hasIntegerRepresentation() above instead of this. 8284 if (isScopedEnumerationType(LHSType) || 8285 isScopedEnumerationType(RHSType)) { 8286 return InvalidOperands(Loc, LHS, RHS); 8287 } 8288 // Sanity-check shift operands 8289 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8290 8291 // "The type of the result is that of the promoted left operand." 8292 return LHSType; 8293 } 8294 8295 static bool IsWithinTemplateSpecialization(Decl *D) { 8296 if (DeclContext *DC = D->getDeclContext()) { 8297 if (isa<ClassTemplateSpecializationDecl>(DC)) 8298 return true; 8299 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8300 return FD->isFunctionTemplateSpecialization(); 8301 } 8302 return false; 8303 } 8304 8305 /// If two different enums are compared, raise a warning. 8306 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8307 Expr *RHS) { 8308 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8309 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8310 8311 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8312 if (!LHSEnumType) 8313 return; 8314 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8315 if (!RHSEnumType) 8316 return; 8317 8318 // Ignore anonymous enums. 8319 if (!LHSEnumType->getDecl()->getIdentifier()) 8320 return; 8321 if (!RHSEnumType->getDecl()->getIdentifier()) 8322 return; 8323 8324 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8325 return; 8326 8327 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8328 << LHSStrippedType << RHSStrippedType 8329 << LHS->getSourceRange() << RHS->getSourceRange(); 8330 } 8331 8332 /// \brief Diagnose bad pointer comparisons. 8333 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8334 ExprResult &LHS, ExprResult &RHS, 8335 bool IsError) { 8336 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8337 : diag::ext_typecheck_comparison_of_distinct_pointers) 8338 << LHS.get()->getType() << RHS.get()->getType() 8339 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8340 } 8341 8342 /// \brief Returns false if the pointers are converted to a composite type, 8343 /// true otherwise. 8344 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8345 ExprResult &LHS, ExprResult &RHS) { 8346 // C++ [expr.rel]p2: 8347 // [...] Pointer conversions (4.10) and qualification 8348 // conversions (4.4) are performed on pointer operands (or on 8349 // a pointer operand and a null pointer constant) to bring 8350 // them to their composite pointer type. [...] 8351 // 8352 // C++ [expr.eq]p1 uses the same notion for (in)equality 8353 // comparisons of pointers. 8354 8355 // C++ [expr.eq]p2: 8356 // In addition, pointers to members can be compared, or a pointer to 8357 // member and a null pointer constant. Pointer to member conversions 8358 // (4.11) and qualification conversions (4.4) are performed to bring 8359 // them to a common type. If one operand is a null pointer constant, 8360 // the common type is the type of the other operand. Otherwise, the 8361 // common type is a pointer to member type similar (4.4) to the type 8362 // of one of the operands, with a cv-qualification signature (4.4) 8363 // that is the union of the cv-qualification signatures of the operand 8364 // types. 8365 8366 QualType LHSType = LHS.get()->getType(); 8367 QualType RHSType = RHS.get()->getType(); 8368 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 8369 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 8370 8371 bool NonStandardCompositeType = false; 8372 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType; 8373 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 8374 if (T.isNull()) { 8375 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 8376 return true; 8377 } 8378 8379 if (NonStandardCompositeType) 8380 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 8381 << LHSType << RHSType << T << LHS.get()->getSourceRange() 8382 << RHS.get()->getSourceRange(); 8383 8384 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 8385 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 8386 return false; 8387 } 8388 8389 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 8390 ExprResult &LHS, 8391 ExprResult &RHS, 8392 bool IsError) { 8393 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 8394 : diag::ext_typecheck_comparison_of_fptr_to_void) 8395 << LHS.get()->getType() << RHS.get()->getType() 8396 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8397 } 8398 8399 static bool isObjCObjectLiteral(ExprResult &E) { 8400 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 8401 case Stmt::ObjCArrayLiteralClass: 8402 case Stmt::ObjCDictionaryLiteralClass: 8403 case Stmt::ObjCStringLiteralClass: 8404 case Stmt::ObjCBoxedExprClass: 8405 return true; 8406 default: 8407 // Note that ObjCBoolLiteral is NOT an object literal! 8408 return false; 8409 } 8410 } 8411 8412 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 8413 const ObjCObjectPointerType *Type = 8414 LHS->getType()->getAs<ObjCObjectPointerType>(); 8415 8416 // If this is not actually an Objective-C object, bail out. 8417 if (!Type) 8418 return false; 8419 8420 // Get the LHS object's interface type. 8421 QualType InterfaceType = Type->getPointeeType(); 8422 8423 // If the RHS isn't an Objective-C object, bail out. 8424 if (!RHS->getType()->isObjCObjectPointerType()) 8425 return false; 8426 8427 // Try to find the -isEqual: method. 8428 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 8429 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 8430 InterfaceType, 8431 /*instance=*/true); 8432 if (!Method) { 8433 if (Type->isObjCIdType()) { 8434 // For 'id', just check the global pool. 8435 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 8436 /*receiverId=*/true); 8437 } else { 8438 // Check protocols. 8439 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 8440 /*instance=*/true); 8441 } 8442 } 8443 8444 if (!Method) 8445 return false; 8446 8447 QualType T = Method->parameters()[0]->getType(); 8448 if (!T->isObjCObjectPointerType()) 8449 return false; 8450 8451 QualType R = Method->getReturnType(); 8452 if (!R->isScalarType()) 8453 return false; 8454 8455 return true; 8456 } 8457 8458 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 8459 FromE = FromE->IgnoreParenImpCasts(); 8460 switch (FromE->getStmtClass()) { 8461 default: 8462 break; 8463 case Stmt::ObjCStringLiteralClass: 8464 // "string literal" 8465 return LK_String; 8466 case Stmt::ObjCArrayLiteralClass: 8467 // "array literal" 8468 return LK_Array; 8469 case Stmt::ObjCDictionaryLiteralClass: 8470 // "dictionary literal" 8471 return LK_Dictionary; 8472 case Stmt::BlockExprClass: 8473 return LK_Block; 8474 case Stmt::ObjCBoxedExprClass: { 8475 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 8476 switch (Inner->getStmtClass()) { 8477 case Stmt::IntegerLiteralClass: 8478 case Stmt::FloatingLiteralClass: 8479 case Stmt::CharacterLiteralClass: 8480 case Stmt::ObjCBoolLiteralExprClass: 8481 case Stmt::CXXBoolLiteralExprClass: 8482 // "numeric literal" 8483 return LK_Numeric; 8484 case Stmt::ImplicitCastExprClass: { 8485 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 8486 // Boolean literals can be represented by implicit casts. 8487 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 8488 return LK_Numeric; 8489 break; 8490 } 8491 default: 8492 break; 8493 } 8494 return LK_Boxed; 8495 } 8496 } 8497 return LK_None; 8498 } 8499 8500 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 8501 ExprResult &LHS, ExprResult &RHS, 8502 BinaryOperator::Opcode Opc){ 8503 Expr *Literal; 8504 Expr *Other; 8505 if (isObjCObjectLiteral(LHS)) { 8506 Literal = LHS.get(); 8507 Other = RHS.get(); 8508 } else { 8509 Literal = RHS.get(); 8510 Other = LHS.get(); 8511 } 8512 8513 // Don't warn on comparisons against nil. 8514 Other = Other->IgnoreParenCasts(); 8515 if (Other->isNullPointerConstant(S.getASTContext(), 8516 Expr::NPC_ValueDependentIsNotNull)) 8517 return; 8518 8519 // This should be kept in sync with warn_objc_literal_comparison. 8520 // LK_String should always be after the other literals, since it has its own 8521 // warning flag. 8522 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 8523 assert(LiteralKind != Sema::LK_Block); 8524 if (LiteralKind == Sema::LK_None) { 8525 llvm_unreachable("Unknown Objective-C object literal kind"); 8526 } 8527 8528 if (LiteralKind == Sema::LK_String) 8529 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 8530 << Literal->getSourceRange(); 8531 else 8532 S.Diag(Loc, diag::warn_objc_literal_comparison) 8533 << LiteralKind << Literal->getSourceRange(); 8534 8535 if (BinaryOperator::isEqualityOp(Opc) && 8536 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 8537 SourceLocation Start = LHS.get()->getLocStart(); 8538 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 8539 CharSourceRange OpRange = 8540 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc)); 8541 8542 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 8543 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 8544 << FixItHint::CreateReplacement(OpRange, " isEqual:") 8545 << FixItHint::CreateInsertion(End, "]"); 8546 } 8547 } 8548 8549 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 8550 ExprResult &RHS, 8551 SourceLocation Loc, 8552 unsigned OpaqueOpc) { 8553 // Check that left hand side is !something. 8554 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 8555 if (!UO || UO->getOpcode() != UO_LNot) return; 8556 8557 // Only check if the right hand side is non-bool arithmetic type. 8558 if (RHS.get()->isKnownToHaveBooleanValue()) return; 8559 8560 // Make sure that the something in !something is not bool. 8561 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 8562 if (SubExpr->isKnownToHaveBooleanValue()) return; 8563 8564 // Emit warning. 8565 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 8566 << Loc; 8567 8568 // First note suggest !(x < y) 8569 SourceLocation FirstOpen = SubExpr->getLocStart(); 8570 SourceLocation FirstClose = RHS.get()->getLocEnd(); 8571 FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose); 8572 if (FirstClose.isInvalid()) 8573 FirstOpen = SourceLocation(); 8574 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 8575 << FixItHint::CreateInsertion(FirstOpen, "(") 8576 << FixItHint::CreateInsertion(FirstClose, ")"); 8577 8578 // Second note suggests (!x) < y 8579 SourceLocation SecondOpen = LHS.get()->getLocStart(); 8580 SourceLocation SecondClose = LHS.get()->getLocEnd(); 8581 SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose); 8582 if (SecondClose.isInvalid()) 8583 SecondOpen = SourceLocation(); 8584 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 8585 << FixItHint::CreateInsertion(SecondOpen, "(") 8586 << FixItHint::CreateInsertion(SecondClose, ")"); 8587 } 8588 8589 // Get the decl for a simple expression: a reference to a variable, 8590 // an implicit C++ field reference, or an implicit ObjC ivar reference. 8591 static ValueDecl *getCompareDecl(Expr *E) { 8592 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 8593 return DR->getDecl(); 8594 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 8595 if (Ivar->isFreeIvar()) 8596 return Ivar->getDecl(); 8597 } 8598 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 8599 if (Mem->isImplicitAccess()) 8600 return Mem->getMemberDecl(); 8601 } 8602 return nullptr; 8603 } 8604 8605 // C99 6.5.8, C++ [expr.rel] 8606 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 8607 SourceLocation Loc, unsigned OpaqueOpc, 8608 bool IsRelational) { 8609 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 8610 8611 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc; 8612 8613 // Handle vector comparisons separately. 8614 if (LHS.get()->getType()->isVectorType() || 8615 RHS.get()->getType()->isVectorType()) 8616 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 8617 8618 QualType LHSType = LHS.get()->getType(); 8619 QualType RHSType = RHS.get()->getType(); 8620 8621 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 8622 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 8623 8624 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 8625 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc); 8626 8627 if (!LHSType->hasFloatingRepresentation() && 8628 !(LHSType->isBlockPointerType() && IsRelational) && 8629 !LHS.get()->getLocStart().isMacroID() && 8630 !RHS.get()->getLocStart().isMacroID() && 8631 ActiveTemplateInstantiations.empty()) { 8632 // For non-floating point types, check for self-comparisons of the form 8633 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 8634 // often indicate logic errors in the program. 8635 // 8636 // NOTE: Don't warn about comparison expressions resulting from macro 8637 // expansion. Also don't warn about comparisons which are only self 8638 // comparisons within a template specialization. The warnings should catch 8639 // obvious cases in the definition of the template anyways. The idea is to 8640 // warn when the typed comparison operator will always evaluate to the same 8641 // result. 8642 ValueDecl *DL = getCompareDecl(LHSStripped); 8643 ValueDecl *DR = getCompareDecl(RHSStripped); 8644 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 8645 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 8646 << 0 // self- 8647 << (Opc == BO_EQ 8648 || Opc == BO_LE 8649 || Opc == BO_GE)); 8650 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 8651 !DL->getType()->isReferenceType() && 8652 !DR->getType()->isReferenceType()) { 8653 // what is it always going to eval to? 8654 char always_evals_to; 8655 switch(Opc) { 8656 case BO_EQ: // e.g. array1 == array2 8657 always_evals_to = 0; // false 8658 break; 8659 case BO_NE: // e.g. array1 != array2 8660 always_evals_to = 1; // true 8661 break; 8662 default: 8663 // best we can say is 'a constant' 8664 always_evals_to = 2; // e.g. array1 <= array2 8665 break; 8666 } 8667 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 8668 << 1 // array 8669 << always_evals_to); 8670 } 8671 8672 if (isa<CastExpr>(LHSStripped)) 8673 LHSStripped = LHSStripped->IgnoreParenCasts(); 8674 if (isa<CastExpr>(RHSStripped)) 8675 RHSStripped = RHSStripped->IgnoreParenCasts(); 8676 8677 // Warn about comparisons against a string constant (unless the other 8678 // operand is null), the user probably wants strcmp. 8679 Expr *literalString = nullptr; 8680 Expr *literalStringStripped = nullptr; 8681 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 8682 !RHSStripped->isNullPointerConstant(Context, 8683 Expr::NPC_ValueDependentIsNull)) { 8684 literalString = LHS.get(); 8685 literalStringStripped = LHSStripped; 8686 } else if ((isa<StringLiteral>(RHSStripped) || 8687 isa<ObjCEncodeExpr>(RHSStripped)) && 8688 !LHSStripped->isNullPointerConstant(Context, 8689 Expr::NPC_ValueDependentIsNull)) { 8690 literalString = RHS.get(); 8691 literalStringStripped = RHSStripped; 8692 } 8693 8694 if (literalString) { 8695 DiagRuntimeBehavior(Loc, nullptr, 8696 PDiag(diag::warn_stringcompare) 8697 << isa<ObjCEncodeExpr>(literalStringStripped) 8698 << literalString->getSourceRange()); 8699 } 8700 } 8701 8702 // C99 6.5.8p3 / C99 6.5.9p4 8703 UsualArithmeticConversions(LHS, RHS); 8704 if (LHS.isInvalid() || RHS.isInvalid()) 8705 return QualType(); 8706 8707 LHSType = LHS.get()->getType(); 8708 RHSType = RHS.get()->getType(); 8709 8710 // The result of comparisons is 'bool' in C++, 'int' in C. 8711 QualType ResultTy = Context.getLogicalOperationType(); 8712 8713 if (IsRelational) { 8714 if (LHSType->isRealType() && RHSType->isRealType()) 8715 return ResultTy; 8716 } else { 8717 // Check for comparisons of floating point operands using != and ==. 8718 if (LHSType->hasFloatingRepresentation()) 8719 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 8720 8721 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 8722 return ResultTy; 8723 } 8724 8725 const Expr::NullPointerConstantKind LHSNullKind = 8726 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 8727 const Expr::NullPointerConstantKind RHSNullKind = 8728 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 8729 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 8730 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 8731 8732 if (!IsRelational && LHSIsNull != RHSIsNull) { 8733 bool IsEquality = Opc == BO_EQ; 8734 if (RHSIsNull) 8735 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 8736 RHS.get()->getSourceRange()); 8737 else 8738 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 8739 LHS.get()->getSourceRange()); 8740 } 8741 8742 // All of the following pointer-related warnings are GCC extensions, except 8743 // when handling null pointer constants. 8744 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 8745 QualType LCanPointeeTy = 8746 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 8747 QualType RCanPointeeTy = 8748 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 8749 8750 if (getLangOpts().CPlusPlus) { 8751 if (LCanPointeeTy == RCanPointeeTy) 8752 return ResultTy; 8753 if (!IsRelational && 8754 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 8755 // Valid unless comparison between non-null pointer and function pointer 8756 // This is a gcc extension compatibility comparison. 8757 // In a SFINAE context, we treat this as a hard error to maintain 8758 // conformance with the C++ standard. 8759 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 8760 && !LHSIsNull && !RHSIsNull) { 8761 diagnoseFunctionPointerToVoidComparison( 8762 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 8763 8764 if (isSFINAEContext()) 8765 return QualType(); 8766 8767 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8768 return ResultTy; 8769 } 8770 } 8771 8772 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 8773 return QualType(); 8774 else 8775 return ResultTy; 8776 } 8777 // C99 6.5.9p2 and C99 6.5.8p2 8778 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 8779 RCanPointeeTy.getUnqualifiedType())) { 8780 // Valid unless a relational comparison of function pointers 8781 if (IsRelational && LCanPointeeTy->isFunctionType()) { 8782 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 8783 << LHSType << RHSType << LHS.get()->getSourceRange() 8784 << RHS.get()->getSourceRange(); 8785 } 8786 } else if (!IsRelational && 8787 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 8788 // Valid unless comparison between non-null pointer and function pointer 8789 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 8790 && !LHSIsNull && !RHSIsNull) 8791 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 8792 /*isError*/false); 8793 } else { 8794 // Invalid 8795 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 8796 } 8797 if (LCanPointeeTy != RCanPointeeTy) { 8798 const PointerType *lhsPtr = LHSType->getAs<PointerType>(); 8799 if (!lhsPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 8800 Diag(Loc, 8801 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8802 << LHSType << RHSType << 0 /* comparison */ 8803 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8804 } 8805 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 8806 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 8807 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 8808 : CK_BitCast; 8809 if (LHSIsNull && !RHSIsNull) 8810 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 8811 else 8812 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 8813 } 8814 return ResultTy; 8815 } 8816 8817 if (getLangOpts().CPlusPlus) { 8818 // Comparison of nullptr_t with itself. 8819 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 8820 return ResultTy; 8821 8822 // Comparison of pointers with null pointer constants and equality 8823 // comparisons of member pointers to null pointer constants. 8824 if (RHSIsNull && 8825 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 8826 (!IsRelational && 8827 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 8828 RHS = ImpCastExprToType(RHS.get(), LHSType, 8829 LHSType->isMemberPointerType() 8830 ? CK_NullToMemberPointer 8831 : CK_NullToPointer); 8832 return ResultTy; 8833 } 8834 if (LHSIsNull && 8835 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 8836 (!IsRelational && 8837 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 8838 LHS = ImpCastExprToType(LHS.get(), RHSType, 8839 RHSType->isMemberPointerType() 8840 ? CK_NullToMemberPointer 8841 : CK_NullToPointer); 8842 return ResultTy; 8843 } 8844 8845 // Comparison of member pointers. 8846 if (!IsRelational && 8847 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 8848 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 8849 return QualType(); 8850 else 8851 return ResultTy; 8852 } 8853 8854 // Handle scoped enumeration types specifically, since they don't promote 8855 // to integers. 8856 if (LHS.get()->getType()->isEnumeralType() && 8857 Context.hasSameUnqualifiedType(LHS.get()->getType(), 8858 RHS.get()->getType())) 8859 return ResultTy; 8860 } 8861 8862 // Handle block pointer types. 8863 if (!IsRelational && LHSType->isBlockPointerType() && 8864 RHSType->isBlockPointerType()) { 8865 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 8866 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 8867 8868 if (!LHSIsNull && !RHSIsNull && 8869 !Context.typesAreCompatible(lpointee, rpointee)) { 8870 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8871 << LHSType << RHSType << LHS.get()->getSourceRange() 8872 << RHS.get()->getSourceRange(); 8873 } 8874 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8875 return ResultTy; 8876 } 8877 8878 // Allow block pointers to be compared with null pointer constants. 8879 if (!IsRelational 8880 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 8881 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 8882 if (!LHSIsNull && !RHSIsNull) { 8883 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 8884 ->getPointeeType()->isVoidType()) 8885 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 8886 ->getPointeeType()->isVoidType()))) 8887 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8888 << LHSType << RHSType << LHS.get()->getSourceRange() 8889 << RHS.get()->getSourceRange(); 8890 } 8891 if (LHSIsNull && !RHSIsNull) 8892 LHS = ImpCastExprToType(LHS.get(), RHSType, 8893 RHSType->isPointerType() ? CK_BitCast 8894 : CK_AnyPointerToBlockPointerCast); 8895 else 8896 RHS = ImpCastExprToType(RHS.get(), LHSType, 8897 LHSType->isPointerType() ? CK_BitCast 8898 : CK_AnyPointerToBlockPointerCast); 8899 return ResultTy; 8900 } 8901 8902 if (LHSType->isObjCObjectPointerType() || 8903 RHSType->isObjCObjectPointerType()) { 8904 const PointerType *LPT = LHSType->getAs<PointerType>(); 8905 const PointerType *RPT = RHSType->getAs<PointerType>(); 8906 if (LPT || RPT) { 8907 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 8908 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 8909 8910 if (!LPtrToVoid && !RPtrToVoid && 8911 !Context.typesAreCompatible(LHSType, RHSType)) { 8912 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8913 /*isError*/false); 8914 } 8915 if (LHSIsNull && !RHSIsNull) { 8916 Expr *E = LHS.get(); 8917 if (getLangOpts().ObjCAutoRefCount) 8918 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 8919 LHS = ImpCastExprToType(E, RHSType, 8920 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8921 } 8922 else { 8923 Expr *E = RHS.get(); 8924 if (getLangOpts().ObjCAutoRefCount) 8925 CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false, 8926 Opc); 8927 RHS = ImpCastExprToType(E, LHSType, 8928 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8929 } 8930 return ResultTy; 8931 } 8932 if (LHSType->isObjCObjectPointerType() && 8933 RHSType->isObjCObjectPointerType()) { 8934 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 8935 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8936 /*isError*/false); 8937 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 8938 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 8939 8940 if (LHSIsNull && !RHSIsNull) 8941 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8942 else 8943 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8944 return ResultTy; 8945 } 8946 } 8947 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 8948 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 8949 unsigned DiagID = 0; 8950 bool isError = false; 8951 if (LangOpts.DebuggerSupport) { 8952 // Under a debugger, allow the comparison of pointers to integers, 8953 // since users tend to want to compare addresses. 8954 } else if ((LHSIsNull && LHSType->isIntegerType()) || 8955 (RHSIsNull && RHSType->isIntegerType())) { 8956 if (IsRelational && !getLangOpts().CPlusPlus) 8957 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 8958 } else if (IsRelational && !getLangOpts().CPlusPlus) 8959 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 8960 else if (getLangOpts().CPlusPlus) { 8961 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 8962 isError = true; 8963 } else 8964 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 8965 8966 if (DiagID) { 8967 Diag(Loc, DiagID) 8968 << LHSType << RHSType << LHS.get()->getSourceRange() 8969 << RHS.get()->getSourceRange(); 8970 if (isError) 8971 return QualType(); 8972 } 8973 8974 if (LHSType->isIntegerType()) 8975 LHS = ImpCastExprToType(LHS.get(), RHSType, 8976 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8977 else 8978 RHS = ImpCastExprToType(RHS.get(), LHSType, 8979 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8980 return ResultTy; 8981 } 8982 8983 // Handle block pointers. 8984 if (!IsRelational && RHSIsNull 8985 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 8986 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8987 return ResultTy; 8988 } 8989 if (!IsRelational && LHSIsNull 8990 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 8991 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 8992 return ResultTy; 8993 } 8994 8995 return InvalidOperands(Loc, LHS, RHS); 8996 } 8997 8998 8999 // Return a signed type that is of identical size and number of elements. 9000 // For floating point vectors, return an integer type of identical size 9001 // and number of elements. 9002 QualType Sema::GetSignedVectorType(QualType V) { 9003 const VectorType *VTy = V->getAs<VectorType>(); 9004 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9005 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9006 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9007 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9008 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9009 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9010 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9011 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9012 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9013 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9014 "Unhandled vector element size in vector compare"); 9015 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9016 } 9017 9018 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9019 /// operates on extended vector types. Instead of producing an IntTy result, 9020 /// like a scalar comparison, a vector comparison produces a vector of integer 9021 /// types. 9022 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9023 SourceLocation Loc, 9024 bool IsRelational) { 9025 // Check to make sure we're operating on vectors of the same type and width, 9026 // Allowing one side to be a scalar of element type. 9027 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9028 /*AllowBothBool*/true, 9029 /*AllowBoolConversions*/getLangOpts().ZVector); 9030 if (vType.isNull()) 9031 return vType; 9032 9033 QualType LHSType = LHS.get()->getType(); 9034 9035 // If AltiVec, the comparison results in a numeric type, i.e. 9036 // bool for C++, int for C 9037 if (getLangOpts().AltiVec && 9038 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9039 return Context.getLogicalOperationType(); 9040 9041 // For non-floating point types, check for self-comparisons of the form 9042 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9043 // often indicate logic errors in the program. 9044 if (!LHSType->hasFloatingRepresentation() && 9045 ActiveTemplateInstantiations.empty()) { 9046 if (DeclRefExpr* DRL 9047 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9048 if (DeclRefExpr* DRR 9049 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9050 if (DRL->getDecl() == DRR->getDecl()) 9051 DiagRuntimeBehavior(Loc, nullptr, 9052 PDiag(diag::warn_comparison_always) 9053 << 0 // self- 9054 << 2 // "a constant" 9055 ); 9056 } 9057 9058 // Check for comparisons of floating point operands using != and ==. 9059 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9060 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9061 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9062 } 9063 9064 // Return a signed type for the vector. 9065 return GetSignedVectorType(LHSType); 9066 } 9067 9068 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9069 SourceLocation Loc) { 9070 // Ensure that either both operands are of the same vector type, or 9071 // one operand is of a vector type and the other is of its element type. 9072 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9073 /*AllowBothBool*/true, 9074 /*AllowBoolConversions*/false); 9075 if (vType.isNull()) 9076 return InvalidOperands(Loc, LHS, RHS); 9077 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9078 vType->hasFloatingRepresentation()) 9079 return InvalidOperands(Loc, LHS, RHS); 9080 9081 return GetSignedVectorType(LHS.get()->getType()); 9082 } 9083 9084 inline QualType Sema::CheckBitwiseOperands( 9085 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9086 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9087 9088 if (LHS.get()->getType()->isVectorType() || 9089 RHS.get()->getType()->isVectorType()) { 9090 if (LHS.get()->getType()->hasIntegerRepresentation() && 9091 RHS.get()->getType()->hasIntegerRepresentation()) 9092 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9093 /*AllowBothBool*/true, 9094 /*AllowBoolConversions*/getLangOpts().ZVector); 9095 return InvalidOperands(Loc, LHS, RHS); 9096 } 9097 9098 ExprResult LHSResult = LHS, RHSResult = RHS; 9099 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9100 IsCompAssign); 9101 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9102 return QualType(); 9103 LHS = LHSResult.get(); 9104 RHS = RHSResult.get(); 9105 9106 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9107 return compType; 9108 return InvalidOperands(Loc, LHS, RHS); 9109 } 9110 9111 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14] 9112 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) { 9113 9114 // Check vector operands differently. 9115 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9116 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9117 9118 // Diagnose cases where the user write a logical and/or but probably meant a 9119 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9120 // is a constant. 9121 if (LHS.get()->getType()->isIntegerType() && 9122 !LHS.get()->getType()->isBooleanType() && 9123 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9124 // Don't warn in macros or template instantiations. 9125 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9126 // If the RHS can be constant folded, and if it constant folds to something 9127 // that isn't 0 or 1 (which indicate a potential logical operation that 9128 // happened to fold to true/false) then warn. 9129 // Parens on the RHS are ignored. 9130 llvm::APSInt Result; 9131 if (RHS.get()->EvaluateAsInt(Result, Context)) 9132 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9133 !RHS.get()->getExprLoc().isMacroID()) || 9134 (Result != 0 && Result != 1)) { 9135 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9136 << RHS.get()->getSourceRange() 9137 << (Opc == BO_LAnd ? "&&" : "||"); 9138 // Suggest replacing the logical operator with the bitwise version 9139 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9140 << (Opc == BO_LAnd ? "&" : "|") 9141 << FixItHint::CreateReplacement(SourceRange( 9142 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(), 9143 getLangOpts())), 9144 Opc == BO_LAnd ? "&" : "|"); 9145 if (Opc == BO_LAnd) 9146 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9147 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9148 << FixItHint::CreateRemoval( 9149 SourceRange( 9150 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(), 9151 0, getSourceManager(), 9152 getLangOpts()), 9153 RHS.get()->getLocEnd())); 9154 } 9155 } 9156 9157 if (!Context.getLangOpts().CPlusPlus) { 9158 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9159 // not operate on the built-in scalar and vector float types. 9160 if (Context.getLangOpts().OpenCL && 9161 Context.getLangOpts().OpenCLVersion < 120) { 9162 if (LHS.get()->getType()->isFloatingType() || 9163 RHS.get()->getType()->isFloatingType()) 9164 return InvalidOperands(Loc, LHS, RHS); 9165 } 9166 9167 LHS = UsualUnaryConversions(LHS.get()); 9168 if (LHS.isInvalid()) 9169 return QualType(); 9170 9171 RHS = UsualUnaryConversions(RHS.get()); 9172 if (RHS.isInvalid()) 9173 return QualType(); 9174 9175 if (!LHS.get()->getType()->isScalarType() || 9176 !RHS.get()->getType()->isScalarType()) 9177 return InvalidOperands(Loc, LHS, RHS); 9178 9179 return Context.IntTy; 9180 } 9181 9182 // The following is safe because we only use this method for 9183 // non-overloadable operands. 9184 9185 // C++ [expr.log.and]p1 9186 // C++ [expr.log.or]p1 9187 // The operands are both contextually converted to type bool. 9188 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9189 if (LHSRes.isInvalid()) 9190 return InvalidOperands(Loc, LHS, RHS); 9191 LHS = LHSRes; 9192 9193 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9194 if (RHSRes.isInvalid()) 9195 return InvalidOperands(Loc, LHS, RHS); 9196 RHS = RHSRes; 9197 9198 // C++ [expr.log.and]p2 9199 // C++ [expr.log.or]p2 9200 // The result is a bool. 9201 return Context.BoolTy; 9202 } 9203 9204 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9205 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9206 if (!ME) return false; 9207 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9208 ObjCMessageExpr *Base = 9209 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 9210 if (!Base) return false; 9211 return Base->getMethodDecl() != nullptr; 9212 } 9213 9214 /// Is the given expression (which must be 'const') a reference to a 9215 /// variable which was originally non-const, but which has become 9216 /// 'const' due to being captured within a block? 9217 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9218 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9219 assert(E->isLValue() && E->getType().isConstQualified()); 9220 E = E->IgnoreParens(); 9221 9222 // Must be a reference to a declaration from an enclosing scope. 9223 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9224 if (!DRE) return NCCK_None; 9225 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9226 9227 // The declaration must be a variable which is not declared 'const'. 9228 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9229 if (!var) return NCCK_None; 9230 if (var->getType().isConstQualified()) return NCCK_None; 9231 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9232 9233 // Decide whether the first capture was for a block or a lambda. 9234 DeclContext *DC = S.CurContext, *Prev = nullptr; 9235 while (DC != var->getDeclContext()) { 9236 Prev = DC; 9237 DC = DC->getParent(); 9238 } 9239 // Unless we have an init-capture, we've gone one step too far. 9240 if (!var->isInitCapture()) 9241 DC = Prev; 9242 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9243 } 9244 9245 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9246 Ty = Ty.getNonReferenceType(); 9247 if (IsDereference && Ty->isPointerType()) 9248 Ty = Ty->getPointeeType(); 9249 return !Ty.isConstQualified(); 9250 } 9251 9252 /// Emit the "read-only variable not assignable" error and print notes to give 9253 /// more information about why the variable is not assignable, such as pointing 9254 /// to the declaration of a const variable, showing that a method is const, or 9255 /// that the function is returning a const reference. 9256 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9257 SourceLocation Loc) { 9258 // Update err_typecheck_assign_const and note_typecheck_assign_const 9259 // when this enum is changed. 9260 enum { 9261 ConstFunction, 9262 ConstVariable, 9263 ConstMember, 9264 ConstMethod, 9265 ConstUnknown, // Keep as last element 9266 }; 9267 9268 SourceRange ExprRange = E->getSourceRange(); 9269 9270 // Only emit one error on the first const found. All other consts will emit 9271 // a note to the error. 9272 bool DiagnosticEmitted = false; 9273 9274 // Track if the current expression is the result of a derefence, and if the 9275 // next checked expression is the result of a derefence. 9276 bool IsDereference = false; 9277 bool NextIsDereference = false; 9278 9279 // Loop to process MemberExpr chains. 9280 while (true) { 9281 IsDereference = NextIsDereference; 9282 NextIsDereference = false; 9283 9284 E = E->IgnoreParenImpCasts(); 9285 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9286 NextIsDereference = ME->isArrow(); 9287 const ValueDecl *VD = ME->getMemberDecl(); 9288 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9289 // Mutable fields can be modified even if the class is const. 9290 if (Field->isMutable()) { 9291 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9292 break; 9293 } 9294 9295 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9296 if (!DiagnosticEmitted) { 9297 S.Diag(Loc, diag::err_typecheck_assign_const) 9298 << ExprRange << ConstMember << false /*static*/ << Field 9299 << Field->getType(); 9300 DiagnosticEmitted = true; 9301 } 9302 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9303 << ConstMember << false /*static*/ << Field << Field->getType() 9304 << Field->getSourceRange(); 9305 } 9306 E = ME->getBase(); 9307 continue; 9308 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9309 if (VDecl->getType().isConstQualified()) { 9310 if (!DiagnosticEmitted) { 9311 S.Diag(Loc, diag::err_typecheck_assign_const) 9312 << ExprRange << ConstMember << true /*static*/ << VDecl 9313 << VDecl->getType(); 9314 DiagnosticEmitted = true; 9315 } 9316 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9317 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9318 << VDecl->getSourceRange(); 9319 } 9320 // Static fields do not inherit constness from parents. 9321 break; 9322 } 9323 break; 9324 } // End MemberExpr 9325 break; 9326 } 9327 9328 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9329 // Function calls 9330 const FunctionDecl *FD = CE->getDirectCallee(); 9331 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9332 if (!DiagnosticEmitted) { 9333 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9334 << ConstFunction << FD; 9335 DiagnosticEmitted = true; 9336 } 9337 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9338 diag::note_typecheck_assign_const) 9339 << ConstFunction << FD << FD->getReturnType() 9340 << FD->getReturnTypeSourceRange(); 9341 } 9342 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9343 // Point to variable declaration. 9344 if (const ValueDecl *VD = DRE->getDecl()) { 9345 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 9346 if (!DiagnosticEmitted) { 9347 S.Diag(Loc, diag::err_typecheck_assign_const) 9348 << ExprRange << ConstVariable << VD << VD->getType(); 9349 DiagnosticEmitted = true; 9350 } 9351 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9352 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 9353 } 9354 } 9355 } else if (isa<CXXThisExpr>(E)) { 9356 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 9357 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 9358 if (MD->isConst()) { 9359 if (!DiagnosticEmitted) { 9360 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9361 << ConstMethod << MD; 9362 DiagnosticEmitted = true; 9363 } 9364 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 9365 << ConstMethod << MD << MD->getSourceRange(); 9366 } 9367 } 9368 } 9369 } 9370 9371 if (DiagnosticEmitted) 9372 return; 9373 9374 // Can't determine a more specific message, so display the generic error. 9375 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 9376 } 9377 9378 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 9379 /// emit an error and return true. If so, return false. 9380 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 9381 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 9382 SourceLocation OrigLoc = Loc; 9383 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 9384 &Loc); 9385 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 9386 IsLV = Expr::MLV_InvalidMessageExpression; 9387 if (IsLV == Expr::MLV_Valid) 9388 return false; 9389 9390 unsigned DiagID = 0; 9391 bool NeedType = false; 9392 switch (IsLV) { // C99 6.5.16p2 9393 case Expr::MLV_ConstQualified: 9394 // Use a specialized diagnostic when we're assigning to an object 9395 // from an enclosing function or block. 9396 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 9397 if (NCCK == NCCK_Block) 9398 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 9399 else 9400 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 9401 break; 9402 } 9403 9404 // In ARC, use some specialized diagnostics for occasions where we 9405 // infer 'const'. These are always pseudo-strong variables. 9406 if (S.getLangOpts().ObjCAutoRefCount) { 9407 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 9408 if (declRef && isa<VarDecl>(declRef->getDecl())) { 9409 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 9410 9411 // Use the normal diagnostic if it's pseudo-__strong but the 9412 // user actually wrote 'const'. 9413 if (var->isARCPseudoStrong() && 9414 (!var->getTypeSourceInfo() || 9415 !var->getTypeSourceInfo()->getType().isConstQualified())) { 9416 // There are two pseudo-strong cases: 9417 // - self 9418 ObjCMethodDecl *method = S.getCurMethodDecl(); 9419 if (method && var == method->getSelfDecl()) 9420 DiagID = method->isClassMethod() 9421 ? diag::err_typecheck_arc_assign_self_class_method 9422 : diag::err_typecheck_arc_assign_self; 9423 9424 // - fast enumeration variables 9425 else 9426 DiagID = diag::err_typecheck_arr_assign_enumeration; 9427 9428 SourceRange Assign; 9429 if (Loc != OrigLoc) 9430 Assign = SourceRange(OrigLoc, OrigLoc); 9431 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9432 // We need to preserve the AST regardless, so migration tool 9433 // can do its job. 9434 return false; 9435 } 9436 } 9437 } 9438 9439 // If none of the special cases above are triggered, then this is a 9440 // simple const assignment. 9441 if (DiagID == 0) { 9442 DiagnoseConstAssignment(S, E, Loc); 9443 return true; 9444 } 9445 9446 break; 9447 case Expr::MLV_ConstAddrSpace: 9448 DiagnoseConstAssignment(S, E, Loc); 9449 return true; 9450 case Expr::MLV_ArrayType: 9451 case Expr::MLV_ArrayTemporary: 9452 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 9453 NeedType = true; 9454 break; 9455 case Expr::MLV_NotObjectType: 9456 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 9457 NeedType = true; 9458 break; 9459 case Expr::MLV_LValueCast: 9460 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 9461 break; 9462 case Expr::MLV_Valid: 9463 llvm_unreachable("did not take early return for MLV_Valid"); 9464 case Expr::MLV_InvalidExpression: 9465 case Expr::MLV_MemberFunction: 9466 case Expr::MLV_ClassTemporary: 9467 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 9468 break; 9469 case Expr::MLV_IncompleteType: 9470 case Expr::MLV_IncompleteVoidType: 9471 return S.RequireCompleteType(Loc, E->getType(), 9472 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 9473 case Expr::MLV_DuplicateVectorComponents: 9474 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 9475 break; 9476 case Expr::MLV_NoSetterProperty: 9477 llvm_unreachable("readonly properties should be processed differently"); 9478 case Expr::MLV_InvalidMessageExpression: 9479 DiagID = diag::error_readonly_message_assignment; 9480 break; 9481 case Expr::MLV_SubObjCPropertySetting: 9482 DiagID = diag::error_no_subobject_property_setting; 9483 break; 9484 } 9485 9486 SourceRange Assign; 9487 if (Loc != OrigLoc) 9488 Assign = SourceRange(OrigLoc, OrigLoc); 9489 if (NeedType) 9490 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 9491 else 9492 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9493 return true; 9494 } 9495 9496 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 9497 SourceLocation Loc, 9498 Sema &Sema) { 9499 // C / C++ fields 9500 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 9501 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 9502 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 9503 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 9504 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 9505 } 9506 9507 // Objective-C instance variables 9508 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 9509 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 9510 if (OL && OR && OL->getDecl() == OR->getDecl()) { 9511 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 9512 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 9513 if (RL && RR && RL->getDecl() == RR->getDecl()) 9514 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 9515 } 9516 } 9517 9518 // C99 6.5.16.1 9519 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 9520 SourceLocation Loc, 9521 QualType CompoundType) { 9522 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 9523 9524 // Verify that LHS is a modifiable lvalue, and emit error if not. 9525 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 9526 return QualType(); 9527 9528 QualType LHSType = LHSExpr->getType(); 9529 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 9530 CompoundType; 9531 AssignConvertType ConvTy; 9532 if (CompoundType.isNull()) { 9533 Expr *RHSCheck = RHS.get(); 9534 9535 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 9536 9537 QualType LHSTy(LHSType); 9538 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 9539 if (RHS.isInvalid()) 9540 return QualType(); 9541 // Special case of NSObject attributes on c-style pointer types. 9542 if (ConvTy == IncompatiblePointer && 9543 ((Context.isObjCNSObjectType(LHSType) && 9544 RHSType->isObjCObjectPointerType()) || 9545 (Context.isObjCNSObjectType(RHSType) && 9546 LHSType->isObjCObjectPointerType()))) 9547 ConvTy = Compatible; 9548 9549 if (ConvTy == Compatible && 9550 LHSType->isObjCObjectType()) 9551 Diag(Loc, diag::err_objc_object_assignment) 9552 << LHSType; 9553 9554 // If the RHS is a unary plus or minus, check to see if they = and + are 9555 // right next to each other. If so, the user may have typo'd "x =+ 4" 9556 // instead of "x += 4". 9557 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 9558 RHSCheck = ICE->getSubExpr(); 9559 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 9560 if ((UO->getOpcode() == UO_Plus || 9561 UO->getOpcode() == UO_Minus) && 9562 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 9563 // Only if the two operators are exactly adjacent. 9564 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 9565 // And there is a space or other character before the subexpr of the 9566 // unary +/-. We don't want to warn on "x=-1". 9567 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 9568 UO->getSubExpr()->getLocStart().isFileID()) { 9569 Diag(Loc, diag::warn_not_compound_assign) 9570 << (UO->getOpcode() == UO_Plus ? "+" : "-") 9571 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 9572 } 9573 } 9574 9575 if (ConvTy == Compatible) { 9576 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 9577 // Warn about retain cycles where a block captures the LHS, but 9578 // not if the LHS is a simple variable into which the block is 9579 // being stored...unless that variable can be captured by reference! 9580 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 9581 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 9582 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 9583 checkRetainCycles(LHSExpr, RHS.get()); 9584 9585 // It is safe to assign a weak reference into a strong variable. 9586 // Although this code can still have problems: 9587 // id x = self.weakProp; 9588 // id y = self.weakProp; 9589 // we do not warn to warn spuriously when 'x' and 'y' are on separate 9590 // paths through the function. This should be revisited if 9591 // -Wrepeated-use-of-weak is made flow-sensitive. 9592 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 9593 RHS.get()->getLocStart())) 9594 getCurFunction()->markSafeWeakUse(RHS.get()); 9595 9596 } else if (getLangOpts().ObjCAutoRefCount) { 9597 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 9598 } 9599 } 9600 } else { 9601 // Compound assignment "x += y" 9602 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 9603 } 9604 9605 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 9606 RHS.get(), AA_Assigning)) 9607 return QualType(); 9608 9609 CheckForNullPointerDereference(*this, LHSExpr); 9610 9611 // C99 6.5.16p3: The type of an assignment expression is the type of the 9612 // left operand unless the left operand has qualified type, in which case 9613 // it is the unqualified version of the type of the left operand. 9614 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 9615 // is converted to the type of the assignment expression (above). 9616 // C++ 5.17p1: the type of the assignment expression is that of its left 9617 // operand. 9618 return (getLangOpts().CPlusPlus 9619 ? LHSType : LHSType.getUnqualifiedType()); 9620 } 9621 9622 // C99 6.5.17 9623 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 9624 SourceLocation Loc) { 9625 LHS = S.CheckPlaceholderExpr(LHS.get()); 9626 RHS = S.CheckPlaceholderExpr(RHS.get()); 9627 if (LHS.isInvalid() || RHS.isInvalid()) 9628 return QualType(); 9629 9630 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 9631 // operands, but not unary promotions. 9632 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 9633 9634 // So we treat the LHS as a ignored value, and in C++ we allow the 9635 // containing site to determine what should be done with the RHS. 9636 LHS = S.IgnoredValueConversions(LHS.get()); 9637 if (LHS.isInvalid()) 9638 return QualType(); 9639 9640 S.DiagnoseUnusedExprResult(LHS.get()); 9641 9642 if (!S.getLangOpts().CPlusPlus) { 9643 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 9644 if (RHS.isInvalid()) 9645 return QualType(); 9646 if (!RHS.get()->getType()->isVoidType()) 9647 S.RequireCompleteType(Loc, RHS.get()->getType(), 9648 diag::err_incomplete_type); 9649 } 9650 9651 return RHS.get()->getType(); 9652 } 9653 9654 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 9655 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 9656 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 9657 ExprValueKind &VK, 9658 ExprObjectKind &OK, 9659 SourceLocation OpLoc, 9660 bool IsInc, bool IsPrefix) { 9661 if (Op->isTypeDependent()) 9662 return S.Context.DependentTy; 9663 9664 QualType ResType = Op->getType(); 9665 // Atomic types can be used for increment / decrement where the non-atomic 9666 // versions can, so ignore the _Atomic() specifier for the purpose of 9667 // checking. 9668 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9669 ResType = ResAtomicType->getValueType(); 9670 9671 assert(!ResType.isNull() && "no type for increment/decrement expression"); 9672 9673 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 9674 // Decrement of bool is not allowed. 9675 if (!IsInc) { 9676 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 9677 return QualType(); 9678 } 9679 // Increment of bool sets it to true, but is deprecated. 9680 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange(); 9681 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 9682 // Error on enum increments and decrements in C++ mode 9683 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 9684 return QualType(); 9685 } else if (ResType->isRealType()) { 9686 // OK! 9687 } else if (ResType->isPointerType()) { 9688 // C99 6.5.2.4p2, 6.5.6p2 9689 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 9690 return QualType(); 9691 } else if (ResType->isObjCObjectPointerType()) { 9692 // On modern runtimes, ObjC pointer arithmetic is forbidden. 9693 // Otherwise, we just need a complete type. 9694 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 9695 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 9696 return QualType(); 9697 } else if (ResType->isAnyComplexType()) { 9698 // C99 does not support ++/-- on complex types, we allow as an extension. 9699 S.Diag(OpLoc, diag::ext_integer_increment_complex) 9700 << ResType << Op->getSourceRange(); 9701 } else if (ResType->isPlaceholderType()) { 9702 ExprResult PR = S.CheckPlaceholderExpr(Op); 9703 if (PR.isInvalid()) return QualType(); 9704 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 9705 IsInc, IsPrefix); 9706 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 9707 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 9708 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 9709 (ResType->getAs<VectorType>()->getVectorKind() != 9710 VectorType::AltiVecBool)) { 9711 // The z vector extensions allow ++ and -- for non-bool vectors. 9712 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 9713 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 9714 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 9715 } else { 9716 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 9717 << ResType << int(IsInc) << Op->getSourceRange(); 9718 return QualType(); 9719 } 9720 // At this point, we know we have a real, complex or pointer type. 9721 // Now make sure the operand is a modifiable lvalue. 9722 if (CheckForModifiableLvalue(Op, OpLoc, S)) 9723 return QualType(); 9724 // In C++, a prefix increment is the same type as the operand. Otherwise 9725 // (in C or with postfix), the increment is the unqualified type of the 9726 // operand. 9727 if (IsPrefix && S.getLangOpts().CPlusPlus) { 9728 VK = VK_LValue; 9729 OK = Op->getObjectKind(); 9730 return ResType; 9731 } else { 9732 VK = VK_RValue; 9733 return ResType.getUnqualifiedType(); 9734 } 9735 } 9736 9737 9738 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 9739 /// This routine allows us to typecheck complex/recursive expressions 9740 /// where the declaration is needed for type checking. We only need to 9741 /// handle cases when the expression references a function designator 9742 /// or is an lvalue. Here are some examples: 9743 /// - &(x) => x 9744 /// - &*****f => f for f a function designator. 9745 /// - &s.xx => s 9746 /// - &s.zz[1].yy -> s, if zz is an array 9747 /// - *(x + 1) -> x, if x is an array 9748 /// - &"123"[2] -> 0 9749 /// - & __real__ x -> x 9750 static ValueDecl *getPrimaryDecl(Expr *E) { 9751 switch (E->getStmtClass()) { 9752 case Stmt::DeclRefExprClass: 9753 return cast<DeclRefExpr>(E)->getDecl(); 9754 case Stmt::MemberExprClass: 9755 // If this is an arrow operator, the address is an offset from 9756 // the base's value, so the object the base refers to is 9757 // irrelevant. 9758 if (cast<MemberExpr>(E)->isArrow()) 9759 return nullptr; 9760 // Otherwise, the expression refers to a part of the base 9761 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 9762 case Stmt::ArraySubscriptExprClass: { 9763 // FIXME: This code shouldn't be necessary! We should catch the implicit 9764 // promotion of register arrays earlier. 9765 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 9766 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 9767 if (ICE->getSubExpr()->getType()->isArrayType()) 9768 return getPrimaryDecl(ICE->getSubExpr()); 9769 } 9770 return nullptr; 9771 } 9772 case Stmt::UnaryOperatorClass: { 9773 UnaryOperator *UO = cast<UnaryOperator>(E); 9774 9775 switch(UO->getOpcode()) { 9776 case UO_Real: 9777 case UO_Imag: 9778 case UO_Extension: 9779 return getPrimaryDecl(UO->getSubExpr()); 9780 default: 9781 return nullptr; 9782 } 9783 } 9784 case Stmt::ParenExprClass: 9785 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 9786 case Stmt::ImplicitCastExprClass: 9787 // If the result of an implicit cast is an l-value, we care about 9788 // the sub-expression; otherwise, the result here doesn't matter. 9789 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 9790 default: 9791 return nullptr; 9792 } 9793 } 9794 9795 namespace { 9796 enum { 9797 AO_Bit_Field = 0, 9798 AO_Vector_Element = 1, 9799 AO_Property_Expansion = 2, 9800 AO_Register_Variable = 3, 9801 AO_No_Error = 4 9802 }; 9803 } 9804 /// \brief Diagnose invalid operand for address of operations. 9805 /// 9806 /// \param Type The type of operand which cannot have its address taken. 9807 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 9808 Expr *E, unsigned Type) { 9809 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 9810 } 9811 9812 /// CheckAddressOfOperand - The operand of & must be either a function 9813 /// designator or an lvalue designating an object. If it is an lvalue, the 9814 /// object cannot be declared with storage class register or be a bit field. 9815 /// Note: The usual conversions are *not* applied to the operand of the & 9816 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 9817 /// In C++, the operand might be an overloaded function name, in which case 9818 /// we allow the '&' but retain the overloaded-function type. 9819 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 9820 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 9821 if (PTy->getKind() == BuiltinType::Overload) { 9822 Expr *E = OrigOp.get()->IgnoreParens(); 9823 if (!isa<OverloadExpr>(E)) { 9824 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 9825 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 9826 << OrigOp.get()->getSourceRange(); 9827 return QualType(); 9828 } 9829 9830 OverloadExpr *Ovl = cast<OverloadExpr>(E); 9831 if (isa<UnresolvedMemberExpr>(Ovl)) 9832 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 9833 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 9834 << OrigOp.get()->getSourceRange(); 9835 return QualType(); 9836 } 9837 9838 return Context.OverloadTy; 9839 } 9840 9841 if (PTy->getKind() == BuiltinType::UnknownAny) 9842 return Context.UnknownAnyTy; 9843 9844 if (PTy->getKind() == BuiltinType::BoundMember) { 9845 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 9846 << OrigOp.get()->getSourceRange(); 9847 return QualType(); 9848 } 9849 9850 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 9851 if (OrigOp.isInvalid()) return QualType(); 9852 } 9853 9854 if (OrigOp.get()->isTypeDependent()) 9855 return Context.DependentTy; 9856 9857 assert(!OrigOp.get()->getType()->isPlaceholderType()); 9858 9859 // Make sure to ignore parentheses in subsequent checks 9860 Expr *op = OrigOp.get()->IgnoreParens(); 9861 9862 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 9863 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 9864 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 9865 return QualType(); 9866 } 9867 9868 if (getLangOpts().C99) { 9869 // Implement C99-only parts of addressof rules. 9870 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 9871 if (uOp->getOpcode() == UO_Deref) 9872 // Per C99 6.5.3.2, the address of a deref always returns a valid result 9873 // (assuming the deref expression is valid). 9874 return uOp->getSubExpr()->getType(); 9875 } 9876 // Technically, there should be a check for array subscript 9877 // expressions here, but the result of one is always an lvalue anyway. 9878 } 9879 ValueDecl *dcl = getPrimaryDecl(op); 9880 Expr::LValueClassification lval = op->ClassifyLValue(Context); 9881 unsigned AddressOfError = AO_No_Error; 9882 9883 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 9884 bool sfinae = (bool)isSFINAEContext(); 9885 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 9886 : diag::ext_typecheck_addrof_temporary) 9887 << op->getType() << op->getSourceRange(); 9888 if (sfinae) 9889 return QualType(); 9890 // Materialize the temporary as an lvalue so that we can take its address. 9891 OrigOp = op = new (Context) 9892 MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 9893 } else if (isa<ObjCSelectorExpr>(op)) { 9894 return Context.getPointerType(op->getType()); 9895 } else if (lval == Expr::LV_MemberFunction) { 9896 // If it's an instance method, make a member pointer. 9897 // The expression must have exactly the form &A::foo. 9898 9899 // If the underlying expression isn't a decl ref, give up. 9900 if (!isa<DeclRefExpr>(op)) { 9901 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 9902 << OrigOp.get()->getSourceRange(); 9903 return QualType(); 9904 } 9905 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 9906 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 9907 9908 // The id-expression was parenthesized. 9909 if (OrigOp.get() != DRE) { 9910 Diag(OpLoc, diag::err_parens_pointer_member_function) 9911 << OrigOp.get()->getSourceRange(); 9912 9913 // The method was named without a qualifier. 9914 } else if (!DRE->getQualifier()) { 9915 if (MD->getParent()->getName().empty()) 9916 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 9917 << op->getSourceRange(); 9918 else { 9919 SmallString<32> Str; 9920 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 9921 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 9922 << op->getSourceRange() 9923 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 9924 } 9925 } 9926 9927 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 9928 if (isa<CXXDestructorDecl>(MD)) 9929 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 9930 9931 QualType MPTy = Context.getMemberPointerType( 9932 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 9933 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 9934 RequireCompleteType(OpLoc, MPTy, 0); 9935 return MPTy; 9936 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 9937 // C99 6.5.3.2p1 9938 // The operand must be either an l-value or a function designator 9939 if (!op->getType()->isFunctionType()) { 9940 // Use a special diagnostic for loads from property references. 9941 if (isa<PseudoObjectExpr>(op)) { 9942 AddressOfError = AO_Property_Expansion; 9943 } else { 9944 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 9945 << op->getType() << op->getSourceRange(); 9946 return QualType(); 9947 } 9948 } 9949 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 9950 // The operand cannot be a bit-field 9951 AddressOfError = AO_Bit_Field; 9952 } else if (op->getObjectKind() == OK_VectorComponent) { 9953 // The operand cannot be an element of a vector 9954 AddressOfError = AO_Vector_Element; 9955 } else if (dcl) { // C99 6.5.3.2p1 9956 // We have an lvalue with a decl. Make sure the decl is not declared 9957 // with the register storage-class specifier. 9958 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 9959 // in C++ it is not error to take address of a register 9960 // variable (c++03 7.1.1P3) 9961 if (vd->getStorageClass() == SC_Register && 9962 !getLangOpts().CPlusPlus) { 9963 AddressOfError = AO_Register_Variable; 9964 } 9965 } else if (isa<MSPropertyDecl>(dcl)) { 9966 AddressOfError = AO_Property_Expansion; 9967 } else if (isa<FunctionTemplateDecl>(dcl)) { 9968 return Context.OverloadTy; 9969 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 9970 // Okay: we can take the address of a field. 9971 // Could be a pointer to member, though, if there is an explicit 9972 // scope qualifier for the class. 9973 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 9974 DeclContext *Ctx = dcl->getDeclContext(); 9975 if (Ctx && Ctx->isRecord()) { 9976 if (dcl->getType()->isReferenceType()) { 9977 Diag(OpLoc, 9978 diag::err_cannot_form_pointer_to_member_of_reference_type) 9979 << dcl->getDeclName() << dcl->getType(); 9980 return QualType(); 9981 } 9982 9983 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 9984 Ctx = Ctx->getParent(); 9985 9986 QualType MPTy = Context.getMemberPointerType( 9987 op->getType(), 9988 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 9989 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 9990 RequireCompleteType(OpLoc, MPTy, 0); 9991 return MPTy; 9992 } 9993 } 9994 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 9995 llvm_unreachable("Unknown/unexpected decl type"); 9996 } 9997 9998 if (AddressOfError != AO_No_Error) { 9999 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10000 return QualType(); 10001 } 10002 10003 if (lval == Expr::LV_IncompleteVoidType) { 10004 // Taking the address of a void variable is technically illegal, but we 10005 // allow it in cases which are otherwise valid. 10006 // Example: "extern void x; void* y = &x;". 10007 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10008 } 10009 10010 // If the operand has type "type", the result has type "pointer to type". 10011 if (op->getType()->isObjCObjectType()) 10012 return Context.getObjCObjectPointerType(op->getType()); 10013 return Context.getPointerType(op->getType()); 10014 } 10015 10016 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10017 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10018 if (!DRE) 10019 return; 10020 const Decl *D = DRE->getDecl(); 10021 if (!D) 10022 return; 10023 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10024 if (!Param) 10025 return; 10026 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10027 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10028 return; 10029 if (FunctionScopeInfo *FD = S.getCurFunction()) 10030 if (!FD->ModifiedNonNullParams.count(Param)) 10031 FD->ModifiedNonNullParams.insert(Param); 10032 } 10033 10034 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10035 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10036 SourceLocation OpLoc) { 10037 if (Op->isTypeDependent()) 10038 return S.Context.DependentTy; 10039 10040 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10041 if (ConvResult.isInvalid()) 10042 return QualType(); 10043 Op = ConvResult.get(); 10044 QualType OpTy = Op->getType(); 10045 QualType Result; 10046 10047 if (isa<CXXReinterpretCastExpr>(Op)) { 10048 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10049 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10050 Op->getSourceRange()); 10051 } 10052 10053 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10054 Result = PT->getPointeeType(); 10055 else if (const ObjCObjectPointerType *OPT = 10056 OpTy->getAs<ObjCObjectPointerType>()) 10057 Result = OPT->getPointeeType(); 10058 else { 10059 ExprResult PR = S.CheckPlaceholderExpr(Op); 10060 if (PR.isInvalid()) return QualType(); 10061 if (PR.get() != Op) 10062 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10063 } 10064 10065 if (Result.isNull()) { 10066 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10067 << OpTy << Op->getSourceRange(); 10068 return QualType(); 10069 } 10070 10071 // Note that per both C89 and C99, indirection is always legal, even if Result 10072 // is an incomplete type or void. It would be possible to warn about 10073 // dereferencing a void pointer, but it's completely well-defined, and such a 10074 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10075 // for pointers to 'void' but is fine for any other pointer type: 10076 // 10077 // C++ [expr.unary.op]p1: 10078 // [...] the expression to which [the unary * operator] is applied shall 10079 // be a pointer to an object type, or a pointer to a function type 10080 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10081 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10082 << OpTy << Op->getSourceRange(); 10083 10084 // Dereferences are usually l-values... 10085 VK = VK_LValue; 10086 10087 // ...except that certain expressions are never l-values in C. 10088 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10089 VK = VK_RValue; 10090 10091 return Result; 10092 } 10093 10094 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10095 BinaryOperatorKind Opc; 10096 switch (Kind) { 10097 default: llvm_unreachable("Unknown binop!"); 10098 case tok::periodstar: Opc = BO_PtrMemD; break; 10099 case tok::arrowstar: Opc = BO_PtrMemI; break; 10100 case tok::star: Opc = BO_Mul; break; 10101 case tok::slash: Opc = BO_Div; break; 10102 case tok::percent: Opc = BO_Rem; break; 10103 case tok::plus: Opc = BO_Add; break; 10104 case tok::minus: Opc = BO_Sub; break; 10105 case tok::lessless: Opc = BO_Shl; break; 10106 case tok::greatergreater: Opc = BO_Shr; break; 10107 case tok::lessequal: Opc = BO_LE; break; 10108 case tok::less: Opc = BO_LT; break; 10109 case tok::greaterequal: Opc = BO_GE; break; 10110 case tok::greater: Opc = BO_GT; break; 10111 case tok::exclaimequal: Opc = BO_NE; break; 10112 case tok::equalequal: Opc = BO_EQ; break; 10113 case tok::amp: Opc = BO_And; break; 10114 case tok::caret: Opc = BO_Xor; break; 10115 case tok::pipe: Opc = BO_Or; break; 10116 case tok::ampamp: Opc = BO_LAnd; break; 10117 case tok::pipepipe: Opc = BO_LOr; break; 10118 case tok::equal: Opc = BO_Assign; break; 10119 case tok::starequal: Opc = BO_MulAssign; break; 10120 case tok::slashequal: Opc = BO_DivAssign; break; 10121 case tok::percentequal: Opc = BO_RemAssign; break; 10122 case tok::plusequal: Opc = BO_AddAssign; break; 10123 case tok::minusequal: Opc = BO_SubAssign; break; 10124 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10125 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10126 case tok::ampequal: Opc = BO_AndAssign; break; 10127 case tok::caretequal: Opc = BO_XorAssign; break; 10128 case tok::pipeequal: Opc = BO_OrAssign; break; 10129 case tok::comma: Opc = BO_Comma; break; 10130 } 10131 return Opc; 10132 } 10133 10134 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10135 tok::TokenKind Kind) { 10136 UnaryOperatorKind Opc; 10137 switch (Kind) { 10138 default: llvm_unreachable("Unknown unary op!"); 10139 case tok::plusplus: Opc = UO_PreInc; break; 10140 case tok::minusminus: Opc = UO_PreDec; break; 10141 case tok::amp: Opc = UO_AddrOf; break; 10142 case tok::star: Opc = UO_Deref; break; 10143 case tok::plus: Opc = UO_Plus; break; 10144 case tok::minus: Opc = UO_Minus; break; 10145 case tok::tilde: Opc = UO_Not; break; 10146 case tok::exclaim: Opc = UO_LNot; break; 10147 case tok::kw___real: Opc = UO_Real; break; 10148 case tok::kw___imag: Opc = UO_Imag; break; 10149 case tok::kw___extension__: Opc = UO_Extension; break; 10150 } 10151 return Opc; 10152 } 10153 10154 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10155 /// This warning is only emitted for builtin assignment operations. It is also 10156 /// suppressed in the event of macro expansions. 10157 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10158 SourceLocation OpLoc) { 10159 if (!S.ActiveTemplateInstantiations.empty()) 10160 return; 10161 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10162 return; 10163 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10164 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10165 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10166 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10167 if (!LHSDeclRef || !RHSDeclRef || 10168 LHSDeclRef->getLocation().isMacroID() || 10169 RHSDeclRef->getLocation().isMacroID()) 10170 return; 10171 const ValueDecl *LHSDecl = 10172 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10173 const ValueDecl *RHSDecl = 10174 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10175 if (LHSDecl != RHSDecl) 10176 return; 10177 if (LHSDecl->getType().isVolatileQualified()) 10178 return; 10179 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10180 if (RefTy->getPointeeType().isVolatileQualified()) 10181 return; 10182 10183 S.Diag(OpLoc, diag::warn_self_assignment) 10184 << LHSDeclRef->getType() 10185 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10186 } 10187 10188 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10189 /// is usually indicative of introspection within the Objective-C pointer. 10190 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10191 SourceLocation OpLoc) { 10192 if (!S.getLangOpts().ObjC1) 10193 return; 10194 10195 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10196 const Expr *LHS = L.get(); 10197 const Expr *RHS = R.get(); 10198 10199 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10200 ObjCPointerExpr = LHS; 10201 OtherExpr = RHS; 10202 } 10203 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10204 ObjCPointerExpr = RHS; 10205 OtherExpr = LHS; 10206 } 10207 10208 // This warning is deliberately made very specific to reduce false 10209 // positives with logic that uses '&' for hashing. This logic mainly 10210 // looks for code trying to introspect into tagged pointers, which 10211 // code should generally never do. 10212 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 10213 unsigned Diag = diag::warn_objc_pointer_masking; 10214 // Determine if we are introspecting the result of performSelectorXXX. 10215 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 10216 // Special case messages to -performSelector and friends, which 10217 // can return non-pointer values boxed in a pointer value. 10218 // Some clients may wish to silence warnings in this subcase. 10219 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 10220 Selector S = ME->getSelector(); 10221 StringRef SelArg0 = S.getNameForSlot(0); 10222 if (SelArg0.startswith("performSelector")) 10223 Diag = diag::warn_objc_pointer_masking_performSelector; 10224 } 10225 10226 S.Diag(OpLoc, Diag) 10227 << ObjCPointerExpr->getSourceRange(); 10228 } 10229 } 10230 10231 static NamedDecl *getDeclFromExpr(Expr *E) { 10232 if (!E) 10233 return nullptr; 10234 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 10235 return DRE->getDecl(); 10236 if (auto *ME = dyn_cast<MemberExpr>(E)) 10237 return ME->getMemberDecl(); 10238 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 10239 return IRE->getDecl(); 10240 return nullptr; 10241 } 10242 10243 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 10244 /// operator @p Opc at location @c TokLoc. This routine only supports 10245 /// built-in operations; ActOnBinOp handles overloaded operators. 10246 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 10247 BinaryOperatorKind Opc, 10248 Expr *LHSExpr, Expr *RHSExpr) { 10249 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10250 // The syntax only allows initializer lists on the RHS of assignment, 10251 // so we don't need to worry about accepting invalid code for 10252 // non-assignment operators. 10253 // C++11 5.17p9: 10254 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 10255 // of x = {} is x = T(). 10256 InitializationKind Kind = 10257 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 10258 InitializedEntity Entity = 10259 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 10260 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 10261 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 10262 if (Init.isInvalid()) 10263 return Init; 10264 RHSExpr = Init.get(); 10265 } 10266 10267 ExprResult LHS = LHSExpr, RHS = RHSExpr; 10268 QualType ResultTy; // Result type of the binary operator. 10269 // The following two variables are used for compound assignment operators 10270 QualType CompLHSTy; // Type of LHS after promotions for computation 10271 QualType CompResultTy; // Type of computation result 10272 ExprValueKind VK = VK_RValue; 10273 ExprObjectKind OK = OK_Ordinary; 10274 10275 if (!getLangOpts().CPlusPlus) { 10276 // C cannot handle TypoExpr nodes on either side of a binop because it 10277 // doesn't handle dependent types properly, so make sure any TypoExprs have 10278 // been dealt with before checking the operands. 10279 LHS = CorrectDelayedTyposInExpr(LHSExpr); 10280 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 10281 if (Opc != BO_Assign) 10282 return ExprResult(E); 10283 // Avoid correcting the RHS to the same Expr as the LHS. 10284 Decl *D = getDeclFromExpr(E); 10285 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 10286 }); 10287 if (!LHS.isUsable() || !RHS.isUsable()) 10288 return ExprError(); 10289 } 10290 10291 switch (Opc) { 10292 case BO_Assign: 10293 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 10294 if (getLangOpts().CPlusPlus && 10295 LHS.get()->getObjectKind() != OK_ObjCProperty) { 10296 VK = LHS.get()->getValueKind(); 10297 OK = LHS.get()->getObjectKind(); 10298 } 10299 if (!ResultTy.isNull()) { 10300 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10301 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 10302 } 10303 RecordModifiableNonNullParam(*this, LHS.get()); 10304 break; 10305 case BO_PtrMemD: 10306 case BO_PtrMemI: 10307 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 10308 Opc == BO_PtrMemI); 10309 break; 10310 case BO_Mul: 10311 case BO_Div: 10312 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 10313 Opc == BO_Div); 10314 break; 10315 case BO_Rem: 10316 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 10317 break; 10318 case BO_Add: 10319 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 10320 break; 10321 case BO_Sub: 10322 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 10323 break; 10324 case BO_Shl: 10325 case BO_Shr: 10326 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 10327 break; 10328 case BO_LE: 10329 case BO_LT: 10330 case BO_GE: 10331 case BO_GT: 10332 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 10333 break; 10334 case BO_EQ: 10335 case BO_NE: 10336 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 10337 break; 10338 case BO_And: 10339 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 10340 case BO_Xor: 10341 case BO_Or: 10342 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 10343 break; 10344 case BO_LAnd: 10345 case BO_LOr: 10346 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 10347 break; 10348 case BO_MulAssign: 10349 case BO_DivAssign: 10350 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 10351 Opc == BO_DivAssign); 10352 CompLHSTy = CompResultTy; 10353 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10354 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10355 break; 10356 case BO_RemAssign: 10357 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 10358 CompLHSTy = CompResultTy; 10359 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10360 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10361 break; 10362 case BO_AddAssign: 10363 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 10364 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10365 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10366 break; 10367 case BO_SubAssign: 10368 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 10369 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10370 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10371 break; 10372 case BO_ShlAssign: 10373 case BO_ShrAssign: 10374 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 10375 CompLHSTy = CompResultTy; 10376 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10377 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10378 break; 10379 case BO_AndAssign: 10380 case BO_OrAssign: // fallthrough 10381 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10382 case BO_XorAssign: 10383 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 10384 CompLHSTy = CompResultTy; 10385 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10386 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10387 break; 10388 case BO_Comma: 10389 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 10390 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 10391 VK = RHS.get()->getValueKind(); 10392 OK = RHS.get()->getObjectKind(); 10393 } 10394 break; 10395 } 10396 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 10397 return ExprError(); 10398 10399 // Check for array bounds violations for both sides of the BinaryOperator 10400 CheckArrayAccess(LHS.get()); 10401 CheckArrayAccess(RHS.get()); 10402 10403 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 10404 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 10405 &Context.Idents.get("object_setClass"), 10406 SourceLocation(), LookupOrdinaryName); 10407 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 10408 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd()); 10409 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 10410 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 10411 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 10412 FixItHint::CreateInsertion(RHSLocEnd, ")"); 10413 } 10414 else 10415 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 10416 } 10417 else if (const ObjCIvarRefExpr *OIRE = 10418 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 10419 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 10420 10421 if (CompResultTy.isNull()) 10422 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 10423 OK, OpLoc, FPFeatures.fp_contract); 10424 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 10425 OK_ObjCProperty) { 10426 VK = VK_LValue; 10427 OK = LHS.get()->getObjectKind(); 10428 } 10429 return new (Context) CompoundAssignOperator( 10430 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 10431 OpLoc, FPFeatures.fp_contract); 10432 } 10433 10434 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 10435 /// operators are mixed in a way that suggests that the programmer forgot that 10436 /// comparison operators have higher precedence. The most typical example of 10437 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 10438 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 10439 SourceLocation OpLoc, Expr *LHSExpr, 10440 Expr *RHSExpr) { 10441 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 10442 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 10443 10444 // Check that one of the sides is a comparison operator. 10445 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 10446 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 10447 if (!isLeftComp && !isRightComp) 10448 return; 10449 10450 // Bitwise operations are sometimes used as eager logical ops. 10451 // Don't diagnose this. 10452 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 10453 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 10454 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise)) 10455 return; 10456 10457 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 10458 OpLoc) 10459 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 10460 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 10461 SourceRange ParensRange = isLeftComp ? 10462 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 10463 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 10464 10465 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 10466 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 10467 SuggestParentheses(Self, OpLoc, 10468 Self.PDiag(diag::note_precedence_silence) << OpStr, 10469 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 10470 SuggestParentheses(Self, OpLoc, 10471 Self.PDiag(diag::note_precedence_bitwise_first) 10472 << BinaryOperator::getOpcodeStr(Opc), 10473 ParensRange); 10474 } 10475 10476 /// \brief It accepts a '&' expr that is inside a '|' one. 10477 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression 10478 /// in parentheses. 10479 static void 10480 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc, 10481 BinaryOperator *Bop) { 10482 assert(Bop->getOpcode() == BO_And); 10483 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or) 10484 << Bop->getSourceRange() << OpLoc; 10485 SuggestParentheses(Self, Bop->getOperatorLoc(), 10486 Self.PDiag(diag::note_precedence_silence) 10487 << Bop->getOpcodeStr(), 10488 Bop->getSourceRange()); 10489 } 10490 10491 /// \brief It accepts a '&&' expr that is inside a '||' one. 10492 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 10493 /// in parentheses. 10494 static void 10495 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 10496 BinaryOperator *Bop) { 10497 assert(Bop->getOpcode() == BO_LAnd); 10498 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 10499 << Bop->getSourceRange() << OpLoc; 10500 SuggestParentheses(Self, Bop->getOperatorLoc(), 10501 Self.PDiag(diag::note_precedence_silence) 10502 << Bop->getOpcodeStr(), 10503 Bop->getSourceRange()); 10504 } 10505 10506 /// \brief Returns true if the given expression can be evaluated as a constant 10507 /// 'true'. 10508 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 10509 bool Res; 10510 return !E->isValueDependent() && 10511 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 10512 } 10513 10514 /// \brief Returns true if the given expression can be evaluated as a constant 10515 /// 'false'. 10516 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 10517 bool Res; 10518 return !E->isValueDependent() && 10519 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 10520 } 10521 10522 /// \brief Look for '&&' in the left hand of a '||' expr. 10523 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 10524 Expr *LHSExpr, Expr *RHSExpr) { 10525 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 10526 if (Bop->getOpcode() == BO_LAnd) { 10527 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 10528 if (EvaluatesAsFalse(S, RHSExpr)) 10529 return; 10530 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 10531 if (!EvaluatesAsTrue(S, Bop->getLHS())) 10532 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 10533 } else if (Bop->getOpcode() == BO_LOr) { 10534 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 10535 // If it's "a || b && 1 || c" we didn't warn earlier for 10536 // "a || b && 1", but warn now. 10537 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 10538 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 10539 } 10540 } 10541 } 10542 } 10543 10544 /// \brief Look for '&&' in the right hand of a '||' expr. 10545 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 10546 Expr *LHSExpr, Expr *RHSExpr) { 10547 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 10548 if (Bop->getOpcode() == BO_LAnd) { 10549 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 10550 if (EvaluatesAsFalse(S, LHSExpr)) 10551 return; 10552 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 10553 if (!EvaluatesAsTrue(S, Bop->getRHS())) 10554 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 10555 } 10556 } 10557 } 10558 10559 /// \brief Look for '&' in the left or right hand of a '|' expr. 10560 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc, 10561 Expr *OrArg) { 10562 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) { 10563 if (Bop->getOpcode() == BO_And) 10564 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop); 10565 } 10566 } 10567 10568 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 10569 Expr *SubExpr, StringRef Shift) { 10570 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 10571 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 10572 StringRef Op = Bop->getOpcodeStr(); 10573 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 10574 << Bop->getSourceRange() << OpLoc << Shift << Op; 10575 SuggestParentheses(S, Bop->getOperatorLoc(), 10576 S.PDiag(diag::note_precedence_silence) << Op, 10577 Bop->getSourceRange()); 10578 } 10579 } 10580 } 10581 10582 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 10583 Expr *LHSExpr, Expr *RHSExpr) { 10584 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 10585 if (!OCE) 10586 return; 10587 10588 FunctionDecl *FD = OCE->getDirectCallee(); 10589 if (!FD || !FD->isOverloadedOperator()) 10590 return; 10591 10592 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 10593 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 10594 return; 10595 10596 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 10597 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 10598 << (Kind == OO_LessLess); 10599 SuggestParentheses(S, OCE->getOperatorLoc(), 10600 S.PDiag(diag::note_precedence_silence) 10601 << (Kind == OO_LessLess ? "<<" : ">>"), 10602 OCE->getSourceRange()); 10603 SuggestParentheses(S, OpLoc, 10604 S.PDiag(diag::note_evaluate_comparison_first), 10605 SourceRange(OCE->getArg(1)->getLocStart(), 10606 RHSExpr->getLocEnd())); 10607 } 10608 10609 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 10610 /// precedence. 10611 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 10612 SourceLocation OpLoc, Expr *LHSExpr, 10613 Expr *RHSExpr){ 10614 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 10615 if (BinaryOperator::isBitwiseOp(Opc)) 10616 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 10617 10618 // Diagnose "arg1 & arg2 | arg3" 10619 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) { 10620 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr); 10621 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr); 10622 } 10623 10624 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 10625 // We don't warn for 'assert(a || b && "bad")' since this is safe. 10626 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 10627 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 10628 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 10629 } 10630 10631 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 10632 || Opc == BO_Shr) { 10633 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 10634 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 10635 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 10636 } 10637 10638 // Warn on overloaded shift operators and comparisons, such as: 10639 // cout << 5 == 4; 10640 if (BinaryOperator::isComparisonOp(Opc)) 10641 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 10642 } 10643 10644 // Binary Operators. 'Tok' is the token for the operator. 10645 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 10646 tok::TokenKind Kind, 10647 Expr *LHSExpr, Expr *RHSExpr) { 10648 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 10649 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 10650 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 10651 10652 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 10653 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 10654 10655 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 10656 } 10657 10658 /// Build an overloaded binary operator expression in the given scope. 10659 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 10660 BinaryOperatorKind Opc, 10661 Expr *LHS, Expr *RHS) { 10662 // Find all of the overloaded operators visible from this 10663 // point. We perform both an operator-name lookup from the local 10664 // scope and an argument-dependent lookup based on the types of 10665 // the arguments. 10666 UnresolvedSet<16> Functions; 10667 OverloadedOperatorKind OverOp 10668 = BinaryOperator::getOverloadedOperator(Opc); 10669 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 10670 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 10671 RHS->getType(), Functions); 10672 10673 // Build the (potentially-overloaded, potentially-dependent) 10674 // binary operation. 10675 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 10676 } 10677 10678 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 10679 BinaryOperatorKind Opc, 10680 Expr *LHSExpr, Expr *RHSExpr) { 10681 // We want to end up calling one of checkPseudoObjectAssignment 10682 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 10683 // both expressions are overloadable or either is type-dependent), 10684 // or CreateBuiltinBinOp (in any other case). We also want to get 10685 // any placeholder types out of the way. 10686 10687 // Handle pseudo-objects in the LHS. 10688 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 10689 // Assignments with a pseudo-object l-value need special analysis. 10690 if (pty->getKind() == BuiltinType::PseudoObject && 10691 BinaryOperator::isAssignmentOp(Opc)) 10692 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 10693 10694 // Don't resolve overloads if the other type is overloadable. 10695 if (pty->getKind() == BuiltinType::Overload) { 10696 // We can't actually test that if we still have a placeholder, 10697 // though. Fortunately, none of the exceptions we see in that 10698 // code below are valid when the LHS is an overload set. Note 10699 // that an overload set can be dependently-typed, but it never 10700 // instantiates to having an overloadable type. 10701 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 10702 if (resolvedRHS.isInvalid()) return ExprError(); 10703 RHSExpr = resolvedRHS.get(); 10704 10705 if (RHSExpr->isTypeDependent() || 10706 RHSExpr->getType()->isOverloadableType()) 10707 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10708 } 10709 10710 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 10711 if (LHS.isInvalid()) return ExprError(); 10712 LHSExpr = LHS.get(); 10713 } 10714 10715 // Handle pseudo-objects in the RHS. 10716 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 10717 // An overload in the RHS can potentially be resolved by the type 10718 // being assigned to. 10719 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 10720 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 10721 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10722 10723 if (LHSExpr->getType()->isOverloadableType()) 10724 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10725 10726 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 10727 } 10728 10729 // Don't resolve overloads if the other type is overloadable. 10730 if (pty->getKind() == BuiltinType::Overload && 10731 LHSExpr->getType()->isOverloadableType()) 10732 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10733 10734 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 10735 if (!resolvedRHS.isUsable()) return ExprError(); 10736 RHSExpr = resolvedRHS.get(); 10737 } 10738 10739 if (getLangOpts().CPlusPlus) { 10740 // If either expression is type-dependent, always build an 10741 // overloaded op. 10742 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 10743 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10744 10745 // Otherwise, build an overloaded op if either expression has an 10746 // overloadable type. 10747 if (LHSExpr->getType()->isOverloadableType() || 10748 RHSExpr->getType()->isOverloadableType()) 10749 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10750 } 10751 10752 // Build a built-in binary operation. 10753 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 10754 } 10755 10756 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 10757 UnaryOperatorKind Opc, 10758 Expr *InputExpr) { 10759 ExprResult Input = InputExpr; 10760 ExprValueKind VK = VK_RValue; 10761 ExprObjectKind OK = OK_Ordinary; 10762 QualType resultType; 10763 switch (Opc) { 10764 case UO_PreInc: 10765 case UO_PreDec: 10766 case UO_PostInc: 10767 case UO_PostDec: 10768 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 10769 OpLoc, 10770 Opc == UO_PreInc || 10771 Opc == UO_PostInc, 10772 Opc == UO_PreInc || 10773 Opc == UO_PreDec); 10774 break; 10775 case UO_AddrOf: 10776 resultType = CheckAddressOfOperand(Input, OpLoc); 10777 RecordModifiableNonNullParam(*this, InputExpr); 10778 break; 10779 case UO_Deref: { 10780 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 10781 if (Input.isInvalid()) return ExprError(); 10782 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 10783 break; 10784 } 10785 case UO_Plus: 10786 case UO_Minus: 10787 Input = UsualUnaryConversions(Input.get()); 10788 if (Input.isInvalid()) return ExprError(); 10789 resultType = Input.get()->getType(); 10790 if (resultType->isDependentType()) 10791 break; 10792 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 10793 break; 10794 else if (resultType->isVectorType() && 10795 // The z vector extensions don't allow + or - with bool vectors. 10796 (!Context.getLangOpts().ZVector || 10797 resultType->getAs<VectorType>()->getVectorKind() != 10798 VectorType::AltiVecBool)) 10799 break; 10800 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 10801 Opc == UO_Plus && 10802 resultType->isPointerType()) 10803 break; 10804 10805 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10806 << resultType << Input.get()->getSourceRange()); 10807 10808 case UO_Not: // bitwise complement 10809 Input = UsualUnaryConversions(Input.get()); 10810 if (Input.isInvalid()) 10811 return ExprError(); 10812 resultType = Input.get()->getType(); 10813 if (resultType->isDependentType()) 10814 break; 10815 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 10816 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 10817 // C99 does not support '~' for complex conjugation. 10818 Diag(OpLoc, diag::ext_integer_complement_complex) 10819 << resultType << Input.get()->getSourceRange(); 10820 else if (resultType->hasIntegerRepresentation()) 10821 break; 10822 else if (resultType->isExtVectorType()) { 10823 if (Context.getLangOpts().OpenCL) { 10824 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 10825 // on vector float types. 10826 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 10827 if (!T->isIntegerType()) 10828 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10829 << resultType << Input.get()->getSourceRange()); 10830 } 10831 break; 10832 } else { 10833 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10834 << resultType << Input.get()->getSourceRange()); 10835 } 10836 break; 10837 10838 case UO_LNot: // logical negation 10839 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 10840 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 10841 if (Input.isInvalid()) return ExprError(); 10842 resultType = Input.get()->getType(); 10843 10844 // Though we still have to promote half FP to float... 10845 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 10846 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 10847 resultType = Context.FloatTy; 10848 } 10849 10850 if (resultType->isDependentType()) 10851 break; 10852 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 10853 // C99 6.5.3.3p1: ok, fallthrough; 10854 if (Context.getLangOpts().CPlusPlus) { 10855 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 10856 // operand contextually converted to bool. 10857 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 10858 ScalarTypeToBooleanCastKind(resultType)); 10859 } else if (Context.getLangOpts().OpenCL && 10860 Context.getLangOpts().OpenCLVersion < 120) { 10861 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 10862 // operate on scalar float types. 10863 if (!resultType->isIntegerType()) 10864 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10865 << resultType << Input.get()->getSourceRange()); 10866 } 10867 } else if (resultType->isExtVectorType()) { 10868 if (Context.getLangOpts().OpenCL && 10869 Context.getLangOpts().OpenCLVersion < 120) { 10870 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 10871 // operate on vector float types. 10872 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 10873 if (!T->isIntegerType()) 10874 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10875 << resultType << Input.get()->getSourceRange()); 10876 } 10877 // Vector logical not returns the signed variant of the operand type. 10878 resultType = GetSignedVectorType(resultType); 10879 break; 10880 } else { 10881 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10882 << resultType << Input.get()->getSourceRange()); 10883 } 10884 10885 // LNot always has type int. C99 6.5.3.3p5. 10886 // In C++, it's bool. C++ 5.3.1p8 10887 resultType = Context.getLogicalOperationType(); 10888 break; 10889 case UO_Real: 10890 case UO_Imag: 10891 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 10892 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 10893 // complex l-values to ordinary l-values and all other values to r-values. 10894 if (Input.isInvalid()) return ExprError(); 10895 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 10896 if (Input.get()->getValueKind() != VK_RValue && 10897 Input.get()->getObjectKind() == OK_Ordinary) 10898 VK = Input.get()->getValueKind(); 10899 } else if (!getLangOpts().CPlusPlus) { 10900 // In C, a volatile scalar is read by __imag. In C++, it is not. 10901 Input = DefaultLvalueConversion(Input.get()); 10902 } 10903 break; 10904 case UO_Extension: 10905 resultType = Input.get()->getType(); 10906 VK = Input.get()->getValueKind(); 10907 OK = Input.get()->getObjectKind(); 10908 break; 10909 } 10910 if (resultType.isNull() || Input.isInvalid()) 10911 return ExprError(); 10912 10913 // Check for array bounds violations in the operand of the UnaryOperator, 10914 // except for the '*' and '&' operators that have to be handled specially 10915 // by CheckArrayAccess (as there are special cases like &array[arraysize] 10916 // that are explicitly defined as valid by the standard). 10917 if (Opc != UO_AddrOf && Opc != UO_Deref) 10918 CheckArrayAccess(Input.get()); 10919 10920 return new (Context) 10921 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 10922 } 10923 10924 /// \brief Determine whether the given expression is a qualified member 10925 /// access expression, of a form that could be turned into a pointer to member 10926 /// with the address-of operator. 10927 static bool isQualifiedMemberAccess(Expr *E) { 10928 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10929 if (!DRE->getQualifier()) 10930 return false; 10931 10932 ValueDecl *VD = DRE->getDecl(); 10933 if (!VD->isCXXClassMember()) 10934 return false; 10935 10936 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 10937 return true; 10938 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 10939 return Method->isInstance(); 10940 10941 return false; 10942 } 10943 10944 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 10945 if (!ULE->getQualifier()) 10946 return false; 10947 10948 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(), 10949 DEnd = ULE->decls_end(); 10950 D != DEnd; ++D) { 10951 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) { 10952 if (Method->isInstance()) 10953 return true; 10954 } else { 10955 // Overload set does not contain methods. 10956 break; 10957 } 10958 } 10959 10960 return false; 10961 } 10962 10963 return false; 10964 } 10965 10966 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 10967 UnaryOperatorKind Opc, Expr *Input) { 10968 // First things first: handle placeholders so that the 10969 // overloaded-operator check considers the right type. 10970 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 10971 // Increment and decrement of pseudo-object references. 10972 if (pty->getKind() == BuiltinType::PseudoObject && 10973 UnaryOperator::isIncrementDecrementOp(Opc)) 10974 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 10975 10976 // extension is always a builtin operator. 10977 if (Opc == UO_Extension) 10978 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10979 10980 // & gets special logic for several kinds of placeholder. 10981 // The builtin code knows what to do. 10982 if (Opc == UO_AddrOf && 10983 (pty->getKind() == BuiltinType::Overload || 10984 pty->getKind() == BuiltinType::UnknownAny || 10985 pty->getKind() == BuiltinType::BoundMember)) 10986 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10987 10988 // Anything else needs to be handled now. 10989 ExprResult Result = CheckPlaceholderExpr(Input); 10990 if (Result.isInvalid()) return ExprError(); 10991 Input = Result.get(); 10992 } 10993 10994 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 10995 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 10996 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 10997 // Find all of the overloaded operators visible from this 10998 // point. We perform both an operator-name lookup from the local 10999 // scope and an argument-dependent lookup based on the types of 11000 // the arguments. 11001 UnresolvedSet<16> Functions; 11002 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11003 if (S && OverOp != OO_None) 11004 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11005 Functions); 11006 11007 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11008 } 11009 11010 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11011 } 11012 11013 // Unary Operators. 'Tok' is the token for the operator. 11014 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11015 tok::TokenKind Op, Expr *Input) { 11016 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11017 } 11018 11019 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11020 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11021 LabelDecl *TheDecl) { 11022 TheDecl->markUsed(Context); 11023 // Create the AST node. The address of a label always has type 'void*'. 11024 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11025 Context.getPointerType(Context.VoidTy)); 11026 } 11027 11028 /// Given the last statement in a statement-expression, check whether 11029 /// the result is a producing expression (like a call to an 11030 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11031 /// release out of the full-expression. Otherwise, return null. 11032 /// Cannot fail. 11033 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11034 // Should always be wrapped with one of these. 11035 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11036 if (!cleanups) return nullptr; 11037 11038 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11039 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11040 return nullptr; 11041 11042 // Splice out the cast. This shouldn't modify any interesting 11043 // features of the statement. 11044 Expr *producer = cast->getSubExpr(); 11045 assert(producer->getType() == cast->getType()); 11046 assert(producer->getValueKind() == cast->getValueKind()); 11047 cleanups->setSubExpr(producer); 11048 return cleanups; 11049 } 11050 11051 void Sema::ActOnStartStmtExpr() { 11052 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11053 } 11054 11055 void Sema::ActOnStmtExprError() { 11056 // Note that function is also called by TreeTransform when leaving a 11057 // StmtExpr scope without rebuilding anything. 11058 11059 DiscardCleanupsInEvaluationContext(); 11060 PopExpressionEvaluationContext(); 11061 } 11062 11063 ExprResult 11064 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11065 SourceLocation RPLoc) { // "({..})" 11066 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11067 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11068 11069 if (hasAnyUnrecoverableErrorsInThisFunction()) 11070 DiscardCleanupsInEvaluationContext(); 11071 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 11072 PopExpressionEvaluationContext(); 11073 11074 // FIXME: there are a variety of strange constraints to enforce here, for 11075 // example, it is not possible to goto into a stmt expression apparently. 11076 // More semantic analysis is needed. 11077 11078 // If there are sub-stmts in the compound stmt, take the type of the last one 11079 // as the type of the stmtexpr. 11080 QualType Ty = Context.VoidTy; 11081 bool StmtExprMayBindToTemp = false; 11082 if (!Compound->body_empty()) { 11083 Stmt *LastStmt = Compound->body_back(); 11084 LabelStmt *LastLabelStmt = nullptr; 11085 // If LastStmt is a label, skip down through into the body. 11086 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11087 LastLabelStmt = Label; 11088 LastStmt = Label->getSubStmt(); 11089 } 11090 11091 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11092 // Do function/array conversion on the last expression, but not 11093 // lvalue-to-rvalue. However, initialize an unqualified type. 11094 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11095 if (LastExpr.isInvalid()) 11096 return ExprError(); 11097 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11098 11099 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11100 // In ARC, if the final expression ends in a consume, splice 11101 // the consume out and bind it later. In the alternate case 11102 // (when dealing with a retainable type), the result 11103 // initialization will create a produce. In both cases the 11104 // result will be +1, and we'll need to balance that out with 11105 // a bind. 11106 if (Expr *rebuiltLastStmt 11107 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11108 LastExpr = rebuiltLastStmt; 11109 } else { 11110 LastExpr = PerformCopyInitialization( 11111 InitializedEntity::InitializeResult(LPLoc, 11112 Ty, 11113 false), 11114 SourceLocation(), 11115 LastExpr); 11116 } 11117 11118 if (LastExpr.isInvalid()) 11119 return ExprError(); 11120 if (LastExpr.get() != nullptr) { 11121 if (!LastLabelStmt) 11122 Compound->setLastStmt(LastExpr.get()); 11123 else 11124 LastLabelStmt->setSubStmt(LastExpr.get()); 11125 StmtExprMayBindToTemp = true; 11126 } 11127 } 11128 } 11129 } 11130 11131 // FIXME: Check that expression type is complete/non-abstract; statement 11132 // expressions are not lvalues. 11133 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11134 if (StmtExprMayBindToTemp) 11135 return MaybeBindToTemporary(ResStmtExpr); 11136 return ResStmtExpr; 11137 } 11138 11139 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11140 TypeSourceInfo *TInfo, 11141 OffsetOfComponent *CompPtr, 11142 unsigned NumComponents, 11143 SourceLocation RParenLoc) { 11144 QualType ArgTy = TInfo->getType(); 11145 bool Dependent = ArgTy->isDependentType(); 11146 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11147 11148 // We must have at least one component that refers to the type, and the first 11149 // one is known to be a field designator. Verify that the ArgTy represents 11150 // a struct/union/class. 11151 if (!Dependent && !ArgTy->isRecordType()) 11152 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11153 << ArgTy << TypeRange); 11154 11155 // Type must be complete per C99 7.17p3 because a declaring a variable 11156 // with an incomplete type would be ill-formed. 11157 if (!Dependent 11158 && RequireCompleteType(BuiltinLoc, ArgTy, 11159 diag::err_offsetof_incomplete_type, TypeRange)) 11160 return ExprError(); 11161 11162 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11163 // GCC extension, diagnose them. 11164 // FIXME: This diagnostic isn't actually visible because the location is in 11165 // a system header! 11166 if (NumComponents != 1) 11167 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11168 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd); 11169 11170 bool DidWarnAboutNonPOD = false; 11171 QualType CurrentType = ArgTy; 11172 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode; 11173 SmallVector<OffsetOfNode, 4> Comps; 11174 SmallVector<Expr*, 4> Exprs; 11175 for (unsigned i = 0; i != NumComponents; ++i) { 11176 const OffsetOfComponent &OC = CompPtr[i]; 11177 if (OC.isBrackets) { 11178 // Offset of an array sub-field. TODO: Should we allow vector elements? 11179 if (!CurrentType->isDependentType()) { 11180 const ArrayType *AT = Context.getAsArrayType(CurrentType); 11181 if(!AT) 11182 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 11183 << CurrentType); 11184 CurrentType = AT->getElementType(); 11185 } else 11186 CurrentType = Context.DependentTy; 11187 11188 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 11189 if (IdxRval.isInvalid()) 11190 return ExprError(); 11191 Expr *Idx = IdxRval.get(); 11192 11193 // The expression must be an integral expression. 11194 // FIXME: An integral constant expression? 11195 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 11196 !Idx->getType()->isIntegerType()) 11197 return ExprError(Diag(Idx->getLocStart(), 11198 diag::err_typecheck_subscript_not_integer) 11199 << Idx->getSourceRange()); 11200 11201 // Record this array index. 11202 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 11203 Exprs.push_back(Idx); 11204 continue; 11205 } 11206 11207 // Offset of a field. 11208 if (CurrentType->isDependentType()) { 11209 // We have the offset of a field, but we can't look into the dependent 11210 // type. Just record the identifier of the field. 11211 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 11212 CurrentType = Context.DependentTy; 11213 continue; 11214 } 11215 11216 // We need to have a complete type to look into. 11217 if (RequireCompleteType(OC.LocStart, CurrentType, 11218 diag::err_offsetof_incomplete_type)) 11219 return ExprError(); 11220 11221 // Look for the designated field. 11222 const RecordType *RC = CurrentType->getAs<RecordType>(); 11223 if (!RC) 11224 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 11225 << CurrentType); 11226 RecordDecl *RD = RC->getDecl(); 11227 11228 // C++ [lib.support.types]p5: 11229 // The macro offsetof accepts a restricted set of type arguments in this 11230 // International Standard. type shall be a POD structure or a POD union 11231 // (clause 9). 11232 // C++11 [support.types]p4: 11233 // If type is not a standard-layout class (Clause 9), the results are 11234 // undefined. 11235 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11236 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 11237 unsigned DiagID = 11238 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 11239 : diag::ext_offsetof_non_pod_type; 11240 11241 if (!IsSafe && !DidWarnAboutNonPOD && 11242 DiagRuntimeBehavior(BuiltinLoc, nullptr, 11243 PDiag(DiagID) 11244 << SourceRange(CompPtr[0].LocStart, OC.LocEnd) 11245 << CurrentType)) 11246 DidWarnAboutNonPOD = true; 11247 } 11248 11249 // Look for the field. 11250 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 11251 LookupQualifiedName(R, RD); 11252 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 11253 IndirectFieldDecl *IndirectMemberDecl = nullptr; 11254 if (!MemberDecl) { 11255 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 11256 MemberDecl = IndirectMemberDecl->getAnonField(); 11257 } 11258 11259 if (!MemberDecl) 11260 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 11261 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 11262 OC.LocEnd)); 11263 11264 // C99 7.17p3: 11265 // (If the specified member is a bit-field, the behavior is undefined.) 11266 // 11267 // We diagnose this as an error. 11268 if (MemberDecl->isBitField()) { 11269 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 11270 << MemberDecl->getDeclName() 11271 << SourceRange(BuiltinLoc, RParenLoc); 11272 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 11273 return ExprError(); 11274 } 11275 11276 RecordDecl *Parent = MemberDecl->getParent(); 11277 if (IndirectMemberDecl) 11278 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 11279 11280 // If the member was found in a base class, introduce OffsetOfNodes for 11281 // the base class indirections. 11282 CXXBasePaths Paths; 11283 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) { 11284 if (Paths.getDetectedVirtual()) { 11285 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 11286 << MemberDecl->getDeclName() 11287 << SourceRange(BuiltinLoc, RParenLoc); 11288 return ExprError(); 11289 } 11290 11291 CXXBasePath &Path = Paths.front(); 11292 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end(); 11293 B != BEnd; ++B) 11294 Comps.push_back(OffsetOfNode(B->Base)); 11295 } 11296 11297 if (IndirectMemberDecl) { 11298 for (auto *FI : IndirectMemberDecl->chain()) { 11299 assert(isa<FieldDecl>(FI)); 11300 Comps.push_back(OffsetOfNode(OC.LocStart, 11301 cast<FieldDecl>(FI), OC.LocEnd)); 11302 } 11303 } else 11304 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 11305 11306 CurrentType = MemberDecl->getType().getNonReferenceType(); 11307 } 11308 11309 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 11310 Comps, Exprs, RParenLoc); 11311 } 11312 11313 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 11314 SourceLocation BuiltinLoc, 11315 SourceLocation TypeLoc, 11316 ParsedType ParsedArgTy, 11317 OffsetOfComponent *CompPtr, 11318 unsigned NumComponents, 11319 SourceLocation RParenLoc) { 11320 11321 TypeSourceInfo *ArgTInfo; 11322 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 11323 if (ArgTy.isNull()) 11324 return ExprError(); 11325 11326 if (!ArgTInfo) 11327 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 11328 11329 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 11330 RParenLoc); 11331 } 11332 11333 11334 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 11335 Expr *CondExpr, 11336 Expr *LHSExpr, Expr *RHSExpr, 11337 SourceLocation RPLoc) { 11338 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 11339 11340 ExprValueKind VK = VK_RValue; 11341 ExprObjectKind OK = OK_Ordinary; 11342 QualType resType; 11343 bool ValueDependent = false; 11344 bool CondIsTrue = false; 11345 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 11346 resType = Context.DependentTy; 11347 ValueDependent = true; 11348 } else { 11349 // The conditional expression is required to be a constant expression. 11350 llvm::APSInt condEval(32); 11351 ExprResult CondICE 11352 = VerifyIntegerConstantExpression(CondExpr, &condEval, 11353 diag::err_typecheck_choose_expr_requires_constant, false); 11354 if (CondICE.isInvalid()) 11355 return ExprError(); 11356 CondExpr = CondICE.get(); 11357 CondIsTrue = condEval.getZExtValue(); 11358 11359 // If the condition is > zero, then the AST type is the same as the LSHExpr. 11360 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 11361 11362 resType = ActiveExpr->getType(); 11363 ValueDependent = ActiveExpr->isValueDependent(); 11364 VK = ActiveExpr->getValueKind(); 11365 OK = ActiveExpr->getObjectKind(); 11366 } 11367 11368 return new (Context) 11369 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 11370 CondIsTrue, resType->isDependentType(), ValueDependent); 11371 } 11372 11373 //===----------------------------------------------------------------------===// 11374 // Clang Extensions. 11375 //===----------------------------------------------------------------------===// 11376 11377 /// ActOnBlockStart - This callback is invoked when a block literal is started. 11378 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 11379 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 11380 11381 if (LangOpts.CPlusPlus) { 11382 Decl *ManglingContextDecl; 11383 if (MangleNumberingContext *MCtx = 11384 getCurrentMangleNumberContext(Block->getDeclContext(), 11385 ManglingContextDecl)) { 11386 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 11387 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 11388 } 11389 } 11390 11391 PushBlockScope(CurScope, Block); 11392 CurContext->addDecl(Block); 11393 if (CurScope) 11394 PushDeclContext(CurScope, Block); 11395 else 11396 CurContext = Block; 11397 11398 getCurBlock()->HasImplicitReturnType = true; 11399 11400 // Enter a new evaluation context to insulate the block from any 11401 // cleanups from the enclosing full-expression. 11402 PushExpressionEvaluationContext(PotentiallyEvaluated); 11403 } 11404 11405 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 11406 Scope *CurScope) { 11407 assert(ParamInfo.getIdentifier() == nullptr && 11408 "block-id should have no identifier!"); 11409 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 11410 BlockScopeInfo *CurBlock = getCurBlock(); 11411 11412 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 11413 QualType T = Sig->getType(); 11414 11415 // FIXME: We should allow unexpanded parameter packs here, but that would, 11416 // in turn, make the block expression contain unexpanded parameter packs. 11417 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 11418 // Drop the parameters. 11419 FunctionProtoType::ExtProtoInfo EPI; 11420 EPI.HasTrailingReturn = false; 11421 EPI.TypeQuals |= DeclSpec::TQ_const; 11422 T = Context.getFunctionType(Context.DependentTy, None, EPI); 11423 Sig = Context.getTrivialTypeSourceInfo(T); 11424 } 11425 11426 // GetTypeForDeclarator always produces a function type for a block 11427 // literal signature. Furthermore, it is always a FunctionProtoType 11428 // unless the function was written with a typedef. 11429 assert(T->isFunctionType() && 11430 "GetTypeForDeclarator made a non-function block signature"); 11431 11432 // Look for an explicit signature in that function type. 11433 FunctionProtoTypeLoc ExplicitSignature; 11434 11435 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 11436 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 11437 11438 // Check whether that explicit signature was synthesized by 11439 // GetTypeForDeclarator. If so, don't save that as part of the 11440 // written signature. 11441 if (ExplicitSignature.getLocalRangeBegin() == 11442 ExplicitSignature.getLocalRangeEnd()) { 11443 // This would be much cheaper if we stored TypeLocs instead of 11444 // TypeSourceInfos. 11445 TypeLoc Result = ExplicitSignature.getReturnLoc(); 11446 unsigned Size = Result.getFullDataSize(); 11447 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 11448 Sig->getTypeLoc().initializeFullCopy(Result, Size); 11449 11450 ExplicitSignature = FunctionProtoTypeLoc(); 11451 } 11452 } 11453 11454 CurBlock->TheDecl->setSignatureAsWritten(Sig); 11455 CurBlock->FunctionType = T; 11456 11457 const FunctionType *Fn = T->getAs<FunctionType>(); 11458 QualType RetTy = Fn->getReturnType(); 11459 bool isVariadic = 11460 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 11461 11462 CurBlock->TheDecl->setIsVariadic(isVariadic); 11463 11464 // Context.DependentTy is used as a placeholder for a missing block 11465 // return type. TODO: what should we do with declarators like: 11466 // ^ * { ... } 11467 // If the answer is "apply template argument deduction".... 11468 if (RetTy != Context.DependentTy) { 11469 CurBlock->ReturnType = RetTy; 11470 CurBlock->TheDecl->setBlockMissingReturnType(false); 11471 CurBlock->HasImplicitReturnType = false; 11472 } 11473 11474 // Push block parameters from the declarator if we had them. 11475 SmallVector<ParmVarDecl*, 8> Params; 11476 if (ExplicitSignature) { 11477 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 11478 ParmVarDecl *Param = ExplicitSignature.getParam(I); 11479 if (Param->getIdentifier() == nullptr && 11480 !Param->isImplicit() && 11481 !Param->isInvalidDecl() && 11482 !getLangOpts().CPlusPlus) 11483 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 11484 Params.push_back(Param); 11485 } 11486 11487 // Fake up parameter variables if we have a typedef, like 11488 // ^ fntype { ... } 11489 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 11490 for (const auto &I : Fn->param_types()) { 11491 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 11492 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 11493 Params.push_back(Param); 11494 } 11495 } 11496 11497 // Set the parameters on the block decl. 11498 if (!Params.empty()) { 11499 CurBlock->TheDecl->setParams(Params); 11500 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 11501 CurBlock->TheDecl->param_end(), 11502 /*CheckParameterNames=*/false); 11503 } 11504 11505 // Finally we can process decl attributes. 11506 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 11507 11508 // Put the parameter variables in scope. 11509 for (auto AI : CurBlock->TheDecl->params()) { 11510 AI->setOwningFunction(CurBlock->TheDecl); 11511 11512 // If this has an identifier, add it to the scope stack. 11513 if (AI->getIdentifier()) { 11514 CheckShadow(CurBlock->TheScope, AI); 11515 11516 PushOnScopeChains(AI, CurBlock->TheScope); 11517 } 11518 } 11519 } 11520 11521 /// ActOnBlockError - If there is an error parsing a block, this callback 11522 /// is invoked to pop the information about the block from the action impl. 11523 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 11524 // Leave the expression-evaluation context. 11525 DiscardCleanupsInEvaluationContext(); 11526 PopExpressionEvaluationContext(); 11527 11528 // Pop off CurBlock, handle nested blocks. 11529 PopDeclContext(); 11530 PopFunctionScopeInfo(); 11531 } 11532 11533 /// ActOnBlockStmtExpr - This is called when the body of a block statement 11534 /// literal was successfully completed. ^(int x){...} 11535 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 11536 Stmt *Body, Scope *CurScope) { 11537 // If blocks are disabled, emit an error. 11538 if (!LangOpts.Blocks) 11539 Diag(CaretLoc, diag::err_blocks_disable); 11540 11541 // Leave the expression-evaluation context. 11542 if (hasAnyUnrecoverableErrorsInThisFunction()) 11543 DiscardCleanupsInEvaluationContext(); 11544 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 11545 PopExpressionEvaluationContext(); 11546 11547 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 11548 11549 if (BSI->HasImplicitReturnType) 11550 deduceClosureReturnType(*BSI); 11551 11552 PopDeclContext(); 11553 11554 QualType RetTy = Context.VoidTy; 11555 if (!BSI->ReturnType.isNull()) 11556 RetTy = BSI->ReturnType; 11557 11558 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 11559 QualType BlockTy; 11560 11561 // Set the captured variables on the block. 11562 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 11563 SmallVector<BlockDecl::Capture, 4> Captures; 11564 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) { 11565 CapturingScopeInfo::Capture &Cap = BSI->Captures[i]; 11566 if (Cap.isThisCapture()) 11567 continue; 11568 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 11569 Cap.isNested(), Cap.getInitExpr()); 11570 Captures.push_back(NewCap); 11571 } 11572 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 11573 11574 // If the user wrote a function type in some form, try to use that. 11575 if (!BSI->FunctionType.isNull()) { 11576 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 11577 11578 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 11579 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 11580 11581 // Turn protoless block types into nullary block types. 11582 if (isa<FunctionNoProtoType>(FTy)) { 11583 FunctionProtoType::ExtProtoInfo EPI; 11584 EPI.ExtInfo = Ext; 11585 BlockTy = Context.getFunctionType(RetTy, None, EPI); 11586 11587 // Otherwise, if we don't need to change anything about the function type, 11588 // preserve its sugar structure. 11589 } else if (FTy->getReturnType() == RetTy && 11590 (!NoReturn || FTy->getNoReturnAttr())) { 11591 BlockTy = BSI->FunctionType; 11592 11593 // Otherwise, make the minimal modifications to the function type. 11594 } else { 11595 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 11596 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11597 EPI.TypeQuals = 0; // FIXME: silently? 11598 EPI.ExtInfo = Ext; 11599 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 11600 } 11601 11602 // If we don't have a function type, just build one from nothing. 11603 } else { 11604 FunctionProtoType::ExtProtoInfo EPI; 11605 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 11606 BlockTy = Context.getFunctionType(RetTy, None, EPI); 11607 } 11608 11609 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 11610 BSI->TheDecl->param_end()); 11611 BlockTy = Context.getBlockPointerType(BlockTy); 11612 11613 // If needed, diagnose invalid gotos and switches in the block. 11614 if (getCurFunction()->NeedsScopeChecking() && 11615 !PP.isCodeCompletionEnabled()) 11616 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 11617 11618 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 11619 11620 // Try to apply the named return value optimization. We have to check again 11621 // if we can do this, though, because blocks keep return statements around 11622 // to deduce an implicit return type. 11623 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 11624 !BSI->TheDecl->isDependentContext()) 11625 computeNRVO(Body, BSI); 11626 11627 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 11628 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 11629 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 11630 11631 // If the block isn't obviously global, i.e. it captures anything at 11632 // all, then we need to do a few things in the surrounding context: 11633 if (Result->getBlockDecl()->hasCaptures()) { 11634 // First, this expression has a new cleanup object. 11635 ExprCleanupObjects.push_back(Result->getBlockDecl()); 11636 ExprNeedsCleanups = true; 11637 11638 // It also gets a branch-protected scope if any of the captured 11639 // variables needs destruction. 11640 for (const auto &CI : Result->getBlockDecl()->captures()) { 11641 const VarDecl *var = CI.getVariable(); 11642 if (var->getType().isDestructedType() != QualType::DK_none) { 11643 getCurFunction()->setHasBranchProtectedScope(); 11644 break; 11645 } 11646 } 11647 } 11648 11649 return Result; 11650 } 11651 11652 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 11653 Expr *E, ParsedType Ty, 11654 SourceLocation RPLoc) { 11655 TypeSourceInfo *TInfo; 11656 GetTypeFromParser(Ty, &TInfo); 11657 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 11658 } 11659 11660 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 11661 Expr *E, TypeSourceInfo *TInfo, 11662 SourceLocation RPLoc) { 11663 Expr *OrigExpr = E; 11664 11665 // Get the va_list type 11666 QualType VaListType = Context.getBuiltinVaListType(); 11667 if (VaListType->isArrayType()) { 11668 // Deal with implicit array decay; for example, on x86-64, 11669 // va_list is an array, but it's supposed to decay to 11670 // a pointer for va_arg. 11671 VaListType = Context.getArrayDecayedType(VaListType); 11672 // Make sure the input expression also decays appropriately. 11673 ExprResult Result = UsualUnaryConversions(E); 11674 if (Result.isInvalid()) 11675 return ExprError(); 11676 E = Result.get(); 11677 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 11678 // If va_list is a record type and we are compiling in C++ mode, 11679 // check the argument using reference binding. 11680 InitializedEntity Entity 11681 = InitializedEntity::InitializeParameter(Context, 11682 Context.getLValueReferenceType(VaListType), false); 11683 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 11684 if (Init.isInvalid()) 11685 return ExprError(); 11686 E = Init.getAs<Expr>(); 11687 } else { 11688 // Otherwise, the va_list argument must be an l-value because 11689 // it is modified by va_arg. 11690 if (!E->isTypeDependent() && 11691 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 11692 return ExprError(); 11693 } 11694 11695 if (!E->isTypeDependent() && 11696 !Context.hasSameType(VaListType, E->getType())) { 11697 return ExprError(Diag(E->getLocStart(), 11698 diag::err_first_argument_to_va_arg_not_of_type_va_list) 11699 << OrigExpr->getType() << E->getSourceRange()); 11700 } 11701 11702 if (!TInfo->getType()->isDependentType()) { 11703 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 11704 diag::err_second_parameter_to_va_arg_incomplete, 11705 TInfo->getTypeLoc())) 11706 return ExprError(); 11707 11708 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 11709 TInfo->getType(), 11710 diag::err_second_parameter_to_va_arg_abstract, 11711 TInfo->getTypeLoc())) 11712 return ExprError(); 11713 11714 if (!TInfo->getType().isPODType(Context)) { 11715 Diag(TInfo->getTypeLoc().getBeginLoc(), 11716 TInfo->getType()->isObjCLifetimeType() 11717 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 11718 : diag::warn_second_parameter_to_va_arg_not_pod) 11719 << TInfo->getType() 11720 << TInfo->getTypeLoc().getSourceRange(); 11721 } 11722 11723 // Check for va_arg where arguments of the given type will be promoted 11724 // (i.e. this va_arg is guaranteed to have undefined behavior). 11725 QualType PromoteType; 11726 if (TInfo->getType()->isPromotableIntegerType()) { 11727 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 11728 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 11729 PromoteType = QualType(); 11730 } 11731 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 11732 PromoteType = Context.DoubleTy; 11733 if (!PromoteType.isNull()) 11734 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 11735 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 11736 << TInfo->getType() 11737 << PromoteType 11738 << TInfo->getTypeLoc().getSourceRange()); 11739 } 11740 11741 QualType T = TInfo->getType().getNonLValueExprType(Context); 11742 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T); 11743 } 11744 11745 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 11746 // The type of __null will be int or long, depending on the size of 11747 // pointers on the target. 11748 QualType Ty; 11749 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 11750 if (pw == Context.getTargetInfo().getIntWidth()) 11751 Ty = Context.IntTy; 11752 else if (pw == Context.getTargetInfo().getLongWidth()) 11753 Ty = Context.LongTy; 11754 else if (pw == Context.getTargetInfo().getLongLongWidth()) 11755 Ty = Context.LongLongTy; 11756 else { 11757 llvm_unreachable("I don't know size of pointer!"); 11758 } 11759 11760 return new (Context) GNUNullExpr(Ty, TokenLoc); 11761 } 11762 11763 bool 11764 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) { 11765 if (!getLangOpts().ObjC1) 11766 return false; 11767 11768 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 11769 if (!PT) 11770 return false; 11771 11772 if (!PT->isObjCIdType()) { 11773 // Check if the destination is the 'NSString' interface. 11774 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 11775 if (!ID || !ID->getIdentifier()->isStr("NSString")) 11776 return false; 11777 } 11778 11779 // Ignore any parens, implicit casts (should only be 11780 // array-to-pointer decays), and not-so-opaque values. The last is 11781 // important for making this trigger for property assignments. 11782 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 11783 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 11784 if (OV->getSourceExpr()) 11785 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 11786 11787 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 11788 if (!SL || !SL->isAscii()) 11789 return false; 11790 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 11791 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 11792 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 11793 return true; 11794 } 11795 11796 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 11797 SourceLocation Loc, 11798 QualType DstType, QualType SrcType, 11799 Expr *SrcExpr, AssignmentAction Action, 11800 bool *Complained) { 11801 if (Complained) 11802 *Complained = false; 11803 11804 // Decode the result (notice that AST's are still created for extensions). 11805 bool CheckInferredResultType = false; 11806 bool isInvalid = false; 11807 unsigned DiagKind = 0; 11808 FixItHint Hint; 11809 ConversionFixItGenerator ConvHints; 11810 bool MayHaveConvFixit = false; 11811 bool MayHaveFunctionDiff = false; 11812 const ObjCInterfaceDecl *IFace = nullptr; 11813 const ObjCProtocolDecl *PDecl = nullptr; 11814 11815 switch (ConvTy) { 11816 case Compatible: 11817 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 11818 return false; 11819 11820 case PointerToInt: 11821 DiagKind = diag::ext_typecheck_convert_pointer_int; 11822 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11823 MayHaveConvFixit = true; 11824 break; 11825 case IntToPointer: 11826 DiagKind = diag::ext_typecheck_convert_int_pointer; 11827 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11828 MayHaveConvFixit = true; 11829 break; 11830 case IncompatiblePointer: 11831 DiagKind = 11832 (Action == AA_Passing_CFAudited ? 11833 diag::err_arc_typecheck_convert_incompatible_pointer : 11834 diag::ext_typecheck_convert_incompatible_pointer); 11835 CheckInferredResultType = DstType->isObjCObjectPointerType() && 11836 SrcType->isObjCObjectPointerType(); 11837 if (Hint.isNull() && !CheckInferredResultType) { 11838 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11839 } 11840 else if (CheckInferredResultType) { 11841 SrcType = SrcType.getUnqualifiedType(); 11842 DstType = DstType.getUnqualifiedType(); 11843 } 11844 MayHaveConvFixit = true; 11845 break; 11846 case IncompatiblePointerSign: 11847 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 11848 break; 11849 case FunctionVoidPointer: 11850 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 11851 break; 11852 case IncompatiblePointerDiscardsQualifiers: { 11853 // Perform array-to-pointer decay if necessary. 11854 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 11855 11856 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 11857 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 11858 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 11859 DiagKind = diag::err_typecheck_incompatible_address_space; 11860 break; 11861 11862 11863 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 11864 DiagKind = diag::err_typecheck_incompatible_ownership; 11865 break; 11866 } 11867 11868 llvm_unreachable("unknown error case for discarding qualifiers!"); 11869 // fallthrough 11870 } 11871 case CompatiblePointerDiscardsQualifiers: 11872 // If the qualifiers lost were because we were applying the 11873 // (deprecated) C++ conversion from a string literal to a char* 11874 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 11875 // Ideally, this check would be performed in 11876 // checkPointerTypesForAssignment. However, that would require a 11877 // bit of refactoring (so that the second argument is an 11878 // expression, rather than a type), which should be done as part 11879 // of a larger effort to fix checkPointerTypesForAssignment for 11880 // C++ semantics. 11881 if (getLangOpts().CPlusPlus && 11882 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 11883 return false; 11884 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 11885 break; 11886 case IncompatibleNestedPointerQualifiers: 11887 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 11888 break; 11889 case IntToBlockPointer: 11890 DiagKind = diag::err_int_to_block_pointer; 11891 break; 11892 case IncompatibleBlockPointer: 11893 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 11894 break; 11895 case IncompatibleObjCQualifiedId: { 11896 if (SrcType->isObjCQualifiedIdType()) { 11897 const ObjCObjectPointerType *srcOPT = 11898 SrcType->getAs<ObjCObjectPointerType>(); 11899 for (auto *srcProto : srcOPT->quals()) { 11900 PDecl = srcProto; 11901 break; 11902 } 11903 if (const ObjCInterfaceType *IFaceT = 11904 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 11905 IFace = IFaceT->getDecl(); 11906 } 11907 else if (DstType->isObjCQualifiedIdType()) { 11908 const ObjCObjectPointerType *dstOPT = 11909 DstType->getAs<ObjCObjectPointerType>(); 11910 for (auto *dstProto : dstOPT->quals()) { 11911 PDecl = dstProto; 11912 break; 11913 } 11914 if (const ObjCInterfaceType *IFaceT = 11915 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 11916 IFace = IFaceT->getDecl(); 11917 } 11918 DiagKind = diag::warn_incompatible_qualified_id; 11919 break; 11920 } 11921 case IncompatibleVectors: 11922 DiagKind = diag::warn_incompatible_vectors; 11923 break; 11924 case IncompatibleObjCWeakRef: 11925 DiagKind = diag::err_arc_weak_unavailable_assign; 11926 break; 11927 case Incompatible: 11928 DiagKind = diag::err_typecheck_convert_incompatible; 11929 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11930 MayHaveConvFixit = true; 11931 isInvalid = true; 11932 MayHaveFunctionDiff = true; 11933 break; 11934 } 11935 11936 QualType FirstType, SecondType; 11937 switch (Action) { 11938 case AA_Assigning: 11939 case AA_Initializing: 11940 // The destination type comes first. 11941 FirstType = DstType; 11942 SecondType = SrcType; 11943 break; 11944 11945 case AA_Returning: 11946 case AA_Passing: 11947 case AA_Passing_CFAudited: 11948 case AA_Converting: 11949 case AA_Sending: 11950 case AA_Casting: 11951 // The source type comes first. 11952 FirstType = SrcType; 11953 SecondType = DstType; 11954 break; 11955 } 11956 11957 PartialDiagnostic FDiag = PDiag(DiagKind); 11958 if (Action == AA_Passing_CFAudited) 11959 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 11960 else 11961 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 11962 11963 // If we can fix the conversion, suggest the FixIts. 11964 assert(ConvHints.isNull() || Hint.isNull()); 11965 if (!ConvHints.isNull()) { 11966 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(), 11967 HE = ConvHints.Hints.end(); HI != HE; ++HI) 11968 FDiag << *HI; 11969 } else { 11970 FDiag << Hint; 11971 } 11972 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 11973 11974 if (MayHaveFunctionDiff) 11975 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 11976 11977 Diag(Loc, FDiag); 11978 if (DiagKind == diag::warn_incompatible_qualified_id && 11979 PDecl && IFace && !IFace->hasDefinition()) 11980 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 11981 << IFace->getName() << PDecl->getName(); 11982 11983 if (SecondType == Context.OverloadTy) 11984 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 11985 FirstType); 11986 11987 if (CheckInferredResultType) 11988 EmitRelatedResultTypeNote(SrcExpr); 11989 11990 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 11991 EmitRelatedResultTypeNoteForReturn(DstType); 11992 11993 if (Complained) 11994 *Complained = true; 11995 return isInvalid; 11996 } 11997 11998 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 11999 llvm::APSInt *Result) { 12000 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12001 public: 12002 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12003 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12004 } 12005 } Diagnoser; 12006 12007 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12008 } 12009 12010 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12011 llvm::APSInt *Result, 12012 unsigned DiagID, 12013 bool AllowFold) { 12014 class IDDiagnoser : public VerifyICEDiagnoser { 12015 unsigned DiagID; 12016 12017 public: 12018 IDDiagnoser(unsigned DiagID) 12019 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12020 12021 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12022 S.Diag(Loc, DiagID) << SR; 12023 } 12024 } Diagnoser(DiagID); 12025 12026 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12027 } 12028 12029 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12030 SourceRange SR) { 12031 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12032 } 12033 12034 ExprResult 12035 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12036 VerifyICEDiagnoser &Diagnoser, 12037 bool AllowFold) { 12038 SourceLocation DiagLoc = E->getLocStart(); 12039 12040 if (getLangOpts().CPlusPlus11) { 12041 // C++11 [expr.const]p5: 12042 // If an expression of literal class type is used in a context where an 12043 // integral constant expression is required, then that class type shall 12044 // have a single non-explicit conversion function to an integral or 12045 // unscoped enumeration type 12046 ExprResult Converted; 12047 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12048 public: 12049 CXX11ConvertDiagnoser(bool Silent) 12050 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12051 Silent, true) {} 12052 12053 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12054 QualType T) override { 12055 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12056 } 12057 12058 SemaDiagnosticBuilder diagnoseIncomplete( 12059 Sema &S, SourceLocation Loc, QualType T) override { 12060 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12061 } 12062 12063 SemaDiagnosticBuilder diagnoseExplicitConv( 12064 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12065 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12066 } 12067 12068 SemaDiagnosticBuilder noteExplicitConv( 12069 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12070 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12071 << ConvTy->isEnumeralType() << ConvTy; 12072 } 12073 12074 SemaDiagnosticBuilder diagnoseAmbiguous( 12075 Sema &S, SourceLocation Loc, QualType T) override { 12076 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12077 } 12078 12079 SemaDiagnosticBuilder noteAmbiguous( 12080 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12081 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12082 << ConvTy->isEnumeralType() << ConvTy; 12083 } 12084 12085 SemaDiagnosticBuilder diagnoseConversion( 12086 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12087 llvm_unreachable("conversion functions are permitted"); 12088 } 12089 } ConvertDiagnoser(Diagnoser.Suppress); 12090 12091 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12092 ConvertDiagnoser); 12093 if (Converted.isInvalid()) 12094 return Converted; 12095 E = Converted.get(); 12096 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12097 return ExprError(); 12098 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12099 // An ICE must be of integral or unscoped enumeration type. 12100 if (!Diagnoser.Suppress) 12101 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12102 return ExprError(); 12103 } 12104 12105 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12106 // in the non-ICE case. 12107 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12108 if (Result) 12109 *Result = E->EvaluateKnownConstInt(Context); 12110 return E; 12111 } 12112 12113 Expr::EvalResult EvalResult; 12114 SmallVector<PartialDiagnosticAt, 8> Notes; 12115 EvalResult.Diag = &Notes; 12116 12117 // Try to evaluate the expression, and produce diagnostics explaining why it's 12118 // not a constant expression as a side-effect. 12119 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12120 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12121 12122 // In C++11, we can rely on diagnostics being produced for any expression 12123 // which is not a constant expression. If no diagnostics were produced, then 12124 // this is a constant expression. 12125 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12126 if (Result) 12127 *Result = EvalResult.Val.getInt(); 12128 return E; 12129 } 12130 12131 // If our only note is the usual "invalid subexpression" note, just point 12132 // the caret at its location rather than producing an essentially 12133 // redundant note. 12134 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12135 diag::note_invalid_subexpr_in_const_expr) { 12136 DiagLoc = Notes[0].first; 12137 Notes.clear(); 12138 } 12139 12140 if (!Folded || !AllowFold) { 12141 if (!Diagnoser.Suppress) { 12142 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12143 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12144 Diag(Notes[I].first, Notes[I].second); 12145 } 12146 12147 return ExprError(); 12148 } 12149 12150 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 12151 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12152 Diag(Notes[I].first, Notes[I].second); 12153 12154 if (Result) 12155 *Result = EvalResult.Val.getInt(); 12156 return E; 12157 } 12158 12159 namespace { 12160 // Handle the case where we conclude a expression which we speculatively 12161 // considered to be unevaluated is actually evaluated. 12162 class TransformToPE : public TreeTransform<TransformToPE> { 12163 typedef TreeTransform<TransformToPE> BaseTransform; 12164 12165 public: 12166 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 12167 12168 // Make sure we redo semantic analysis 12169 bool AlwaysRebuild() { return true; } 12170 12171 // Make sure we handle LabelStmts correctly. 12172 // FIXME: This does the right thing, but maybe we need a more general 12173 // fix to TreeTransform? 12174 StmtResult TransformLabelStmt(LabelStmt *S) { 12175 S->getDecl()->setStmt(nullptr); 12176 return BaseTransform::TransformLabelStmt(S); 12177 } 12178 12179 // We need to special-case DeclRefExprs referring to FieldDecls which 12180 // are not part of a member pointer formation; normal TreeTransforming 12181 // doesn't catch this case because of the way we represent them in the AST. 12182 // FIXME: This is a bit ugly; is it really the best way to handle this 12183 // case? 12184 // 12185 // Error on DeclRefExprs referring to FieldDecls. 12186 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 12187 if (isa<FieldDecl>(E->getDecl()) && 12188 !SemaRef.isUnevaluatedContext()) 12189 return SemaRef.Diag(E->getLocation(), 12190 diag::err_invalid_non_static_member_use) 12191 << E->getDecl() << E->getSourceRange(); 12192 12193 return BaseTransform::TransformDeclRefExpr(E); 12194 } 12195 12196 // Exception: filter out member pointer formation 12197 ExprResult TransformUnaryOperator(UnaryOperator *E) { 12198 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 12199 return E; 12200 12201 return BaseTransform::TransformUnaryOperator(E); 12202 } 12203 12204 ExprResult TransformLambdaExpr(LambdaExpr *E) { 12205 // Lambdas never need to be transformed. 12206 return E; 12207 } 12208 }; 12209 } 12210 12211 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 12212 assert(isUnevaluatedContext() && 12213 "Should only transform unevaluated expressions"); 12214 ExprEvalContexts.back().Context = 12215 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 12216 if (isUnevaluatedContext()) 12217 return E; 12218 return TransformToPE(*this).TransformExpr(E); 12219 } 12220 12221 void 12222 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12223 Decl *LambdaContextDecl, 12224 bool IsDecltype) { 12225 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), 12226 ExprNeedsCleanups, LambdaContextDecl, 12227 IsDecltype); 12228 ExprNeedsCleanups = false; 12229 if (!MaybeODRUseExprs.empty()) 12230 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 12231 } 12232 12233 void 12234 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12235 ReuseLambdaContextDecl_t, 12236 bool IsDecltype) { 12237 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 12238 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 12239 } 12240 12241 void Sema::PopExpressionEvaluationContext() { 12242 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 12243 unsigned NumTypos = Rec.NumTypos; 12244 12245 if (!Rec.Lambdas.empty()) { 12246 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12247 unsigned D; 12248 if (Rec.isUnevaluated()) { 12249 // C++11 [expr.prim.lambda]p2: 12250 // A lambda-expression shall not appear in an unevaluated operand 12251 // (Clause 5). 12252 D = diag::err_lambda_unevaluated_operand; 12253 } else { 12254 // C++1y [expr.const]p2: 12255 // A conditional-expression e is a core constant expression unless the 12256 // evaluation of e, following the rules of the abstract machine, would 12257 // evaluate [...] a lambda-expression. 12258 D = diag::err_lambda_in_constant_expression; 12259 } 12260 for (const auto *L : Rec.Lambdas) 12261 Diag(L->getLocStart(), D); 12262 } else { 12263 // Mark the capture expressions odr-used. This was deferred 12264 // during lambda expression creation. 12265 for (auto *Lambda : Rec.Lambdas) { 12266 for (auto *C : Lambda->capture_inits()) 12267 MarkDeclarationsReferencedInExpr(C); 12268 } 12269 } 12270 } 12271 12272 // When are coming out of an unevaluated context, clear out any 12273 // temporaries that we may have created as part of the evaluation of 12274 // the expression in that context: they aren't relevant because they 12275 // will never be constructed. 12276 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12277 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 12278 ExprCleanupObjects.end()); 12279 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 12280 CleanupVarDeclMarking(); 12281 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 12282 // Otherwise, merge the contexts together. 12283 } else { 12284 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 12285 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 12286 Rec.SavedMaybeODRUseExprs.end()); 12287 } 12288 12289 // Pop the current expression evaluation context off the stack. 12290 ExprEvalContexts.pop_back(); 12291 12292 if (!ExprEvalContexts.empty()) 12293 ExprEvalContexts.back().NumTypos += NumTypos; 12294 else 12295 assert(NumTypos == 0 && "There are outstanding typos after popping the " 12296 "last ExpressionEvaluationContextRecord"); 12297 } 12298 12299 void Sema::DiscardCleanupsInEvaluationContext() { 12300 ExprCleanupObjects.erase( 12301 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 12302 ExprCleanupObjects.end()); 12303 ExprNeedsCleanups = false; 12304 MaybeODRUseExprs.clear(); 12305 } 12306 12307 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 12308 if (!E->getType()->isVariablyModifiedType()) 12309 return E; 12310 return TransformToPotentiallyEvaluated(E); 12311 } 12312 12313 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 12314 // Do not mark anything as "used" within a dependent context; wait for 12315 // an instantiation. 12316 if (SemaRef.CurContext->isDependentContext()) 12317 return false; 12318 12319 switch (SemaRef.ExprEvalContexts.back().Context) { 12320 case Sema::Unevaluated: 12321 case Sema::UnevaluatedAbstract: 12322 // We are in an expression that is not potentially evaluated; do nothing. 12323 // (Depending on how you read the standard, we actually do need to do 12324 // something here for null pointer constants, but the standard's 12325 // definition of a null pointer constant is completely crazy.) 12326 return false; 12327 12328 case Sema::ConstantEvaluated: 12329 case Sema::PotentiallyEvaluated: 12330 // We are in a potentially evaluated expression (or a constant-expression 12331 // in C++03); we need to do implicit template instantiation, implicitly 12332 // define class members, and mark most declarations as used. 12333 return true; 12334 12335 case Sema::PotentiallyEvaluatedIfUsed: 12336 // Referenced declarations will only be used if the construct in the 12337 // containing expression is used. 12338 return false; 12339 } 12340 llvm_unreachable("Invalid context"); 12341 } 12342 12343 /// \brief Mark a function referenced, and check whether it is odr-used 12344 /// (C++ [basic.def.odr]p2, C99 6.9p3) 12345 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 12346 bool OdrUse) { 12347 assert(Func && "No function?"); 12348 12349 Func->setReferenced(); 12350 12351 // C++11 [basic.def.odr]p3: 12352 // A function whose name appears as a potentially-evaluated expression is 12353 // odr-used if it is the unique lookup result or the selected member of a 12354 // set of overloaded functions [...]. 12355 // 12356 // We (incorrectly) mark overload resolution as an unevaluated context, so we 12357 // can just check that here. Skip the rest of this function if we've already 12358 // marked the function as used. 12359 if (Func->isUsed(/*CheckUsedAttr=*/false) || 12360 !IsPotentiallyEvaluatedContext(*this)) { 12361 // C++11 [temp.inst]p3: 12362 // Unless a function template specialization has been explicitly 12363 // instantiated or explicitly specialized, the function template 12364 // specialization is implicitly instantiated when the specialization is 12365 // referenced in a context that requires a function definition to exist. 12366 // 12367 // We consider constexpr function templates to be referenced in a context 12368 // that requires a definition to exist whenever they are referenced. 12369 // 12370 // FIXME: This instantiates constexpr functions too frequently. If this is 12371 // really an unevaluated context (and we're not just in the definition of a 12372 // function template or overload resolution or other cases which we 12373 // incorrectly consider to be unevaluated contexts), and we're not in a 12374 // subexpression which we actually need to evaluate (for instance, a 12375 // template argument, array bound or an expression in a braced-init-list), 12376 // we are not permitted to instantiate this constexpr function definition. 12377 // 12378 // FIXME: This also implicitly defines special members too frequently. They 12379 // are only supposed to be implicitly defined if they are odr-used, but they 12380 // are not odr-used from constant expressions in unevaluated contexts. 12381 // However, they cannot be referenced if they are deleted, and they are 12382 // deleted whenever the implicit definition of the special member would 12383 // fail. 12384 if (!Func->isConstexpr() || Func->getBody()) 12385 return; 12386 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 12387 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 12388 return; 12389 } 12390 12391 // Note that this declaration has been used. 12392 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 12393 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 12394 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 12395 if (Constructor->isDefaultConstructor()) { 12396 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 12397 return; 12398 DefineImplicitDefaultConstructor(Loc, Constructor); 12399 } else if (Constructor->isCopyConstructor()) { 12400 DefineImplicitCopyConstructor(Loc, Constructor); 12401 } else if (Constructor->isMoveConstructor()) { 12402 DefineImplicitMoveConstructor(Loc, Constructor); 12403 } 12404 } else if (Constructor->getInheritedConstructor()) { 12405 DefineInheritingConstructor(Loc, Constructor); 12406 } 12407 } else if (CXXDestructorDecl *Destructor = 12408 dyn_cast<CXXDestructorDecl>(Func)) { 12409 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 12410 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 12411 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 12412 return; 12413 DefineImplicitDestructor(Loc, Destructor); 12414 } 12415 if (Destructor->isVirtual() && getLangOpts().AppleKext) 12416 MarkVTableUsed(Loc, Destructor->getParent()); 12417 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 12418 if (MethodDecl->isOverloadedOperator() && 12419 MethodDecl->getOverloadedOperator() == OO_Equal) { 12420 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 12421 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 12422 if (MethodDecl->isCopyAssignmentOperator()) 12423 DefineImplicitCopyAssignment(Loc, MethodDecl); 12424 else 12425 DefineImplicitMoveAssignment(Loc, MethodDecl); 12426 } 12427 } else if (isa<CXXConversionDecl>(MethodDecl) && 12428 MethodDecl->getParent()->isLambda()) { 12429 CXXConversionDecl *Conversion = 12430 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 12431 if (Conversion->isLambdaToBlockPointerConversion()) 12432 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 12433 else 12434 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 12435 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 12436 MarkVTableUsed(Loc, MethodDecl->getParent()); 12437 } 12438 12439 // Recursive functions should be marked when used from another function. 12440 // FIXME: Is this really right? 12441 if (CurContext == Func) return; 12442 12443 // Resolve the exception specification for any function which is 12444 // used: CodeGen will need it. 12445 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 12446 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 12447 ResolveExceptionSpec(Loc, FPT); 12448 12449 if (!OdrUse) return; 12450 12451 // Implicit instantiation of function templates and member functions of 12452 // class templates. 12453 if (Func->isImplicitlyInstantiable()) { 12454 bool AlreadyInstantiated = false; 12455 SourceLocation PointOfInstantiation = Loc; 12456 if (FunctionTemplateSpecializationInfo *SpecInfo 12457 = Func->getTemplateSpecializationInfo()) { 12458 if (SpecInfo->getPointOfInstantiation().isInvalid()) 12459 SpecInfo->setPointOfInstantiation(Loc); 12460 else if (SpecInfo->getTemplateSpecializationKind() 12461 == TSK_ImplicitInstantiation) { 12462 AlreadyInstantiated = true; 12463 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 12464 } 12465 } else if (MemberSpecializationInfo *MSInfo 12466 = Func->getMemberSpecializationInfo()) { 12467 if (MSInfo->getPointOfInstantiation().isInvalid()) 12468 MSInfo->setPointOfInstantiation(Loc); 12469 else if (MSInfo->getTemplateSpecializationKind() 12470 == TSK_ImplicitInstantiation) { 12471 AlreadyInstantiated = true; 12472 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 12473 } 12474 } 12475 12476 if (!AlreadyInstantiated || Func->isConstexpr()) { 12477 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 12478 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 12479 ActiveTemplateInstantiations.size()) 12480 PendingLocalImplicitInstantiations.push_back( 12481 std::make_pair(Func, PointOfInstantiation)); 12482 else if (Func->isConstexpr()) 12483 // Do not defer instantiations of constexpr functions, to avoid the 12484 // expression evaluator needing to call back into Sema if it sees a 12485 // call to such a function. 12486 InstantiateFunctionDefinition(PointOfInstantiation, Func); 12487 else { 12488 PendingInstantiations.push_back(std::make_pair(Func, 12489 PointOfInstantiation)); 12490 // Notify the consumer that a function was implicitly instantiated. 12491 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 12492 } 12493 } 12494 } else { 12495 // Walk redefinitions, as some of them may be instantiable. 12496 for (auto i : Func->redecls()) { 12497 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 12498 MarkFunctionReferenced(Loc, i); 12499 } 12500 } 12501 12502 // Keep track of used but undefined functions. 12503 if (!Func->isDefined()) { 12504 if (mightHaveNonExternalLinkage(Func)) 12505 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 12506 else if (Func->getMostRecentDecl()->isInlined() && 12507 !LangOpts.GNUInline && 12508 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 12509 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 12510 } 12511 12512 // Normally the most current decl is marked used while processing the use and 12513 // any subsequent decls are marked used by decl merging. This fails with 12514 // template instantiation since marking can happen at the end of the file 12515 // and, because of the two phase lookup, this function is called with at 12516 // decl in the middle of a decl chain. We loop to maintain the invariant 12517 // that once a decl is used, all decls after it are also used. 12518 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 12519 F->markUsed(Context); 12520 if (F == Func) 12521 break; 12522 } 12523 } 12524 12525 static void 12526 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 12527 VarDecl *var, DeclContext *DC) { 12528 DeclContext *VarDC = var->getDeclContext(); 12529 12530 // If the parameter still belongs to the translation unit, then 12531 // we're actually just using one parameter in the declaration of 12532 // the next. 12533 if (isa<ParmVarDecl>(var) && 12534 isa<TranslationUnitDecl>(VarDC)) 12535 return; 12536 12537 // For C code, don't diagnose about capture if we're not actually in code 12538 // right now; it's impossible to write a non-constant expression outside of 12539 // function context, so we'll get other (more useful) diagnostics later. 12540 // 12541 // For C++, things get a bit more nasty... it would be nice to suppress this 12542 // diagnostic for certain cases like using a local variable in an array bound 12543 // for a member of a local class, but the correct predicate is not obvious. 12544 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 12545 return; 12546 12547 if (isa<CXXMethodDecl>(VarDC) && 12548 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 12549 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 12550 << var->getIdentifier(); 12551 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 12552 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 12553 << var->getIdentifier() << fn->getDeclName(); 12554 } else if (isa<BlockDecl>(VarDC)) { 12555 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 12556 << var->getIdentifier(); 12557 } else { 12558 // FIXME: Is there any other context where a local variable can be 12559 // declared? 12560 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 12561 << var->getIdentifier(); 12562 } 12563 12564 S.Diag(var->getLocation(), diag::note_entity_declared_at) 12565 << var->getIdentifier(); 12566 12567 // FIXME: Add additional diagnostic info about class etc. which prevents 12568 // capture. 12569 } 12570 12571 12572 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 12573 bool &SubCapturesAreNested, 12574 QualType &CaptureType, 12575 QualType &DeclRefType) { 12576 // Check whether we've already captured it. 12577 if (CSI->CaptureMap.count(Var)) { 12578 // If we found a capture, any subcaptures are nested. 12579 SubCapturesAreNested = true; 12580 12581 // Retrieve the capture type for this variable. 12582 CaptureType = CSI->getCapture(Var).getCaptureType(); 12583 12584 // Compute the type of an expression that refers to this variable. 12585 DeclRefType = CaptureType.getNonReferenceType(); 12586 12587 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 12588 if (Cap.isCopyCapture() && 12589 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable)) 12590 DeclRefType.addConst(); 12591 return true; 12592 } 12593 return false; 12594 } 12595 12596 // Only block literals, captured statements, and lambda expressions can 12597 // capture; other scopes don't work. 12598 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 12599 SourceLocation Loc, 12600 const bool Diagnose, Sema &S) { 12601 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 12602 return getLambdaAwareParentOfDeclContext(DC); 12603 else if (Var->hasLocalStorage()) { 12604 if (Diagnose) 12605 diagnoseUncapturableValueReference(S, Loc, Var, DC); 12606 } 12607 return nullptr; 12608 } 12609 12610 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 12611 // certain types of variables (unnamed, variably modified types etc.) 12612 // so check for eligibility. 12613 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 12614 SourceLocation Loc, 12615 const bool Diagnose, Sema &S) { 12616 12617 bool IsBlock = isa<BlockScopeInfo>(CSI); 12618 bool IsLambda = isa<LambdaScopeInfo>(CSI); 12619 12620 // Lambdas are not allowed to capture unnamed variables 12621 // (e.g. anonymous unions). 12622 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 12623 // assuming that's the intent. 12624 if (IsLambda && !Var->getDeclName()) { 12625 if (Diagnose) { 12626 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 12627 S.Diag(Var->getLocation(), diag::note_declared_at); 12628 } 12629 return false; 12630 } 12631 12632 // Prohibit variably-modified types in blocks; they're difficult to deal with. 12633 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 12634 if (Diagnose) { 12635 S.Diag(Loc, diag::err_ref_vm_type); 12636 S.Diag(Var->getLocation(), diag::note_previous_decl) 12637 << Var->getDeclName(); 12638 } 12639 return false; 12640 } 12641 // Prohibit structs with flexible array members too. 12642 // We cannot capture what is in the tail end of the struct. 12643 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 12644 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 12645 if (Diagnose) { 12646 if (IsBlock) 12647 S.Diag(Loc, diag::err_ref_flexarray_type); 12648 else 12649 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 12650 << Var->getDeclName(); 12651 S.Diag(Var->getLocation(), diag::note_previous_decl) 12652 << Var->getDeclName(); 12653 } 12654 return false; 12655 } 12656 } 12657 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 12658 // Lambdas and captured statements are not allowed to capture __block 12659 // variables; they don't support the expected semantics. 12660 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 12661 if (Diagnose) { 12662 S.Diag(Loc, diag::err_capture_block_variable) 12663 << Var->getDeclName() << !IsLambda; 12664 S.Diag(Var->getLocation(), diag::note_previous_decl) 12665 << Var->getDeclName(); 12666 } 12667 return false; 12668 } 12669 12670 return true; 12671 } 12672 12673 // Returns true if the capture by block was successful. 12674 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 12675 SourceLocation Loc, 12676 const bool BuildAndDiagnose, 12677 QualType &CaptureType, 12678 QualType &DeclRefType, 12679 const bool Nested, 12680 Sema &S) { 12681 Expr *CopyExpr = nullptr; 12682 bool ByRef = false; 12683 12684 // Blocks are not allowed to capture arrays. 12685 if (CaptureType->isArrayType()) { 12686 if (BuildAndDiagnose) { 12687 S.Diag(Loc, diag::err_ref_array_type); 12688 S.Diag(Var->getLocation(), diag::note_previous_decl) 12689 << Var->getDeclName(); 12690 } 12691 return false; 12692 } 12693 12694 // Forbid the block-capture of autoreleasing variables. 12695 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 12696 if (BuildAndDiagnose) { 12697 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 12698 << /*block*/ 0; 12699 S.Diag(Var->getLocation(), diag::note_previous_decl) 12700 << Var->getDeclName(); 12701 } 12702 return false; 12703 } 12704 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 12705 if (HasBlocksAttr || CaptureType->isReferenceType()) { 12706 // Block capture by reference does not change the capture or 12707 // declaration reference types. 12708 ByRef = true; 12709 } else { 12710 // Block capture by copy introduces 'const'. 12711 CaptureType = CaptureType.getNonReferenceType().withConst(); 12712 DeclRefType = CaptureType; 12713 12714 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 12715 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 12716 // The capture logic needs the destructor, so make sure we mark it. 12717 // Usually this is unnecessary because most local variables have 12718 // their destructors marked at declaration time, but parameters are 12719 // an exception because it's technically only the call site that 12720 // actually requires the destructor. 12721 if (isa<ParmVarDecl>(Var)) 12722 S.FinalizeVarWithDestructor(Var, Record); 12723 12724 // Enter a new evaluation context to insulate the copy 12725 // full-expression. 12726 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 12727 12728 // According to the blocks spec, the capture of a variable from 12729 // the stack requires a const copy constructor. This is not true 12730 // of the copy/move done to move a __block variable to the heap. 12731 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 12732 DeclRefType.withConst(), 12733 VK_LValue, Loc); 12734 12735 ExprResult Result 12736 = S.PerformCopyInitialization( 12737 InitializedEntity::InitializeBlock(Var->getLocation(), 12738 CaptureType, false), 12739 Loc, DeclRef); 12740 12741 // Build a full-expression copy expression if initialization 12742 // succeeded and used a non-trivial constructor. Recover from 12743 // errors by pretending that the copy isn't necessary. 12744 if (!Result.isInvalid() && 12745 !cast<CXXConstructExpr>(Result.get())->getConstructor() 12746 ->isTrivial()) { 12747 Result = S.MaybeCreateExprWithCleanups(Result); 12748 CopyExpr = Result.get(); 12749 } 12750 } 12751 } 12752 } 12753 12754 // Actually capture the variable. 12755 if (BuildAndDiagnose) 12756 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 12757 SourceLocation(), CaptureType, CopyExpr); 12758 12759 return true; 12760 12761 } 12762 12763 12764 /// \brief Capture the given variable in the captured region. 12765 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 12766 VarDecl *Var, 12767 SourceLocation Loc, 12768 const bool BuildAndDiagnose, 12769 QualType &CaptureType, 12770 QualType &DeclRefType, 12771 const bool RefersToCapturedVariable, 12772 Sema &S) { 12773 12774 // By default, capture variables by reference. 12775 bool ByRef = true; 12776 // Using an LValue reference type is consistent with Lambdas (see below). 12777 if (S.getLangOpts().OpenMP && S.IsOpenMPCapturedVar(Var)) 12778 DeclRefType = DeclRefType.getUnqualifiedType(); 12779 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 12780 Expr *CopyExpr = nullptr; 12781 if (BuildAndDiagnose) { 12782 // The current implementation assumes that all variables are captured 12783 // by references. Since there is no capture by copy, no expression 12784 // evaluation will be needed. 12785 RecordDecl *RD = RSI->TheRecordDecl; 12786 12787 FieldDecl *Field 12788 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 12789 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 12790 nullptr, false, ICIS_NoInit); 12791 Field->setImplicit(true); 12792 Field->setAccess(AS_private); 12793 RD->addDecl(Field); 12794 12795 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 12796 DeclRefType, VK_LValue, Loc); 12797 Var->setReferenced(true); 12798 Var->markUsed(S.Context); 12799 } 12800 12801 // Actually capture the variable. 12802 if (BuildAndDiagnose) 12803 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 12804 SourceLocation(), CaptureType, CopyExpr); 12805 12806 12807 return true; 12808 } 12809 12810 /// \brief Create a field within the lambda class for the variable 12811 /// being captured. 12812 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, VarDecl *Var, 12813 QualType FieldType, QualType DeclRefType, 12814 SourceLocation Loc, 12815 bool RefersToCapturedVariable) { 12816 CXXRecordDecl *Lambda = LSI->Lambda; 12817 12818 // Build the non-static data member. 12819 FieldDecl *Field 12820 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 12821 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 12822 nullptr, false, ICIS_NoInit); 12823 Field->setImplicit(true); 12824 Field->setAccess(AS_private); 12825 Lambda->addDecl(Field); 12826 } 12827 12828 /// \brief Capture the given variable in the lambda. 12829 static bool captureInLambda(LambdaScopeInfo *LSI, 12830 VarDecl *Var, 12831 SourceLocation Loc, 12832 const bool BuildAndDiagnose, 12833 QualType &CaptureType, 12834 QualType &DeclRefType, 12835 const bool RefersToCapturedVariable, 12836 const Sema::TryCaptureKind Kind, 12837 SourceLocation EllipsisLoc, 12838 const bool IsTopScope, 12839 Sema &S) { 12840 12841 // Determine whether we are capturing by reference or by value. 12842 bool ByRef = false; 12843 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 12844 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 12845 } else { 12846 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 12847 } 12848 12849 // Compute the type of the field that will capture this variable. 12850 if (ByRef) { 12851 // C++11 [expr.prim.lambda]p15: 12852 // An entity is captured by reference if it is implicitly or 12853 // explicitly captured but not captured by copy. It is 12854 // unspecified whether additional unnamed non-static data 12855 // members are declared in the closure type for entities 12856 // captured by reference. 12857 // 12858 // FIXME: It is not clear whether we want to build an lvalue reference 12859 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 12860 // to do the former, while EDG does the latter. Core issue 1249 will 12861 // clarify, but for now we follow GCC because it's a more permissive and 12862 // easily defensible position. 12863 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 12864 } else { 12865 // C++11 [expr.prim.lambda]p14: 12866 // For each entity captured by copy, an unnamed non-static 12867 // data member is declared in the closure type. The 12868 // declaration order of these members is unspecified. The type 12869 // of such a data member is the type of the corresponding 12870 // captured entity if the entity is not a reference to an 12871 // object, or the referenced type otherwise. [Note: If the 12872 // captured entity is a reference to a function, the 12873 // corresponding data member is also a reference to a 12874 // function. - end note ] 12875 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 12876 if (!RefType->getPointeeType()->isFunctionType()) 12877 CaptureType = RefType->getPointeeType(); 12878 } 12879 12880 // Forbid the lambda copy-capture of autoreleasing variables. 12881 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 12882 if (BuildAndDiagnose) { 12883 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 12884 S.Diag(Var->getLocation(), diag::note_previous_decl) 12885 << Var->getDeclName(); 12886 } 12887 return false; 12888 } 12889 12890 // Make sure that by-copy captures are of a complete and non-abstract type. 12891 if (BuildAndDiagnose) { 12892 if (!CaptureType->isDependentType() && 12893 S.RequireCompleteType(Loc, CaptureType, 12894 diag::err_capture_of_incomplete_type, 12895 Var->getDeclName())) 12896 return false; 12897 12898 if (S.RequireNonAbstractType(Loc, CaptureType, 12899 diag::err_capture_of_abstract_type)) 12900 return false; 12901 } 12902 } 12903 12904 // Capture this variable in the lambda. 12905 if (BuildAndDiagnose) 12906 addAsFieldToClosureType(S, LSI, Var, CaptureType, DeclRefType, Loc, 12907 RefersToCapturedVariable); 12908 12909 // Compute the type of a reference to this captured variable. 12910 if (ByRef) 12911 DeclRefType = CaptureType.getNonReferenceType(); 12912 else { 12913 // C++ [expr.prim.lambda]p5: 12914 // The closure type for a lambda-expression has a public inline 12915 // function call operator [...]. This function call operator is 12916 // declared const (9.3.1) if and only if the lambda-expression’s 12917 // parameter-declaration-clause is not followed by mutable. 12918 DeclRefType = CaptureType.getNonReferenceType(); 12919 if (!LSI->Mutable && !CaptureType->isReferenceType()) 12920 DeclRefType.addConst(); 12921 } 12922 12923 // Add the capture. 12924 if (BuildAndDiagnose) 12925 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 12926 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 12927 12928 return true; 12929 } 12930 12931 bool Sema::tryCaptureVariable( 12932 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 12933 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 12934 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 12935 // An init-capture is notionally from the context surrounding its 12936 // declaration, but its parent DC is the lambda class. 12937 DeclContext *VarDC = Var->getDeclContext(); 12938 if (Var->isInitCapture()) 12939 VarDC = VarDC->getParent(); 12940 12941 DeclContext *DC = CurContext; 12942 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 12943 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 12944 // We need to sync up the Declaration Context with the 12945 // FunctionScopeIndexToStopAt 12946 if (FunctionScopeIndexToStopAt) { 12947 unsigned FSIndex = FunctionScopes.size() - 1; 12948 while (FSIndex != MaxFunctionScopesIndex) { 12949 DC = getLambdaAwareParentOfDeclContext(DC); 12950 --FSIndex; 12951 } 12952 } 12953 12954 12955 // If the variable is declared in the current context, there is no need to 12956 // capture it. 12957 if (VarDC == DC) return true; 12958 12959 // Capture global variables if it is required to use private copy of this 12960 // variable. 12961 bool IsGlobal = !Var->hasLocalStorage(); 12962 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedVar(Var))) 12963 return true; 12964 12965 // Walk up the stack to determine whether we can capture the variable, 12966 // performing the "simple" checks that don't depend on type. We stop when 12967 // we've either hit the declared scope of the variable or find an existing 12968 // capture of that variable. We start from the innermost capturing-entity 12969 // (the DC) and ensure that all intervening capturing-entities 12970 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 12971 // declcontext can either capture the variable or have already captured 12972 // the variable. 12973 CaptureType = Var->getType(); 12974 DeclRefType = CaptureType.getNonReferenceType(); 12975 bool Nested = false; 12976 bool Explicit = (Kind != TryCapture_Implicit); 12977 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 12978 unsigned OpenMPLevel = 0; 12979 do { 12980 // Only block literals, captured statements, and lambda expressions can 12981 // capture; other scopes don't work. 12982 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 12983 ExprLoc, 12984 BuildAndDiagnose, 12985 *this); 12986 // We need to check for the parent *first* because, if we *have* 12987 // private-captured a global variable, we need to recursively capture it in 12988 // intermediate blocks, lambdas, etc. 12989 if (!ParentDC) { 12990 if (IsGlobal) { 12991 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 12992 break; 12993 } 12994 return true; 12995 } 12996 12997 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 12998 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 12999 13000 13001 // Check whether we've already captured it. 13002 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13003 DeclRefType)) 13004 break; 13005 if (getLangOpts().OpenMP) { 13006 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13007 // OpenMP private variables should not be captured in outer scope, so 13008 // just break here. 13009 if (RSI->CapRegionKind == CR_OpenMP) { 13010 if (isOpenMPPrivateVar(Var, OpenMPLevel)) { 13011 Nested = true; 13012 DeclRefType = DeclRefType.getUnqualifiedType(); 13013 CaptureType = Context.getLValueReferenceType(DeclRefType); 13014 break; 13015 } 13016 ++OpenMPLevel; 13017 } 13018 } 13019 } 13020 // If we are instantiating a generic lambda call operator body, 13021 // we do not want to capture new variables. What was captured 13022 // during either a lambdas transformation or initial parsing 13023 // should be used. 13024 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13025 if (BuildAndDiagnose) { 13026 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13027 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13028 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13029 Diag(Var->getLocation(), diag::note_previous_decl) 13030 << Var->getDeclName(); 13031 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13032 } else 13033 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13034 } 13035 return true; 13036 } 13037 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13038 // certain types of variables (unnamed, variably modified types etc.) 13039 // so check for eligibility. 13040 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13041 return true; 13042 13043 // Try to capture variable-length arrays types. 13044 if (Var->getType()->isVariablyModifiedType()) { 13045 // We're going to walk down into the type and look for VLA 13046 // expressions. 13047 QualType QTy = Var->getType(); 13048 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13049 QTy = PVD->getOriginalType(); 13050 do { 13051 const Type *Ty = QTy.getTypePtr(); 13052 switch (Ty->getTypeClass()) { 13053 #define TYPE(Class, Base) 13054 #define ABSTRACT_TYPE(Class, Base) 13055 #define NON_CANONICAL_TYPE(Class, Base) 13056 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 13057 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 13058 #include "clang/AST/TypeNodes.def" 13059 QTy = QualType(); 13060 break; 13061 // These types are never variably-modified. 13062 case Type::Builtin: 13063 case Type::Complex: 13064 case Type::Vector: 13065 case Type::ExtVector: 13066 case Type::Record: 13067 case Type::Enum: 13068 case Type::Elaborated: 13069 case Type::TemplateSpecialization: 13070 case Type::ObjCObject: 13071 case Type::ObjCInterface: 13072 case Type::ObjCObjectPointer: 13073 llvm_unreachable("type class is never variably-modified!"); 13074 case Type::Adjusted: 13075 QTy = cast<AdjustedType>(Ty)->getOriginalType(); 13076 break; 13077 case Type::Decayed: 13078 QTy = cast<DecayedType>(Ty)->getPointeeType(); 13079 break; 13080 case Type::Pointer: 13081 QTy = cast<PointerType>(Ty)->getPointeeType(); 13082 break; 13083 case Type::BlockPointer: 13084 QTy = cast<BlockPointerType>(Ty)->getPointeeType(); 13085 break; 13086 case Type::LValueReference: 13087 case Type::RValueReference: 13088 QTy = cast<ReferenceType>(Ty)->getPointeeType(); 13089 break; 13090 case Type::MemberPointer: 13091 QTy = cast<MemberPointerType>(Ty)->getPointeeType(); 13092 break; 13093 case Type::ConstantArray: 13094 case Type::IncompleteArray: 13095 // Losing element qualification here is fine. 13096 QTy = cast<ArrayType>(Ty)->getElementType(); 13097 break; 13098 case Type::VariableArray: { 13099 // Losing element qualification here is fine. 13100 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 13101 13102 // Unknown size indication requires no size computation. 13103 // Otherwise, evaluate and record it. 13104 if (auto Size = VAT->getSizeExpr()) { 13105 if (!CSI->isVLATypeCaptured(VAT)) { 13106 RecordDecl *CapRecord = nullptr; 13107 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 13108 CapRecord = LSI->Lambda; 13109 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13110 CapRecord = CRSI->TheRecordDecl; 13111 } 13112 if (CapRecord) { 13113 auto ExprLoc = Size->getExprLoc(); 13114 auto SizeType = Context.getSizeType(); 13115 // Build the non-static data member. 13116 auto Field = FieldDecl::Create( 13117 Context, CapRecord, ExprLoc, ExprLoc, 13118 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 13119 /*BW*/ nullptr, /*Mutable*/ false, 13120 /*InitStyle*/ ICIS_NoInit); 13121 Field->setImplicit(true); 13122 Field->setAccess(AS_private); 13123 Field->setCapturedVLAType(VAT); 13124 CapRecord->addDecl(Field); 13125 13126 CSI->addVLATypeCapture(ExprLoc, SizeType); 13127 } 13128 } 13129 } 13130 QTy = VAT->getElementType(); 13131 break; 13132 } 13133 case Type::FunctionProto: 13134 case Type::FunctionNoProto: 13135 QTy = cast<FunctionType>(Ty)->getReturnType(); 13136 break; 13137 case Type::Paren: 13138 case Type::TypeOf: 13139 case Type::UnaryTransform: 13140 case Type::Attributed: 13141 case Type::SubstTemplateTypeParm: 13142 case Type::PackExpansion: 13143 // Keep walking after single level desugaring. 13144 QTy = QTy.getSingleStepDesugaredType(getASTContext()); 13145 break; 13146 case Type::Typedef: 13147 QTy = cast<TypedefType>(Ty)->desugar(); 13148 break; 13149 case Type::Decltype: 13150 QTy = cast<DecltypeType>(Ty)->desugar(); 13151 break; 13152 case Type::Auto: 13153 QTy = cast<AutoType>(Ty)->getDeducedType(); 13154 break; 13155 case Type::TypeOfExpr: 13156 QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 13157 break; 13158 case Type::Atomic: 13159 QTy = cast<AtomicType>(Ty)->getValueType(); 13160 break; 13161 } 13162 } while (!QTy.isNull() && QTy->isVariablyModifiedType()); 13163 } 13164 13165 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 13166 // No capture-default, and this is not an explicit capture 13167 // so cannot capture this variable. 13168 if (BuildAndDiagnose) { 13169 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13170 Diag(Var->getLocation(), diag::note_previous_decl) 13171 << Var->getDeclName(); 13172 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 13173 diag::note_lambda_decl); 13174 // FIXME: If we error out because an outer lambda can not implicitly 13175 // capture a variable that an inner lambda explicitly captures, we 13176 // should have the inner lambda do the explicit capture - because 13177 // it makes for cleaner diagnostics later. This would purely be done 13178 // so that the diagnostic does not misleadingly claim that a variable 13179 // can not be captured by a lambda implicitly even though it is captured 13180 // explicitly. Suggestion: 13181 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 13182 // at the function head 13183 // - cache the StartingDeclContext - this must be a lambda 13184 // - captureInLambda in the innermost lambda the variable. 13185 } 13186 return true; 13187 } 13188 13189 FunctionScopesIndex--; 13190 DC = ParentDC; 13191 Explicit = false; 13192 } while (!VarDC->Equals(DC)); 13193 13194 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 13195 // computing the type of the capture at each step, checking type-specific 13196 // requirements, and adding captures if requested. 13197 // If the variable had already been captured previously, we start capturing 13198 // at the lambda nested within that one. 13199 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 13200 ++I) { 13201 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 13202 13203 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 13204 if (!captureInBlock(BSI, Var, ExprLoc, 13205 BuildAndDiagnose, CaptureType, 13206 DeclRefType, Nested, *this)) 13207 return true; 13208 Nested = true; 13209 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13210 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 13211 BuildAndDiagnose, CaptureType, 13212 DeclRefType, Nested, *this)) 13213 return true; 13214 Nested = true; 13215 } else { 13216 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13217 if (!captureInLambda(LSI, Var, ExprLoc, 13218 BuildAndDiagnose, CaptureType, 13219 DeclRefType, Nested, Kind, EllipsisLoc, 13220 /*IsTopScope*/I == N - 1, *this)) 13221 return true; 13222 Nested = true; 13223 } 13224 } 13225 return false; 13226 } 13227 13228 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 13229 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 13230 QualType CaptureType; 13231 QualType DeclRefType; 13232 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 13233 /*BuildAndDiagnose=*/true, CaptureType, 13234 DeclRefType, nullptr); 13235 } 13236 13237 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 13238 QualType CaptureType; 13239 QualType DeclRefType; 13240 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13241 /*BuildAndDiagnose=*/false, CaptureType, 13242 DeclRefType, nullptr); 13243 } 13244 13245 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 13246 QualType CaptureType; 13247 QualType DeclRefType; 13248 13249 // Determine whether we can capture this variable. 13250 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13251 /*BuildAndDiagnose=*/false, CaptureType, 13252 DeclRefType, nullptr)) 13253 return QualType(); 13254 13255 return DeclRefType; 13256 } 13257 13258 13259 13260 // If either the type of the variable or the initializer is dependent, 13261 // return false. Otherwise, determine whether the variable is a constant 13262 // expression. Use this if you need to know if a variable that might or 13263 // might not be dependent is truly a constant expression. 13264 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 13265 ASTContext &Context) { 13266 13267 if (Var->getType()->isDependentType()) 13268 return false; 13269 const VarDecl *DefVD = nullptr; 13270 Var->getAnyInitializer(DefVD); 13271 if (!DefVD) 13272 return false; 13273 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 13274 Expr *Init = cast<Expr>(Eval->Value); 13275 if (Init->isValueDependent()) 13276 return false; 13277 return IsVariableAConstantExpression(Var, Context); 13278 } 13279 13280 13281 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 13282 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 13283 // an object that satisfies the requirements for appearing in a 13284 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 13285 // is immediately applied." This function handles the lvalue-to-rvalue 13286 // conversion part. 13287 MaybeODRUseExprs.erase(E->IgnoreParens()); 13288 13289 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 13290 // to a variable that is a constant expression, and if so, identify it as 13291 // a reference to a variable that does not involve an odr-use of that 13292 // variable. 13293 if (LambdaScopeInfo *LSI = getCurLambda()) { 13294 Expr *SansParensExpr = E->IgnoreParens(); 13295 VarDecl *Var = nullptr; 13296 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 13297 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 13298 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 13299 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 13300 13301 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 13302 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 13303 } 13304 } 13305 13306 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 13307 Res = CorrectDelayedTyposInExpr(Res); 13308 13309 if (!Res.isUsable()) 13310 return Res; 13311 13312 // If a constant-expression is a reference to a variable where we delay 13313 // deciding whether it is an odr-use, just assume we will apply the 13314 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 13315 // (a non-type template argument), we have special handling anyway. 13316 UpdateMarkingForLValueToRValue(Res.get()); 13317 return Res; 13318 } 13319 13320 void Sema::CleanupVarDeclMarking() { 13321 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(), 13322 e = MaybeODRUseExprs.end(); 13323 i != e; ++i) { 13324 VarDecl *Var; 13325 SourceLocation Loc; 13326 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) { 13327 Var = cast<VarDecl>(DRE->getDecl()); 13328 Loc = DRE->getLocation(); 13329 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) { 13330 Var = cast<VarDecl>(ME->getMemberDecl()); 13331 Loc = ME->getMemberLoc(); 13332 } else { 13333 llvm_unreachable("Unexpected expression"); 13334 } 13335 13336 MarkVarDeclODRUsed(Var, Loc, *this, 13337 /*MaxFunctionScopeIndex Pointer*/ nullptr); 13338 } 13339 13340 MaybeODRUseExprs.clear(); 13341 } 13342 13343 13344 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 13345 VarDecl *Var, Expr *E) { 13346 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 13347 "Invalid Expr argument to DoMarkVarDeclReferenced"); 13348 Var->setReferenced(); 13349 13350 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 13351 bool MarkODRUsed = true; 13352 13353 // If the context is not potentially evaluated, this is not an odr-use and 13354 // does not trigger instantiation. 13355 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 13356 if (SemaRef.isUnevaluatedContext()) 13357 return; 13358 13359 // If we don't yet know whether this context is going to end up being an 13360 // evaluated context, and we're referencing a variable from an enclosing 13361 // scope, add a potential capture. 13362 // 13363 // FIXME: Is this necessary? These contexts are only used for default 13364 // arguments, where local variables can't be used. 13365 const bool RefersToEnclosingScope = 13366 (SemaRef.CurContext != Var->getDeclContext() && 13367 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 13368 if (RefersToEnclosingScope) { 13369 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 13370 // If a variable could potentially be odr-used, defer marking it so 13371 // until we finish analyzing the full expression for any 13372 // lvalue-to-rvalue 13373 // or discarded value conversions that would obviate odr-use. 13374 // Add it to the list of potential captures that will be analyzed 13375 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 13376 // unless the variable is a reference that was initialized by a constant 13377 // expression (this will never need to be captured or odr-used). 13378 assert(E && "Capture variable should be used in an expression."); 13379 if (!Var->getType()->isReferenceType() || 13380 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 13381 LSI->addPotentialCapture(E->IgnoreParens()); 13382 } 13383 } 13384 13385 if (!isTemplateInstantiation(TSK)) 13386 return; 13387 13388 // Instantiate, but do not mark as odr-used, variable templates. 13389 MarkODRUsed = false; 13390 } 13391 13392 VarTemplateSpecializationDecl *VarSpec = 13393 dyn_cast<VarTemplateSpecializationDecl>(Var); 13394 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 13395 "Can't instantiate a partial template specialization."); 13396 13397 // Perform implicit instantiation of static data members, static data member 13398 // templates of class templates, and variable template specializations. Delay 13399 // instantiations of variable templates, except for those that could be used 13400 // in a constant expression. 13401 if (isTemplateInstantiation(TSK)) { 13402 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 13403 13404 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 13405 if (Var->getPointOfInstantiation().isInvalid()) { 13406 // This is a modification of an existing AST node. Notify listeners. 13407 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 13408 L->StaticDataMemberInstantiated(Var); 13409 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 13410 // Don't bother trying to instantiate it again, unless we might need 13411 // its initializer before we get to the end of the TU. 13412 TryInstantiating = false; 13413 } 13414 13415 if (Var->getPointOfInstantiation().isInvalid()) 13416 Var->setTemplateSpecializationKind(TSK, Loc); 13417 13418 if (TryInstantiating) { 13419 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 13420 bool InstantiationDependent = false; 13421 bool IsNonDependent = 13422 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 13423 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 13424 : true; 13425 13426 // Do not instantiate specializations that are still type-dependent. 13427 if (IsNonDependent) { 13428 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 13429 // Do not defer instantiations of variables which could be used in a 13430 // constant expression. 13431 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 13432 } else { 13433 SemaRef.PendingInstantiations 13434 .push_back(std::make_pair(Var, PointOfInstantiation)); 13435 } 13436 } 13437 } 13438 } 13439 13440 if(!MarkODRUsed) return; 13441 13442 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 13443 // the requirements for appearing in a constant expression (5.19) and, if 13444 // it is an object, the lvalue-to-rvalue conversion (4.1) 13445 // is immediately applied." We check the first part here, and 13446 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 13447 // Note that we use the C++11 definition everywhere because nothing in 13448 // C++03 depends on whether we get the C++03 version correct. The second 13449 // part does not apply to references, since they are not objects. 13450 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 13451 // A reference initialized by a constant expression can never be 13452 // odr-used, so simply ignore it. 13453 if (!Var->getType()->isReferenceType()) 13454 SemaRef.MaybeODRUseExprs.insert(E); 13455 } else 13456 MarkVarDeclODRUsed(Var, Loc, SemaRef, 13457 /*MaxFunctionScopeIndex ptr*/ nullptr); 13458 } 13459 13460 /// \brief Mark a variable referenced, and check whether it is odr-used 13461 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 13462 /// used directly for normal expressions referring to VarDecl. 13463 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 13464 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 13465 } 13466 13467 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 13468 Decl *D, Expr *E, bool OdrUse) { 13469 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 13470 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 13471 return; 13472 } 13473 13474 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 13475 13476 // If this is a call to a method via a cast, also mark the method in the 13477 // derived class used in case codegen can devirtualize the call. 13478 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 13479 if (!ME) 13480 return; 13481 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 13482 if (!MD) 13483 return; 13484 // Only attempt to devirtualize if this is truly a virtual call. 13485 bool IsVirtualCall = MD->isVirtual() && 13486 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 13487 if (!IsVirtualCall) 13488 return; 13489 const Expr *Base = ME->getBase(); 13490 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 13491 if (!MostDerivedClassDecl) 13492 return; 13493 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 13494 if (!DM || DM->isPure()) 13495 return; 13496 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 13497 } 13498 13499 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 13500 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 13501 // TODO: update this with DR# once a defect report is filed. 13502 // C++11 defect. The address of a pure member should not be an ODR use, even 13503 // if it's a qualified reference. 13504 bool OdrUse = true; 13505 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 13506 if (Method->isVirtual()) 13507 OdrUse = false; 13508 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 13509 } 13510 13511 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 13512 void Sema::MarkMemberReferenced(MemberExpr *E) { 13513 // C++11 [basic.def.odr]p2: 13514 // A non-overloaded function whose name appears as a potentially-evaluated 13515 // expression or a member of a set of candidate functions, if selected by 13516 // overload resolution when referred to from a potentially-evaluated 13517 // expression, is odr-used, unless it is a pure virtual function and its 13518 // name is not explicitly qualified. 13519 bool OdrUse = true; 13520 if (E->performsVirtualDispatch(getLangOpts())) { 13521 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 13522 if (Method->isPure()) 13523 OdrUse = false; 13524 } 13525 SourceLocation Loc = E->getMemberLoc().isValid() ? 13526 E->getMemberLoc() : E->getLocStart(); 13527 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 13528 } 13529 13530 /// \brief Perform marking for a reference to an arbitrary declaration. It 13531 /// marks the declaration referenced, and performs odr-use checking for 13532 /// functions and variables. This method should not be used when building a 13533 /// normal expression which refers to a variable. 13534 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 13535 if (OdrUse) { 13536 if (auto *VD = dyn_cast<VarDecl>(D)) { 13537 MarkVariableReferenced(Loc, VD); 13538 return; 13539 } 13540 } 13541 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 13542 MarkFunctionReferenced(Loc, FD, OdrUse); 13543 return; 13544 } 13545 D->setReferenced(); 13546 } 13547 13548 namespace { 13549 // Mark all of the declarations referenced 13550 // FIXME: Not fully implemented yet! We need to have a better understanding 13551 // of when we're entering 13552 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 13553 Sema &S; 13554 SourceLocation Loc; 13555 13556 public: 13557 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 13558 13559 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 13560 13561 bool TraverseTemplateArgument(const TemplateArgument &Arg); 13562 bool TraverseRecordType(RecordType *T); 13563 }; 13564 } 13565 13566 bool MarkReferencedDecls::TraverseTemplateArgument( 13567 const TemplateArgument &Arg) { 13568 if (Arg.getKind() == TemplateArgument::Declaration) { 13569 if (Decl *D = Arg.getAsDecl()) 13570 S.MarkAnyDeclReferenced(Loc, D, true); 13571 } 13572 13573 return Inherited::TraverseTemplateArgument(Arg); 13574 } 13575 13576 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 13577 if (ClassTemplateSpecializationDecl *Spec 13578 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 13579 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 13580 return TraverseTemplateArguments(Args.data(), Args.size()); 13581 } 13582 13583 return true; 13584 } 13585 13586 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 13587 MarkReferencedDecls Marker(*this, Loc); 13588 Marker.TraverseType(Context.getCanonicalType(T)); 13589 } 13590 13591 namespace { 13592 /// \brief Helper class that marks all of the declarations referenced by 13593 /// potentially-evaluated subexpressions as "referenced". 13594 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 13595 Sema &S; 13596 bool SkipLocalVariables; 13597 13598 public: 13599 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 13600 13601 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 13602 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 13603 13604 void VisitDeclRefExpr(DeclRefExpr *E) { 13605 // If we were asked not to visit local variables, don't. 13606 if (SkipLocalVariables) { 13607 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 13608 if (VD->hasLocalStorage()) 13609 return; 13610 } 13611 13612 S.MarkDeclRefReferenced(E); 13613 } 13614 13615 void VisitMemberExpr(MemberExpr *E) { 13616 S.MarkMemberReferenced(E); 13617 Inherited::VisitMemberExpr(E); 13618 } 13619 13620 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 13621 S.MarkFunctionReferenced(E->getLocStart(), 13622 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 13623 Visit(E->getSubExpr()); 13624 } 13625 13626 void VisitCXXNewExpr(CXXNewExpr *E) { 13627 if (E->getOperatorNew()) 13628 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 13629 if (E->getOperatorDelete()) 13630 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 13631 Inherited::VisitCXXNewExpr(E); 13632 } 13633 13634 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 13635 if (E->getOperatorDelete()) 13636 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 13637 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 13638 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 13639 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 13640 S.MarkFunctionReferenced(E->getLocStart(), 13641 S.LookupDestructor(Record)); 13642 } 13643 13644 Inherited::VisitCXXDeleteExpr(E); 13645 } 13646 13647 void VisitCXXConstructExpr(CXXConstructExpr *E) { 13648 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 13649 Inherited::VisitCXXConstructExpr(E); 13650 } 13651 13652 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 13653 Visit(E->getExpr()); 13654 } 13655 13656 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 13657 Inherited::VisitImplicitCastExpr(E); 13658 13659 if (E->getCastKind() == CK_LValueToRValue) 13660 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 13661 } 13662 }; 13663 } 13664 13665 /// \brief Mark any declarations that appear within this expression or any 13666 /// potentially-evaluated subexpressions as "referenced". 13667 /// 13668 /// \param SkipLocalVariables If true, don't mark local variables as 13669 /// 'referenced'. 13670 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 13671 bool SkipLocalVariables) { 13672 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 13673 } 13674 13675 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 13676 /// of the program being compiled. 13677 /// 13678 /// This routine emits the given diagnostic when the code currently being 13679 /// type-checked is "potentially evaluated", meaning that there is a 13680 /// possibility that the code will actually be executable. Code in sizeof() 13681 /// expressions, code used only during overload resolution, etc., are not 13682 /// potentially evaluated. This routine will suppress such diagnostics or, 13683 /// in the absolutely nutty case of potentially potentially evaluated 13684 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 13685 /// later. 13686 /// 13687 /// This routine should be used for all diagnostics that describe the run-time 13688 /// behavior of a program, such as passing a non-POD value through an ellipsis. 13689 /// Failure to do so will likely result in spurious diagnostics or failures 13690 /// during overload resolution or within sizeof/alignof/typeof/typeid. 13691 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 13692 const PartialDiagnostic &PD) { 13693 switch (ExprEvalContexts.back().Context) { 13694 case Unevaluated: 13695 case UnevaluatedAbstract: 13696 // The argument will never be evaluated, so don't complain. 13697 break; 13698 13699 case ConstantEvaluated: 13700 // Relevant diagnostics should be produced by constant evaluation. 13701 break; 13702 13703 case PotentiallyEvaluated: 13704 case PotentiallyEvaluatedIfUsed: 13705 if (Statement && getCurFunctionOrMethodDecl()) { 13706 FunctionScopes.back()->PossiblyUnreachableDiags. 13707 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 13708 } 13709 else 13710 Diag(Loc, PD); 13711 13712 return true; 13713 } 13714 13715 return false; 13716 } 13717 13718 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 13719 CallExpr *CE, FunctionDecl *FD) { 13720 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 13721 return false; 13722 13723 // If we're inside a decltype's expression, don't check for a valid return 13724 // type or construct temporaries until we know whether this is the last call. 13725 if (ExprEvalContexts.back().IsDecltype) { 13726 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 13727 return false; 13728 } 13729 13730 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 13731 FunctionDecl *FD; 13732 CallExpr *CE; 13733 13734 public: 13735 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 13736 : FD(FD), CE(CE) { } 13737 13738 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 13739 if (!FD) { 13740 S.Diag(Loc, diag::err_call_incomplete_return) 13741 << T << CE->getSourceRange(); 13742 return; 13743 } 13744 13745 S.Diag(Loc, diag::err_call_function_incomplete_return) 13746 << CE->getSourceRange() << FD->getDeclName() << T; 13747 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 13748 << FD->getDeclName(); 13749 } 13750 } Diagnoser(FD, CE); 13751 13752 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 13753 return true; 13754 13755 return false; 13756 } 13757 13758 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 13759 // will prevent this condition from triggering, which is what we want. 13760 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 13761 SourceLocation Loc; 13762 13763 unsigned diagnostic = diag::warn_condition_is_assignment; 13764 bool IsOrAssign = false; 13765 13766 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 13767 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 13768 return; 13769 13770 IsOrAssign = Op->getOpcode() == BO_OrAssign; 13771 13772 // Greylist some idioms by putting them into a warning subcategory. 13773 if (ObjCMessageExpr *ME 13774 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 13775 Selector Sel = ME->getSelector(); 13776 13777 // self = [<foo> init...] 13778 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 13779 diagnostic = diag::warn_condition_is_idiomatic_assignment; 13780 13781 // <foo> = [<bar> nextObject] 13782 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 13783 diagnostic = diag::warn_condition_is_idiomatic_assignment; 13784 } 13785 13786 Loc = Op->getOperatorLoc(); 13787 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 13788 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 13789 return; 13790 13791 IsOrAssign = Op->getOperator() == OO_PipeEqual; 13792 Loc = Op->getOperatorLoc(); 13793 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 13794 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 13795 else { 13796 // Not an assignment. 13797 return; 13798 } 13799 13800 Diag(Loc, diagnostic) << E->getSourceRange(); 13801 13802 SourceLocation Open = E->getLocStart(); 13803 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd()); 13804 Diag(Loc, diag::note_condition_assign_silence) 13805 << FixItHint::CreateInsertion(Open, "(") 13806 << FixItHint::CreateInsertion(Close, ")"); 13807 13808 if (IsOrAssign) 13809 Diag(Loc, diag::note_condition_or_assign_to_comparison) 13810 << FixItHint::CreateReplacement(Loc, "!="); 13811 else 13812 Diag(Loc, diag::note_condition_assign_to_comparison) 13813 << FixItHint::CreateReplacement(Loc, "=="); 13814 } 13815 13816 /// \brief Redundant parentheses over an equality comparison can indicate 13817 /// that the user intended an assignment used as condition. 13818 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 13819 // Don't warn if the parens came from a macro. 13820 SourceLocation parenLoc = ParenE->getLocStart(); 13821 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 13822 return; 13823 // Don't warn for dependent expressions. 13824 if (ParenE->isTypeDependent()) 13825 return; 13826 13827 Expr *E = ParenE->IgnoreParens(); 13828 13829 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 13830 if (opE->getOpcode() == BO_EQ && 13831 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 13832 == Expr::MLV_Valid) { 13833 SourceLocation Loc = opE->getOperatorLoc(); 13834 13835 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 13836 SourceRange ParenERange = ParenE->getSourceRange(); 13837 Diag(Loc, diag::note_equality_comparison_silence) 13838 << FixItHint::CreateRemoval(ParenERange.getBegin()) 13839 << FixItHint::CreateRemoval(ParenERange.getEnd()); 13840 Diag(Loc, diag::note_equality_comparison_to_assign) 13841 << FixItHint::CreateReplacement(Loc, "="); 13842 } 13843 } 13844 13845 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 13846 DiagnoseAssignmentAsCondition(E); 13847 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 13848 DiagnoseEqualityWithExtraParens(parenE); 13849 13850 ExprResult result = CheckPlaceholderExpr(E); 13851 if (result.isInvalid()) return ExprError(); 13852 E = result.get(); 13853 13854 if (!E->isTypeDependent()) { 13855 if (getLangOpts().CPlusPlus) 13856 return CheckCXXBooleanCondition(E); // C++ 6.4p4 13857 13858 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 13859 if (ERes.isInvalid()) 13860 return ExprError(); 13861 E = ERes.get(); 13862 13863 QualType T = E->getType(); 13864 if (!T->isScalarType()) { // C99 6.8.4.1p1 13865 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 13866 << T << E->getSourceRange(); 13867 return ExprError(); 13868 } 13869 CheckBoolLikeConversion(E, Loc); 13870 } 13871 13872 return E; 13873 } 13874 13875 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 13876 Expr *SubExpr) { 13877 if (!SubExpr) 13878 return ExprError(); 13879 13880 return CheckBooleanCondition(SubExpr, Loc); 13881 } 13882 13883 namespace { 13884 /// A visitor for rebuilding a call to an __unknown_any expression 13885 /// to have an appropriate type. 13886 struct RebuildUnknownAnyFunction 13887 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 13888 13889 Sema &S; 13890 13891 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 13892 13893 ExprResult VisitStmt(Stmt *S) { 13894 llvm_unreachable("unexpected statement!"); 13895 } 13896 13897 ExprResult VisitExpr(Expr *E) { 13898 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 13899 << E->getSourceRange(); 13900 return ExprError(); 13901 } 13902 13903 /// Rebuild an expression which simply semantically wraps another 13904 /// expression which it shares the type and value kind of. 13905 template <class T> ExprResult rebuildSugarExpr(T *E) { 13906 ExprResult SubResult = Visit(E->getSubExpr()); 13907 if (SubResult.isInvalid()) return ExprError(); 13908 13909 Expr *SubExpr = SubResult.get(); 13910 E->setSubExpr(SubExpr); 13911 E->setType(SubExpr->getType()); 13912 E->setValueKind(SubExpr->getValueKind()); 13913 assert(E->getObjectKind() == OK_Ordinary); 13914 return E; 13915 } 13916 13917 ExprResult VisitParenExpr(ParenExpr *E) { 13918 return rebuildSugarExpr(E); 13919 } 13920 13921 ExprResult VisitUnaryExtension(UnaryOperator *E) { 13922 return rebuildSugarExpr(E); 13923 } 13924 13925 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 13926 ExprResult SubResult = Visit(E->getSubExpr()); 13927 if (SubResult.isInvalid()) return ExprError(); 13928 13929 Expr *SubExpr = SubResult.get(); 13930 E->setSubExpr(SubExpr); 13931 E->setType(S.Context.getPointerType(SubExpr->getType())); 13932 assert(E->getValueKind() == VK_RValue); 13933 assert(E->getObjectKind() == OK_Ordinary); 13934 return E; 13935 } 13936 13937 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 13938 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 13939 13940 E->setType(VD->getType()); 13941 13942 assert(E->getValueKind() == VK_RValue); 13943 if (S.getLangOpts().CPlusPlus && 13944 !(isa<CXXMethodDecl>(VD) && 13945 cast<CXXMethodDecl>(VD)->isInstance())) 13946 E->setValueKind(VK_LValue); 13947 13948 return E; 13949 } 13950 13951 ExprResult VisitMemberExpr(MemberExpr *E) { 13952 return resolveDecl(E, E->getMemberDecl()); 13953 } 13954 13955 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 13956 return resolveDecl(E, E->getDecl()); 13957 } 13958 }; 13959 } 13960 13961 /// Given a function expression of unknown-any type, try to rebuild it 13962 /// to have a function type. 13963 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 13964 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 13965 if (Result.isInvalid()) return ExprError(); 13966 return S.DefaultFunctionArrayConversion(Result.get()); 13967 } 13968 13969 namespace { 13970 /// A visitor for rebuilding an expression of type __unknown_anytype 13971 /// into one which resolves the type directly on the referring 13972 /// expression. Strict preservation of the original source 13973 /// structure is not a goal. 13974 struct RebuildUnknownAnyExpr 13975 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 13976 13977 Sema &S; 13978 13979 /// The current destination type. 13980 QualType DestType; 13981 13982 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 13983 : S(S), DestType(CastType) {} 13984 13985 ExprResult VisitStmt(Stmt *S) { 13986 llvm_unreachable("unexpected statement!"); 13987 } 13988 13989 ExprResult VisitExpr(Expr *E) { 13990 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 13991 << E->getSourceRange(); 13992 return ExprError(); 13993 } 13994 13995 ExprResult VisitCallExpr(CallExpr *E); 13996 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 13997 13998 /// Rebuild an expression which simply semantically wraps another 13999 /// expression which it shares the type and value kind of. 14000 template <class T> ExprResult rebuildSugarExpr(T *E) { 14001 ExprResult SubResult = Visit(E->getSubExpr()); 14002 if (SubResult.isInvalid()) return ExprError(); 14003 Expr *SubExpr = SubResult.get(); 14004 E->setSubExpr(SubExpr); 14005 E->setType(SubExpr->getType()); 14006 E->setValueKind(SubExpr->getValueKind()); 14007 assert(E->getObjectKind() == OK_Ordinary); 14008 return E; 14009 } 14010 14011 ExprResult VisitParenExpr(ParenExpr *E) { 14012 return rebuildSugarExpr(E); 14013 } 14014 14015 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14016 return rebuildSugarExpr(E); 14017 } 14018 14019 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14020 const PointerType *Ptr = DestType->getAs<PointerType>(); 14021 if (!Ptr) { 14022 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14023 << E->getSourceRange(); 14024 return ExprError(); 14025 } 14026 assert(E->getValueKind() == VK_RValue); 14027 assert(E->getObjectKind() == OK_Ordinary); 14028 E->setType(DestType); 14029 14030 // Build the sub-expression as if it were an object of the pointee type. 14031 DestType = Ptr->getPointeeType(); 14032 ExprResult SubResult = Visit(E->getSubExpr()); 14033 if (SubResult.isInvalid()) return ExprError(); 14034 E->setSubExpr(SubResult.get()); 14035 return E; 14036 } 14037 14038 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14039 14040 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14041 14042 ExprResult VisitMemberExpr(MemberExpr *E) { 14043 return resolveDecl(E, E->getMemberDecl()); 14044 } 14045 14046 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14047 return resolveDecl(E, E->getDecl()); 14048 } 14049 }; 14050 } 14051 14052 /// Rebuilds a call expression which yielded __unknown_anytype. 14053 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14054 Expr *CalleeExpr = E->getCallee(); 14055 14056 enum FnKind { 14057 FK_MemberFunction, 14058 FK_FunctionPointer, 14059 FK_BlockPointer 14060 }; 14061 14062 FnKind Kind; 14063 QualType CalleeType = CalleeExpr->getType(); 14064 if (CalleeType == S.Context.BoundMemberTy) { 14065 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14066 Kind = FK_MemberFunction; 14067 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14068 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14069 CalleeType = Ptr->getPointeeType(); 14070 Kind = FK_FunctionPointer; 14071 } else { 14072 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14073 Kind = FK_BlockPointer; 14074 } 14075 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14076 14077 // Verify that this is a legal result type of a function. 14078 if (DestType->isArrayType() || DestType->isFunctionType()) { 14079 unsigned diagID = diag::err_func_returning_array_function; 14080 if (Kind == FK_BlockPointer) 14081 diagID = diag::err_block_returning_array_function; 14082 14083 S.Diag(E->getExprLoc(), diagID) 14084 << DestType->isFunctionType() << DestType; 14085 return ExprError(); 14086 } 14087 14088 // Otherwise, go ahead and set DestType as the call's result. 14089 E->setType(DestType.getNonLValueExprType(S.Context)); 14090 E->setValueKind(Expr::getValueKindForType(DestType)); 14091 assert(E->getObjectKind() == OK_Ordinary); 14092 14093 // Rebuild the function type, replacing the result type with DestType. 14094 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14095 if (Proto) { 14096 // __unknown_anytype(...) is a special case used by the debugger when 14097 // it has no idea what a function's signature is. 14098 // 14099 // We want to build this call essentially under the K&R 14100 // unprototyped rules, but making a FunctionNoProtoType in C++ 14101 // would foul up all sorts of assumptions. However, we cannot 14102 // simply pass all arguments as variadic arguments, nor can we 14103 // portably just call the function under a non-variadic type; see 14104 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14105 // However, it turns out that in practice it is generally safe to 14106 // call a function declared as "A foo(B,C,D);" under the prototype 14107 // "A foo(B,C,D,...);". The only known exception is with the 14108 // Windows ABI, where any variadic function is implicitly cdecl 14109 // regardless of its normal CC. Therefore we change the parameter 14110 // types to match the types of the arguments. 14111 // 14112 // This is a hack, but it is far superior to moving the 14113 // corresponding target-specific code from IR-gen to Sema/AST. 14114 14115 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14116 SmallVector<QualType, 8> ArgTypes; 14117 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14118 ArgTypes.reserve(E->getNumArgs()); 14119 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14120 Expr *Arg = E->getArg(i); 14121 QualType ArgType = Arg->getType(); 14122 if (E->isLValue()) { 14123 ArgType = S.Context.getLValueReferenceType(ArgType); 14124 } else if (E->isXValue()) { 14125 ArgType = S.Context.getRValueReferenceType(ArgType); 14126 } 14127 ArgTypes.push_back(ArgType); 14128 } 14129 ParamTypes = ArgTypes; 14130 } 14131 DestType = S.Context.getFunctionType(DestType, ParamTypes, 14132 Proto->getExtProtoInfo()); 14133 } else { 14134 DestType = S.Context.getFunctionNoProtoType(DestType, 14135 FnType->getExtInfo()); 14136 } 14137 14138 // Rebuild the appropriate pointer-to-function type. 14139 switch (Kind) { 14140 case FK_MemberFunction: 14141 // Nothing to do. 14142 break; 14143 14144 case FK_FunctionPointer: 14145 DestType = S.Context.getPointerType(DestType); 14146 break; 14147 14148 case FK_BlockPointer: 14149 DestType = S.Context.getBlockPointerType(DestType); 14150 break; 14151 } 14152 14153 // Finally, we can recurse. 14154 ExprResult CalleeResult = Visit(CalleeExpr); 14155 if (!CalleeResult.isUsable()) return ExprError(); 14156 E->setCallee(CalleeResult.get()); 14157 14158 // Bind a temporary if necessary. 14159 return S.MaybeBindToTemporary(E); 14160 } 14161 14162 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 14163 // Verify that this is a legal result type of a call. 14164 if (DestType->isArrayType() || DestType->isFunctionType()) { 14165 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 14166 << DestType->isFunctionType() << DestType; 14167 return ExprError(); 14168 } 14169 14170 // Rewrite the method result type if available. 14171 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 14172 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 14173 Method->setReturnType(DestType); 14174 } 14175 14176 // Change the type of the message. 14177 E->setType(DestType.getNonReferenceType()); 14178 E->setValueKind(Expr::getValueKindForType(DestType)); 14179 14180 return S.MaybeBindToTemporary(E); 14181 } 14182 14183 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 14184 // The only case we should ever see here is a function-to-pointer decay. 14185 if (E->getCastKind() == CK_FunctionToPointerDecay) { 14186 assert(E->getValueKind() == VK_RValue); 14187 assert(E->getObjectKind() == OK_Ordinary); 14188 14189 E->setType(DestType); 14190 14191 // Rebuild the sub-expression as the pointee (function) type. 14192 DestType = DestType->castAs<PointerType>()->getPointeeType(); 14193 14194 ExprResult Result = Visit(E->getSubExpr()); 14195 if (!Result.isUsable()) return ExprError(); 14196 14197 E->setSubExpr(Result.get()); 14198 return E; 14199 } else if (E->getCastKind() == CK_LValueToRValue) { 14200 assert(E->getValueKind() == VK_RValue); 14201 assert(E->getObjectKind() == OK_Ordinary); 14202 14203 assert(isa<BlockPointerType>(E->getType())); 14204 14205 E->setType(DestType); 14206 14207 // The sub-expression has to be a lvalue reference, so rebuild it as such. 14208 DestType = S.Context.getLValueReferenceType(DestType); 14209 14210 ExprResult Result = Visit(E->getSubExpr()); 14211 if (!Result.isUsable()) return ExprError(); 14212 14213 E->setSubExpr(Result.get()); 14214 return E; 14215 } else { 14216 llvm_unreachable("Unhandled cast type!"); 14217 } 14218 } 14219 14220 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 14221 ExprValueKind ValueKind = VK_LValue; 14222 QualType Type = DestType; 14223 14224 // We know how to make this work for certain kinds of decls: 14225 14226 // - functions 14227 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 14228 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 14229 DestType = Ptr->getPointeeType(); 14230 ExprResult Result = resolveDecl(E, VD); 14231 if (Result.isInvalid()) return ExprError(); 14232 return S.ImpCastExprToType(Result.get(), Type, 14233 CK_FunctionToPointerDecay, VK_RValue); 14234 } 14235 14236 if (!Type->isFunctionType()) { 14237 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 14238 << VD << E->getSourceRange(); 14239 return ExprError(); 14240 } 14241 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 14242 // We must match the FunctionDecl's type to the hack introduced in 14243 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 14244 // type. See the lengthy commentary in that routine. 14245 QualType FDT = FD->getType(); 14246 const FunctionType *FnType = FDT->castAs<FunctionType>(); 14247 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 14248 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 14249 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 14250 SourceLocation Loc = FD->getLocation(); 14251 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 14252 FD->getDeclContext(), 14253 Loc, Loc, FD->getNameInfo().getName(), 14254 DestType, FD->getTypeSourceInfo(), 14255 SC_None, false/*isInlineSpecified*/, 14256 FD->hasPrototype(), 14257 false/*isConstexprSpecified*/); 14258 14259 if (FD->getQualifier()) 14260 NewFD->setQualifierInfo(FD->getQualifierLoc()); 14261 14262 SmallVector<ParmVarDecl*, 16> Params; 14263 for (const auto &AI : FT->param_types()) { 14264 ParmVarDecl *Param = 14265 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 14266 Param->setScopeInfo(0, Params.size()); 14267 Params.push_back(Param); 14268 } 14269 NewFD->setParams(Params); 14270 DRE->setDecl(NewFD); 14271 VD = DRE->getDecl(); 14272 } 14273 } 14274 14275 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 14276 if (MD->isInstance()) { 14277 ValueKind = VK_RValue; 14278 Type = S.Context.BoundMemberTy; 14279 } 14280 14281 // Function references aren't l-values in C. 14282 if (!S.getLangOpts().CPlusPlus) 14283 ValueKind = VK_RValue; 14284 14285 // - variables 14286 } else if (isa<VarDecl>(VD)) { 14287 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 14288 Type = RefTy->getPointeeType(); 14289 } else if (Type->isFunctionType()) { 14290 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 14291 << VD << E->getSourceRange(); 14292 return ExprError(); 14293 } 14294 14295 // - nothing else 14296 } else { 14297 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 14298 << VD << E->getSourceRange(); 14299 return ExprError(); 14300 } 14301 14302 // Modifying the declaration like this is friendly to IR-gen but 14303 // also really dangerous. 14304 VD->setType(DestType); 14305 E->setType(Type); 14306 E->setValueKind(ValueKind); 14307 return E; 14308 } 14309 14310 /// Check a cast of an unknown-any type. We intentionally only 14311 /// trigger this for C-style casts. 14312 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 14313 Expr *CastExpr, CastKind &CastKind, 14314 ExprValueKind &VK, CXXCastPath &Path) { 14315 // Rewrite the casted expression from scratch. 14316 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 14317 if (!result.isUsable()) return ExprError(); 14318 14319 CastExpr = result.get(); 14320 VK = CastExpr->getValueKind(); 14321 CastKind = CK_NoOp; 14322 14323 return CastExpr; 14324 } 14325 14326 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 14327 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 14328 } 14329 14330 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 14331 Expr *arg, QualType ¶mType) { 14332 // If the syntactic form of the argument is not an explicit cast of 14333 // any sort, just do default argument promotion. 14334 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 14335 if (!castArg) { 14336 ExprResult result = DefaultArgumentPromotion(arg); 14337 if (result.isInvalid()) return ExprError(); 14338 paramType = result.get()->getType(); 14339 return result; 14340 } 14341 14342 // Otherwise, use the type that was written in the explicit cast. 14343 assert(!arg->hasPlaceholderType()); 14344 paramType = castArg->getTypeAsWritten(); 14345 14346 // Copy-initialize a parameter of that type. 14347 InitializedEntity entity = 14348 InitializedEntity::InitializeParameter(Context, paramType, 14349 /*consumed*/ false); 14350 return PerformCopyInitialization(entity, callLoc, arg); 14351 } 14352 14353 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 14354 Expr *orig = E; 14355 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 14356 while (true) { 14357 E = E->IgnoreParenImpCasts(); 14358 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 14359 E = call->getCallee(); 14360 diagID = diag::err_uncasted_call_of_unknown_any; 14361 } else { 14362 break; 14363 } 14364 } 14365 14366 SourceLocation loc; 14367 NamedDecl *d; 14368 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 14369 loc = ref->getLocation(); 14370 d = ref->getDecl(); 14371 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 14372 loc = mem->getMemberLoc(); 14373 d = mem->getMemberDecl(); 14374 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 14375 diagID = diag::err_uncasted_call_of_unknown_any; 14376 loc = msg->getSelectorStartLoc(); 14377 d = msg->getMethodDecl(); 14378 if (!d) { 14379 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 14380 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 14381 << orig->getSourceRange(); 14382 return ExprError(); 14383 } 14384 } else { 14385 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14386 << E->getSourceRange(); 14387 return ExprError(); 14388 } 14389 14390 S.Diag(loc, diagID) << d << orig->getSourceRange(); 14391 14392 // Never recoverable. 14393 return ExprError(); 14394 } 14395 14396 /// Check for operands with placeholder types and complain if found. 14397 /// Returns true if there was an error and no recovery was possible. 14398 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 14399 if (!getLangOpts().CPlusPlus) { 14400 // C cannot handle TypoExpr nodes on either side of a binop because it 14401 // doesn't handle dependent types properly, so make sure any TypoExprs have 14402 // been dealt with before checking the operands. 14403 ExprResult Result = CorrectDelayedTyposInExpr(E); 14404 if (!Result.isUsable()) return ExprError(); 14405 E = Result.get(); 14406 } 14407 14408 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 14409 if (!placeholderType) return E; 14410 14411 switch (placeholderType->getKind()) { 14412 14413 // Overloaded expressions. 14414 case BuiltinType::Overload: { 14415 // Try to resolve a single function template specialization. 14416 // This is obligatory. 14417 ExprResult result = E; 14418 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 14419 return result; 14420 14421 // If that failed, try to recover with a call. 14422 } else { 14423 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 14424 /*complain*/ true); 14425 return result; 14426 } 14427 } 14428 14429 // Bound member functions. 14430 case BuiltinType::BoundMember: { 14431 ExprResult result = E; 14432 const Expr *BME = E->IgnoreParens(); 14433 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 14434 // Try to give a nicer diagnostic if it is a bound member that we recognize. 14435 if (isa<CXXPseudoDestructorExpr>(BME)) { 14436 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 14437 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 14438 if (ME->getMemberNameInfo().getName().getNameKind() == 14439 DeclarationName::CXXDestructorName) 14440 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 14441 } 14442 tryToRecoverWithCall(result, PD, 14443 /*complain*/ true); 14444 return result; 14445 } 14446 14447 // ARC unbridged casts. 14448 case BuiltinType::ARCUnbridgedCast: { 14449 Expr *realCast = stripARCUnbridgedCast(E); 14450 diagnoseARCUnbridgedCast(realCast); 14451 return realCast; 14452 } 14453 14454 // Expressions of unknown type. 14455 case BuiltinType::UnknownAny: 14456 return diagnoseUnknownAnyExpr(*this, E); 14457 14458 // Pseudo-objects. 14459 case BuiltinType::PseudoObject: 14460 return checkPseudoObjectRValue(E); 14461 14462 case BuiltinType::BuiltinFn: { 14463 // Accept __noop without parens by implicitly converting it to a call expr. 14464 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 14465 if (DRE) { 14466 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 14467 if (FD->getBuiltinID() == Builtin::BI__noop) { 14468 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 14469 CK_BuiltinFnToFnPtr).get(); 14470 return new (Context) CallExpr(Context, E, None, Context.IntTy, 14471 VK_RValue, SourceLocation()); 14472 } 14473 } 14474 14475 Diag(E->getLocStart(), diag::err_builtin_fn_use); 14476 return ExprError(); 14477 } 14478 14479 // Expressions of unknown type. 14480 case BuiltinType::OMPArraySection: 14481 Diag(E->getLocStart(), diag::err_omp_array_section_use); 14482 return ExprError(); 14483 14484 // Everything else should be impossible. 14485 #define BUILTIN_TYPE(Id, SingletonId) \ 14486 case BuiltinType::Id: 14487 #define PLACEHOLDER_TYPE(Id, SingletonId) 14488 #include "clang/AST/BuiltinTypes.def" 14489 break; 14490 } 14491 14492 llvm_unreachable("invalid placeholder type!"); 14493 } 14494 14495 bool Sema::CheckCaseExpression(Expr *E) { 14496 if (E->isTypeDependent()) 14497 return true; 14498 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 14499 return E->getType()->isIntegralOrEnumerationType(); 14500 return false; 14501 } 14502 14503 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 14504 ExprResult 14505 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 14506 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 14507 "Unknown Objective-C Boolean value!"); 14508 QualType BoolT = Context.ObjCBuiltinBoolTy; 14509 if (!Context.getBOOLDecl()) { 14510 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 14511 Sema::LookupOrdinaryName); 14512 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 14513 NamedDecl *ND = Result.getFoundDecl(); 14514 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 14515 Context.setBOOLDecl(TD); 14516 } 14517 } 14518 if (Context.getBOOLDecl()) 14519 BoolT = Context.getBOOLType(); 14520 return new (Context) 14521 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 14522 } 14523