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 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 331 if (Pos != SuppressedDiagnostics.end()) { 332 for (const PartialDiagnosticAt &Suppressed : Pos->second) 333 Diag(Suppressed.first, Suppressed.second); 334 335 // Clear out the list of suppressed diagnostics, so that we don't emit 336 // them again for this specialization. However, we don't obsolete this 337 // entry from the table, because we want to avoid ever emitting these 338 // diagnostics again. 339 Pos->second.clear(); 340 } 341 342 // C++ [basic.start.main]p3: 343 // The function 'main' shall not be used within a program. 344 if (cast<FunctionDecl>(D)->isMain()) 345 Diag(Loc, diag::ext_main_used); 346 } 347 348 // See if this is an auto-typed variable whose initializer we are parsing. 349 if (ParsingInitForAutoVars.count(D)) { 350 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType(); 351 352 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 353 << D->getDeclName() << (unsigned)AT->getKeyword(); 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 = 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, bool Diagnose) { 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 if (Diagnose) 513 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address); 514 return ExprError(); 515 } 516 517 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 518 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 519 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 520 return ExprError(); 521 522 E = ImpCastExprToType(E, Context.getPointerType(Ty), 523 CK_FunctionToPointerDecay).get(); 524 } else if (Ty->isArrayType()) { 525 // In C90 mode, arrays only promote to pointers if the array expression is 526 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 527 // type 'array of type' is converted to an expression that has type 'pointer 528 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 529 // that has type 'array of type' ...". The relevant change is "an lvalue" 530 // (C90) to "an expression" (C99). 531 // 532 // C++ 4.2p1: 533 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 534 // T" can be converted to an rvalue of type "pointer to T". 535 // 536 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 537 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 538 CK_ArrayToPointerDecay).get(); 539 } 540 return E; 541 } 542 543 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 544 // Check to see if we are dereferencing a null pointer. If so, 545 // and if not volatile-qualified, this is undefined behavior that the 546 // optimizer will delete, so warn about it. People sometimes try to use this 547 // to get a deterministic trap and are surprised by clang's behavior. This 548 // only handles the pattern "*null", which is a very syntactic check. 549 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 550 if (UO->getOpcode() == UO_Deref && 551 UO->getSubExpr()->IgnoreParenCasts()-> 552 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 553 !UO->getType().isVolatileQualified()) { 554 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 555 S.PDiag(diag::warn_indirection_through_null) 556 << UO->getSubExpr()->getSourceRange()); 557 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 558 S.PDiag(diag::note_indirection_through_null)); 559 } 560 } 561 562 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 563 SourceLocation AssignLoc, 564 const Expr* RHS) { 565 const ObjCIvarDecl *IV = OIRE->getDecl(); 566 if (!IV) 567 return; 568 569 DeclarationName MemberName = IV->getDeclName(); 570 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 571 if (!Member || !Member->isStr("isa")) 572 return; 573 574 const Expr *Base = OIRE->getBase(); 575 QualType BaseType = Base->getType(); 576 if (OIRE->isArrow()) 577 BaseType = BaseType->getPointeeType(); 578 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 579 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 580 ObjCInterfaceDecl *ClassDeclared = nullptr; 581 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 582 if (!ClassDeclared->getSuperClass() 583 && (*ClassDeclared->ivar_begin()) == IV) { 584 if (RHS) { 585 NamedDecl *ObjectSetClass = 586 S.LookupSingleName(S.TUScope, 587 &S.Context.Idents.get("object_setClass"), 588 SourceLocation(), S.LookupOrdinaryName); 589 if (ObjectSetClass) { 590 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd()); 591 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) << 592 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") << 593 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(), 594 AssignLoc), ",") << 595 FixItHint::CreateInsertion(RHSLocEnd, ")"); 596 } 597 else 598 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 599 } else { 600 NamedDecl *ObjectGetClass = 601 S.LookupSingleName(S.TUScope, 602 &S.Context.Idents.get("object_getClass"), 603 SourceLocation(), S.LookupOrdinaryName); 604 if (ObjectGetClass) 605 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) << 606 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") << 607 FixItHint::CreateReplacement( 608 SourceRange(OIRE->getOpLoc(), 609 OIRE->getLocEnd()), ")"); 610 else 611 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 612 } 613 S.Diag(IV->getLocation(), diag::note_ivar_decl); 614 } 615 } 616 } 617 618 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 619 // Handle any placeholder expressions which made it here. 620 if (E->getType()->isPlaceholderType()) { 621 ExprResult result = CheckPlaceholderExpr(E); 622 if (result.isInvalid()) return ExprError(); 623 E = result.get(); 624 } 625 626 // C++ [conv.lval]p1: 627 // A glvalue of a non-function, non-array type T can be 628 // converted to a prvalue. 629 if (!E->isGLValue()) return E; 630 631 QualType T = E->getType(); 632 assert(!T.isNull() && "r-value conversion on typeless expression?"); 633 634 // We don't want to throw lvalue-to-rvalue casts on top of 635 // expressions of certain types in C++. 636 if (getLangOpts().CPlusPlus && 637 (E->getType() == Context.OverloadTy || 638 T->isDependentType() || 639 T->isRecordType())) 640 return E; 641 642 // The C standard is actually really unclear on this point, and 643 // DR106 tells us what the result should be but not why. It's 644 // generally best to say that void types just doesn't undergo 645 // lvalue-to-rvalue at all. Note that expressions of unqualified 646 // 'void' type are never l-values, but qualified void can be. 647 if (T->isVoidType()) 648 return E; 649 650 // OpenCL usually rejects direct accesses to values of 'half' type. 651 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 && 652 T->isHalfType()) { 653 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 654 << 0 << T; 655 return ExprError(); 656 } 657 658 CheckForNullPointerDereference(*this, E); 659 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 660 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 661 &Context.Idents.get("object_getClass"), 662 SourceLocation(), LookupOrdinaryName); 663 if (ObjectGetClass) 664 Diag(E->getExprLoc(), diag::warn_objc_isa_use) << 665 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") << 666 FixItHint::CreateReplacement( 667 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 668 else 669 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 670 } 671 else if (const ObjCIvarRefExpr *OIRE = 672 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 673 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 674 675 // C++ [conv.lval]p1: 676 // [...] If T is a non-class type, the type of the prvalue is the 677 // cv-unqualified version of T. Otherwise, the type of the 678 // rvalue is T. 679 // 680 // C99 6.3.2.1p2: 681 // If the lvalue has qualified type, the value has the unqualified 682 // version of the type of the lvalue; otherwise, the value has the 683 // type of the lvalue. 684 if (T.hasQualifiers()) 685 T = T.getUnqualifiedType(); 686 687 // Under the MS ABI, lock down the inheritance model now. 688 if (T->isMemberPointerType() && 689 Context.getTargetInfo().getCXXABI().isMicrosoft()) 690 (void)isCompleteType(E->getExprLoc(), T); 691 692 UpdateMarkingForLValueToRValue(E); 693 694 // Loading a __weak object implicitly retains the value, so we need a cleanup to 695 // balance that. 696 if (getLangOpts().ObjCAutoRefCount && 697 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 698 ExprNeedsCleanups = true; 699 700 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 701 nullptr, VK_RValue); 702 703 // C11 6.3.2.1p2: 704 // ... if the lvalue has atomic type, the value has the non-atomic version 705 // of the type of the lvalue ... 706 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 707 T = Atomic->getValueType().getUnqualifiedType(); 708 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 709 nullptr, VK_RValue); 710 } 711 712 return Res; 713 } 714 715 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 716 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 717 if (Res.isInvalid()) 718 return ExprError(); 719 Res = DefaultLvalueConversion(Res.get()); 720 if (Res.isInvalid()) 721 return ExprError(); 722 return Res; 723 } 724 725 /// CallExprUnaryConversions - a special case of an unary conversion 726 /// performed on a function designator of a call expression. 727 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 728 QualType Ty = E->getType(); 729 ExprResult Res = E; 730 // Only do implicit cast for a function type, but not for a pointer 731 // to function type. 732 if (Ty->isFunctionType()) { 733 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 734 CK_FunctionToPointerDecay).get(); 735 if (Res.isInvalid()) 736 return ExprError(); 737 } 738 Res = DefaultLvalueConversion(Res.get()); 739 if (Res.isInvalid()) 740 return ExprError(); 741 return Res.get(); 742 } 743 744 /// UsualUnaryConversions - Performs various conversions that are common to most 745 /// operators (C99 6.3). The conversions of array and function types are 746 /// sometimes suppressed. For example, the array->pointer conversion doesn't 747 /// apply if the array is an argument to the sizeof or address (&) operators. 748 /// In these instances, this routine should *not* be called. 749 ExprResult Sema::UsualUnaryConversions(Expr *E) { 750 // First, convert to an r-value. 751 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 752 if (Res.isInvalid()) 753 return ExprError(); 754 E = Res.get(); 755 756 QualType Ty = E->getType(); 757 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 758 759 // Half FP have to be promoted to float unless it is natively supported 760 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 761 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 762 763 // Try to perform integral promotions if the object has a theoretically 764 // promotable type. 765 if (Ty->isIntegralOrUnscopedEnumerationType()) { 766 // C99 6.3.1.1p2: 767 // 768 // The following may be used in an expression wherever an int or 769 // unsigned int may be used: 770 // - an object or expression with an integer type whose integer 771 // conversion rank is less than or equal to the rank of int 772 // and unsigned int. 773 // - A bit-field of type _Bool, int, signed int, or unsigned int. 774 // 775 // If an int can represent all values of the original type, the 776 // value is converted to an int; otherwise, it is converted to an 777 // unsigned int. These are called the integer promotions. All 778 // other types are unchanged by the integer promotions. 779 780 QualType PTy = Context.isPromotableBitField(E); 781 if (!PTy.isNull()) { 782 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 783 return E; 784 } 785 if (Ty->isPromotableIntegerType()) { 786 QualType PT = Context.getPromotedIntegerType(Ty); 787 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 788 return E; 789 } 790 } 791 return E; 792 } 793 794 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 795 /// do not have a prototype. Arguments that have type float or __fp16 796 /// are promoted to double. All other argument types are converted by 797 /// UsualUnaryConversions(). 798 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 799 QualType Ty = E->getType(); 800 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 801 802 ExprResult Res = UsualUnaryConversions(E); 803 if (Res.isInvalid()) 804 return ExprError(); 805 E = Res.get(); 806 807 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to 808 // double. 809 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 810 if (BTy && (BTy->getKind() == BuiltinType::Half || 811 BTy->getKind() == BuiltinType::Float)) 812 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get(); 813 814 // C++ performs lvalue-to-rvalue conversion as a default argument 815 // promotion, even on class types, but note: 816 // C++11 [conv.lval]p2: 817 // When an lvalue-to-rvalue conversion occurs in an unevaluated 818 // operand or a subexpression thereof the value contained in the 819 // referenced object is not accessed. Otherwise, if the glvalue 820 // has a class type, the conversion copy-initializes a temporary 821 // of type T from the glvalue and the result of the conversion 822 // is a prvalue for the temporary. 823 // FIXME: add some way to gate this entire thing for correctness in 824 // potentially potentially evaluated contexts. 825 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 826 ExprResult Temp = PerformCopyInitialization( 827 InitializedEntity::InitializeTemporary(E->getType()), 828 E->getExprLoc(), E); 829 if (Temp.isInvalid()) 830 return ExprError(); 831 E = Temp.get(); 832 } 833 834 return E; 835 } 836 837 /// Determine the degree of POD-ness for an expression. 838 /// Incomplete types are considered POD, since this check can be performed 839 /// when we're in an unevaluated context. 840 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 841 if (Ty->isIncompleteType()) { 842 // C++11 [expr.call]p7: 843 // After these conversions, if the argument does not have arithmetic, 844 // enumeration, pointer, pointer to member, or class type, the program 845 // is ill-formed. 846 // 847 // Since we've already performed array-to-pointer and function-to-pointer 848 // decay, the only such type in C++ is cv void. This also handles 849 // initializer lists as variadic arguments. 850 if (Ty->isVoidType()) 851 return VAK_Invalid; 852 853 if (Ty->isObjCObjectType()) 854 return VAK_Invalid; 855 return VAK_Valid; 856 } 857 858 if (Ty.isCXX98PODType(Context)) 859 return VAK_Valid; 860 861 // C++11 [expr.call]p7: 862 // Passing a potentially-evaluated argument of class type (Clause 9) 863 // having a non-trivial copy constructor, a non-trivial move constructor, 864 // or a non-trivial destructor, with no corresponding parameter, 865 // is conditionally-supported with implementation-defined semantics. 866 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 867 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 868 if (!Record->hasNonTrivialCopyConstructor() && 869 !Record->hasNonTrivialMoveConstructor() && 870 !Record->hasNonTrivialDestructor()) 871 return VAK_ValidInCXX11; 872 873 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 874 return VAK_Valid; 875 876 if (Ty->isObjCObjectType()) 877 return VAK_Invalid; 878 879 if (getLangOpts().MSVCCompat) 880 return VAK_MSVCUndefined; 881 882 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 883 // permitted to reject them. We should consider doing so. 884 return VAK_Undefined; 885 } 886 887 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 888 // Don't allow one to pass an Objective-C interface to a vararg. 889 const QualType &Ty = E->getType(); 890 VarArgKind VAK = isValidVarArgType(Ty); 891 892 // Complain about passing non-POD types through varargs. 893 switch (VAK) { 894 case VAK_ValidInCXX11: 895 DiagRuntimeBehavior( 896 E->getLocStart(), nullptr, 897 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) 898 << Ty << CT); 899 // Fall through. 900 case VAK_Valid: 901 if (Ty->isRecordType()) { 902 // This is unlikely to be what the user intended. If the class has a 903 // 'c_str' member function, the user probably meant to call that. 904 DiagRuntimeBehavior(E->getLocStart(), nullptr, 905 PDiag(diag::warn_pass_class_arg_to_vararg) 906 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 907 } 908 break; 909 910 case VAK_Undefined: 911 case VAK_MSVCUndefined: 912 DiagRuntimeBehavior( 913 E->getLocStart(), nullptr, 914 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 915 << getLangOpts().CPlusPlus11 << Ty << CT); 916 break; 917 918 case VAK_Invalid: 919 if (Ty->isObjCObjectType()) 920 DiagRuntimeBehavior( 921 E->getLocStart(), nullptr, 922 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 923 << Ty << CT); 924 else 925 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg) 926 << isa<InitListExpr>(E) << Ty << CT; 927 break; 928 } 929 } 930 931 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 932 /// will create a trap if the resulting type is not a POD type. 933 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 934 FunctionDecl *FDecl) { 935 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 936 // Strip the unbridged-cast placeholder expression off, if applicable. 937 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 938 (CT == VariadicMethod || 939 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 940 E = stripARCUnbridgedCast(E); 941 942 // Otherwise, do normal placeholder checking. 943 } else { 944 ExprResult ExprRes = CheckPlaceholderExpr(E); 945 if (ExprRes.isInvalid()) 946 return ExprError(); 947 E = ExprRes.get(); 948 } 949 } 950 951 ExprResult ExprRes = DefaultArgumentPromotion(E); 952 if (ExprRes.isInvalid()) 953 return ExprError(); 954 E = ExprRes.get(); 955 956 // Diagnostics regarding non-POD argument types are 957 // emitted along with format string checking in Sema::CheckFunctionCall(). 958 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 959 // Turn this into a trap. 960 CXXScopeSpec SS; 961 SourceLocation TemplateKWLoc; 962 UnqualifiedId Name; 963 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 964 E->getLocStart()); 965 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 966 Name, true, false); 967 if (TrapFn.isInvalid()) 968 return ExprError(); 969 970 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), 971 E->getLocStart(), None, 972 E->getLocEnd()); 973 if (Call.isInvalid()) 974 return ExprError(); 975 976 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma, 977 Call.get(), E); 978 if (Comma.isInvalid()) 979 return ExprError(); 980 return Comma.get(); 981 } 982 983 if (!getLangOpts().CPlusPlus && 984 RequireCompleteType(E->getExprLoc(), E->getType(), 985 diag::err_call_incomplete_argument)) 986 return ExprError(); 987 988 return E; 989 } 990 991 /// \brief Converts an integer to complex float type. Helper function of 992 /// UsualArithmeticConversions() 993 /// 994 /// \return false if the integer expression is an integer type and is 995 /// successfully converted to the complex type. 996 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 997 ExprResult &ComplexExpr, 998 QualType IntTy, 999 QualType ComplexTy, 1000 bool SkipCast) { 1001 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 1002 if (SkipCast) return false; 1003 if (IntTy->isIntegerType()) { 1004 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 1005 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 1006 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1007 CK_FloatingRealToComplex); 1008 } else { 1009 assert(IntTy->isComplexIntegerType()); 1010 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 1011 CK_IntegralComplexToFloatingComplex); 1012 } 1013 return false; 1014 } 1015 1016 /// \brief Handle arithmetic conversion with complex types. Helper function of 1017 /// UsualArithmeticConversions() 1018 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 1019 ExprResult &RHS, QualType LHSType, 1020 QualType RHSType, 1021 bool IsCompAssign) { 1022 // if we have an integer operand, the result is the complex type. 1023 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 1024 /*skipCast*/false)) 1025 return LHSType; 1026 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 1027 /*skipCast*/IsCompAssign)) 1028 return RHSType; 1029 1030 // This handles complex/complex, complex/float, or float/complex. 1031 // When both operands are complex, the shorter operand is converted to the 1032 // type of the longer, and that is the type of the result. This corresponds 1033 // to what is done when combining two real floating-point operands. 1034 // The fun begins when size promotion occur across type domains. 1035 // From H&S 6.3.4: When one operand is complex and the other is a real 1036 // floating-point type, the less precise type is converted, within it's 1037 // real or complex domain, to the precision of the other type. For example, 1038 // when combining a "long double" with a "double _Complex", the 1039 // "double _Complex" is promoted to "long double _Complex". 1040 1041 // Compute the rank of the two types, regardless of whether they are complex. 1042 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1043 1044 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 1045 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 1046 QualType LHSElementType = 1047 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1048 QualType RHSElementType = 1049 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1050 1051 QualType ResultType = S.Context.getComplexType(LHSElementType); 1052 if (Order < 0) { 1053 // Promote the precision of the LHS if not an assignment. 1054 ResultType = S.Context.getComplexType(RHSElementType); 1055 if (!IsCompAssign) { 1056 if (LHSComplexType) 1057 LHS = 1058 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1059 else 1060 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1061 } 1062 } else if (Order > 0) { 1063 // Promote the precision of the RHS. 1064 if (RHSComplexType) 1065 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1066 else 1067 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1068 } 1069 return ResultType; 1070 } 1071 1072 /// \brief Hande arithmetic conversion from integer to float. Helper function 1073 /// of UsualArithmeticConversions() 1074 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1075 ExprResult &IntExpr, 1076 QualType FloatTy, QualType IntTy, 1077 bool ConvertFloat, bool ConvertInt) { 1078 if (IntTy->isIntegerType()) { 1079 if (ConvertInt) 1080 // Convert intExpr to the lhs floating point type. 1081 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1082 CK_IntegralToFloating); 1083 return FloatTy; 1084 } 1085 1086 // Convert both sides to the appropriate complex float. 1087 assert(IntTy->isComplexIntegerType()); 1088 QualType result = S.Context.getComplexType(FloatTy); 1089 1090 // _Complex int -> _Complex float 1091 if (ConvertInt) 1092 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1093 CK_IntegralComplexToFloatingComplex); 1094 1095 // float -> _Complex float 1096 if (ConvertFloat) 1097 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1098 CK_FloatingRealToComplex); 1099 1100 return result; 1101 } 1102 1103 /// \brief Handle arithmethic conversion with floating point types. Helper 1104 /// function of UsualArithmeticConversions() 1105 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1106 ExprResult &RHS, QualType LHSType, 1107 QualType RHSType, bool IsCompAssign) { 1108 bool LHSFloat = LHSType->isRealFloatingType(); 1109 bool RHSFloat = RHSType->isRealFloatingType(); 1110 1111 // If we have two real floating types, convert the smaller operand 1112 // to the bigger result. 1113 if (LHSFloat && RHSFloat) { 1114 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1115 if (order > 0) { 1116 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1117 return LHSType; 1118 } 1119 1120 assert(order < 0 && "illegal float comparison"); 1121 if (!IsCompAssign) 1122 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1123 return RHSType; 1124 } 1125 1126 if (LHSFloat) { 1127 // Half FP has to be promoted to float unless it is natively supported 1128 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1129 LHSType = S.Context.FloatTy; 1130 1131 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1132 /*convertFloat=*/!IsCompAssign, 1133 /*convertInt=*/ true); 1134 } 1135 assert(RHSFloat); 1136 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1137 /*convertInt=*/ true, 1138 /*convertFloat=*/!IsCompAssign); 1139 } 1140 1141 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1142 1143 namespace { 1144 /// These helper callbacks are placed in an anonymous namespace to 1145 /// permit their use as function template parameters. 1146 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1147 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1148 } 1149 1150 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1151 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1152 CK_IntegralComplexCast); 1153 } 1154 } 1155 1156 /// \brief Handle integer arithmetic conversions. Helper function of 1157 /// UsualArithmeticConversions() 1158 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1159 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1160 ExprResult &RHS, QualType LHSType, 1161 QualType RHSType, bool IsCompAssign) { 1162 // The rules for this case are in C99 6.3.1.8 1163 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1164 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1165 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1166 if (LHSSigned == RHSSigned) { 1167 // Same signedness; use the higher-ranked type 1168 if (order >= 0) { 1169 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1170 return LHSType; 1171 } else if (!IsCompAssign) 1172 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1173 return RHSType; 1174 } else if (order != (LHSSigned ? 1 : -1)) { 1175 // The unsigned type has greater than or equal rank to the 1176 // signed type, so use the unsigned type 1177 if (RHSSigned) { 1178 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1179 return LHSType; 1180 } else if (!IsCompAssign) 1181 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1182 return RHSType; 1183 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1184 // The two types are different widths; if we are here, that 1185 // means the signed type is larger than the unsigned type, so 1186 // use the signed type. 1187 if (LHSSigned) { 1188 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1189 return LHSType; 1190 } else if (!IsCompAssign) 1191 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1192 return RHSType; 1193 } else { 1194 // The signed type is higher-ranked than the unsigned type, 1195 // but isn't actually any bigger (like unsigned int and long 1196 // on most 32-bit systems). Use the unsigned type corresponding 1197 // to the signed type. 1198 QualType result = 1199 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1200 RHS = (*doRHSCast)(S, RHS.get(), result); 1201 if (!IsCompAssign) 1202 LHS = (*doLHSCast)(S, LHS.get(), result); 1203 return result; 1204 } 1205 } 1206 1207 /// \brief Handle conversions with GCC complex int extension. Helper function 1208 /// of UsualArithmeticConversions() 1209 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1210 ExprResult &RHS, QualType LHSType, 1211 QualType RHSType, 1212 bool IsCompAssign) { 1213 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1214 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1215 1216 if (LHSComplexInt && RHSComplexInt) { 1217 QualType LHSEltType = LHSComplexInt->getElementType(); 1218 QualType RHSEltType = RHSComplexInt->getElementType(); 1219 QualType ScalarType = 1220 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1221 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1222 1223 return S.Context.getComplexType(ScalarType); 1224 } 1225 1226 if (LHSComplexInt) { 1227 QualType LHSEltType = LHSComplexInt->getElementType(); 1228 QualType ScalarType = 1229 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1230 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1231 QualType ComplexType = S.Context.getComplexType(ScalarType); 1232 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1233 CK_IntegralRealToComplex); 1234 1235 return ComplexType; 1236 } 1237 1238 assert(RHSComplexInt); 1239 1240 QualType RHSEltType = RHSComplexInt->getElementType(); 1241 QualType ScalarType = 1242 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1243 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1244 QualType ComplexType = S.Context.getComplexType(ScalarType); 1245 1246 if (!IsCompAssign) 1247 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1248 CK_IntegralRealToComplex); 1249 return ComplexType; 1250 } 1251 1252 /// UsualArithmeticConversions - Performs various conversions that are common to 1253 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1254 /// routine returns the first non-arithmetic type found. The client is 1255 /// responsible for emitting appropriate error diagnostics. 1256 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1257 bool IsCompAssign) { 1258 if (!IsCompAssign) { 1259 LHS = UsualUnaryConversions(LHS.get()); 1260 if (LHS.isInvalid()) 1261 return QualType(); 1262 } 1263 1264 RHS = UsualUnaryConversions(RHS.get()); 1265 if (RHS.isInvalid()) 1266 return QualType(); 1267 1268 // For conversion purposes, we ignore any qualifiers. 1269 // For example, "const float" and "float" are equivalent. 1270 QualType LHSType = 1271 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1272 QualType RHSType = 1273 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1274 1275 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1276 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1277 LHSType = AtomicLHS->getValueType(); 1278 1279 // If both types are identical, no conversion is needed. 1280 if (LHSType == RHSType) 1281 return LHSType; 1282 1283 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1284 // The caller can deal with this (e.g. pointer + int). 1285 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1286 return QualType(); 1287 1288 // Apply unary and bitfield promotions to the LHS's type. 1289 QualType LHSUnpromotedType = LHSType; 1290 if (LHSType->isPromotableIntegerType()) 1291 LHSType = Context.getPromotedIntegerType(LHSType); 1292 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1293 if (!LHSBitfieldPromoteTy.isNull()) 1294 LHSType = LHSBitfieldPromoteTy; 1295 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1296 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1297 1298 // If both types are identical, no conversion is needed. 1299 if (LHSType == RHSType) 1300 return LHSType; 1301 1302 // At this point, we have two different arithmetic types. 1303 1304 // Handle complex types first (C99 6.3.1.8p1). 1305 if (LHSType->isComplexType() || RHSType->isComplexType()) 1306 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1307 IsCompAssign); 1308 1309 // Now handle "real" floating types (i.e. float, double, long double). 1310 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1311 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1312 IsCompAssign); 1313 1314 // Handle GCC complex int extension. 1315 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1316 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1317 IsCompAssign); 1318 1319 // Finally, we have two differing integer types. 1320 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1321 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1322 } 1323 1324 1325 //===----------------------------------------------------------------------===// 1326 // Semantic Analysis for various Expression Types 1327 //===----------------------------------------------------------------------===// 1328 1329 1330 ExprResult 1331 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1332 SourceLocation DefaultLoc, 1333 SourceLocation RParenLoc, 1334 Expr *ControllingExpr, 1335 ArrayRef<ParsedType> ArgTypes, 1336 ArrayRef<Expr *> ArgExprs) { 1337 unsigned NumAssocs = ArgTypes.size(); 1338 assert(NumAssocs == ArgExprs.size()); 1339 1340 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1341 for (unsigned i = 0; i < NumAssocs; ++i) { 1342 if (ArgTypes[i]) 1343 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1344 else 1345 Types[i] = nullptr; 1346 } 1347 1348 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1349 ControllingExpr, 1350 llvm::makeArrayRef(Types, NumAssocs), 1351 ArgExprs); 1352 delete [] Types; 1353 return ER; 1354 } 1355 1356 ExprResult 1357 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1358 SourceLocation DefaultLoc, 1359 SourceLocation RParenLoc, 1360 Expr *ControllingExpr, 1361 ArrayRef<TypeSourceInfo *> Types, 1362 ArrayRef<Expr *> Exprs) { 1363 unsigned NumAssocs = Types.size(); 1364 assert(NumAssocs == Exprs.size()); 1365 1366 // Decay and strip qualifiers for the controlling expression type, and handle 1367 // placeholder type replacement. See committee discussion from WG14 DR423. 1368 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1369 if (R.isInvalid()) 1370 return ExprError(); 1371 ControllingExpr = R.get(); 1372 1373 // The controlling expression is an unevaluated operand, so side effects are 1374 // likely unintended. 1375 if (ActiveTemplateInstantiations.empty() && 1376 ControllingExpr->HasSideEffects(Context, false)) 1377 Diag(ControllingExpr->getExprLoc(), 1378 diag::warn_side_effects_unevaluated_context); 1379 1380 bool TypeErrorFound = false, 1381 IsResultDependent = ControllingExpr->isTypeDependent(), 1382 ContainsUnexpandedParameterPack 1383 = ControllingExpr->containsUnexpandedParameterPack(); 1384 1385 for (unsigned i = 0; i < NumAssocs; ++i) { 1386 if (Exprs[i]->containsUnexpandedParameterPack()) 1387 ContainsUnexpandedParameterPack = true; 1388 1389 if (Types[i]) { 1390 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1391 ContainsUnexpandedParameterPack = true; 1392 1393 if (Types[i]->getType()->isDependentType()) { 1394 IsResultDependent = true; 1395 } else { 1396 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1397 // complete object type other than a variably modified type." 1398 unsigned D = 0; 1399 if (Types[i]->getType()->isIncompleteType()) 1400 D = diag::err_assoc_type_incomplete; 1401 else if (!Types[i]->getType()->isObjectType()) 1402 D = diag::err_assoc_type_nonobject; 1403 else if (Types[i]->getType()->isVariablyModifiedType()) 1404 D = diag::err_assoc_type_variably_modified; 1405 1406 if (D != 0) { 1407 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1408 << Types[i]->getTypeLoc().getSourceRange() 1409 << Types[i]->getType(); 1410 TypeErrorFound = true; 1411 } 1412 1413 // C11 6.5.1.1p2 "No two generic associations in the same generic 1414 // selection shall specify compatible types." 1415 for (unsigned j = i+1; j < NumAssocs; ++j) 1416 if (Types[j] && !Types[j]->getType()->isDependentType() && 1417 Context.typesAreCompatible(Types[i]->getType(), 1418 Types[j]->getType())) { 1419 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1420 diag::err_assoc_compatible_types) 1421 << Types[j]->getTypeLoc().getSourceRange() 1422 << Types[j]->getType() 1423 << Types[i]->getType(); 1424 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1425 diag::note_compat_assoc) 1426 << Types[i]->getTypeLoc().getSourceRange() 1427 << Types[i]->getType(); 1428 TypeErrorFound = true; 1429 } 1430 } 1431 } 1432 } 1433 if (TypeErrorFound) 1434 return ExprError(); 1435 1436 // If we determined that the generic selection is result-dependent, don't 1437 // try to compute the result expression. 1438 if (IsResultDependent) 1439 return new (Context) GenericSelectionExpr( 1440 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1441 ContainsUnexpandedParameterPack); 1442 1443 SmallVector<unsigned, 1> CompatIndices; 1444 unsigned DefaultIndex = -1U; 1445 for (unsigned i = 0; i < NumAssocs; ++i) { 1446 if (!Types[i]) 1447 DefaultIndex = i; 1448 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1449 Types[i]->getType())) 1450 CompatIndices.push_back(i); 1451 } 1452 1453 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1454 // type compatible with at most one of the types named in its generic 1455 // association list." 1456 if (CompatIndices.size() > 1) { 1457 // We strip parens here because the controlling expression is typically 1458 // parenthesized in macro definitions. 1459 ControllingExpr = ControllingExpr->IgnoreParens(); 1460 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match) 1461 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1462 << (unsigned) CompatIndices.size(); 1463 for (unsigned I : CompatIndices) { 1464 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1465 diag::note_compat_assoc) 1466 << Types[I]->getTypeLoc().getSourceRange() 1467 << Types[I]->getType(); 1468 } 1469 return ExprError(); 1470 } 1471 1472 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1473 // its controlling expression shall have type compatible with exactly one of 1474 // the types named in its generic association list." 1475 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1476 // We strip parens here because the controlling expression is typically 1477 // parenthesized in macro definitions. 1478 ControllingExpr = ControllingExpr->IgnoreParens(); 1479 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match) 1480 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1481 return ExprError(); 1482 } 1483 1484 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1485 // type name that is compatible with the type of the controlling expression, 1486 // then the result expression of the generic selection is the expression 1487 // in that generic association. Otherwise, the result expression of the 1488 // generic selection is the expression in the default generic association." 1489 unsigned ResultIndex = 1490 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1491 1492 return new (Context) GenericSelectionExpr( 1493 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1494 ContainsUnexpandedParameterPack, ResultIndex); 1495 } 1496 1497 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1498 /// location of the token and the offset of the ud-suffix within it. 1499 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1500 unsigned Offset) { 1501 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1502 S.getLangOpts()); 1503 } 1504 1505 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1506 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1507 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1508 IdentifierInfo *UDSuffix, 1509 SourceLocation UDSuffixLoc, 1510 ArrayRef<Expr*> Args, 1511 SourceLocation LitEndLoc) { 1512 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1513 1514 QualType ArgTy[2]; 1515 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1516 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1517 if (ArgTy[ArgIdx]->isArrayType()) 1518 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1519 } 1520 1521 DeclarationName OpName = 1522 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1523 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1524 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1525 1526 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1527 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1528 /*AllowRaw*/false, /*AllowTemplate*/false, 1529 /*AllowStringTemplate*/false) == Sema::LOLR_Error) 1530 return ExprError(); 1531 1532 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1533 } 1534 1535 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1536 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1537 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1538 /// multiple tokens. However, the common case is that StringToks points to one 1539 /// string. 1540 /// 1541 ExprResult 1542 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1543 assert(!StringToks.empty() && "Must have at least one string!"); 1544 1545 StringLiteralParser Literal(StringToks, PP); 1546 if (Literal.hadError) 1547 return ExprError(); 1548 1549 SmallVector<SourceLocation, 4> StringTokLocs; 1550 for (const Token &Tok : StringToks) 1551 StringTokLocs.push_back(Tok.getLocation()); 1552 1553 QualType CharTy = Context.CharTy; 1554 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1555 if (Literal.isWide()) { 1556 CharTy = Context.getWideCharType(); 1557 Kind = StringLiteral::Wide; 1558 } else if (Literal.isUTF8()) { 1559 Kind = StringLiteral::UTF8; 1560 } else if (Literal.isUTF16()) { 1561 CharTy = Context.Char16Ty; 1562 Kind = StringLiteral::UTF16; 1563 } else if (Literal.isUTF32()) { 1564 CharTy = Context.Char32Ty; 1565 Kind = StringLiteral::UTF32; 1566 } else if (Literal.isPascal()) { 1567 CharTy = Context.UnsignedCharTy; 1568 } 1569 1570 QualType CharTyConst = CharTy; 1571 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1572 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1573 CharTyConst.addConst(); 1574 1575 // Get an array type for the string, according to C99 6.4.5. This includes 1576 // the nul terminator character as well as the string length for pascal 1577 // strings. 1578 QualType StrTy = Context.getConstantArrayType(CharTyConst, 1579 llvm::APInt(32, Literal.GetNumStringChars()+1), 1580 ArrayType::Normal, 0); 1581 1582 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space. 1583 if (getLangOpts().OpenCL) { 1584 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant); 1585 } 1586 1587 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1588 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1589 Kind, Literal.Pascal, StrTy, 1590 &StringTokLocs[0], 1591 StringTokLocs.size()); 1592 if (Literal.getUDSuffix().empty()) 1593 return Lit; 1594 1595 // We're building a user-defined literal. 1596 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1597 SourceLocation UDSuffixLoc = 1598 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1599 Literal.getUDSuffixOffset()); 1600 1601 // Make sure we're allowed user-defined literals here. 1602 if (!UDLScope) 1603 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1604 1605 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1606 // operator "" X (str, len) 1607 QualType SizeType = Context.getSizeType(); 1608 1609 DeclarationName OpName = 1610 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1611 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1612 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1613 1614 QualType ArgTy[] = { 1615 Context.getArrayDecayedType(StrTy), SizeType 1616 }; 1617 1618 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1619 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1620 /*AllowRaw*/false, /*AllowTemplate*/false, 1621 /*AllowStringTemplate*/true)) { 1622 1623 case LOLR_Cooked: { 1624 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1625 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1626 StringTokLocs[0]); 1627 Expr *Args[] = { Lit, LenArg }; 1628 1629 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1630 } 1631 1632 case LOLR_StringTemplate: { 1633 TemplateArgumentListInfo ExplicitArgs; 1634 1635 unsigned CharBits = Context.getIntWidth(CharTy); 1636 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1637 llvm::APSInt Value(CharBits, CharIsUnsigned); 1638 1639 TemplateArgument TypeArg(CharTy); 1640 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1641 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1642 1643 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1644 Value = Lit->getCodeUnit(I); 1645 TemplateArgument Arg(Context, Value, CharTy); 1646 TemplateArgumentLocInfo ArgInfo; 1647 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1648 } 1649 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1650 &ExplicitArgs); 1651 } 1652 case LOLR_Raw: 1653 case LOLR_Template: 1654 llvm_unreachable("unexpected literal operator lookup result"); 1655 case LOLR_Error: 1656 return ExprError(); 1657 } 1658 llvm_unreachable("unexpected literal operator lookup result"); 1659 } 1660 1661 ExprResult 1662 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1663 SourceLocation Loc, 1664 const CXXScopeSpec *SS) { 1665 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1666 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1667 } 1668 1669 /// BuildDeclRefExpr - Build an expression that references a 1670 /// declaration that does not require a closure capture. 1671 ExprResult 1672 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1673 const DeclarationNameInfo &NameInfo, 1674 const CXXScopeSpec *SS, NamedDecl *FoundD, 1675 const TemplateArgumentListInfo *TemplateArgs) { 1676 if (getLangOpts().CUDA) 1677 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 1678 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) { 1679 if (CheckCUDATarget(Caller, Callee)) { 1680 Diag(NameInfo.getLoc(), diag::err_ref_bad_target) 1681 << IdentifyCUDATarget(Callee) << D->getIdentifier() 1682 << IdentifyCUDATarget(Caller); 1683 Diag(D->getLocation(), diag::note_previous_decl) 1684 << D->getIdentifier(); 1685 return ExprError(); 1686 } 1687 } 1688 1689 bool RefersToCapturedVariable = 1690 isa<VarDecl>(D) && 1691 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1692 1693 DeclRefExpr *E; 1694 if (isa<VarTemplateSpecializationDecl>(D)) { 1695 VarTemplateSpecializationDecl *VarSpec = 1696 cast<VarTemplateSpecializationDecl>(D); 1697 1698 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1699 : NestedNameSpecifierLoc(), 1700 VarSpec->getTemplateKeywordLoc(), D, 1701 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1702 FoundD, TemplateArgs); 1703 } else { 1704 assert(!TemplateArgs && "No template arguments for non-variable" 1705 " template specialization references"); 1706 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1707 : NestedNameSpecifierLoc(), 1708 SourceLocation(), D, RefersToCapturedVariable, 1709 NameInfo, Ty, VK, FoundD); 1710 } 1711 1712 MarkDeclRefReferenced(E); 1713 1714 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1715 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && 1716 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart())) 1717 recordUseOfEvaluatedWeak(E); 1718 1719 // Just in case we're building an illegal pointer-to-member. 1720 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1721 if (FD && FD->isBitField()) 1722 E->setObjectKind(OK_BitField); 1723 1724 return E; 1725 } 1726 1727 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1728 /// possibly a list of template arguments. 1729 /// 1730 /// If this produces template arguments, it is permitted to call 1731 /// DecomposeTemplateName. 1732 /// 1733 /// This actually loses a lot of source location information for 1734 /// non-standard name kinds; we should consider preserving that in 1735 /// some way. 1736 void 1737 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1738 TemplateArgumentListInfo &Buffer, 1739 DeclarationNameInfo &NameInfo, 1740 const TemplateArgumentListInfo *&TemplateArgs) { 1741 if (Id.getKind() == UnqualifiedId::IK_TemplateId) { 1742 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1743 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1744 1745 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1746 Id.TemplateId->NumArgs); 1747 translateTemplateArguments(TemplateArgsPtr, Buffer); 1748 1749 TemplateName TName = Id.TemplateId->Template.get(); 1750 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1751 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1752 TemplateArgs = &Buffer; 1753 } else { 1754 NameInfo = GetNameFromUnqualifiedId(Id); 1755 TemplateArgs = nullptr; 1756 } 1757 } 1758 1759 static void emitEmptyLookupTypoDiagnostic( 1760 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1761 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1762 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1763 DeclContext *Ctx = 1764 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1765 if (!TC) { 1766 // Emit a special diagnostic for failed member lookups. 1767 // FIXME: computing the declaration context might fail here (?) 1768 if (Ctx) 1769 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1770 << SS.getRange(); 1771 else 1772 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1773 return; 1774 } 1775 1776 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1777 bool DroppedSpecifier = 1778 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1779 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1780 ? diag::note_implicit_param_decl 1781 : diag::note_previous_decl; 1782 if (!Ctx) 1783 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1784 SemaRef.PDiag(NoteID)); 1785 else 1786 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1787 << Typo << Ctx << DroppedSpecifier 1788 << SS.getRange(), 1789 SemaRef.PDiag(NoteID)); 1790 } 1791 1792 /// Diagnose an empty lookup. 1793 /// 1794 /// \return false if new lookup candidates were found 1795 bool 1796 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1797 std::unique_ptr<CorrectionCandidateCallback> CCC, 1798 TemplateArgumentListInfo *ExplicitTemplateArgs, 1799 ArrayRef<Expr *> Args, TypoExpr **Out) { 1800 DeclarationName Name = R.getLookupName(); 1801 1802 unsigned diagnostic = diag::err_undeclared_var_use; 1803 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1804 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1805 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1806 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1807 diagnostic = diag::err_undeclared_use; 1808 diagnostic_suggest = diag::err_undeclared_use_suggest; 1809 } 1810 1811 // If the original lookup was an unqualified lookup, fake an 1812 // unqualified lookup. This is useful when (for example) the 1813 // original lookup would not have found something because it was a 1814 // dependent name. 1815 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1816 while (DC) { 1817 if (isa<CXXRecordDecl>(DC)) { 1818 LookupQualifiedName(R, DC); 1819 1820 if (!R.empty()) { 1821 // Don't give errors about ambiguities in this lookup. 1822 R.suppressDiagnostics(); 1823 1824 // During a default argument instantiation the CurContext points 1825 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1826 // function parameter list, hence add an explicit check. 1827 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() && 1828 ActiveTemplateInstantiations.back().Kind == 1829 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 1830 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1831 bool isInstance = CurMethod && 1832 CurMethod->isInstance() && 1833 DC == CurMethod->getParent() && !isDefaultArgument; 1834 1835 // Give a code modification hint to insert 'this->'. 1836 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1837 // Actually quite difficult! 1838 if (getLangOpts().MSVCCompat) 1839 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1840 if (isInstance) { 1841 Diag(R.getNameLoc(), diagnostic) << Name 1842 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1843 CheckCXXThisCapture(R.getNameLoc()); 1844 } else { 1845 Diag(R.getNameLoc(), diagnostic) << Name; 1846 } 1847 1848 // Do we really want to note all of these? 1849 for (NamedDecl *D : R) 1850 Diag(D->getLocation(), diag::note_dependent_var_use); 1851 1852 // Return true if we are inside a default argument instantiation 1853 // and the found name refers to an instance member function, otherwise 1854 // the function calling DiagnoseEmptyLookup will try to create an 1855 // implicit member call and this is wrong for default argument. 1856 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1857 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1858 return true; 1859 } 1860 1861 // Tell the callee to try to recover. 1862 return false; 1863 } 1864 1865 R.clear(); 1866 } 1867 1868 // In Microsoft mode, if we are performing lookup from within a friend 1869 // function definition declared at class scope then we must set 1870 // DC to the lexical parent to be able to search into the parent 1871 // class. 1872 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1873 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1874 DC->getLexicalParent()->isRecord()) 1875 DC = DC->getLexicalParent(); 1876 else 1877 DC = DC->getParent(); 1878 } 1879 1880 // We didn't find anything, so try to correct for a typo. 1881 TypoCorrection Corrected; 1882 if (S && Out) { 1883 SourceLocation TypoLoc = R.getNameLoc(); 1884 assert(!ExplicitTemplateArgs && 1885 "Diagnosing an empty lookup with explicit template args!"); 1886 *Out = CorrectTypoDelayed( 1887 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1888 [=](const TypoCorrection &TC) { 1889 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1890 diagnostic, diagnostic_suggest); 1891 }, 1892 nullptr, CTK_ErrorRecovery); 1893 if (*Out) 1894 return true; 1895 } else if (S && (Corrected = 1896 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1897 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1898 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1899 bool DroppedSpecifier = 1900 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1901 R.setLookupName(Corrected.getCorrection()); 1902 1903 bool AcceptableWithRecovery = false; 1904 bool AcceptableWithoutRecovery = false; 1905 NamedDecl *ND = Corrected.getFoundDecl(); 1906 if (ND) { 1907 if (Corrected.isOverloaded()) { 1908 OverloadCandidateSet OCS(R.getNameLoc(), 1909 OverloadCandidateSet::CSK_Normal); 1910 OverloadCandidateSet::iterator Best; 1911 for (NamedDecl *CD : Corrected) { 1912 if (FunctionTemplateDecl *FTD = 1913 dyn_cast<FunctionTemplateDecl>(CD)) 1914 AddTemplateOverloadCandidate( 1915 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1916 Args, OCS); 1917 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1918 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1919 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1920 Args, OCS); 1921 } 1922 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1923 case OR_Success: 1924 ND = Best->FoundDecl; 1925 Corrected.setCorrectionDecl(ND); 1926 break; 1927 default: 1928 // FIXME: Arbitrarily pick the first declaration for the note. 1929 Corrected.setCorrectionDecl(ND); 1930 break; 1931 } 1932 } 1933 R.addDecl(ND); 1934 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1935 CXXRecordDecl *Record = nullptr; 1936 if (Corrected.getCorrectionSpecifier()) { 1937 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1938 Record = Ty->getAsCXXRecordDecl(); 1939 } 1940 if (!Record) 1941 Record = cast<CXXRecordDecl>( 1942 ND->getDeclContext()->getRedeclContext()); 1943 R.setNamingClass(Record); 1944 } 1945 1946 auto *UnderlyingND = ND->getUnderlyingDecl(); 1947 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1948 isa<FunctionTemplateDecl>(UnderlyingND); 1949 // FIXME: If we ended up with a typo for a type name or 1950 // Objective-C class name, we're in trouble because the parser 1951 // is in the wrong place to recover. Suggest the typo 1952 // correction, but don't make it a fix-it since we're not going 1953 // to recover well anyway. 1954 AcceptableWithoutRecovery = 1955 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1956 } else { 1957 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1958 // because we aren't able to recover. 1959 AcceptableWithoutRecovery = true; 1960 } 1961 1962 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1963 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1964 ? diag::note_implicit_param_decl 1965 : diag::note_previous_decl; 1966 if (SS.isEmpty()) 1967 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1968 PDiag(NoteID), AcceptableWithRecovery); 1969 else 1970 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 1971 << Name << computeDeclContext(SS, false) 1972 << DroppedSpecifier << SS.getRange(), 1973 PDiag(NoteID), AcceptableWithRecovery); 1974 1975 // Tell the callee whether to try to recover. 1976 return !AcceptableWithRecovery; 1977 } 1978 } 1979 R.clear(); 1980 1981 // Emit a special diagnostic for failed member lookups. 1982 // FIXME: computing the declaration context might fail here (?) 1983 if (!SS.isEmpty()) { 1984 Diag(R.getNameLoc(), diag::err_no_member) 1985 << Name << computeDeclContext(SS, false) 1986 << SS.getRange(); 1987 return true; 1988 } 1989 1990 // Give up, we can't recover. 1991 Diag(R.getNameLoc(), diagnostic) << Name; 1992 return true; 1993 } 1994 1995 /// In Microsoft mode, if we are inside a template class whose parent class has 1996 /// dependent base classes, and we can't resolve an unqualified identifier, then 1997 /// assume the identifier is a member of a dependent base class. We can only 1998 /// recover successfully in static methods, instance methods, and other contexts 1999 /// where 'this' is available. This doesn't precisely match MSVC's 2000 /// instantiation model, but it's close enough. 2001 static Expr * 2002 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2003 DeclarationNameInfo &NameInfo, 2004 SourceLocation TemplateKWLoc, 2005 const TemplateArgumentListInfo *TemplateArgs) { 2006 // Only try to recover from lookup into dependent bases in static methods or 2007 // contexts where 'this' is available. 2008 QualType ThisType = S.getCurrentThisType(); 2009 const CXXRecordDecl *RD = nullptr; 2010 if (!ThisType.isNull()) 2011 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2012 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2013 RD = MD->getParent(); 2014 if (!RD || !RD->hasAnyDependentBases()) 2015 return nullptr; 2016 2017 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2018 // is available, suggest inserting 'this->' as a fixit. 2019 SourceLocation Loc = NameInfo.getLoc(); 2020 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2021 DB << NameInfo.getName() << RD; 2022 2023 if (!ThisType.isNull()) { 2024 DB << FixItHint::CreateInsertion(Loc, "this->"); 2025 return CXXDependentScopeMemberExpr::Create( 2026 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2027 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2028 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2029 } 2030 2031 // Synthesize a fake NNS that points to the derived class. This will 2032 // perform name lookup during template instantiation. 2033 CXXScopeSpec SS; 2034 auto *NNS = 2035 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2036 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2037 return DependentScopeDeclRefExpr::Create( 2038 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2039 TemplateArgs); 2040 } 2041 2042 ExprResult 2043 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2044 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2045 bool HasTrailingLParen, bool IsAddressOfOperand, 2046 std::unique_ptr<CorrectionCandidateCallback> CCC, 2047 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2048 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2049 "cannot be direct & operand and have a trailing lparen"); 2050 if (SS.isInvalid()) 2051 return ExprError(); 2052 2053 TemplateArgumentListInfo TemplateArgsBuffer; 2054 2055 // Decompose the UnqualifiedId into the following data. 2056 DeclarationNameInfo NameInfo; 2057 const TemplateArgumentListInfo *TemplateArgs; 2058 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2059 2060 DeclarationName Name = NameInfo.getName(); 2061 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2062 SourceLocation NameLoc = NameInfo.getLoc(); 2063 2064 // C++ [temp.dep.expr]p3: 2065 // An id-expression is type-dependent if it contains: 2066 // -- an identifier that was declared with a dependent type, 2067 // (note: handled after lookup) 2068 // -- a template-id that is dependent, 2069 // (note: handled in BuildTemplateIdExpr) 2070 // -- a conversion-function-id that specifies a dependent type, 2071 // -- a nested-name-specifier that contains a class-name that 2072 // names a dependent type. 2073 // Determine whether this is a member of an unknown specialization; 2074 // we need to handle these differently. 2075 bool DependentID = false; 2076 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2077 Name.getCXXNameType()->isDependentType()) { 2078 DependentID = true; 2079 } else if (SS.isSet()) { 2080 if (DeclContext *DC = computeDeclContext(SS, false)) { 2081 if (RequireCompleteDeclContext(SS, DC)) 2082 return ExprError(); 2083 } else { 2084 DependentID = true; 2085 } 2086 } 2087 2088 if (DependentID) 2089 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2090 IsAddressOfOperand, TemplateArgs); 2091 2092 // Perform the required lookup. 2093 LookupResult R(*this, NameInfo, 2094 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 2095 ? LookupObjCImplicitSelfParam : LookupOrdinaryName); 2096 if (TemplateArgs) { 2097 // Lookup the template name again to correctly establish the context in 2098 // which it was found. This is really unfortunate as we already did the 2099 // lookup to determine that it was a template name in the first place. If 2100 // this becomes a performance hit, we can work harder to preserve those 2101 // results until we get here but it's likely not worth it. 2102 bool MemberOfUnknownSpecialization; 2103 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2104 MemberOfUnknownSpecialization); 2105 2106 if (MemberOfUnknownSpecialization || 2107 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2108 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2109 IsAddressOfOperand, TemplateArgs); 2110 } else { 2111 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2112 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2113 2114 // If the result might be in a dependent base class, this is a dependent 2115 // id-expression. 2116 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2117 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2118 IsAddressOfOperand, TemplateArgs); 2119 2120 // If this reference is in an Objective-C method, then we need to do 2121 // some special Objective-C lookup, too. 2122 if (IvarLookupFollowUp) { 2123 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2124 if (E.isInvalid()) 2125 return ExprError(); 2126 2127 if (Expr *Ex = E.getAs<Expr>()) 2128 return Ex; 2129 } 2130 } 2131 2132 if (R.isAmbiguous()) 2133 return ExprError(); 2134 2135 // This could be an implicitly declared function reference (legal in C90, 2136 // extension in C99, forbidden in C++). 2137 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2138 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2139 if (D) R.addDecl(D); 2140 } 2141 2142 // Determine whether this name might be a candidate for 2143 // argument-dependent lookup. 2144 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2145 2146 if (R.empty() && !ADL) { 2147 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2148 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2149 TemplateKWLoc, TemplateArgs)) 2150 return E; 2151 } 2152 2153 // Don't diagnose an empty lookup for inline assembly. 2154 if (IsInlineAsmIdentifier) 2155 return ExprError(); 2156 2157 // If this name wasn't predeclared and if this is not a function 2158 // call, diagnose the problem. 2159 TypoExpr *TE = nullptr; 2160 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2161 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2162 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2163 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2164 "Typo correction callback misconfigured"); 2165 if (CCC) { 2166 // Make sure the callback knows what the typo being diagnosed is. 2167 CCC->setTypoName(II); 2168 if (SS.isValid()) 2169 CCC->setTypoNNS(SS.getScopeRep()); 2170 } 2171 if (DiagnoseEmptyLookup(S, SS, R, 2172 CCC ? std::move(CCC) : std::move(DefaultValidator), 2173 nullptr, None, &TE)) { 2174 if (TE && KeywordReplacement) { 2175 auto &State = getTypoExprState(TE); 2176 auto BestTC = State.Consumer->getNextCorrection(); 2177 if (BestTC.isKeyword()) { 2178 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2179 if (State.DiagHandler) 2180 State.DiagHandler(BestTC); 2181 KeywordReplacement->startToken(); 2182 KeywordReplacement->setKind(II->getTokenID()); 2183 KeywordReplacement->setIdentifierInfo(II); 2184 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2185 // Clean up the state associated with the TypoExpr, since it has 2186 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2187 clearDelayedTypo(TE); 2188 // Signal that a correction to a keyword was performed by returning a 2189 // valid-but-null ExprResult. 2190 return (Expr*)nullptr; 2191 } 2192 State.Consumer->resetCorrectionStream(); 2193 } 2194 return TE ? TE : ExprError(); 2195 } 2196 2197 assert(!R.empty() && 2198 "DiagnoseEmptyLookup returned false but added no results"); 2199 2200 // If we found an Objective-C instance variable, let 2201 // LookupInObjCMethod build the appropriate expression to 2202 // reference the ivar. 2203 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2204 R.clear(); 2205 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2206 // In a hopelessly buggy code, Objective-C instance variable 2207 // lookup fails and no expression will be built to reference it. 2208 if (!E.isInvalid() && !E.get()) 2209 return ExprError(); 2210 return E; 2211 } 2212 } 2213 2214 // This is guaranteed from this point on. 2215 assert(!R.empty() || ADL); 2216 2217 // Check whether this might be a C++ implicit instance member access. 2218 // C++ [class.mfct.non-static]p3: 2219 // When an id-expression that is not part of a class member access 2220 // syntax and not used to form a pointer to member is used in the 2221 // body of a non-static member function of class X, if name lookup 2222 // resolves the name in the id-expression to a non-static non-type 2223 // member of some class C, the id-expression is transformed into a 2224 // class member access expression using (*this) as the 2225 // postfix-expression to the left of the . operator. 2226 // 2227 // But we don't actually need to do this for '&' operands if R 2228 // resolved to a function or overloaded function set, because the 2229 // expression is ill-formed if it actually works out to be a 2230 // non-static member function: 2231 // 2232 // C++ [expr.ref]p4: 2233 // Otherwise, if E1.E2 refers to a non-static member function. . . 2234 // [t]he expression can be used only as the left-hand operand of a 2235 // member function call. 2236 // 2237 // There are other safeguards against such uses, but it's important 2238 // to get this right here so that we don't end up making a 2239 // spuriously dependent expression if we're inside a dependent 2240 // instance method. 2241 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2242 bool MightBeImplicitMember; 2243 if (!IsAddressOfOperand) 2244 MightBeImplicitMember = true; 2245 else if (!SS.isEmpty()) 2246 MightBeImplicitMember = false; 2247 else if (R.isOverloadedResult()) 2248 MightBeImplicitMember = false; 2249 else if (R.isUnresolvableResult()) 2250 MightBeImplicitMember = true; 2251 else 2252 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2253 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2254 isa<MSPropertyDecl>(R.getFoundDecl()); 2255 2256 if (MightBeImplicitMember) 2257 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2258 R, TemplateArgs, S); 2259 } 2260 2261 if (TemplateArgs || TemplateKWLoc.isValid()) { 2262 2263 // In C++1y, if this is a variable template id, then check it 2264 // in BuildTemplateIdExpr(). 2265 // The single lookup result must be a variable template declaration. 2266 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId && 2267 Id.TemplateId->Kind == TNK_Var_template) { 2268 assert(R.getAsSingle<VarTemplateDecl>() && 2269 "There should only be one declaration found."); 2270 } 2271 2272 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2273 } 2274 2275 return BuildDeclarationNameExpr(SS, R, ADL); 2276 } 2277 2278 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2279 /// declaration name, generally during template instantiation. 2280 /// There's a large number of things which don't need to be done along 2281 /// this path. 2282 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2283 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2284 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2285 DeclContext *DC = computeDeclContext(SS, false); 2286 if (!DC) 2287 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2288 NameInfo, /*TemplateArgs=*/nullptr); 2289 2290 if (RequireCompleteDeclContext(SS, DC)) 2291 return ExprError(); 2292 2293 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2294 LookupQualifiedName(R, DC); 2295 2296 if (R.isAmbiguous()) 2297 return ExprError(); 2298 2299 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2300 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2301 NameInfo, /*TemplateArgs=*/nullptr); 2302 2303 if (R.empty()) { 2304 Diag(NameInfo.getLoc(), diag::err_no_member) 2305 << NameInfo.getName() << DC << SS.getRange(); 2306 return ExprError(); 2307 } 2308 2309 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2310 // Diagnose a missing typename if this resolved unambiguously to a type in 2311 // a dependent context. If we can recover with a type, downgrade this to 2312 // a warning in Microsoft compatibility mode. 2313 unsigned DiagID = diag::err_typename_missing; 2314 if (RecoveryTSI && getLangOpts().MSVCCompat) 2315 DiagID = diag::ext_typename_missing; 2316 SourceLocation Loc = SS.getBeginLoc(); 2317 auto D = Diag(Loc, DiagID); 2318 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2319 << SourceRange(Loc, NameInfo.getEndLoc()); 2320 2321 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2322 // context. 2323 if (!RecoveryTSI) 2324 return ExprError(); 2325 2326 // Only issue the fixit if we're prepared to recover. 2327 D << FixItHint::CreateInsertion(Loc, "typename "); 2328 2329 // Recover by pretending this was an elaborated type. 2330 QualType Ty = Context.getTypeDeclType(TD); 2331 TypeLocBuilder TLB; 2332 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2333 2334 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2335 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2336 QTL.setElaboratedKeywordLoc(SourceLocation()); 2337 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2338 2339 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2340 2341 return ExprEmpty(); 2342 } 2343 2344 // Defend against this resolving to an implicit member access. We usually 2345 // won't get here if this might be a legitimate a class member (we end up in 2346 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2347 // a pointer-to-member or in an unevaluated context in C++11. 2348 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2349 return BuildPossibleImplicitMemberExpr(SS, 2350 /*TemplateKWLoc=*/SourceLocation(), 2351 R, /*TemplateArgs=*/nullptr, S); 2352 2353 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2354 } 2355 2356 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2357 /// detected that we're currently inside an ObjC method. Perform some 2358 /// additional lookup. 2359 /// 2360 /// Ideally, most of this would be done by lookup, but there's 2361 /// actually quite a lot of extra work involved. 2362 /// 2363 /// Returns a null sentinel to indicate trivial success. 2364 ExprResult 2365 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2366 IdentifierInfo *II, bool AllowBuiltinCreation) { 2367 SourceLocation Loc = Lookup.getNameLoc(); 2368 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2369 2370 // Check for error condition which is already reported. 2371 if (!CurMethod) 2372 return ExprError(); 2373 2374 // There are two cases to handle here. 1) scoped lookup could have failed, 2375 // in which case we should look for an ivar. 2) scoped lookup could have 2376 // found a decl, but that decl is outside the current instance method (i.e. 2377 // a global variable). In these two cases, we do a lookup for an ivar with 2378 // this name, if the lookup sucedes, we replace it our current decl. 2379 2380 // If we're in a class method, we don't normally want to look for 2381 // ivars. But if we don't find anything else, and there's an 2382 // ivar, that's an error. 2383 bool IsClassMethod = CurMethod->isClassMethod(); 2384 2385 bool LookForIvars; 2386 if (Lookup.empty()) 2387 LookForIvars = true; 2388 else if (IsClassMethod) 2389 LookForIvars = false; 2390 else 2391 LookForIvars = (Lookup.isSingleResult() && 2392 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2393 ObjCInterfaceDecl *IFace = nullptr; 2394 if (LookForIvars) { 2395 IFace = CurMethod->getClassInterface(); 2396 ObjCInterfaceDecl *ClassDeclared; 2397 ObjCIvarDecl *IV = nullptr; 2398 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2399 // Diagnose using an ivar in a class method. 2400 if (IsClassMethod) 2401 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2402 << IV->getDeclName()); 2403 2404 // If we're referencing an invalid decl, just return this as a silent 2405 // error node. The error diagnostic was already emitted on the decl. 2406 if (IV->isInvalidDecl()) 2407 return ExprError(); 2408 2409 // Check if referencing a field with __attribute__((deprecated)). 2410 if (DiagnoseUseOfDecl(IV, Loc)) 2411 return ExprError(); 2412 2413 // Diagnose the use of an ivar outside of the declaring class. 2414 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2415 !declaresSameEntity(ClassDeclared, IFace) && 2416 !getLangOpts().DebuggerSupport) 2417 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName(); 2418 2419 // FIXME: This should use a new expr for a direct reference, don't 2420 // turn this into Self->ivar, just return a BareIVarExpr or something. 2421 IdentifierInfo &II = Context.Idents.get("self"); 2422 UnqualifiedId SelfName; 2423 SelfName.setIdentifier(&II, SourceLocation()); 2424 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam); 2425 CXXScopeSpec SelfScopeSpec; 2426 SourceLocation TemplateKWLoc; 2427 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2428 SelfName, false, false); 2429 if (SelfExpr.isInvalid()) 2430 return ExprError(); 2431 2432 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2433 if (SelfExpr.isInvalid()) 2434 return ExprError(); 2435 2436 MarkAnyDeclReferenced(Loc, IV, true); 2437 2438 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2439 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2440 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2441 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2442 2443 ObjCIvarRefExpr *Result = new (Context) 2444 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2445 IV->getLocation(), SelfExpr.get(), true, true); 2446 2447 if (getLangOpts().ObjCAutoRefCount) { 2448 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2449 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2450 recordUseOfEvaluatedWeak(Result); 2451 } 2452 if (CurContext->isClosure()) 2453 Diag(Loc, diag::warn_implicitly_retains_self) 2454 << FixItHint::CreateInsertion(Loc, "self->"); 2455 } 2456 2457 return Result; 2458 } 2459 } else if (CurMethod->isInstanceMethod()) { 2460 // We should warn if a local variable hides an ivar. 2461 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2462 ObjCInterfaceDecl *ClassDeclared; 2463 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2464 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2465 declaresSameEntity(IFace, ClassDeclared)) 2466 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2467 } 2468 } 2469 } else if (Lookup.isSingleResult() && 2470 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2471 // If accessing a stand-alone ivar in a class method, this is an error. 2472 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2473 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method) 2474 << IV->getDeclName()); 2475 } 2476 2477 if (Lookup.empty() && II && AllowBuiltinCreation) { 2478 // FIXME. Consolidate this with similar code in LookupName. 2479 if (unsigned BuiltinID = II->getBuiltinID()) { 2480 if (!(getLangOpts().CPlusPlus && 2481 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2482 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2483 S, Lookup.isForRedeclaration(), 2484 Lookup.getNameLoc()); 2485 if (D) Lookup.addDecl(D); 2486 } 2487 } 2488 } 2489 // Sentinel value saying that we didn't do anything special. 2490 return ExprResult((Expr *)nullptr); 2491 } 2492 2493 /// \brief Cast a base object to a member's actual type. 2494 /// 2495 /// Logically this happens in three phases: 2496 /// 2497 /// * First we cast from the base type to the naming class. 2498 /// The naming class is the class into which we were looking 2499 /// when we found the member; it's the qualifier type if a 2500 /// qualifier was provided, and otherwise it's the base type. 2501 /// 2502 /// * Next we cast from the naming class to the declaring class. 2503 /// If the member we found was brought into a class's scope by 2504 /// a using declaration, this is that class; otherwise it's 2505 /// the class declaring the member. 2506 /// 2507 /// * Finally we cast from the declaring class to the "true" 2508 /// declaring class of the member. This conversion does not 2509 /// obey access control. 2510 ExprResult 2511 Sema::PerformObjectMemberConversion(Expr *From, 2512 NestedNameSpecifier *Qualifier, 2513 NamedDecl *FoundDecl, 2514 NamedDecl *Member) { 2515 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2516 if (!RD) 2517 return From; 2518 2519 QualType DestRecordType; 2520 QualType DestType; 2521 QualType FromRecordType; 2522 QualType FromType = From->getType(); 2523 bool PointerConversions = false; 2524 if (isa<FieldDecl>(Member)) { 2525 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2526 2527 if (FromType->getAs<PointerType>()) { 2528 DestType = Context.getPointerType(DestRecordType); 2529 FromRecordType = FromType->getPointeeType(); 2530 PointerConversions = true; 2531 } else { 2532 DestType = DestRecordType; 2533 FromRecordType = FromType; 2534 } 2535 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2536 if (Method->isStatic()) 2537 return From; 2538 2539 DestType = Method->getThisType(Context); 2540 DestRecordType = DestType->getPointeeType(); 2541 2542 if (FromType->getAs<PointerType>()) { 2543 FromRecordType = FromType->getPointeeType(); 2544 PointerConversions = true; 2545 } else { 2546 FromRecordType = FromType; 2547 DestType = DestRecordType; 2548 } 2549 } else { 2550 // No conversion necessary. 2551 return From; 2552 } 2553 2554 if (DestType->isDependentType() || FromType->isDependentType()) 2555 return From; 2556 2557 // If the unqualified types are the same, no conversion is necessary. 2558 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2559 return From; 2560 2561 SourceRange FromRange = From->getSourceRange(); 2562 SourceLocation FromLoc = FromRange.getBegin(); 2563 2564 ExprValueKind VK = From->getValueKind(); 2565 2566 // C++ [class.member.lookup]p8: 2567 // [...] Ambiguities can often be resolved by qualifying a name with its 2568 // class name. 2569 // 2570 // If the member was a qualified name and the qualified referred to a 2571 // specific base subobject type, we'll cast to that intermediate type 2572 // first and then to the object in which the member is declared. That allows 2573 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2574 // 2575 // class Base { public: int x; }; 2576 // class Derived1 : public Base { }; 2577 // class Derived2 : public Base { }; 2578 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2579 // 2580 // void VeryDerived::f() { 2581 // x = 17; // error: ambiguous base subobjects 2582 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2583 // } 2584 if (Qualifier && Qualifier->getAsType()) { 2585 QualType QType = QualType(Qualifier->getAsType(), 0); 2586 assert(QType->isRecordType() && "lookup done with non-record type"); 2587 2588 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2589 2590 // In C++98, the qualifier type doesn't actually have to be a base 2591 // type of the object type, in which case we just ignore it. 2592 // Otherwise build the appropriate casts. 2593 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2594 CXXCastPath BasePath; 2595 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2596 FromLoc, FromRange, &BasePath)) 2597 return ExprError(); 2598 2599 if (PointerConversions) 2600 QType = Context.getPointerType(QType); 2601 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2602 VK, &BasePath).get(); 2603 2604 FromType = QType; 2605 FromRecordType = QRecordType; 2606 2607 // If the qualifier type was the same as the destination type, 2608 // we're done. 2609 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2610 return From; 2611 } 2612 } 2613 2614 bool IgnoreAccess = false; 2615 2616 // If we actually found the member through a using declaration, cast 2617 // down to the using declaration's type. 2618 // 2619 // Pointer equality is fine here because only one declaration of a 2620 // class ever has member declarations. 2621 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2622 assert(isa<UsingShadowDecl>(FoundDecl)); 2623 QualType URecordType = Context.getTypeDeclType( 2624 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2625 2626 // We only need to do this if the naming-class to declaring-class 2627 // conversion is non-trivial. 2628 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2629 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2630 CXXCastPath BasePath; 2631 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2632 FromLoc, FromRange, &BasePath)) 2633 return ExprError(); 2634 2635 QualType UType = URecordType; 2636 if (PointerConversions) 2637 UType = Context.getPointerType(UType); 2638 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2639 VK, &BasePath).get(); 2640 FromType = UType; 2641 FromRecordType = URecordType; 2642 } 2643 2644 // We don't do access control for the conversion from the 2645 // declaring class to the true declaring class. 2646 IgnoreAccess = true; 2647 } 2648 2649 CXXCastPath BasePath; 2650 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2651 FromLoc, FromRange, &BasePath, 2652 IgnoreAccess)) 2653 return ExprError(); 2654 2655 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2656 VK, &BasePath); 2657 } 2658 2659 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2660 const LookupResult &R, 2661 bool HasTrailingLParen) { 2662 // Only when used directly as the postfix-expression of a call. 2663 if (!HasTrailingLParen) 2664 return false; 2665 2666 // Never if a scope specifier was provided. 2667 if (SS.isSet()) 2668 return false; 2669 2670 // Only in C++ or ObjC++. 2671 if (!getLangOpts().CPlusPlus) 2672 return false; 2673 2674 // Turn off ADL when we find certain kinds of declarations during 2675 // normal lookup: 2676 for (NamedDecl *D : R) { 2677 // C++0x [basic.lookup.argdep]p3: 2678 // -- a declaration of a class member 2679 // Since using decls preserve this property, we check this on the 2680 // original decl. 2681 if (D->isCXXClassMember()) 2682 return false; 2683 2684 // C++0x [basic.lookup.argdep]p3: 2685 // -- a block-scope function declaration that is not a 2686 // using-declaration 2687 // NOTE: we also trigger this for function templates (in fact, we 2688 // don't check the decl type at all, since all other decl types 2689 // turn off ADL anyway). 2690 if (isa<UsingShadowDecl>(D)) 2691 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2692 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2693 return false; 2694 2695 // C++0x [basic.lookup.argdep]p3: 2696 // -- a declaration that is neither a function or a function 2697 // template 2698 // And also for builtin functions. 2699 if (isa<FunctionDecl>(D)) { 2700 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2701 2702 // But also builtin functions. 2703 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2704 return false; 2705 } else if (!isa<FunctionTemplateDecl>(D)) 2706 return false; 2707 } 2708 2709 return true; 2710 } 2711 2712 2713 /// Diagnoses obvious problems with the use of the given declaration 2714 /// as an expression. This is only actually called for lookups that 2715 /// were not overloaded, and it doesn't promise that the declaration 2716 /// will in fact be used. 2717 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2718 if (isa<TypedefNameDecl>(D)) { 2719 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2720 return true; 2721 } 2722 2723 if (isa<ObjCInterfaceDecl>(D)) { 2724 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2725 return true; 2726 } 2727 2728 if (isa<NamespaceDecl>(D)) { 2729 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2730 return true; 2731 } 2732 2733 return false; 2734 } 2735 2736 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2737 LookupResult &R, bool NeedsADL, 2738 bool AcceptInvalidDecl) { 2739 // If this is a single, fully-resolved result and we don't need ADL, 2740 // just build an ordinary singleton decl ref. 2741 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>()) 2742 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2743 R.getRepresentativeDecl(), nullptr, 2744 AcceptInvalidDecl); 2745 2746 // We only need to check the declaration if there's exactly one 2747 // result, because in the overloaded case the results can only be 2748 // functions and function templates. 2749 if (R.isSingleResult() && 2750 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2751 return ExprError(); 2752 2753 // Otherwise, just build an unresolved lookup expression. Suppress 2754 // any lookup-related diagnostics; we'll hash these out later, when 2755 // we've picked a target. 2756 R.suppressDiagnostics(); 2757 2758 UnresolvedLookupExpr *ULE 2759 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2760 SS.getWithLocInContext(Context), 2761 R.getLookupNameInfo(), 2762 NeedsADL, R.isOverloadedResult(), 2763 R.begin(), R.end()); 2764 2765 return ULE; 2766 } 2767 2768 /// \brief Complete semantic analysis for a reference to the given declaration. 2769 ExprResult Sema::BuildDeclarationNameExpr( 2770 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2771 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2772 bool AcceptInvalidDecl) { 2773 assert(D && "Cannot refer to a NULL declaration"); 2774 assert(!isa<FunctionTemplateDecl>(D) && 2775 "Cannot refer unambiguously to a function template"); 2776 2777 SourceLocation Loc = NameInfo.getLoc(); 2778 if (CheckDeclInExpr(*this, Loc, D)) 2779 return ExprError(); 2780 2781 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2782 // Specifically diagnose references to class templates that are missing 2783 // a template argument list. 2784 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0) 2785 << Template << SS.getRange(); 2786 Diag(Template->getLocation(), diag::note_template_decl_here); 2787 return ExprError(); 2788 } 2789 2790 // Make sure that we're referring to a value. 2791 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2792 if (!VD) { 2793 Diag(Loc, diag::err_ref_non_value) 2794 << D << SS.getRange(); 2795 Diag(D->getLocation(), diag::note_declared_at); 2796 return ExprError(); 2797 } 2798 2799 // Check whether this declaration can be used. Note that we suppress 2800 // this check when we're going to perform argument-dependent lookup 2801 // on this function name, because this might not be the function 2802 // that overload resolution actually selects. 2803 if (DiagnoseUseOfDecl(VD, Loc)) 2804 return ExprError(); 2805 2806 // Only create DeclRefExpr's for valid Decl's. 2807 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2808 return ExprError(); 2809 2810 // Handle members of anonymous structs and unions. If we got here, 2811 // and the reference is to a class member indirect field, then this 2812 // must be the subject of a pointer-to-member expression. 2813 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2814 if (!indirectField->isCXXClassMember()) 2815 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2816 indirectField); 2817 2818 { 2819 QualType type = VD->getType(); 2820 ExprValueKind valueKind = VK_RValue; 2821 2822 switch (D->getKind()) { 2823 // Ignore all the non-ValueDecl kinds. 2824 #define ABSTRACT_DECL(kind) 2825 #define VALUE(type, base) 2826 #define DECL(type, base) \ 2827 case Decl::type: 2828 #include "clang/AST/DeclNodes.inc" 2829 llvm_unreachable("invalid value decl kind"); 2830 2831 // These shouldn't make it here. 2832 case Decl::ObjCAtDefsField: 2833 case Decl::ObjCIvar: 2834 llvm_unreachable("forming non-member reference to ivar?"); 2835 2836 // Enum constants are always r-values and never references. 2837 // Unresolved using declarations are dependent. 2838 case Decl::EnumConstant: 2839 case Decl::UnresolvedUsingValue: 2840 valueKind = VK_RValue; 2841 break; 2842 2843 // Fields and indirect fields that got here must be for 2844 // pointer-to-member expressions; we just call them l-values for 2845 // internal consistency, because this subexpression doesn't really 2846 // exist in the high-level semantics. 2847 case Decl::Field: 2848 case Decl::IndirectField: 2849 assert(getLangOpts().CPlusPlus && 2850 "building reference to field in C?"); 2851 2852 // These can't have reference type in well-formed programs, but 2853 // for internal consistency we do this anyway. 2854 type = type.getNonReferenceType(); 2855 valueKind = VK_LValue; 2856 break; 2857 2858 // Non-type template parameters are either l-values or r-values 2859 // depending on the type. 2860 case Decl::NonTypeTemplateParm: { 2861 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2862 type = reftype->getPointeeType(); 2863 valueKind = VK_LValue; // even if the parameter is an r-value reference 2864 break; 2865 } 2866 2867 // For non-references, we need to strip qualifiers just in case 2868 // the template parameter was declared as 'const int' or whatever. 2869 valueKind = VK_RValue; 2870 type = type.getUnqualifiedType(); 2871 break; 2872 } 2873 2874 case Decl::Var: 2875 case Decl::VarTemplateSpecialization: 2876 case Decl::VarTemplatePartialSpecialization: 2877 // In C, "extern void blah;" is valid and is an r-value. 2878 if (!getLangOpts().CPlusPlus && 2879 !type.hasQualifiers() && 2880 type->isVoidType()) { 2881 valueKind = VK_RValue; 2882 break; 2883 } 2884 // fallthrough 2885 2886 case Decl::ImplicitParam: 2887 case Decl::ParmVar: { 2888 // These are always l-values. 2889 valueKind = VK_LValue; 2890 type = type.getNonReferenceType(); 2891 2892 // FIXME: Does the addition of const really only apply in 2893 // potentially-evaluated contexts? Since the variable isn't actually 2894 // captured in an unevaluated context, it seems that the answer is no. 2895 if (!isUnevaluatedContext()) { 2896 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2897 if (!CapturedType.isNull()) 2898 type = CapturedType; 2899 } 2900 2901 break; 2902 } 2903 2904 case Decl::Function: { 2905 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2906 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2907 type = Context.BuiltinFnTy; 2908 valueKind = VK_RValue; 2909 break; 2910 } 2911 } 2912 2913 const FunctionType *fty = type->castAs<FunctionType>(); 2914 2915 // If we're referring to a function with an __unknown_anytype 2916 // result type, make the entire expression __unknown_anytype. 2917 if (fty->getReturnType() == Context.UnknownAnyTy) { 2918 type = Context.UnknownAnyTy; 2919 valueKind = VK_RValue; 2920 break; 2921 } 2922 2923 // Functions are l-values in C++. 2924 if (getLangOpts().CPlusPlus) { 2925 valueKind = VK_LValue; 2926 break; 2927 } 2928 2929 // C99 DR 316 says that, if a function type comes from a 2930 // function definition (without a prototype), that type is only 2931 // used for checking compatibility. Therefore, when referencing 2932 // the function, we pretend that we don't have the full function 2933 // type. 2934 if (!cast<FunctionDecl>(VD)->hasPrototype() && 2935 isa<FunctionProtoType>(fty)) 2936 type = Context.getFunctionNoProtoType(fty->getReturnType(), 2937 fty->getExtInfo()); 2938 2939 // Functions are r-values in C. 2940 valueKind = VK_RValue; 2941 break; 2942 } 2943 2944 case Decl::MSProperty: 2945 valueKind = VK_LValue; 2946 break; 2947 2948 case Decl::CXXMethod: 2949 // If we're referring to a method with an __unknown_anytype 2950 // result type, make the entire expression __unknown_anytype. 2951 // This should only be possible with a type written directly. 2952 if (const FunctionProtoType *proto 2953 = dyn_cast<FunctionProtoType>(VD->getType())) 2954 if (proto->getReturnType() == Context.UnknownAnyTy) { 2955 type = Context.UnknownAnyTy; 2956 valueKind = VK_RValue; 2957 break; 2958 } 2959 2960 // C++ methods are l-values if static, r-values if non-static. 2961 if (cast<CXXMethodDecl>(VD)->isStatic()) { 2962 valueKind = VK_LValue; 2963 break; 2964 } 2965 // fallthrough 2966 2967 case Decl::CXXConversion: 2968 case Decl::CXXDestructor: 2969 case Decl::CXXConstructor: 2970 valueKind = VK_RValue; 2971 break; 2972 } 2973 2974 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 2975 TemplateArgs); 2976 } 2977 } 2978 2979 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 2980 SmallString<32> &Target) { 2981 Target.resize(CharByteWidth * (Source.size() + 1)); 2982 char *ResultPtr = &Target[0]; 2983 const UTF8 *ErrorPtr; 2984 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 2985 (void)success; 2986 assert(success); 2987 Target.resize(ResultPtr - &Target[0]); 2988 } 2989 2990 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 2991 PredefinedExpr::IdentType IT) { 2992 // Pick the current block, lambda, captured statement or function. 2993 Decl *currentDecl = nullptr; 2994 if (const BlockScopeInfo *BSI = getCurBlock()) 2995 currentDecl = BSI->TheDecl; 2996 else if (const LambdaScopeInfo *LSI = getCurLambda()) 2997 currentDecl = LSI->CallOperator; 2998 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 2999 currentDecl = CSI->TheCapturedDecl; 3000 else 3001 currentDecl = getCurFunctionOrMethodDecl(); 3002 3003 if (!currentDecl) { 3004 Diag(Loc, diag::ext_predef_outside_function); 3005 currentDecl = Context.getTranslationUnitDecl(); 3006 } 3007 3008 QualType ResTy; 3009 StringLiteral *SL = nullptr; 3010 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3011 ResTy = Context.DependentTy; 3012 else { 3013 // Pre-defined identifiers are of type char[x], where x is the length of 3014 // the string. 3015 auto Str = PredefinedExpr::ComputeName(IT, currentDecl); 3016 unsigned Length = Str.length(); 3017 3018 llvm::APInt LengthI(32, Length + 1); 3019 if (IT == PredefinedExpr::LFunction) { 3020 ResTy = Context.WideCharTy.withConst(); 3021 SmallString<32> RawChars; 3022 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3023 Str, RawChars); 3024 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3025 /*IndexTypeQuals*/ 0); 3026 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3027 /*Pascal*/ false, ResTy, Loc); 3028 } else { 3029 ResTy = Context.CharTy.withConst(); 3030 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3031 /*IndexTypeQuals*/ 0); 3032 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3033 /*Pascal*/ false, ResTy, Loc); 3034 } 3035 } 3036 3037 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL); 3038 } 3039 3040 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3041 PredefinedExpr::IdentType IT; 3042 3043 switch (Kind) { 3044 default: llvm_unreachable("Unknown simple primary expr!"); 3045 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3046 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break; 3047 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS] 3048 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS] 3049 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break; 3050 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break; 3051 } 3052 3053 return BuildPredefinedExpr(Loc, IT); 3054 } 3055 3056 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3057 SmallString<16> CharBuffer; 3058 bool Invalid = false; 3059 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3060 if (Invalid) 3061 return ExprError(); 3062 3063 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3064 PP, Tok.getKind()); 3065 if (Literal.hadError()) 3066 return ExprError(); 3067 3068 QualType Ty; 3069 if (Literal.isWide()) 3070 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3071 else if (Literal.isUTF16()) 3072 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3073 else if (Literal.isUTF32()) 3074 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3075 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3076 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3077 else 3078 Ty = Context.CharTy; // 'x' -> char in C++ 3079 3080 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3081 if (Literal.isWide()) 3082 Kind = CharacterLiteral::Wide; 3083 else if (Literal.isUTF16()) 3084 Kind = CharacterLiteral::UTF16; 3085 else if (Literal.isUTF32()) 3086 Kind = CharacterLiteral::UTF32; 3087 else if (Literal.isUTF8()) 3088 Kind = CharacterLiteral::UTF8; 3089 3090 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3091 Tok.getLocation()); 3092 3093 if (Literal.getUDSuffix().empty()) 3094 return Lit; 3095 3096 // We're building a user-defined literal. 3097 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3098 SourceLocation UDSuffixLoc = 3099 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3100 3101 // Make sure we're allowed user-defined literals here. 3102 if (!UDLScope) 3103 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3104 3105 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3106 // operator "" X (ch) 3107 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3108 Lit, Tok.getLocation()); 3109 } 3110 3111 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3112 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3113 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3114 Context.IntTy, Loc); 3115 } 3116 3117 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3118 QualType Ty, SourceLocation Loc) { 3119 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3120 3121 using llvm::APFloat; 3122 APFloat Val(Format); 3123 3124 APFloat::opStatus result = Literal.GetFloatValue(Val); 3125 3126 // Overflow is always an error, but underflow is only an error if 3127 // we underflowed to zero (APFloat reports denormals as underflow). 3128 if ((result & APFloat::opOverflow) || 3129 ((result & APFloat::opUnderflow) && Val.isZero())) { 3130 unsigned diagnostic; 3131 SmallString<20> buffer; 3132 if (result & APFloat::opOverflow) { 3133 diagnostic = diag::warn_float_overflow; 3134 APFloat::getLargest(Format).toString(buffer); 3135 } else { 3136 diagnostic = diag::warn_float_underflow; 3137 APFloat::getSmallest(Format).toString(buffer); 3138 } 3139 3140 S.Diag(Loc, diagnostic) 3141 << Ty 3142 << StringRef(buffer.data(), buffer.size()); 3143 } 3144 3145 bool isExact = (result == APFloat::opOK); 3146 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3147 } 3148 3149 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3150 assert(E && "Invalid expression"); 3151 3152 if (E->isValueDependent()) 3153 return false; 3154 3155 QualType QT = E->getType(); 3156 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3157 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3158 return true; 3159 } 3160 3161 llvm::APSInt ValueAPS; 3162 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3163 3164 if (R.isInvalid()) 3165 return true; 3166 3167 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3168 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3169 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3170 << ValueAPS.toString(10) << ValueIsPositive; 3171 return true; 3172 } 3173 3174 return false; 3175 } 3176 3177 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3178 // Fast path for a single digit (which is quite common). A single digit 3179 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3180 if (Tok.getLength() == 1) { 3181 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3182 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3183 } 3184 3185 SmallString<128> SpellingBuffer; 3186 // NumericLiteralParser wants to overread by one character. Add padding to 3187 // the buffer in case the token is copied to the buffer. If getSpelling() 3188 // returns a StringRef to the memory buffer, it should have a null char at 3189 // the EOF, so it is also safe. 3190 SpellingBuffer.resize(Tok.getLength() + 1); 3191 3192 // Get the spelling of the token, which eliminates trigraphs, etc. 3193 bool Invalid = false; 3194 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3195 if (Invalid) 3196 return ExprError(); 3197 3198 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3199 if (Literal.hadError) 3200 return ExprError(); 3201 3202 if (Literal.hasUDSuffix()) { 3203 // We're building a user-defined literal. 3204 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3205 SourceLocation UDSuffixLoc = 3206 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3207 3208 // Make sure we're allowed user-defined literals here. 3209 if (!UDLScope) 3210 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3211 3212 QualType CookedTy; 3213 if (Literal.isFloatingLiteral()) { 3214 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3215 // long double, the literal is treated as a call of the form 3216 // operator "" X (f L) 3217 CookedTy = Context.LongDoubleTy; 3218 } else { 3219 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3220 // unsigned long long, the literal is treated as a call of the form 3221 // operator "" X (n ULL) 3222 CookedTy = Context.UnsignedLongLongTy; 3223 } 3224 3225 DeclarationName OpName = 3226 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3227 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3228 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3229 3230 SourceLocation TokLoc = Tok.getLocation(); 3231 3232 // Perform literal operator lookup to determine if we're building a raw 3233 // literal or a cooked one. 3234 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3235 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3236 /*AllowRaw*/true, /*AllowTemplate*/true, 3237 /*AllowStringTemplate*/false)) { 3238 case LOLR_Error: 3239 return ExprError(); 3240 3241 case LOLR_Cooked: { 3242 Expr *Lit; 3243 if (Literal.isFloatingLiteral()) { 3244 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3245 } else { 3246 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3247 if (Literal.GetIntegerValue(ResultVal)) 3248 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3249 << /* Unsigned */ 1; 3250 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3251 Tok.getLocation()); 3252 } 3253 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3254 } 3255 3256 case LOLR_Raw: { 3257 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3258 // literal is treated as a call of the form 3259 // operator "" X ("n") 3260 unsigned Length = Literal.getUDSuffixOffset(); 3261 QualType StrTy = Context.getConstantArrayType( 3262 Context.CharTy.withConst(), llvm::APInt(32, Length + 1), 3263 ArrayType::Normal, 0); 3264 Expr *Lit = StringLiteral::Create( 3265 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3266 /*Pascal*/false, StrTy, &TokLoc, 1); 3267 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3268 } 3269 3270 case LOLR_Template: { 3271 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3272 // template), L is treated as a call fo the form 3273 // operator "" X <'c1', 'c2', ... 'ck'>() 3274 // where n is the source character sequence c1 c2 ... ck. 3275 TemplateArgumentListInfo ExplicitArgs; 3276 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3277 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3278 llvm::APSInt Value(CharBits, CharIsUnsigned); 3279 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3280 Value = TokSpelling[I]; 3281 TemplateArgument Arg(Context, Value, Context.CharTy); 3282 TemplateArgumentLocInfo ArgInfo; 3283 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3284 } 3285 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3286 &ExplicitArgs); 3287 } 3288 case LOLR_StringTemplate: 3289 llvm_unreachable("unexpected literal operator lookup result"); 3290 } 3291 } 3292 3293 Expr *Res; 3294 3295 if (Literal.isFloatingLiteral()) { 3296 QualType Ty; 3297 if (Literal.isFloat) 3298 Ty = Context.FloatTy; 3299 else if (!Literal.isLong) 3300 Ty = Context.DoubleTy; 3301 else 3302 Ty = Context.LongDoubleTy; 3303 3304 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3305 3306 if (Ty == Context.DoubleTy) { 3307 if (getLangOpts().SinglePrecisionConstants) { 3308 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3309 } else if (getLangOpts().OpenCL && 3310 !((getLangOpts().OpenCLVersion >= 120) || 3311 getOpenCLOptions().cl_khr_fp64)) { 3312 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3313 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3314 } 3315 } 3316 } else if (!Literal.isIntegerLiteral()) { 3317 return ExprError(); 3318 } else { 3319 QualType Ty; 3320 3321 // 'long long' is a C99 or C++11 feature. 3322 if (!getLangOpts().C99 && Literal.isLongLong) { 3323 if (getLangOpts().CPlusPlus) 3324 Diag(Tok.getLocation(), 3325 getLangOpts().CPlusPlus11 ? 3326 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3327 else 3328 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3329 } 3330 3331 // Get the value in the widest-possible width. 3332 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3333 llvm::APInt ResultVal(MaxWidth, 0); 3334 3335 if (Literal.GetIntegerValue(ResultVal)) { 3336 // If this value didn't fit into uintmax_t, error and force to ull. 3337 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3338 << /* Unsigned */ 1; 3339 Ty = Context.UnsignedLongLongTy; 3340 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3341 "long long is not intmax_t?"); 3342 } else { 3343 // If this value fits into a ULL, try to figure out what else it fits into 3344 // according to the rules of C99 6.4.4.1p5. 3345 3346 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3347 // be an unsigned int. 3348 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3349 3350 // Check from smallest to largest, picking the smallest type we can. 3351 unsigned Width = 0; 3352 3353 // Microsoft specific integer suffixes are explicitly sized. 3354 if (Literal.MicrosoftInteger) { 3355 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3356 Width = 8; 3357 Ty = Context.CharTy; 3358 } else { 3359 Width = Literal.MicrosoftInteger; 3360 Ty = Context.getIntTypeForBitwidth(Width, 3361 /*Signed=*/!Literal.isUnsigned); 3362 } 3363 } 3364 3365 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3366 // Are int/unsigned possibilities? 3367 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3368 3369 // Does it fit in a unsigned int? 3370 if (ResultVal.isIntN(IntSize)) { 3371 // Does it fit in a signed int? 3372 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3373 Ty = Context.IntTy; 3374 else if (AllowUnsigned) 3375 Ty = Context.UnsignedIntTy; 3376 Width = IntSize; 3377 } 3378 } 3379 3380 // Are long/unsigned long possibilities? 3381 if (Ty.isNull() && !Literal.isLongLong) { 3382 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3383 3384 // Does it fit in a unsigned long? 3385 if (ResultVal.isIntN(LongSize)) { 3386 // Does it fit in a signed long? 3387 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3388 Ty = Context.LongTy; 3389 else if (AllowUnsigned) 3390 Ty = Context.UnsignedLongTy; 3391 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3392 // is compatible. 3393 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3394 const unsigned LongLongSize = 3395 Context.getTargetInfo().getLongLongWidth(); 3396 Diag(Tok.getLocation(), 3397 getLangOpts().CPlusPlus 3398 ? Literal.isLong 3399 ? diag::warn_old_implicitly_unsigned_long_cxx 3400 : /*C++98 UB*/ diag:: 3401 ext_old_implicitly_unsigned_long_cxx 3402 : diag::warn_old_implicitly_unsigned_long) 3403 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3404 : /*will be ill-formed*/ 1); 3405 Ty = Context.UnsignedLongTy; 3406 } 3407 Width = LongSize; 3408 } 3409 } 3410 3411 // Check long long if needed. 3412 if (Ty.isNull()) { 3413 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3414 3415 // Does it fit in a unsigned long long? 3416 if (ResultVal.isIntN(LongLongSize)) { 3417 // Does it fit in a signed long long? 3418 // To be compatible with MSVC, hex integer literals ending with the 3419 // LL or i64 suffix are always signed in Microsoft mode. 3420 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3421 (getLangOpts().MicrosoftExt && Literal.isLongLong))) 3422 Ty = Context.LongLongTy; 3423 else if (AllowUnsigned) 3424 Ty = Context.UnsignedLongLongTy; 3425 Width = LongLongSize; 3426 } 3427 } 3428 3429 // If we still couldn't decide a type, we probably have something that 3430 // does not fit in a signed long long, but has no U suffix. 3431 if (Ty.isNull()) { 3432 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3433 Ty = Context.UnsignedLongLongTy; 3434 Width = Context.getTargetInfo().getLongLongWidth(); 3435 } 3436 3437 if (ResultVal.getBitWidth() != Width) 3438 ResultVal = ResultVal.trunc(Width); 3439 } 3440 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3441 } 3442 3443 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3444 if (Literal.isImaginary) 3445 Res = new (Context) ImaginaryLiteral(Res, 3446 Context.getComplexType(Res->getType())); 3447 3448 return Res; 3449 } 3450 3451 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3452 assert(E && "ActOnParenExpr() missing expr"); 3453 return new (Context) ParenExpr(L, R, E); 3454 } 3455 3456 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3457 SourceLocation Loc, 3458 SourceRange ArgRange) { 3459 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3460 // scalar or vector data type argument..." 3461 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3462 // type (C99 6.2.5p18) or void. 3463 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3464 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3465 << T << ArgRange; 3466 return true; 3467 } 3468 3469 assert((T->isVoidType() || !T->isIncompleteType()) && 3470 "Scalar types should always be complete"); 3471 return false; 3472 } 3473 3474 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3475 SourceLocation Loc, 3476 SourceRange ArgRange, 3477 UnaryExprOrTypeTrait TraitKind) { 3478 // Invalid types must be hard errors for SFINAE in C++. 3479 if (S.LangOpts.CPlusPlus) 3480 return true; 3481 3482 // C99 6.5.3.4p1: 3483 if (T->isFunctionType() && 3484 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) { 3485 // sizeof(function)/alignof(function) is allowed as an extension. 3486 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3487 << TraitKind << ArgRange; 3488 return false; 3489 } 3490 3491 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3492 // this is an error (OpenCL v1.1 s6.3.k) 3493 if (T->isVoidType()) { 3494 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3495 : diag::ext_sizeof_alignof_void_type; 3496 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3497 return false; 3498 } 3499 3500 return true; 3501 } 3502 3503 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3504 SourceLocation Loc, 3505 SourceRange ArgRange, 3506 UnaryExprOrTypeTrait TraitKind) { 3507 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3508 // runtime doesn't allow it. 3509 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3510 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3511 << T << (TraitKind == UETT_SizeOf) 3512 << ArgRange; 3513 return true; 3514 } 3515 3516 return false; 3517 } 3518 3519 /// \brief Check whether E is a pointer from a decayed array type (the decayed 3520 /// pointer type is equal to T) and emit a warning if it is. 3521 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3522 Expr *E) { 3523 // Don't warn if the operation changed the type. 3524 if (T != E->getType()) 3525 return; 3526 3527 // Now look for array decays. 3528 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3529 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3530 return; 3531 3532 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3533 << ICE->getType() 3534 << ICE->getSubExpr()->getType(); 3535 } 3536 3537 /// \brief Check the constraints on expression operands to unary type expression 3538 /// and type traits. 3539 /// 3540 /// Completes any types necessary and validates the constraints on the operand 3541 /// expression. The logic mostly mirrors the type-based overload, but may modify 3542 /// the expression as it completes the type for that expression through template 3543 /// instantiation, etc. 3544 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3545 UnaryExprOrTypeTrait ExprKind) { 3546 QualType ExprTy = E->getType(); 3547 assert(!ExprTy->isReferenceType()); 3548 3549 if (ExprKind == UETT_VecStep) 3550 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3551 E->getSourceRange()); 3552 3553 // Whitelist some types as extensions 3554 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3555 E->getSourceRange(), ExprKind)) 3556 return false; 3557 3558 // 'alignof' applied to an expression only requires the base element type of 3559 // the expression to be complete. 'sizeof' requires the expression's type to 3560 // be complete (and will attempt to complete it if it's an array of unknown 3561 // bound). 3562 if (ExprKind == UETT_AlignOf) { 3563 if (RequireCompleteType(E->getExprLoc(), 3564 Context.getBaseElementType(E->getType()), 3565 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3566 E->getSourceRange())) 3567 return true; 3568 } else { 3569 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3570 ExprKind, E->getSourceRange())) 3571 return true; 3572 } 3573 3574 // Completing the expression's type may have changed it. 3575 ExprTy = E->getType(); 3576 assert(!ExprTy->isReferenceType()); 3577 3578 if (ExprTy->isFunctionType()) { 3579 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3580 << ExprKind << E->getSourceRange(); 3581 return true; 3582 } 3583 3584 // The operand for sizeof and alignof is in an unevaluated expression context, 3585 // so side effects could result in unintended consequences. 3586 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) && 3587 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false)) 3588 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3589 3590 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3591 E->getSourceRange(), ExprKind)) 3592 return true; 3593 3594 if (ExprKind == UETT_SizeOf) { 3595 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3596 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3597 QualType OType = PVD->getOriginalType(); 3598 QualType Type = PVD->getType(); 3599 if (Type->isPointerType() && OType->isArrayType()) { 3600 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3601 << Type << OType; 3602 Diag(PVD->getLocation(), diag::note_declared_at); 3603 } 3604 } 3605 } 3606 3607 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3608 // decays into a pointer and returns an unintended result. This is most 3609 // likely a typo for "sizeof(array) op x". 3610 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3611 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3612 BO->getLHS()); 3613 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3614 BO->getRHS()); 3615 } 3616 } 3617 3618 return false; 3619 } 3620 3621 /// \brief Check the constraints on operands to unary expression and type 3622 /// traits. 3623 /// 3624 /// This will complete any types necessary, and validate the various constraints 3625 /// on those operands. 3626 /// 3627 /// The UsualUnaryConversions() function is *not* called by this routine. 3628 /// C99 6.3.2.1p[2-4] all state: 3629 /// Except when it is the operand of the sizeof operator ... 3630 /// 3631 /// C++ [expr.sizeof]p4 3632 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3633 /// standard conversions are not applied to the operand of sizeof. 3634 /// 3635 /// This policy is followed for all of the unary trait expressions. 3636 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3637 SourceLocation OpLoc, 3638 SourceRange ExprRange, 3639 UnaryExprOrTypeTrait ExprKind) { 3640 if (ExprType->isDependentType()) 3641 return false; 3642 3643 // C++ [expr.sizeof]p2: 3644 // When applied to a reference or a reference type, the result 3645 // is the size of the referenced type. 3646 // C++11 [expr.alignof]p3: 3647 // When alignof is applied to a reference type, the result 3648 // shall be the alignment of the referenced type. 3649 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3650 ExprType = Ref->getPointeeType(); 3651 3652 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3653 // When alignof or _Alignof is applied to an array type, the result 3654 // is the alignment of the element type. 3655 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign) 3656 ExprType = Context.getBaseElementType(ExprType); 3657 3658 if (ExprKind == UETT_VecStep) 3659 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3660 3661 // Whitelist some types as extensions 3662 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3663 ExprKind)) 3664 return false; 3665 3666 if (RequireCompleteType(OpLoc, ExprType, 3667 diag::err_sizeof_alignof_incomplete_type, 3668 ExprKind, ExprRange)) 3669 return true; 3670 3671 if (ExprType->isFunctionType()) { 3672 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3673 << ExprKind << ExprRange; 3674 return true; 3675 } 3676 3677 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3678 ExprKind)) 3679 return true; 3680 3681 return false; 3682 } 3683 3684 static bool CheckAlignOfExpr(Sema &S, Expr *E) { 3685 E = E->IgnoreParens(); 3686 3687 // Cannot know anything else if the expression is dependent. 3688 if (E->isTypeDependent()) 3689 return false; 3690 3691 if (E->getObjectKind() == OK_BitField) { 3692 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3693 << 1 << E->getSourceRange(); 3694 return true; 3695 } 3696 3697 ValueDecl *D = nullptr; 3698 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3699 D = DRE->getDecl(); 3700 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3701 D = ME->getMemberDecl(); 3702 } 3703 3704 // If it's a field, require the containing struct to have a 3705 // complete definition so that we can compute the layout. 3706 // 3707 // This can happen in C++11 onwards, either by naming the member 3708 // in a way that is not transformed into a member access expression 3709 // (in an unevaluated operand, for instance), or by naming the member 3710 // in a trailing-return-type. 3711 // 3712 // For the record, since __alignof__ on expressions is a GCC 3713 // extension, GCC seems to permit this but always gives the 3714 // nonsensical answer 0. 3715 // 3716 // We don't really need the layout here --- we could instead just 3717 // directly check for all the appropriate alignment-lowing 3718 // attributes --- but that would require duplicating a lot of 3719 // logic that just isn't worth duplicating for such a marginal 3720 // use-case. 3721 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3722 // Fast path this check, since we at least know the record has a 3723 // definition if we can find a member of it. 3724 if (!FD->getParent()->isCompleteDefinition()) { 3725 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3726 << E->getSourceRange(); 3727 return true; 3728 } 3729 3730 // Otherwise, if it's a field, and the field doesn't have 3731 // reference type, then it must have a complete type (or be a 3732 // flexible array member, which we explicitly want to 3733 // white-list anyway), which makes the following checks trivial. 3734 if (!FD->getType()->isReferenceType()) 3735 return false; 3736 } 3737 3738 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf); 3739 } 3740 3741 bool Sema::CheckVecStepExpr(Expr *E) { 3742 E = E->IgnoreParens(); 3743 3744 // Cannot know anything else if the expression is dependent. 3745 if (E->isTypeDependent()) 3746 return false; 3747 3748 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3749 } 3750 3751 /// \brief Build a sizeof or alignof expression given a type operand. 3752 ExprResult 3753 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3754 SourceLocation OpLoc, 3755 UnaryExprOrTypeTrait ExprKind, 3756 SourceRange R) { 3757 if (!TInfo) 3758 return ExprError(); 3759 3760 QualType T = TInfo->getType(); 3761 3762 if (!T->isDependentType() && 3763 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 3764 return ExprError(); 3765 3766 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3767 return new (Context) UnaryExprOrTypeTraitExpr( 3768 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 3769 } 3770 3771 /// \brief Build a sizeof or alignof expression given an expression 3772 /// operand. 3773 ExprResult 3774 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3775 UnaryExprOrTypeTrait ExprKind) { 3776 ExprResult PE = CheckPlaceholderExpr(E); 3777 if (PE.isInvalid()) 3778 return ExprError(); 3779 3780 E = PE.get(); 3781 3782 // Verify that the operand is valid. 3783 bool isInvalid = false; 3784 if (E->isTypeDependent()) { 3785 // Delay type-checking for type-dependent expressions. 3786 } else if (ExprKind == UETT_AlignOf) { 3787 isInvalid = CheckAlignOfExpr(*this, E); 3788 } else if (ExprKind == UETT_VecStep) { 3789 isInvalid = CheckVecStepExpr(E); 3790 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 3791 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 3792 isInvalid = true; 3793 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 3794 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 3795 isInvalid = true; 3796 } else { 3797 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 3798 } 3799 3800 if (isInvalid) 3801 return ExprError(); 3802 3803 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 3804 PE = TransformToPotentiallyEvaluated(E); 3805 if (PE.isInvalid()) return ExprError(); 3806 E = PE.get(); 3807 } 3808 3809 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 3810 return new (Context) UnaryExprOrTypeTraitExpr( 3811 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 3812 } 3813 3814 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 3815 /// expr and the same for @c alignof and @c __alignof 3816 /// Note that the ArgRange is invalid if isType is false. 3817 ExprResult 3818 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3819 UnaryExprOrTypeTrait ExprKind, bool IsType, 3820 void *TyOrEx, SourceRange ArgRange) { 3821 // If error parsing type, ignore. 3822 if (!TyOrEx) return ExprError(); 3823 3824 if (IsType) { 3825 TypeSourceInfo *TInfo; 3826 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 3827 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 3828 } 3829 3830 Expr *ArgEx = (Expr *)TyOrEx; 3831 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 3832 return Result; 3833 } 3834 3835 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 3836 bool IsReal) { 3837 if (V.get()->isTypeDependent()) 3838 return S.Context.DependentTy; 3839 3840 // _Real and _Imag are only l-values for normal l-values. 3841 if (V.get()->getObjectKind() != OK_Ordinary) { 3842 V = S.DefaultLvalueConversion(V.get()); 3843 if (V.isInvalid()) 3844 return QualType(); 3845 } 3846 3847 // These operators return the element type of a complex type. 3848 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 3849 return CT->getElementType(); 3850 3851 // Otherwise they pass through real integer and floating point types here. 3852 if (V.get()->getType()->isArithmeticType()) 3853 return V.get()->getType(); 3854 3855 // Test for placeholders. 3856 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 3857 if (PR.isInvalid()) return QualType(); 3858 if (PR.get() != V.get()) { 3859 V = PR; 3860 return CheckRealImagOperand(S, V, Loc, IsReal); 3861 } 3862 3863 // Reject anything else. 3864 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 3865 << (IsReal ? "__real" : "__imag"); 3866 return QualType(); 3867 } 3868 3869 3870 3871 ExprResult 3872 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3873 tok::TokenKind Kind, Expr *Input) { 3874 UnaryOperatorKind Opc; 3875 switch (Kind) { 3876 default: llvm_unreachable("Unknown unary op!"); 3877 case tok::plusplus: Opc = UO_PostInc; break; 3878 case tok::minusminus: Opc = UO_PostDec; break; 3879 } 3880 3881 // Since this might is a postfix expression, get rid of ParenListExprs. 3882 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 3883 if (Result.isInvalid()) return ExprError(); 3884 Input = Result.get(); 3885 3886 return BuildUnaryOp(S, OpLoc, Opc, Input); 3887 } 3888 3889 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal. 3890 /// 3891 /// \return true on error 3892 static bool checkArithmeticOnObjCPointer(Sema &S, 3893 SourceLocation opLoc, 3894 Expr *op) { 3895 assert(op->getType()->isObjCObjectPointerType()); 3896 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 3897 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 3898 return false; 3899 3900 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 3901 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 3902 << op->getSourceRange(); 3903 return true; 3904 } 3905 3906 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 3907 auto *BaseNoParens = Base->IgnoreParens(); 3908 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 3909 return MSProp->getPropertyDecl()->getType()->isArrayType(); 3910 return isa<MSPropertySubscriptExpr>(BaseNoParens); 3911 } 3912 3913 ExprResult 3914 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 3915 Expr *idx, SourceLocation rbLoc) { 3916 if (base && !base->getType().isNull() && 3917 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 3918 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 3919 /*Length=*/nullptr, rbLoc); 3920 3921 // Since this might be a postfix expression, get rid of ParenListExprs. 3922 if (isa<ParenListExpr>(base)) { 3923 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 3924 if (result.isInvalid()) return ExprError(); 3925 base = result.get(); 3926 } 3927 3928 // Handle any non-overload placeholder types in the base and index 3929 // expressions. We can't handle overloads here because the other 3930 // operand might be an overloadable type, in which case the overload 3931 // resolution for the operator overload should get the first crack 3932 // at the overload. 3933 bool IsMSPropertySubscript = false; 3934 if (base->getType()->isNonOverloadPlaceholderType()) { 3935 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 3936 if (!IsMSPropertySubscript) { 3937 ExprResult result = CheckPlaceholderExpr(base); 3938 if (result.isInvalid()) 3939 return ExprError(); 3940 base = result.get(); 3941 } 3942 } 3943 if (idx->getType()->isNonOverloadPlaceholderType()) { 3944 ExprResult result = CheckPlaceholderExpr(idx); 3945 if (result.isInvalid()) return ExprError(); 3946 idx = result.get(); 3947 } 3948 3949 // Build an unanalyzed expression if either operand is type-dependent. 3950 if (getLangOpts().CPlusPlus && 3951 (base->isTypeDependent() || idx->isTypeDependent())) { 3952 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 3953 VK_LValue, OK_Ordinary, rbLoc); 3954 } 3955 3956 // MSDN, property (C++) 3957 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 3958 // This attribute can also be used in the declaration of an empty array in a 3959 // class or structure definition. For example: 3960 // __declspec(property(get=GetX, put=PutX)) int x[]; 3961 // The above statement indicates that x[] can be used with one or more array 3962 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 3963 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 3964 if (IsMSPropertySubscript) { 3965 // Build MS property subscript expression if base is MS property reference 3966 // or MS property subscript. 3967 return new (Context) MSPropertySubscriptExpr( 3968 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 3969 } 3970 3971 // Use C++ overloaded-operator rules if either operand has record 3972 // type. The spec says to do this if either type is *overloadable*, 3973 // but enum types can't declare subscript operators or conversion 3974 // operators, so there's nothing interesting for overload resolution 3975 // to do if there aren't any record types involved. 3976 // 3977 // ObjC pointers have their own subscripting logic that is not tied 3978 // to overload resolution and so should not take this path. 3979 if (getLangOpts().CPlusPlus && 3980 (base->getType()->isRecordType() || 3981 (!base->getType()->isObjCObjectPointerType() && 3982 idx->getType()->isRecordType()))) { 3983 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 3984 } 3985 3986 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 3987 } 3988 3989 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 3990 Expr *LowerBound, 3991 SourceLocation ColonLoc, Expr *Length, 3992 SourceLocation RBLoc) { 3993 if (Base->getType()->isPlaceholderType() && 3994 !Base->getType()->isSpecificPlaceholderType( 3995 BuiltinType::OMPArraySection)) { 3996 ExprResult Result = CheckPlaceholderExpr(Base); 3997 if (Result.isInvalid()) 3998 return ExprError(); 3999 Base = Result.get(); 4000 } 4001 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4002 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4003 if (Result.isInvalid()) 4004 return ExprError(); 4005 LowerBound = Result.get(); 4006 } 4007 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4008 ExprResult Result = CheckPlaceholderExpr(Length); 4009 if (Result.isInvalid()) 4010 return ExprError(); 4011 Length = Result.get(); 4012 } 4013 4014 // Build an unanalyzed expression if either operand is type-dependent. 4015 if (Base->isTypeDependent() || 4016 (LowerBound && 4017 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4018 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4019 return new (Context) 4020 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4021 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4022 } 4023 4024 // Perform default conversions. 4025 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4026 QualType ResultTy; 4027 if (OriginalTy->isAnyPointerType()) { 4028 ResultTy = OriginalTy->getPointeeType(); 4029 } else if (OriginalTy->isArrayType()) { 4030 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4031 } else { 4032 return ExprError( 4033 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4034 << Base->getSourceRange()); 4035 } 4036 // C99 6.5.2.1p1 4037 if (LowerBound) { 4038 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4039 LowerBound); 4040 if (Res.isInvalid()) 4041 return ExprError(Diag(LowerBound->getExprLoc(), 4042 diag::err_omp_typecheck_section_not_integer) 4043 << 0 << LowerBound->getSourceRange()); 4044 LowerBound = Res.get(); 4045 4046 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4047 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4048 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4049 << 0 << LowerBound->getSourceRange(); 4050 } 4051 if (Length) { 4052 auto Res = 4053 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4054 if (Res.isInvalid()) 4055 return ExprError(Diag(Length->getExprLoc(), 4056 diag::err_omp_typecheck_section_not_integer) 4057 << 1 << Length->getSourceRange()); 4058 Length = Res.get(); 4059 4060 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4061 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4062 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4063 << 1 << Length->getSourceRange(); 4064 } 4065 4066 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4067 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4068 // type. Note that functions are not objects, and that (in C99 parlance) 4069 // incomplete types are not object types. 4070 if (ResultTy->isFunctionType()) { 4071 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4072 << ResultTy << Base->getSourceRange(); 4073 return ExprError(); 4074 } 4075 4076 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4077 diag::err_omp_section_incomplete_type, Base)) 4078 return ExprError(); 4079 4080 if (LowerBound) { 4081 llvm::APSInt LowerBoundValue; 4082 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) { 4083 // OpenMP 4.0, [2.4 Array Sections] 4084 // The lower-bound and length must evaluate to non-negative integers. 4085 if (LowerBoundValue.isNegative()) { 4086 Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative) 4087 << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true) 4088 << LowerBound->getSourceRange(); 4089 return ExprError(); 4090 } 4091 } 4092 } 4093 4094 if (Length) { 4095 llvm::APSInt LengthValue; 4096 if (Length->EvaluateAsInt(LengthValue, Context)) { 4097 // OpenMP 4.0, [2.4 Array Sections] 4098 // The lower-bound and length must evaluate to non-negative integers. 4099 if (LengthValue.isNegative()) { 4100 Diag(Length->getExprLoc(), diag::err_omp_section_negative) 4101 << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4102 << Length->getSourceRange(); 4103 return ExprError(); 4104 } 4105 } 4106 } else if (ColonLoc.isValid() && 4107 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4108 !OriginalTy->isVariableArrayType()))) { 4109 // OpenMP 4.0, [2.4 Array Sections] 4110 // When the size of the array dimension is not known, the length must be 4111 // specified explicitly. 4112 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4113 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4114 return ExprError(); 4115 } 4116 4117 return new (Context) 4118 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4119 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4120 } 4121 4122 ExprResult 4123 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4124 Expr *Idx, SourceLocation RLoc) { 4125 Expr *LHSExp = Base; 4126 Expr *RHSExp = Idx; 4127 4128 // Perform default conversions. 4129 if (!LHSExp->getType()->getAs<VectorType>()) { 4130 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4131 if (Result.isInvalid()) 4132 return ExprError(); 4133 LHSExp = Result.get(); 4134 } 4135 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4136 if (Result.isInvalid()) 4137 return ExprError(); 4138 RHSExp = Result.get(); 4139 4140 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4141 ExprValueKind VK = VK_LValue; 4142 ExprObjectKind OK = OK_Ordinary; 4143 4144 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4145 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4146 // in the subscript position. As a result, we need to derive the array base 4147 // and index from the expression types. 4148 Expr *BaseExpr, *IndexExpr; 4149 QualType ResultType; 4150 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4151 BaseExpr = LHSExp; 4152 IndexExpr = RHSExp; 4153 ResultType = Context.DependentTy; 4154 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4155 BaseExpr = LHSExp; 4156 IndexExpr = RHSExp; 4157 ResultType = PTy->getPointeeType(); 4158 } else if (const ObjCObjectPointerType *PTy = 4159 LHSTy->getAs<ObjCObjectPointerType>()) { 4160 BaseExpr = LHSExp; 4161 IndexExpr = RHSExp; 4162 4163 // Use custom logic if this should be the pseudo-object subscript 4164 // expression. 4165 if (!LangOpts.isSubscriptPointerArithmetic()) 4166 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4167 nullptr); 4168 4169 ResultType = PTy->getPointeeType(); 4170 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4171 // Handle the uncommon case of "123[Ptr]". 4172 BaseExpr = RHSExp; 4173 IndexExpr = LHSExp; 4174 ResultType = PTy->getPointeeType(); 4175 } else if (const ObjCObjectPointerType *PTy = 4176 RHSTy->getAs<ObjCObjectPointerType>()) { 4177 // Handle the uncommon case of "123[Ptr]". 4178 BaseExpr = RHSExp; 4179 IndexExpr = LHSExp; 4180 ResultType = PTy->getPointeeType(); 4181 if (!LangOpts.isSubscriptPointerArithmetic()) { 4182 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4183 << ResultType << BaseExpr->getSourceRange(); 4184 return ExprError(); 4185 } 4186 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4187 BaseExpr = LHSExp; // vectors: V[123] 4188 IndexExpr = RHSExp; 4189 VK = LHSExp->getValueKind(); 4190 if (VK != VK_RValue) 4191 OK = OK_VectorComponent; 4192 4193 // FIXME: need to deal with const... 4194 ResultType = VTy->getElementType(); 4195 } else if (LHSTy->isArrayType()) { 4196 // If we see an array that wasn't promoted by 4197 // DefaultFunctionArrayLvalueConversion, it must be an array that 4198 // wasn't promoted because of the C90 rule that doesn't 4199 // allow promoting non-lvalue arrays. Warn, then 4200 // force the promotion here. 4201 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4202 LHSExp->getSourceRange(); 4203 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4204 CK_ArrayToPointerDecay).get(); 4205 LHSTy = LHSExp->getType(); 4206 4207 BaseExpr = LHSExp; 4208 IndexExpr = RHSExp; 4209 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4210 } else if (RHSTy->isArrayType()) { 4211 // Same as previous, except for 123[f().a] case 4212 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) << 4213 RHSExp->getSourceRange(); 4214 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4215 CK_ArrayToPointerDecay).get(); 4216 RHSTy = RHSExp->getType(); 4217 4218 BaseExpr = RHSExp; 4219 IndexExpr = LHSExp; 4220 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4221 } else { 4222 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4223 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4224 } 4225 // C99 6.5.2.1p1 4226 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4227 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4228 << IndexExpr->getSourceRange()); 4229 4230 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4231 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4232 && !IndexExpr->isTypeDependent()) 4233 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4234 4235 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4236 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4237 // type. Note that Functions are not objects, and that (in C99 parlance) 4238 // incomplete types are not object types. 4239 if (ResultType->isFunctionType()) { 4240 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type) 4241 << ResultType << BaseExpr->getSourceRange(); 4242 return ExprError(); 4243 } 4244 4245 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4246 // GNU extension: subscripting on pointer to void 4247 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4248 << BaseExpr->getSourceRange(); 4249 4250 // C forbids expressions of unqualified void type from being l-values. 4251 // See IsCForbiddenLValueType. 4252 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4253 } else if (!ResultType->isDependentType() && 4254 RequireCompleteType(LLoc, ResultType, 4255 diag::err_subscript_incomplete_type, BaseExpr)) 4256 return ExprError(); 4257 4258 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4259 !ResultType.isCForbiddenLValueType()); 4260 4261 return new (Context) 4262 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4263 } 4264 4265 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4266 FunctionDecl *FD, 4267 ParmVarDecl *Param) { 4268 if (Param->hasUnparsedDefaultArg()) { 4269 Diag(CallLoc, 4270 diag::err_use_of_default_argument_to_function_declared_later) << 4271 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4272 Diag(UnparsedDefaultArgLocs[Param], 4273 diag::note_default_argument_declared_here); 4274 return ExprError(); 4275 } 4276 4277 if (Param->hasUninstantiatedDefaultArg()) { 4278 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4279 4280 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated, 4281 Param); 4282 4283 // Instantiate the expression. 4284 MultiLevelTemplateArgumentList MutiLevelArgList 4285 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4286 4287 InstantiatingTemplate Inst(*this, CallLoc, Param, 4288 MutiLevelArgList.getInnermost()); 4289 if (Inst.isInvalid()) 4290 return ExprError(); 4291 4292 ExprResult Result; 4293 { 4294 // C++ [dcl.fct.default]p5: 4295 // The names in the [default argument] expression are bound, and 4296 // the semantic constraints are checked, at the point where the 4297 // default argument expression appears. 4298 ContextRAII SavedContext(*this, FD); 4299 LocalInstantiationScope Local(*this); 4300 Result = SubstExpr(UninstExpr, MutiLevelArgList); 4301 } 4302 if (Result.isInvalid()) 4303 return ExprError(); 4304 4305 // Check the expression as an initializer for the parameter. 4306 InitializedEntity Entity 4307 = InitializedEntity::InitializeParameter(Context, Param); 4308 InitializationKind Kind 4309 = InitializationKind::CreateCopy(Param->getLocation(), 4310 /*FIXME:EqualLoc*/UninstExpr->getLocStart()); 4311 Expr *ResultE = Result.getAs<Expr>(); 4312 4313 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4314 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4315 if (Result.isInvalid()) 4316 return ExprError(); 4317 4318 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4319 Param->getOuterLocStart()); 4320 if (Result.isInvalid()) 4321 return ExprError(); 4322 4323 // Remember the instantiated default argument. 4324 Param->setDefaultArg(Result.getAs<Expr>()); 4325 if (ASTMutationListener *L = getASTMutationListener()) { 4326 L->DefaultArgumentInstantiated(Param); 4327 } 4328 } 4329 4330 // If the default expression creates temporaries, we need to 4331 // push them to the current stack of expression temporaries so they'll 4332 // be properly destroyed. 4333 // FIXME: We should really be rebuilding the default argument with new 4334 // bound temporaries; see the comment in PR5810. 4335 // We don't need to do that with block decls, though, because 4336 // blocks in default argument expression can never capture anything. 4337 if (isa<ExprWithCleanups>(Param->getInit())) { 4338 // Set the "needs cleanups" bit regardless of whether there are 4339 // any explicit objects. 4340 ExprNeedsCleanups = true; 4341 4342 // Append all the objects to the cleanup list. Right now, this 4343 // should always be a no-op, because blocks in default argument 4344 // expressions should never be able to capture anything. 4345 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() && 4346 "default argument expression has capturing blocks?"); 4347 } 4348 4349 // We already type-checked the argument, so we know it works. 4350 // Just mark all of the declarations in this potentially-evaluated expression 4351 // as being "referenced". 4352 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4353 /*SkipLocalVariables=*/true); 4354 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4355 } 4356 4357 4358 Sema::VariadicCallType 4359 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4360 Expr *Fn) { 4361 if (Proto && Proto->isVariadic()) { 4362 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4363 return VariadicConstructor; 4364 else if (Fn && Fn->getType()->isBlockPointerType()) 4365 return VariadicBlock; 4366 else if (FDecl) { 4367 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4368 if (Method->isInstance()) 4369 return VariadicMethod; 4370 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4371 return VariadicMethod; 4372 return VariadicFunction; 4373 } 4374 return VariadicDoesNotApply; 4375 } 4376 4377 namespace { 4378 class FunctionCallCCC : public FunctionCallFilterCCC { 4379 public: 4380 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4381 unsigned NumArgs, MemberExpr *ME) 4382 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4383 FunctionName(FuncName) {} 4384 4385 bool ValidateCandidate(const TypoCorrection &candidate) override { 4386 if (!candidate.getCorrectionSpecifier() || 4387 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4388 return false; 4389 } 4390 4391 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4392 } 4393 4394 private: 4395 const IdentifierInfo *const FunctionName; 4396 }; 4397 } 4398 4399 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4400 FunctionDecl *FDecl, 4401 ArrayRef<Expr *> Args) { 4402 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4403 DeclarationName FuncName = FDecl->getDeclName(); 4404 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart(); 4405 4406 if (TypoCorrection Corrected = S.CorrectTypo( 4407 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4408 S.getScopeForContext(S.CurContext), nullptr, 4409 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4410 Args.size(), ME), 4411 Sema::CTK_ErrorRecovery)) { 4412 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4413 if (Corrected.isOverloaded()) { 4414 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4415 OverloadCandidateSet::iterator Best; 4416 for (NamedDecl *CD : Corrected) { 4417 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4418 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4419 OCS); 4420 } 4421 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4422 case OR_Success: 4423 ND = Best->FoundDecl; 4424 Corrected.setCorrectionDecl(ND); 4425 break; 4426 default: 4427 break; 4428 } 4429 } 4430 ND = ND->getUnderlyingDecl(); 4431 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4432 return Corrected; 4433 } 4434 } 4435 return TypoCorrection(); 4436 } 4437 4438 /// ConvertArgumentsForCall - Converts the arguments specified in 4439 /// Args/NumArgs to the parameter types of the function FDecl with 4440 /// function prototype Proto. Call is the call expression itself, and 4441 /// Fn is the function expression. For a C++ member function, this 4442 /// routine does not attempt to convert the object argument. Returns 4443 /// true if the call is ill-formed. 4444 bool 4445 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4446 FunctionDecl *FDecl, 4447 const FunctionProtoType *Proto, 4448 ArrayRef<Expr *> Args, 4449 SourceLocation RParenLoc, 4450 bool IsExecConfig) { 4451 // Bail out early if calling a builtin with custom typechecking. 4452 if (FDecl) 4453 if (unsigned ID = FDecl->getBuiltinID()) 4454 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4455 return false; 4456 4457 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4458 // assignment, to the types of the corresponding parameter, ... 4459 unsigned NumParams = Proto->getNumParams(); 4460 bool Invalid = false; 4461 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4462 unsigned FnKind = Fn->getType()->isBlockPointerType() 4463 ? 1 /* block */ 4464 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4465 : 0 /* function */); 4466 4467 // If too few arguments are available (and we don't have default 4468 // arguments for the remaining parameters), don't make the call. 4469 if (Args.size() < NumParams) { 4470 if (Args.size() < MinArgs) { 4471 TypoCorrection TC; 4472 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4473 unsigned diag_id = 4474 MinArgs == NumParams && !Proto->isVariadic() 4475 ? diag::err_typecheck_call_too_few_args_suggest 4476 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4477 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4478 << static_cast<unsigned>(Args.size()) 4479 << TC.getCorrectionRange()); 4480 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4481 Diag(RParenLoc, 4482 MinArgs == NumParams && !Proto->isVariadic() 4483 ? diag::err_typecheck_call_too_few_args_one 4484 : diag::err_typecheck_call_too_few_args_at_least_one) 4485 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4486 else 4487 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4488 ? diag::err_typecheck_call_too_few_args 4489 : diag::err_typecheck_call_too_few_args_at_least) 4490 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4491 << Fn->getSourceRange(); 4492 4493 // Emit the location of the prototype. 4494 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4495 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4496 << FDecl; 4497 4498 return true; 4499 } 4500 Call->setNumArgs(Context, NumParams); 4501 } 4502 4503 // If too many are passed and not variadic, error on the extras and drop 4504 // them. 4505 if (Args.size() > NumParams) { 4506 if (!Proto->isVariadic()) { 4507 TypoCorrection TC; 4508 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4509 unsigned diag_id = 4510 MinArgs == NumParams && !Proto->isVariadic() 4511 ? diag::err_typecheck_call_too_many_args_suggest 4512 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4513 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4514 << static_cast<unsigned>(Args.size()) 4515 << TC.getCorrectionRange()); 4516 } else if (NumParams == 1 && FDecl && 4517 FDecl->getParamDecl(0)->getDeclName()) 4518 Diag(Args[NumParams]->getLocStart(), 4519 MinArgs == NumParams 4520 ? diag::err_typecheck_call_too_many_args_one 4521 : diag::err_typecheck_call_too_many_args_at_most_one) 4522 << FnKind << FDecl->getParamDecl(0) 4523 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4524 << SourceRange(Args[NumParams]->getLocStart(), 4525 Args.back()->getLocEnd()); 4526 else 4527 Diag(Args[NumParams]->getLocStart(), 4528 MinArgs == NumParams 4529 ? diag::err_typecheck_call_too_many_args 4530 : diag::err_typecheck_call_too_many_args_at_most) 4531 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4532 << Fn->getSourceRange() 4533 << SourceRange(Args[NumParams]->getLocStart(), 4534 Args.back()->getLocEnd()); 4535 4536 // Emit the location of the prototype. 4537 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4538 Diag(FDecl->getLocStart(), diag::note_callee_decl) 4539 << FDecl; 4540 4541 // This deletes the extra arguments. 4542 Call->setNumArgs(Context, NumParams); 4543 return true; 4544 } 4545 } 4546 SmallVector<Expr *, 8> AllArgs; 4547 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4548 4549 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl, 4550 Proto, 0, Args, AllArgs, CallType); 4551 if (Invalid) 4552 return true; 4553 unsigned TotalNumArgs = AllArgs.size(); 4554 for (unsigned i = 0; i < TotalNumArgs; ++i) 4555 Call->setArg(i, AllArgs[i]); 4556 4557 return false; 4558 } 4559 4560 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4561 const FunctionProtoType *Proto, 4562 unsigned FirstParam, ArrayRef<Expr *> Args, 4563 SmallVectorImpl<Expr *> &AllArgs, 4564 VariadicCallType CallType, bool AllowExplicit, 4565 bool IsListInitialization) { 4566 unsigned NumParams = Proto->getNumParams(); 4567 bool Invalid = false; 4568 size_t ArgIx = 0; 4569 // Continue to check argument types (even if we have too few/many args). 4570 for (unsigned i = FirstParam; i < NumParams; i++) { 4571 QualType ProtoArgType = Proto->getParamType(i); 4572 4573 Expr *Arg; 4574 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4575 if (ArgIx < Args.size()) { 4576 Arg = Args[ArgIx++]; 4577 4578 if (RequireCompleteType(Arg->getLocStart(), 4579 ProtoArgType, 4580 diag::err_call_incomplete_argument, Arg)) 4581 return true; 4582 4583 // Strip the unbridged-cast placeholder expression off, if applicable. 4584 bool CFAudited = false; 4585 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4586 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4587 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4588 Arg = stripARCUnbridgedCast(Arg); 4589 else if (getLangOpts().ObjCAutoRefCount && 4590 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4591 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4592 CFAudited = true; 4593 4594 InitializedEntity Entity = 4595 Param ? InitializedEntity::InitializeParameter(Context, Param, 4596 ProtoArgType) 4597 : InitializedEntity::InitializeParameter( 4598 Context, ProtoArgType, Proto->isParamConsumed(i)); 4599 4600 // Remember that parameter belongs to a CF audited API. 4601 if (CFAudited) 4602 Entity.setParameterCFAudited(); 4603 4604 ExprResult ArgE = PerformCopyInitialization( 4605 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4606 if (ArgE.isInvalid()) 4607 return true; 4608 4609 Arg = ArgE.getAs<Expr>(); 4610 } else { 4611 assert(Param && "can't use default arguments without a known callee"); 4612 4613 ExprResult ArgExpr = 4614 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4615 if (ArgExpr.isInvalid()) 4616 return true; 4617 4618 Arg = ArgExpr.getAs<Expr>(); 4619 } 4620 4621 // Check for array bounds violations for each argument to the call. This 4622 // check only triggers warnings when the argument isn't a more complex Expr 4623 // with its own checking, such as a BinaryOperator. 4624 CheckArrayAccess(Arg); 4625 4626 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 4627 CheckStaticArrayArgument(CallLoc, Param, Arg); 4628 4629 AllArgs.push_back(Arg); 4630 } 4631 4632 // If this is a variadic call, handle args passed through "...". 4633 if (CallType != VariadicDoesNotApply) { 4634 // Assume that extern "C" functions with variadic arguments that 4635 // return __unknown_anytype aren't *really* variadic. 4636 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 4637 FDecl->isExternC()) { 4638 for (Expr *A : Args.slice(ArgIx)) { 4639 QualType paramType; // ignored 4640 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 4641 Invalid |= arg.isInvalid(); 4642 AllArgs.push_back(arg.get()); 4643 } 4644 4645 // Otherwise do argument promotion, (C99 6.5.2.2p7). 4646 } else { 4647 for (Expr *A : Args.slice(ArgIx)) { 4648 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 4649 Invalid |= Arg.isInvalid(); 4650 AllArgs.push_back(Arg.get()); 4651 } 4652 } 4653 4654 // Check for array bounds violations. 4655 for (Expr *A : Args.slice(ArgIx)) 4656 CheckArrayAccess(A); 4657 } 4658 return Invalid; 4659 } 4660 4661 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 4662 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 4663 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 4664 TL = DTL.getOriginalLoc(); 4665 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 4666 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 4667 << ATL.getLocalSourceRange(); 4668 } 4669 4670 /// CheckStaticArrayArgument - If the given argument corresponds to a static 4671 /// array parameter, check that it is non-null, and that if it is formed by 4672 /// array-to-pointer decay, the underlying array is sufficiently large. 4673 /// 4674 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 4675 /// array type derivation, then for each call to the function, the value of the 4676 /// corresponding actual argument shall provide access to the first element of 4677 /// an array with at least as many elements as specified by the size expression. 4678 void 4679 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 4680 ParmVarDecl *Param, 4681 const Expr *ArgExpr) { 4682 // Static array parameters are not supported in C++. 4683 if (!Param || getLangOpts().CPlusPlus) 4684 return; 4685 4686 QualType OrigTy = Param->getOriginalType(); 4687 4688 const ArrayType *AT = Context.getAsArrayType(OrigTy); 4689 if (!AT || AT->getSizeModifier() != ArrayType::Static) 4690 return; 4691 4692 if (ArgExpr->isNullPointerConstant(Context, 4693 Expr::NPC_NeverValueDependent)) { 4694 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 4695 DiagnoseCalleeStaticArrayParam(*this, Param); 4696 return; 4697 } 4698 4699 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 4700 if (!CAT) 4701 return; 4702 4703 const ConstantArrayType *ArgCAT = 4704 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 4705 if (!ArgCAT) 4706 return; 4707 4708 if (ArgCAT->getSize().ult(CAT->getSize())) { 4709 Diag(CallLoc, diag::warn_static_array_too_small) 4710 << ArgExpr->getSourceRange() 4711 << (unsigned) ArgCAT->getSize().getZExtValue() 4712 << (unsigned) CAT->getSize().getZExtValue(); 4713 DiagnoseCalleeStaticArrayParam(*this, Param); 4714 } 4715 } 4716 4717 /// Given a function expression of unknown-any type, try to rebuild it 4718 /// to have a function type. 4719 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 4720 4721 /// Is the given type a placeholder that we need to lower out 4722 /// immediately during argument processing? 4723 static bool isPlaceholderToRemoveAsArg(QualType type) { 4724 // Placeholders are never sugared. 4725 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 4726 if (!placeholder) return false; 4727 4728 switch (placeholder->getKind()) { 4729 // Ignore all the non-placeholder types. 4730 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 4731 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 4732 #include "clang/AST/BuiltinTypes.def" 4733 return false; 4734 4735 // We cannot lower out overload sets; they might validly be resolved 4736 // by the call machinery. 4737 case BuiltinType::Overload: 4738 return false; 4739 4740 // Unbridged casts in ARC can be handled in some call positions and 4741 // should be left in place. 4742 case BuiltinType::ARCUnbridgedCast: 4743 return false; 4744 4745 // Pseudo-objects should be converted as soon as possible. 4746 case BuiltinType::PseudoObject: 4747 return true; 4748 4749 // The debugger mode could theoretically but currently does not try 4750 // to resolve unknown-typed arguments based on known parameter types. 4751 case BuiltinType::UnknownAny: 4752 return true; 4753 4754 // These are always invalid as call arguments and should be reported. 4755 case BuiltinType::BoundMember: 4756 case BuiltinType::BuiltinFn: 4757 case BuiltinType::OMPArraySection: 4758 return true; 4759 4760 } 4761 llvm_unreachable("bad builtin type kind"); 4762 } 4763 4764 /// Check an argument list for placeholders that we won't try to 4765 /// handle later. 4766 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 4767 // Apply this processing to all the arguments at once instead of 4768 // dying at the first failure. 4769 bool hasInvalid = false; 4770 for (size_t i = 0, e = args.size(); i != e; i++) { 4771 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 4772 ExprResult result = S.CheckPlaceholderExpr(args[i]); 4773 if (result.isInvalid()) hasInvalid = true; 4774 else args[i] = result.get(); 4775 } else if (hasInvalid) { 4776 (void)S.CorrectDelayedTyposInExpr(args[i]); 4777 } 4778 } 4779 return hasInvalid; 4780 } 4781 4782 /// If a builtin function has a pointer argument with no explicit address 4783 /// space, then it should be able to accept a pointer to any address 4784 /// space as input. In order to do this, we need to replace the 4785 /// standard builtin declaration with one that uses the same address space 4786 /// as the call. 4787 /// 4788 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 4789 /// it does not contain any pointer arguments without 4790 /// an address space qualifer. Otherwise the rewritten 4791 /// FunctionDecl is returned. 4792 /// TODO: Handle pointer return types. 4793 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 4794 const FunctionDecl *FDecl, 4795 MultiExprArg ArgExprs) { 4796 4797 QualType DeclType = FDecl->getType(); 4798 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 4799 4800 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 4801 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 4802 return nullptr; 4803 4804 bool NeedsNewDecl = false; 4805 unsigned i = 0; 4806 SmallVector<QualType, 8> OverloadParams; 4807 4808 for (QualType ParamType : FT->param_types()) { 4809 4810 // Convert array arguments to pointer to simplify type lookup. 4811 Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get(); 4812 QualType ArgType = Arg->getType(); 4813 if (!ParamType->isPointerType() || 4814 ParamType.getQualifiers().hasAddressSpace() || 4815 !ArgType->isPointerType() || 4816 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 4817 OverloadParams.push_back(ParamType); 4818 continue; 4819 } 4820 4821 NeedsNewDecl = true; 4822 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace(); 4823 4824 QualType PointeeType = ParamType->getPointeeType(); 4825 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 4826 OverloadParams.push_back(Context.getPointerType(PointeeType)); 4827 } 4828 4829 if (!NeedsNewDecl) 4830 return nullptr; 4831 4832 FunctionProtoType::ExtProtoInfo EPI; 4833 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 4834 OverloadParams, EPI); 4835 DeclContext *Parent = Context.getTranslationUnitDecl(); 4836 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 4837 FDecl->getLocation(), 4838 FDecl->getLocation(), 4839 FDecl->getIdentifier(), 4840 OverloadTy, 4841 /*TInfo=*/nullptr, 4842 SC_Extern, false, 4843 /*hasPrototype=*/true); 4844 SmallVector<ParmVarDecl*, 16> Params; 4845 FT = cast<FunctionProtoType>(OverloadTy); 4846 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 4847 QualType ParamType = FT->getParamType(i); 4848 ParmVarDecl *Parm = 4849 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 4850 SourceLocation(), nullptr, ParamType, 4851 /*TInfo=*/nullptr, SC_None, nullptr); 4852 Parm->setScopeInfo(0, i); 4853 Params.push_back(Parm); 4854 } 4855 OverloadDecl->setParams(Params); 4856 return OverloadDecl; 4857 } 4858 4859 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 4860 /// This provides the location of the left/right parens and a list of comma 4861 /// locations. 4862 ExprResult 4863 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 4864 MultiExprArg ArgExprs, SourceLocation RParenLoc, 4865 Expr *ExecConfig, bool IsExecConfig) { 4866 // Since this might be a postfix expression, get rid of ParenListExprs. 4867 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn); 4868 if (Result.isInvalid()) return ExprError(); 4869 Fn = Result.get(); 4870 4871 if (checkArgsForPlaceholders(*this, ArgExprs)) 4872 return ExprError(); 4873 4874 if (getLangOpts().CPlusPlus) { 4875 // If this is a pseudo-destructor expression, build the call immediately. 4876 if (isa<CXXPseudoDestructorExpr>(Fn)) { 4877 if (!ArgExprs.empty()) { 4878 // Pseudo-destructor calls should not have any arguments. 4879 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args) 4880 << FixItHint::CreateRemoval( 4881 SourceRange(ArgExprs.front()->getLocStart(), 4882 ArgExprs.back()->getLocEnd())); 4883 } 4884 4885 return new (Context) 4886 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 4887 } 4888 if (Fn->getType() == Context.PseudoObjectTy) { 4889 ExprResult result = CheckPlaceholderExpr(Fn); 4890 if (result.isInvalid()) return ExprError(); 4891 Fn = result.get(); 4892 } 4893 4894 // Determine whether this is a dependent call inside a C++ template, 4895 // in which case we won't do any semantic analysis now. 4896 // FIXME: Will need to cache the results of name lookup (including ADL) in 4897 // Fn. 4898 bool Dependent = false; 4899 if (Fn->isTypeDependent()) 4900 Dependent = true; 4901 else if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 4902 Dependent = true; 4903 4904 if (Dependent) { 4905 if (ExecConfig) { 4906 return new (Context) CUDAKernelCallExpr( 4907 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 4908 Context.DependentTy, VK_RValue, RParenLoc); 4909 } else { 4910 return new (Context) CallExpr( 4911 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 4912 } 4913 } 4914 4915 // Determine whether this is a call to an object (C++ [over.call.object]). 4916 if (Fn->getType()->isRecordType()) 4917 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs, 4918 RParenLoc); 4919 4920 if (Fn->getType() == Context.UnknownAnyTy) { 4921 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4922 if (result.isInvalid()) return ExprError(); 4923 Fn = result.get(); 4924 } 4925 4926 if (Fn->getType() == Context.BoundMemberTy) { 4927 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 4928 } 4929 } 4930 4931 // Check for overloaded calls. This can happen even in C due to extensions. 4932 if (Fn->getType() == Context.OverloadTy) { 4933 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 4934 4935 // We aren't supposed to apply this logic for if there's an '&' involved. 4936 if (!find.HasFormOfMemberPointer) { 4937 OverloadExpr *ovl = find.Expression; 4938 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 4939 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs, 4940 RParenLoc, ExecConfig, 4941 /*AllowTypoCorrection=*/true, 4942 find.IsAddressOfOperand); 4943 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc); 4944 } 4945 } 4946 4947 // If we're directly calling a function, get the appropriate declaration. 4948 if (Fn->getType() == Context.UnknownAnyTy) { 4949 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 4950 if (result.isInvalid()) return ExprError(); 4951 Fn = result.get(); 4952 } 4953 4954 Expr *NakedFn = Fn->IgnoreParens(); 4955 4956 bool CallingNDeclIndirectly = false; 4957 NamedDecl *NDecl = nullptr; 4958 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 4959 if (UnOp->getOpcode() == UO_AddrOf) { 4960 CallingNDeclIndirectly = true; 4961 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 4962 } 4963 } 4964 4965 if (isa<DeclRefExpr>(NakedFn)) { 4966 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 4967 4968 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 4969 if (FDecl && FDecl->getBuiltinID()) { 4970 // Rewrite the function decl for this builtin by replacing parameters 4971 // with no explicit address space with the address space of the arguments 4972 // in ArgExprs. 4973 if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 4974 NDecl = FDecl; 4975 Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(), 4976 SourceLocation(), FDecl, false, 4977 SourceLocation(), FDecl->getType(), 4978 Fn->getValueKind(), FDecl); 4979 } 4980 } 4981 } else if (isa<MemberExpr>(NakedFn)) 4982 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 4983 4984 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 4985 if (CallingNDeclIndirectly && 4986 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 4987 Fn->getLocStart())) 4988 return ExprError(); 4989 4990 if (FD->hasAttr<EnableIfAttr>()) { 4991 if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) { 4992 Diag(Fn->getLocStart(), 4993 isa<CXXMethodDecl>(FD) ? 4994 diag::err_ovl_no_viable_member_function_in_call : 4995 diag::err_ovl_no_viable_function_in_call) 4996 << FD << FD->getSourceRange(); 4997 Diag(FD->getLocation(), 4998 diag::note_ovl_candidate_disabled_by_enable_if_attr) 4999 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5000 } 5001 } 5002 } 5003 5004 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5005 ExecConfig, IsExecConfig); 5006 } 5007 5008 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5009 /// 5010 /// __builtin_astype( value, dst type ) 5011 /// 5012 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5013 SourceLocation BuiltinLoc, 5014 SourceLocation RParenLoc) { 5015 ExprValueKind VK = VK_RValue; 5016 ExprObjectKind OK = OK_Ordinary; 5017 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5018 QualType SrcTy = E->getType(); 5019 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5020 return ExprError(Diag(BuiltinLoc, 5021 diag::err_invalid_astype_of_different_size) 5022 << DstTy 5023 << SrcTy 5024 << E->getSourceRange()); 5025 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5026 } 5027 5028 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5029 /// provided arguments. 5030 /// 5031 /// __builtin_convertvector( value, dst type ) 5032 /// 5033 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5034 SourceLocation BuiltinLoc, 5035 SourceLocation RParenLoc) { 5036 TypeSourceInfo *TInfo; 5037 GetTypeFromParser(ParsedDestTy, &TInfo); 5038 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5039 } 5040 5041 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5042 /// i.e. an expression not of \p OverloadTy. The expression should 5043 /// unary-convert to an expression of function-pointer or 5044 /// block-pointer type. 5045 /// 5046 /// \param NDecl the declaration being called, if available 5047 ExprResult 5048 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5049 SourceLocation LParenLoc, 5050 ArrayRef<Expr *> Args, 5051 SourceLocation RParenLoc, 5052 Expr *Config, bool IsExecConfig) { 5053 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5054 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5055 5056 // Promote the function operand. 5057 // We special-case function promotion here because we only allow promoting 5058 // builtin functions to function pointers in the callee of a call. 5059 ExprResult Result; 5060 if (BuiltinID && 5061 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5062 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()), 5063 CK_BuiltinFnToFnPtr).get(); 5064 } else { 5065 Result = CallExprUnaryConversions(Fn); 5066 } 5067 if (Result.isInvalid()) 5068 return ExprError(); 5069 Fn = Result.get(); 5070 5071 // Make the call expr early, before semantic checks. This guarantees cleanup 5072 // of arguments and function on error. 5073 CallExpr *TheCall; 5074 if (Config) 5075 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn, 5076 cast<CallExpr>(Config), Args, 5077 Context.BoolTy, VK_RValue, 5078 RParenLoc); 5079 else 5080 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy, 5081 VK_RValue, RParenLoc); 5082 5083 if (!getLangOpts().CPlusPlus) { 5084 // C cannot always handle TypoExpr nodes in builtin calls and direct 5085 // function calls as their argument checking don't necessarily handle 5086 // dependent types properly, so make sure any TypoExprs have been 5087 // dealt with. 5088 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5089 if (!Result.isUsable()) return ExprError(); 5090 TheCall = dyn_cast<CallExpr>(Result.get()); 5091 if (!TheCall) return Result; 5092 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()); 5093 } 5094 5095 // Bail out early if calling a builtin with custom typechecking. 5096 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5097 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5098 5099 retry: 5100 const FunctionType *FuncT; 5101 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5102 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5103 // have type pointer to function". 5104 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5105 if (!FuncT) 5106 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5107 << Fn->getType() << Fn->getSourceRange()); 5108 } else if (const BlockPointerType *BPT = 5109 Fn->getType()->getAs<BlockPointerType>()) { 5110 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5111 } else { 5112 // Handle calls to expressions of unknown-any type. 5113 if (Fn->getType() == Context.UnknownAnyTy) { 5114 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5115 if (rewrite.isInvalid()) return ExprError(); 5116 Fn = rewrite.get(); 5117 TheCall->setCallee(Fn); 5118 goto retry; 5119 } 5120 5121 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5122 << Fn->getType() << Fn->getSourceRange()); 5123 } 5124 5125 if (getLangOpts().CUDA) { 5126 if (Config) { 5127 // CUDA: Kernel calls must be to global functions 5128 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5129 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5130 << FDecl->getName() << Fn->getSourceRange()); 5131 5132 // CUDA: Kernel function must have 'void' return type 5133 if (!FuncT->getReturnType()->isVoidType()) 5134 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5135 << Fn->getType() << Fn->getSourceRange()); 5136 } else { 5137 // CUDA: Calls to global functions must be configured 5138 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5139 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5140 << FDecl->getName() << Fn->getSourceRange()); 5141 } 5142 } 5143 5144 // Check for a valid return type 5145 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall, 5146 FDecl)) 5147 return ExprError(); 5148 5149 // We know the result type of the call, set it. 5150 TheCall->setType(FuncT->getCallResultType(Context)); 5151 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5152 5153 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT); 5154 if (Proto) { 5155 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5156 IsExecConfig)) 5157 return ExprError(); 5158 } else { 5159 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5160 5161 if (FDecl) { 5162 // Check if we have too few/too many template arguments, based 5163 // on our knowledge of the function definition. 5164 const FunctionDecl *Def = nullptr; 5165 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5166 Proto = Def->getType()->getAs<FunctionProtoType>(); 5167 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5168 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5169 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5170 } 5171 5172 // If the function we're calling isn't a function prototype, but we have 5173 // a function prototype from a prior declaratiom, use that prototype. 5174 if (!FDecl->hasPrototype()) 5175 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5176 } 5177 5178 // Promote the arguments (C99 6.5.2.2p6). 5179 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5180 Expr *Arg = Args[i]; 5181 5182 if (Proto && i < Proto->getNumParams()) { 5183 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5184 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5185 ExprResult ArgE = 5186 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5187 if (ArgE.isInvalid()) 5188 return true; 5189 5190 Arg = ArgE.getAs<Expr>(); 5191 5192 } else { 5193 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5194 5195 if (ArgE.isInvalid()) 5196 return true; 5197 5198 Arg = ArgE.getAs<Expr>(); 5199 } 5200 5201 if (RequireCompleteType(Arg->getLocStart(), 5202 Arg->getType(), 5203 diag::err_call_incomplete_argument, Arg)) 5204 return ExprError(); 5205 5206 TheCall->setArg(i, Arg); 5207 } 5208 } 5209 5210 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5211 if (!Method->isStatic()) 5212 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5213 << Fn->getSourceRange()); 5214 5215 // Check for sentinels 5216 if (NDecl) 5217 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5218 5219 // Do special checking on direct calls to functions. 5220 if (FDecl) { 5221 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5222 return ExprError(); 5223 5224 if (BuiltinID) 5225 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5226 } else if (NDecl) { 5227 if (CheckPointerCall(NDecl, TheCall, Proto)) 5228 return ExprError(); 5229 } else { 5230 if (CheckOtherCall(TheCall, Proto)) 5231 return ExprError(); 5232 } 5233 5234 return MaybeBindToTemporary(TheCall); 5235 } 5236 5237 ExprResult 5238 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5239 SourceLocation RParenLoc, Expr *InitExpr) { 5240 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5241 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5242 5243 TypeSourceInfo *TInfo; 5244 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5245 if (!TInfo) 5246 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5247 5248 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5249 } 5250 5251 ExprResult 5252 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5253 SourceLocation RParenLoc, Expr *LiteralExpr) { 5254 QualType literalType = TInfo->getType(); 5255 5256 if (literalType->isArrayType()) { 5257 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5258 diag::err_illegal_decl_array_incomplete_type, 5259 SourceRange(LParenLoc, 5260 LiteralExpr->getSourceRange().getEnd()))) 5261 return ExprError(); 5262 if (literalType->isVariableArrayType()) 5263 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5264 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5265 } else if (!literalType->isDependentType() && 5266 RequireCompleteType(LParenLoc, literalType, 5267 diag::err_typecheck_decl_incomplete_type, 5268 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5269 return ExprError(); 5270 5271 InitializedEntity Entity 5272 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5273 InitializationKind Kind 5274 = InitializationKind::CreateCStyleCast(LParenLoc, 5275 SourceRange(LParenLoc, RParenLoc), 5276 /*InitList=*/true); 5277 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5278 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5279 &literalType); 5280 if (Result.isInvalid()) 5281 return ExprError(); 5282 LiteralExpr = Result.get(); 5283 5284 bool isFileScope = getCurFunctionOrMethodDecl() == nullptr; 5285 if (isFileScope && 5286 !LiteralExpr->isTypeDependent() && 5287 !LiteralExpr->isValueDependent() && 5288 !literalType->isDependentType()) { // 6.5.2.5p3 5289 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5290 return ExprError(); 5291 } 5292 5293 // In C, compound literals are l-values for some reason. 5294 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue; 5295 5296 return MaybeBindToTemporary( 5297 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5298 VK, LiteralExpr, isFileScope)); 5299 } 5300 5301 ExprResult 5302 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5303 SourceLocation RBraceLoc) { 5304 // Immediately handle non-overload placeholders. Overloads can be 5305 // resolved contextually, but everything else here can't. 5306 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5307 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5308 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5309 5310 // Ignore failures; dropping the entire initializer list because 5311 // of one failure would be terrible for indexing/etc. 5312 if (result.isInvalid()) continue; 5313 5314 InitArgList[I] = result.get(); 5315 } 5316 } 5317 5318 // Semantic analysis for initializers is done by ActOnDeclarator() and 5319 // CheckInitializer() - it requires knowledge of the object being intialized. 5320 5321 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5322 RBraceLoc); 5323 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5324 return E; 5325 } 5326 5327 /// Do an explicit extend of the given block pointer if we're in ARC. 5328 void Sema::maybeExtendBlockObject(ExprResult &E) { 5329 assert(E.get()->getType()->isBlockPointerType()); 5330 assert(E.get()->isRValue()); 5331 5332 // Only do this in an r-value context. 5333 if (!getLangOpts().ObjCAutoRefCount) return; 5334 5335 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5336 CK_ARCExtendBlockObject, E.get(), 5337 /*base path*/ nullptr, VK_RValue); 5338 ExprNeedsCleanups = true; 5339 } 5340 5341 /// Prepare a conversion of the given expression to an ObjC object 5342 /// pointer type. 5343 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5344 QualType type = E.get()->getType(); 5345 if (type->isObjCObjectPointerType()) { 5346 return CK_BitCast; 5347 } else if (type->isBlockPointerType()) { 5348 maybeExtendBlockObject(E); 5349 return CK_BlockPointerToObjCPointerCast; 5350 } else { 5351 assert(type->isPointerType()); 5352 return CK_CPointerToObjCPointerCast; 5353 } 5354 } 5355 5356 /// Prepares for a scalar cast, performing all the necessary stages 5357 /// except the final cast and returning the kind required. 5358 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5359 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5360 // Also, callers should have filtered out the invalid cases with 5361 // pointers. Everything else should be possible. 5362 5363 QualType SrcTy = Src.get()->getType(); 5364 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5365 return CK_NoOp; 5366 5367 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5368 case Type::STK_MemberPointer: 5369 llvm_unreachable("member pointer type in C"); 5370 5371 case Type::STK_CPointer: 5372 case Type::STK_BlockPointer: 5373 case Type::STK_ObjCObjectPointer: 5374 switch (DestTy->getScalarTypeKind()) { 5375 case Type::STK_CPointer: { 5376 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5377 unsigned DestAS = DestTy->getPointeeType().getAddressSpace(); 5378 if (SrcAS != DestAS) 5379 return CK_AddressSpaceConversion; 5380 return CK_BitCast; 5381 } 5382 case Type::STK_BlockPointer: 5383 return (SrcKind == Type::STK_BlockPointer 5384 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5385 case Type::STK_ObjCObjectPointer: 5386 if (SrcKind == Type::STK_ObjCObjectPointer) 5387 return CK_BitCast; 5388 if (SrcKind == Type::STK_CPointer) 5389 return CK_CPointerToObjCPointerCast; 5390 maybeExtendBlockObject(Src); 5391 return CK_BlockPointerToObjCPointerCast; 5392 case Type::STK_Bool: 5393 return CK_PointerToBoolean; 5394 case Type::STK_Integral: 5395 return CK_PointerToIntegral; 5396 case Type::STK_Floating: 5397 case Type::STK_FloatingComplex: 5398 case Type::STK_IntegralComplex: 5399 case Type::STK_MemberPointer: 5400 llvm_unreachable("illegal cast from pointer"); 5401 } 5402 llvm_unreachable("Should have returned before this"); 5403 5404 case Type::STK_Bool: // casting from bool is like casting from an integer 5405 case Type::STK_Integral: 5406 switch (DestTy->getScalarTypeKind()) { 5407 case Type::STK_CPointer: 5408 case Type::STK_ObjCObjectPointer: 5409 case Type::STK_BlockPointer: 5410 if (Src.get()->isNullPointerConstant(Context, 5411 Expr::NPC_ValueDependentIsNull)) 5412 return CK_NullToPointer; 5413 return CK_IntegralToPointer; 5414 case Type::STK_Bool: 5415 return CK_IntegralToBoolean; 5416 case Type::STK_Integral: 5417 return CK_IntegralCast; 5418 case Type::STK_Floating: 5419 return CK_IntegralToFloating; 5420 case Type::STK_IntegralComplex: 5421 Src = ImpCastExprToType(Src.get(), 5422 DestTy->castAs<ComplexType>()->getElementType(), 5423 CK_IntegralCast); 5424 return CK_IntegralRealToComplex; 5425 case Type::STK_FloatingComplex: 5426 Src = ImpCastExprToType(Src.get(), 5427 DestTy->castAs<ComplexType>()->getElementType(), 5428 CK_IntegralToFloating); 5429 return CK_FloatingRealToComplex; 5430 case Type::STK_MemberPointer: 5431 llvm_unreachable("member pointer type in C"); 5432 } 5433 llvm_unreachable("Should have returned before this"); 5434 5435 case Type::STK_Floating: 5436 switch (DestTy->getScalarTypeKind()) { 5437 case Type::STK_Floating: 5438 return CK_FloatingCast; 5439 case Type::STK_Bool: 5440 return CK_FloatingToBoolean; 5441 case Type::STK_Integral: 5442 return CK_FloatingToIntegral; 5443 case Type::STK_FloatingComplex: 5444 Src = ImpCastExprToType(Src.get(), 5445 DestTy->castAs<ComplexType>()->getElementType(), 5446 CK_FloatingCast); 5447 return CK_FloatingRealToComplex; 5448 case Type::STK_IntegralComplex: 5449 Src = ImpCastExprToType(Src.get(), 5450 DestTy->castAs<ComplexType>()->getElementType(), 5451 CK_FloatingToIntegral); 5452 return CK_IntegralRealToComplex; 5453 case Type::STK_CPointer: 5454 case Type::STK_ObjCObjectPointer: 5455 case Type::STK_BlockPointer: 5456 llvm_unreachable("valid float->pointer cast?"); 5457 case Type::STK_MemberPointer: 5458 llvm_unreachable("member pointer type in C"); 5459 } 5460 llvm_unreachable("Should have returned before this"); 5461 5462 case Type::STK_FloatingComplex: 5463 switch (DestTy->getScalarTypeKind()) { 5464 case Type::STK_FloatingComplex: 5465 return CK_FloatingComplexCast; 5466 case Type::STK_IntegralComplex: 5467 return CK_FloatingComplexToIntegralComplex; 5468 case Type::STK_Floating: { 5469 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5470 if (Context.hasSameType(ET, DestTy)) 5471 return CK_FloatingComplexToReal; 5472 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 5473 return CK_FloatingCast; 5474 } 5475 case Type::STK_Bool: 5476 return CK_FloatingComplexToBoolean; 5477 case Type::STK_Integral: 5478 Src = ImpCastExprToType(Src.get(), 5479 SrcTy->castAs<ComplexType>()->getElementType(), 5480 CK_FloatingComplexToReal); 5481 return CK_FloatingToIntegral; 5482 case Type::STK_CPointer: 5483 case Type::STK_ObjCObjectPointer: 5484 case Type::STK_BlockPointer: 5485 llvm_unreachable("valid complex float->pointer cast?"); 5486 case Type::STK_MemberPointer: 5487 llvm_unreachable("member pointer type in C"); 5488 } 5489 llvm_unreachable("Should have returned before this"); 5490 5491 case Type::STK_IntegralComplex: 5492 switch (DestTy->getScalarTypeKind()) { 5493 case Type::STK_FloatingComplex: 5494 return CK_IntegralComplexToFloatingComplex; 5495 case Type::STK_IntegralComplex: 5496 return CK_IntegralComplexCast; 5497 case Type::STK_Integral: { 5498 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 5499 if (Context.hasSameType(ET, DestTy)) 5500 return CK_IntegralComplexToReal; 5501 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 5502 return CK_IntegralCast; 5503 } 5504 case Type::STK_Bool: 5505 return CK_IntegralComplexToBoolean; 5506 case Type::STK_Floating: 5507 Src = ImpCastExprToType(Src.get(), 5508 SrcTy->castAs<ComplexType>()->getElementType(), 5509 CK_IntegralComplexToReal); 5510 return CK_IntegralToFloating; 5511 case Type::STK_CPointer: 5512 case Type::STK_ObjCObjectPointer: 5513 case Type::STK_BlockPointer: 5514 llvm_unreachable("valid complex int->pointer cast?"); 5515 case Type::STK_MemberPointer: 5516 llvm_unreachable("member pointer type in C"); 5517 } 5518 llvm_unreachable("Should have returned before this"); 5519 } 5520 5521 llvm_unreachable("Unhandled scalar cast"); 5522 } 5523 5524 static bool breakDownVectorType(QualType type, uint64_t &len, 5525 QualType &eltType) { 5526 // Vectors are simple. 5527 if (const VectorType *vecType = type->getAs<VectorType>()) { 5528 len = vecType->getNumElements(); 5529 eltType = vecType->getElementType(); 5530 assert(eltType->isScalarType()); 5531 return true; 5532 } 5533 5534 // We allow lax conversion to and from non-vector types, but only if 5535 // they're real types (i.e. non-complex, non-pointer scalar types). 5536 if (!type->isRealType()) return false; 5537 5538 len = 1; 5539 eltType = type; 5540 return true; 5541 } 5542 5543 /// Are the two types lax-compatible vector types? That is, given 5544 /// that one of them is a vector, do they have equal storage sizes, 5545 /// where the storage size is the number of elements times the element 5546 /// size? 5547 /// 5548 /// This will also return false if either of the types is neither a 5549 /// vector nor a real type. 5550 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 5551 assert(destTy->isVectorType() || srcTy->isVectorType()); 5552 5553 // Disallow lax conversions between scalars and ExtVectors (these 5554 // conversions are allowed for other vector types because common headers 5555 // depend on them). Most scalar OP ExtVector cases are handled by the 5556 // splat path anyway, which does what we want (convert, not bitcast). 5557 // What this rules out for ExtVectors is crazy things like char4*float. 5558 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 5559 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 5560 5561 uint64_t srcLen, destLen; 5562 QualType srcEltTy, destEltTy; 5563 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 5564 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 5565 5566 // ASTContext::getTypeSize will return the size rounded up to a 5567 // power of 2, so instead of using that, we need to use the raw 5568 // element size multiplied by the element count. 5569 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 5570 uint64_t destEltSize = Context.getTypeSize(destEltTy); 5571 5572 return (srcLen * srcEltSize == destLen * destEltSize); 5573 } 5574 5575 /// Is this a legal conversion between two types, one of which is 5576 /// known to be a vector type? 5577 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 5578 assert(destTy->isVectorType() || srcTy->isVectorType()); 5579 5580 if (!Context.getLangOpts().LaxVectorConversions) 5581 return false; 5582 return areLaxCompatibleVectorTypes(srcTy, destTy); 5583 } 5584 5585 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 5586 CastKind &Kind) { 5587 assert(VectorTy->isVectorType() && "Not a vector type!"); 5588 5589 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 5590 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 5591 return Diag(R.getBegin(), 5592 Ty->isVectorType() ? 5593 diag::err_invalid_conversion_between_vectors : 5594 diag::err_invalid_conversion_between_vector_and_integer) 5595 << VectorTy << Ty << R; 5596 } else 5597 return Diag(R.getBegin(), 5598 diag::err_invalid_conversion_between_vector_and_scalar) 5599 << VectorTy << Ty << R; 5600 5601 Kind = CK_BitCast; 5602 return false; 5603 } 5604 5605 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 5606 Expr *CastExpr, CastKind &Kind) { 5607 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 5608 5609 QualType SrcTy = CastExpr->getType(); 5610 5611 // If SrcTy is a VectorType, the total size must match to explicitly cast to 5612 // an ExtVectorType. 5613 // In OpenCL, casts between vectors of different types are not allowed. 5614 // (See OpenCL 6.2). 5615 if (SrcTy->isVectorType()) { 5616 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) 5617 || (getLangOpts().OpenCL && 5618 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) { 5619 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 5620 << DestTy << SrcTy << R; 5621 return ExprError(); 5622 } 5623 Kind = CK_BitCast; 5624 return CastExpr; 5625 } 5626 5627 // All non-pointer scalars can be cast to ExtVector type. The appropriate 5628 // conversion will take place first from scalar to elt type, and then 5629 // splat from elt type to vector. 5630 if (SrcTy->isPointerType()) 5631 return Diag(R.getBegin(), 5632 diag::err_invalid_conversion_between_vector_and_scalar) 5633 << DestTy << SrcTy << R; 5634 5635 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType(); 5636 ExprResult CastExprRes = CastExpr; 5637 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy); 5638 if (CastExprRes.isInvalid()) 5639 return ExprError(); 5640 CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get(); 5641 5642 Kind = CK_VectorSplat; 5643 return CastExpr; 5644 } 5645 5646 ExprResult 5647 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 5648 Declarator &D, ParsedType &Ty, 5649 SourceLocation RParenLoc, Expr *CastExpr) { 5650 assert(!D.isInvalidType() && (CastExpr != nullptr) && 5651 "ActOnCastExpr(): missing type or expr"); 5652 5653 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 5654 if (D.isInvalidType()) 5655 return ExprError(); 5656 5657 if (getLangOpts().CPlusPlus) { 5658 // Check that there are no default arguments (C++ only). 5659 CheckExtraCXXDefaultArguments(D); 5660 } else { 5661 // Make sure any TypoExprs have been dealt with. 5662 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 5663 if (!Res.isUsable()) 5664 return ExprError(); 5665 CastExpr = Res.get(); 5666 } 5667 5668 checkUnusedDeclAttributes(D); 5669 5670 QualType castType = castTInfo->getType(); 5671 Ty = CreateParsedType(castType, castTInfo); 5672 5673 bool isVectorLiteral = false; 5674 5675 // Check for an altivec or OpenCL literal, 5676 // i.e. all the elements are integer constants. 5677 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 5678 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 5679 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 5680 && castType->isVectorType() && (PE || PLE)) { 5681 if (PLE && PLE->getNumExprs() == 0) { 5682 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 5683 return ExprError(); 5684 } 5685 if (PE || PLE->getNumExprs() == 1) { 5686 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 5687 if (!E->getType()->isVectorType()) 5688 isVectorLiteral = true; 5689 } 5690 else 5691 isVectorLiteral = true; 5692 } 5693 5694 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 5695 // then handle it as such. 5696 if (isVectorLiteral) 5697 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 5698 5699 // If the Expr being casted is a ParenListExpr, handle it specially. 5700 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 5701 // sequence of BinOp comma operators. 5702 if (isa<ParenListExpr>(CastExpr)) { 5703 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 5704 if (Result.isInvalid()) return ExprError(); 5705 CastExpr = Result.get(); 5706 } 5707 5708 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 5709 !getSourceManager().isInSystemMacro(LParenLoc)) 5710 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 5711 5712 CheckTollFreeBridgeCast(castType, CastExpr); 5713 5714 CheckObjCBridgeRelatedCast(castType, CastExpr); 5715 5716 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 5717 } 5718 5719 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 5720 SourceLocation RParenLoc, Expr *E, 5721 TypeSourceInfo *TInfo) { 5722 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 5723 "Expected paren or paren list expression"); 5724 5725 Expr **exprs; 5726 unsigned numExprs; 5727 Expr *subExpr; 5728 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 5729 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 5730 LiteralLParenLoc = PE->getLParenLoc(); 5731 LiteralRParenLoc = PE->getRParenLoc(); 5732 exprs = PE->getExprs(); 5733 numExprs = PE->getNumExprs(); 5734 } else { // isa<ParenExpr> by assertion at function entrance 5735 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 5736 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 5737 subExpr = cast<ParenExpr>(E)->getSubExpr(); 5738 exprs = &subExpr; 5739 numExprs = 1; 5740 } 5741 5742 QualType Ty = TInfo->getType(); 5743 assert(Ty->isVectorType() && "Expected vector type"); 5744 5745 SmallVector<Expr *, 8> initExprs; 5746 const VectorType *VTy = Ty->getAs<VectorType>(); 5747 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 5748 5749 // '(...)' form of vector initialization in AltiVec: the number of 5750 // initializers must be one or must match the size of the vector. 5751 // If a single value is specified in the initializer then it will be 5752 // replicated to all the components of the vector 5753 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 5754 // The number of initializers must be one or must match the size of the 5755 // vector. If a single value is specified in the initializer then it will 5756 // be replicated to all the components of the vector 5757 if (numExprs == 1) { 5758 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5759 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5760 if (Literal.isInvalid()) 5761 return ExprError(); 5762 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5763 PrepareScalarCast(Literal, ElemTy)); 5764 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5765 } 5766 else if (numExprs < numElems) { 5767 Diag(E->getExprLoc(), 5768 diag::err_incorrect_number_of_vector_initializers); 5769 return ExprError(); 5770 } 5771 else 5772 initExprs.append(exprs, exprs + numExprs); 5773 } 5774 else { 5775 // For OpenCL, when the number of initializers is a single value, 5776 // it will be replicated to all components of the vector. 5777 if (getLangOpts().OpenCL && 5778 VTy->getVectorKind() == VectorType::GenericVector && 5779 numExprs == 1) { 5780 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 5781 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 5782 if (Literal.isInvalid()) 5783 return ExprError(); 5784 Literal = ImpCastExprToType(Literal.get(), ElemTy, 5785 PrepareScalarCast(Literal, ElemTy)); 5786 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 5787 } 5788 5789 initExprs.append(exprs, exprs + numExprs); 5790 } 5791 // FIXME: This means that pretty-printing the final AST will produce curly 5792 // braces instead of the original commas. 5793 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 5794 initExprs, LiteralRParenLoc); 5795 initE->setType(Ty); 5796 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 5797 } 5798 5799 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 5800 /// the ParenListExpr into a sequence of comma binary operators. 5801 ExprResult 5802 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 5803 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 5804 if (!E) 5805 return OrigExpr; 5806 5807 ExprResult Result(E->getExpr(0)); 5808 5809 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 5810 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 5811 E->getExpr(i)); 5812 5813 if (Result.isInvalid()) return ExprError(); 5814 5815 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 5816 } 5817 5818 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 5819 SourceLocation R, 5820 MultiExprArg Val) { 5821 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R); 5822 return expr; 5823 } 5824 5825 /// \brief Emit a specialized diagnostic when one expression is a null pointer 5826 /// constant and the other is not a pointer. Returns true if a diagnostic is 5827 /// emitted. 5828 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 5829 SourceLocation QuestionLoc) { 5830 Expr *NullExpr = LHSExpr; 5831 Expr *NonPointerExpr = RHSExpr; 5832 Expr::NullPointerConstantKind NullKind = 5833 NullExpr->isNullPointerConstant(Context, 5834 Expr::NPC_ValueDependentIsNotNull); 5835 5836 if (NullKind == Expr::NPCK_NotNull) { 5837 NullExpr = RHSExpr; 5838 NonPointerExpr = LHSExpr; 5839 NullKind = 5840 NullExpr->isNullPointerConstant(Context, 5841 Expr::NPC_ValueDependentIsNotNull); 5842 } 5843 5844 if (NullKind == Expr::NPCK_NotNull) 5845 return false; 5846 5847 if (NullKind == Expr::NPCK_ZeroExpression) 5848 return false; 5849 5850 if (NullKind == Expr::NPCK_ZeroLiteral) { 5851 // In this case, check to make sure that we got here from a "NULL" 5852 // string in the source code. 5853 NullExpr = NullExpr->IgnoreParenImpCasts(); 5854 SourceLocation loc = NullExpr->getExprLoc(); 5855 if (!findMacroSpelling(loc, "NULL")) 5856 return false; 5857 } 5858 5859 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 5860 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 5861 << NonPointerExpr->getType() << DiagType 5862 << NonPointerExpr->getSourceRange(); 5863 return true; 5864 } 5865 5866 /// \brief Return false if the condition expression is valid, true otherwise. 5867 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 5868 QualType CondTy = Cond->getType(); 5869 5870 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 5871 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 5872 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 5873 << CondTy << Cond->getSourceRange(); 5874 return true; 5875 } 5876 5877 // C99 6.5.15p2 5878 if (CondTy->isScalarType()) return false; 5879 5880 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 5881 << CondTy << Cond->getSourceRange(); 5882 return true; 5883 } 5884 5885 /// \brief Handle when one or both operands are void type. 5886 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 5887 ExprResult &RHS) { 5888 Expr *LHSExpr = LHS.get(); 5889 Expr *RHSExpr = RHS.get(); 5890 5891 if (!LHSExpr->getType()->isVoidType()) 5892 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5893 << RHSExpr->getSourceRange(); 5894 if (!RHSExpr->getType()->isVoidType()) 5895 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void) 5896 << LHSExpr->getSourceRange(); 5897 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 5898 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 5899 return S.Context.VoidTy; 5900 } 5901 5902 /// \brief Return false if the NullExpr can be promoted to PointerTy, 5903 /// true otherwise. 5904 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 5905 QualType PointerTy) { 5906 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 5907 !NullExpr.get()->isNullPointerConstant(S.Context, 5908 Expr::NPC_ValueDependentIsNull)) 5909 return true; 5910 5911 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 5912 return false; 5913 } 5914 5915 /// \brief Checks compatibility between two pointers and return the resulting 5916 /// type. 5917 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 5918 ExprResult &RHS, 5919 SourceLocation Loc) { 5920 QualType LHSTy = LHS.get()->getType(); 5921 QualType RHSTy = RHS.get()->getType(); 5922 5923 if (S.Context.hasSameType(LHSTy, RHSTy)) { 5924 // Two identical pointers types are always compatible. 5925 return LHSTy; 5926 } 5927 5928 QualType lhptee, rhptee; 5929 5930 // Get the pointee types. 5931 bool IsBlockPointer = false; 5932 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 5933 lhptee = LHSBTy->getPointeeType(); 5934 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 5935 IsBlockPointer = true; 5936 } else { 5937 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 5938 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 5939 } 5940 5941 // C99 6.5.15p6: If both operands are pointers to compatible types or to 5942 // differently qualified versions of compatible types, the result type is 5943 // a pointer to an appropriately qualified version of the composite 5944 // type. 5945 5946 // Only CVR-qualifiers exist in the standard, and the differently-qualified 5947 // clause doesn't make sense for our extensions. E.g. address space 2 should 5948 // be incompatible with address space 3: they may live on different devices or 5949 // anything. 5950 Qualifiers lhQual = lhptee.getQualifiers(); 5951 Qualifiers rhQual = rhptee.getQualifiers(); 5952 5953 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 5954 lhQual.removeCVRQualifiers(); 5955 rhQual.removeCVRQualifiers(); 5956 5957 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 5958 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 5959 5960 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 5961 5962 if (CompositeTy.isNull()) { 5963 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 5964 << LHSTy << RHSTy << LHS.get()->getSourceRange() 5965 << RHS.get()->getSourceRange(); 5966 // In this situation, we assume void* type. No especially good 5967 // reason, but this is what gcc does, and we do have to pick 5968 // to get a consistent AST. 5969 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy); 5970 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 5971 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 5972 return incompatTy; 5973 } 5974 5975 // The pointer types are compatible. 5976 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual); 5977 if (IsBlockPointer) 5978 ResultTy = S.Context.getBlockPointerType(ResultTy); 5979 else 5980 ResultTy = S.Context.getPointerType(ResultTy); 5981 5982 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast); 5983 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast); 5984 return ResultTy; 5985 } 5986 5987 /// \brief Return the resulting type when the operands are both block pointers. 5988 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 5989 ExprResult &LHS, 5990 ExprResult &RHS, 5991 SourceLocation Loc) { 5992 QualType LHSTy = LHS.get()->getType(); 5993 QualType RHSTy = RHS.get()->getType(); 5994 5995 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 5996 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 5997 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 5998 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 5999 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6000 return destType; 6001 } 6002 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6003 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6004 << RHS.get()->getSourceRange(); 6005 return QualType(); 6006 } 6007 6008 // We have 2 block pointer types. 6009 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6010 } 6011 6012 /// \brief Return the resulting type when the operands are both pointers. 6013 static QualType 6014 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6015 ExprResult &RHS, 6016 SourceLocation Loc) { 6017 // get the pointer types 6018 QualType LHSTy = LHS.get()->getType(); 6019 QualType RHSTy = RHS.get()->getType(); 6020 6021 // get the "pointed to" types 6022 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6023 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6024 6025 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6026 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6027 // Figure out necessary qualifiers (C99 6.5.15p6) 6028 QualType destPointee 6029 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6030 QualType destType = S.Context.getPointerType(destPointee); 6031 // Add qualifiers if necessary. 6032 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6033 // Promote to void*. 6034 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6035 return destType; 6036 } 6037 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6038 QualType destPointee 6039 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6040 QualType destType = S.Context.getPointerType(destPointee); 6041 // Add qualifiers if necessary. 6042 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6043 // Promote to void*. 6044 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6045 return destType; 6046 } 6047 6048 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6049 } 6050 6051 /// \brief Return false if the first expression is not an integer and the second 6052 /// expression is not a pointer, true otherwise. 6053 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6054 Expr* PointerExpr, SourceLocation Loc, 6055 bool IsIntFirstExpr) { 6056 if (!PointerExpr->getType()->isPointerType() || 6057 !Int.get()->getType()->isIntegerType()) 6058 return false; 6059 6060 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6061 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6062 6063 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6064 << Expr1->getType() << Expr2->getType() 6065 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6066 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6067 CK_IntegralToPointer); 6068 return true; 6069 } 6070 6071 /// \brief Simple conversion between integer and floating point types. 6072 /// 6073 /// Used when handling the OpenCL conditional operator where the 6074 /// condition is a vector while the other operands are scalar. 6075 /// 6076 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6077 /// types are either integer or floating type. Between the two 6078 /// operands, the type with the higher rank is defined as the "result 6079 /// type". The other operand needs to be promoted to the same type. No 6080 /// other type promotion is allowed. We cannot use 6081 /// UsualArithmeticConversions() for this purpose, since it always 6082 /// promotes promotable types. 6083 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6084 ExprResult &RHS, 6085 SourceLocation QuestionLoc) { 6086 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6087 if (LHS.isInvalid()) 6088 return QualType(); 6089 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6090 if (RHS.isInvalid()) 6091 return QualType(); 6092 6093 // For conversion purposes, we ignore any qualifiers. 6094 // For example, "const float" and "float" are equivalent. 6095 QualType LHSType = 6096 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6097 QualType RHSType = 6098 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6099 6100 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6101 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6102 << LHSType << LHS.get()->getSourceRange(); 6103 return QualType(); 6104 } 6105 6106 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6107 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6108 << RHSType << RHS.get()->getSourceRange(); 6109 return QualType(); 6110 } 6111 6112 // If both types are identical, no conversion is needed. 6113 if (LHSType == RHSType) 6114 return LHSType; 6115 6116 // Now handle "real" floating types (i.e. float, double, long double). 6117 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6118 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6119 /*IsCompAssign = */ false); 6120 6121 // Finally, we have two differing integer types. 6122 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6123 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6124 } 6125 6126 /// \brief Convert scalar operands to a vector that matches the 6127 /// condition in length. 6128 /// 6129 /// Used when handling the OpenCL conditional operator where the 6130 /// condition is a vector while the other operands are scalar. 6131 /// 6132 /// We first compute the "result type" for the scalar operands 6133 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6134 /// into a vector of that type where the length matches the condition 6135 /// vector type. s6.11.6 requires that the element types of the result 6136 /// and the condition must have the same number of bits. 6137 static QualType 6138 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6139 QualType CondTy, SourceLocation QuestionLoc) { 6140 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6141 if (ResTy.isNull()) return QualType(); 6142 6143 const VectorType *CV = CondTy->getAs<VectorType>(); 6144 assert(CV); 6145 6146 // Determine the vector result type 6147 unsigned NumElements = CV->getNumElements(); 6148 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6149 6150 // Ensure that all types have the same number of bits 6151 if (S.Context.getTypeSize(CV->getElementType()) 6152 != S.Context.getTypeSize(ResTy)) { 6153 // Since VectorTy is created internally, it does not pretty print 6154 // with an OpenCL name. Instead, we just print a description. 6155 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6156 SmallString<64> Str; 6157 llvm::raw_svector_ostream OS(Str); 6158 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6159 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6160 << CondTy << OS.str(); 6161 return QualType(); 6162 } 6163 6164 // Convert operands to the vector result type 6165 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6166 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6167 6168 return VectorTy; 6169 } 6170 6171 /// \brief Return false if this is a valid OpenCL condition vector 6172 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6173 SourceLocation QuestionLoc) { 6174 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6175 // integral type. 6176 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6177 assert(CondTy); 6178 QualType EleTy = CondTy->getElementType(); 6179 if (EleTy->isIntegerType()) return false; 6180 6181 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6182 << Cond->getType() << Cond->getSourceRange(); 6183 return true; 6184 } 6185 6186 /// \brief Return false if the vector condition type and the vector 6187 /// result type are compatible. 6188 /// 6189 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6190 /// number of elements, and their element types have the same number 6191 /// of bits. 6192 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6193 SourceLocation QuestionLoc) { 6194 const VectorType *CV = CondTy->getAs<VectorType>(); 6195 const VectorType *RV = VecResTy->getAs<VectorType>(); 6196 assert(CV && RV); 6197 6198 if (CV->getNumElements() != RV->getNumElements()) { 6199 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6200 << CondTy << VecResTy; 6201 return true; 6202 } 6203 6204 QualType CVE = CV->getElementType(); 6205 QualType RVE = RV->getElementType(); 6206 6207 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6208 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6209 << CondTy << VecResTy; 6210 return true; 6211 } 6212 6213 return false; 6214 } 6215 6216 /// \brief Return the resulting type for the conditional operator in 6217 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6218 /// s6.3.i) when the condition is a vector type. 6219 static QualType 6220 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6221 ExprResult &LHS, ExprResult &RHS, 6222 SourceLocation QuestionLoc) { 6223 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6224 if (Cond.isInvalid()) 6225 return QualType(); 6226 QualType CondTy = Cond.get()->getType(); 6227 6228 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6229 return QualType(); 6230 6231 // If either operand is a vector then find the vector type of the 6232 // result as specified in OpenCL v1.1 s6.3.i. 6233 if (LHS.get()->getType()->isVectorType() || 6234 RHS.get()->getType()->isVectorType()) { 6235 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6236 /*isCompAssign*/false, 6237 /*AllowBothBool*/true, 6238 /*AllowBoolConversions*/false); 6239 if (VecResTy.isNull()) return QualType(); 6240 // The result type must match the condition type as specified in 6241 // OpenCL v1.1 s6.11.6. 6242 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6243 return QualType(); 6244 return VecResTy; 6245 } 6246 6247 // Both operands are scalar. 6248 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6249 } 6250 6251 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6252 /// In that case, LHS = cond. 6253 /// C99 6.5.15 6254 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6255 ExprResult &RHS, ExprValueKind &VK, 6256 ExprObjectKind &OK, 6257 SourceLocation QuestionLoc) { 6258 6259 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6260 if (!LHSResult.isUsable()) return QualType(); 6261 LHS = LHSResult; 6262 6263 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6264 if (!RHSResult.isUsable()) return QualType(); 6265 RHS = RHSResult; 6266 6267 // C++ is sufficiently different to merit its own checker. 6268 if (getLangOpts().CPlusPlus) 6269 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6270 6271 VK = VK_RValue; 6272 OK = OK_Ordinary; 6273 6274 // The OpenCL operator with a vector condition is sufficiently 6275 // different to merit its own checker. 6276 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6277 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6278 6279 // First, check the condition. 6280 Cond = UsualUnaryConversions(Cond.get()); 6281 if (Cond.isInvalid()) 6282 return QualType(); 6283 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6284 return QualType(); 6285 6286 // Now check the two expressions. 6287 if (LHS.get()->getType()->isVectorType() || 6288 RHS.get()->getType()->isVectorType()) 6289 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6290 /*AllowBothBool*/true, 6291 /*AllowBoolConversions*/false); 6292 6293 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6294 if (LHS.isInvalid() || RHS.isInvalid()) 6295 return QualType(); 6296 6297 QualType LHSTy = LHS.get()->getType(); 6298 QualType RHSTy = RHS.get()->getType(); 6299 6300 // If both operands have arithmetic type, do the usual arithmetic conversions 6301 // to find a common type: C99 6.5.15p3,5. 6302 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 6303 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 6304 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 6305 6306 return ResTy; 6307 } 6308 6309 // If both operands are the same structure or union type, the result is that 6310 // type. 6311 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 6312 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 6313 if (LHSRT->getDecl() == RHSRT->getDecl()) 6314 // "If both the operands have structure or union type, the result has 6315 // that type." This implies that CV qualifiers are dropped. 6316 return LHSTy.getUnqualifiedType(); 6317 // FIXME: Type of conditional expression must be complete in C mode. 6318 } 6319 6320 // C99 6.5.15p5: "If both operands have void type, the result has void type." 6321 // The following || allows only one side to be void (a GCC-ism). 6322 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 6323 return checkConditionalVoidType(*this, LHS, RHS); 6324 } 6325 6326 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 6327 // the type of the other operand." 6328 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 6329 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 6330 6331 // All objective-c pointer type analysis is done here. 6332 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 6333 QuestionLoc); 6334 if (LHS.isInvalid() || RHS.isInvalid()) 6335 return QualType(); 6336 if (!compositeType.isNull()) 6337 return compositeType; 6338 6339 6340 // Handle block pointer types. 6341 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 6342 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 6343 QuestionLoc); 6344 6345 // Check constraints for C object pointers types (C99 6.5.15p3,6). 6346 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 6347 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 6348 QuestionLoc); 6349 6350 // GCC compatibility: soften pointer/integer mismatch. Note that 6351 // null pointers have been filtered out by this point. 6352 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 6353 /*isIntFirstExpr=*/true)) 6354 return RHSTy; 6355 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 6356 /*isIntFirstExpr=*/false)) 6357 return LHSTy; 6358 6359 // Emit a better diagnostic if one of the expressions is a null pointer 6360 // constant and the other is not a pointer type. In this case, the user most 6361 // likely forgot to take the address of the other expression. 6362 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 6363 return QualType(); 6364 6365 // Otherwise, the operands are not compatible. 6366 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 6367 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6368 << RHS.get()->getSourceRange(); 6369 return QualType(); 6370 } 6371 6372 /// FindCompositeObjCPointerType - Helper method to find composite type of 6373 /// two objective-c pointer types of the two input expressions. 6374 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6375 SourceLocation QuestionLoc) { 6376 QualType LHSTy = LHS.get()->getType(); 6377 QualType RHSTy = RHS.get()->getType(); 6378 6379 // Handle things like Class and struct objc_class*. Here we case the result 6380 // to the pseudo-builtin, because that will be implicitly cast back to the 6381 // redefinition type if an attempt is made to access its fields. 6382 if (LHSTy->isObjCClassType() && 6383 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 6384 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6385 return LHSTy; 6386 } 6387 if (RHSTy->isObjCClassType() && 6388 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 6389 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6390 return RHSTy; 6391 } 6392 // And the same for struct objc_object* / id 6393 if (LHSTy->isObjCIdType() && 6394 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 6395 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 6396 return LHSTy; 6397 } 6398 if (RHSTy->isObjCIdType() && 6399 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 6400 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 6401 return RHSTy; 6402 } 6403 // And the same for struct objc_selector* / SEL 6404 if (Context.isObjCSelType(LHSTy) && 6405 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 6406 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 6407 return LHSTy; 6408 } 6409 if (Context.isObjCSelType(RHSTy) && 6410 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 6411 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 6412 return RHSTy; 6413 } 6414 // Check constraints for Objective-C object pointers types. 6415 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 6416 6417 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 6418 // Two identical object pointer types are always compatible. 6419 return LHSTy; 6420 } 6421 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 6422 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 6423 QualType compositeType = LHSTy; 6424 6425 // If both operands are interfaces and either operand can be 6426 // assigned to the other, use that type as the composite 6427 // type. This allows 6428 // xxx ? (A*) a : (B*) b 6429 // where B is a subclass of A. 6430 // 6431 // Additionally, as for assignment, if either type is 'id' 6432 // allow silent coercion. Finally, if the types are 6433 // incompatible then make sure to use 'id' as the composite 6434 // type so the result is acceptable for sending messages to. 6435 6436 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 6437 // It could return the composite type. 6438 if (!(compositeType = 6439 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 6440 // Nothing more to do. 6441 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 6442 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 6443 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 6444 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 6445 } else if ((LHSTy->isObjCQualifiedIdType() || 6446 RHSTy->isObjCQualifiedIdType()) && 6447 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 6448 // Need to handle "id<xx>" explicitly. 6449 // GCC allows qualified id and any Objective-C type to devolve to 6450 // id. Currently localizing to here until clear this should be 6451 // part of ObjCQualifiedIdTypesAreCompatible. 6452 compositeType = Context.getObjCIdType(); 6453 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 6454 compositeType = Context.getObjCIdType(); 6455 } else { 6456 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 6457 << LHSTy << RHSTy 6458 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6459 QualType incompatTy = Context.getObjCIdType(); 6460 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 6461 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 6462 return incompatTy; 6463 } 6464 // The object pointer types are compatible. 6465 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 6466 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 6467 return compositeType; 6468 } 6469 // Check Objective-C object pointer types and 'void *' 6470 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 6471 if (getLangOpts().ObjCAutoRefCount) { 6472 // ARC forbids the implicit conversion of object pointers to 'void *', 6473 // so these types are not compatible. 6474 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6475 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6476 LHS = RHS = true; 6477 return QualType(); 6478 } 6479 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6480 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6481 QualType destPointee 6482 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6483 QualType destType = Context.getPointerType(destPointee); 6484 // Add qualifiers if necessary. 6485 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6486 // Promote to void*. 6487 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6488 return destType; 6489 } 6490 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 6491 if (getLangOpts().ObjCAutoRefCount) { 6492 // ARC forbids the implicit conversion of object pointers to 'void *', 6493 // so these types are not compatible. 6494 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 6495 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 6496 LHS = RHS = true; 6497 return QualType(); 6498 } 6499 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 6500 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6501 QualType destPointee 6502 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6503 QualType destType = Context.getPointerType(destPointee); 6504 // Add qualifiers if necessary. 6505 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6506 // Promote to void*. 6507 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6508 return destType; 6509 } 6510 return QualType(); 6511 } 6512 6513 /// SuggestParentheses - Emit a note with a fixit hint that wraps 6514 /// ParenRange in parentheses. 6515 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 6516 const PartialDiagnostic &Note, 6517 SourceRange ParenRange) { 6518 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 6519 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 6520 EndLoc.isValid()) { 6521 Self.Diag(Loc, Note) 6522 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 6523 << FixItHint::CreateInsertion(EndLoc, ")"); 6524 } else { 6525 // We can't display the parentheses, so just show the bare note. 6526 Self.Diag(Loc, Note) << ParenRange; 6527 } 6528 } 6529 6530 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 6531 return BinaryOperator::isAdditiveOp(Opc) || 6532 BinaryOperator::isMultiplicativeOp(Opc) || 6533 BinaryOperator::isShiftOp(Opc); 6534 } 6535 6536 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 6537 /// expression, either using a built-in or overloaded operator, 6538 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 6539 /// expression. 6540 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 6541 Expr **RHSExprs) { 6542 // Don't strip parenthesis: we should not warn if E is in parenthesis. 6543 E = E->IgnoreImpCasts(); 6544 E = E->IgnoreConversionOperator(); 6545 E = E->IgnoreImpCasts(); 6546 6547 // Built-in binary operator. 6548 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 6549 if (IsArithmeticOp(OP->getOpcode())) { 6550 *Opcode = OP->getOpcode(); 6551 *RHSExprs = OP->getRHS(); 6552 return true; 6553 } 6554 } 6555 6556 // Overloaded operator. 6557 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 6558 if (Call->getNumArgs() != 2) 6559 return false; 6560 6561 // Make sure this is really a binary operator that is safe to pass into 6562 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 6563 OverloadedOperatorKind OO = Call->getOperator(); 6564 if (OO < OO_Plus || OO > OO_Arrow || 6565 OO == OO_PlusPlus || OO == OO_MinusMinus) 6566 return false; 6567 6568 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 6569 if (IsArithmeticOp(OpKind)) { 6570 *Opcode = OpKind; 6571 *RHSExprs = Call->getArg(1); 6572 return true; 6573 } 6574 } 6575 6576 return false; 6577 } 6578 6579 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 6580 /// or is a logical expression such as (x==y) which has int type, but is 6581 /// commonly interpreted as boolean. 6582 static bool ExprLooksBoolean(Expr *E) { 6583 E = E->IgnoreParenImpCasts(); 6584 6585 if (E->getType()->isBooleanType()) 6586 return true; 6587 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 6588 return OP->isComparisonOp() || OP->isLogicalOp(); 6589 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 6590 return OP->getOpcode() == UO_LNot; 6591 if (E->getType()->isPointerType()) 6592 return true; 6593 6594 return false; 6595 } 6596 6597 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 6598 /// and binary operator are mixed in a way that suggests the programmer assumed 6599 /// the conditional operator has higher precedence, for example: 6600 /// "int x = a + someBinaryCondition ? 1 : 2". 6601 static void DiagnoseConditionalPrecedence(Sema &Self, 6602 SourceLocation OpLoc, 6603 Expr *Condition, 6604 Expr *LHSExpr, 6605 Expr *RHSExpr) { 6606 BinaryOperatorKind CondOpcode; 6607 Expr *CondRHS; 6608 6609 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 6610 return; 6611 if (!ExprLooksBoolean(CondRHS)) 6612 return; 6613 6614 // The condition is an arithmetic binary expression, with a right- 6615 // hand side that looks boolean, so warn. 6616 6617 Self.Diag(OpLoc, diag::warn_precedence_conditional) 6618 << Condition->getSourceRange() 6619 << BinaryOperator::getOpcodeStr(CondOpcode); 6620 6621 SuggestParentheses(Self, OpLoc, 6622 Self.PDiag(diag::note_precedence_silence) 6623 << BinaryOperator::getOpcodeStr(CondOpcode), 6624 SourceRange(Condition->getLocStart(), Condition->getLocEnd())); 6625 6626 SuggestParentheses(Self, OpLoc, 6627 Self.PDiag(diag::note_precedence_conditional_first), 6628 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd())); 6629 } 6630 6631 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 6632 /// in the case of a the GNU conditional expr extension. 6633 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 6634 SourceLocation ColonLoc, 6635 Expr *CondExpr, Expr *LHSExpr, 6636 Expr *RHSExpr) { 6637 if (!getLangOpts().CPlusPlus) { 6638 // C cannot handle TypoExpr nodes in the condition because it 6639 // doesn't handle dependent types properly, so make sure any TypoExprs have 6640 // been dealt with before checking the operands. 6641 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 6642 if (!CondResult.isUsable()) return ExprError(); 6643 CondExpr = CondResult.get(); 6644 } 6645 6646 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 6647 // was the condition. 6648 OpaqueValueExpr *opaqueValue = nullptr; 6649 Expr *commonExpr = nullptr; 6650 if (!LHSExpr) { 6651 commonExpr = CondExpr; 6652 // Lower out placeholder types first. This is important so that we don't 6653 // try to capture a placeholder. This happens in few cases in C++; such 6654 // as Objective-C++'s dictionary subscripting syntax. 6655 if (commonExpr->hasPlaceholderType()) { 6656 ExprResult result = CheckPlaceholderExpr(commonExpr); 6657 if (!result.isUsable()) return ExprError(); 6658 commonExpr = result.get(); 6659 } 6660 // We usually want to apply unary conversions *before* saving, except 6661 // in the special case of a C++ l-value conditional. 6662 if (!(getLangOpts().CPlusPlus 6663 && !commonExpr->isTypeDependent() 6664 && commonExpr->getValueKind() == RHSExpr->getValueKind() 6665 && commonExpr->isGLValue() 6666 && commonExpr->isOrdinaryOrBitFieldObject() 6667 && RHSExpr->isOrdinaryOrBitFieldObject() 6668 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 6669 ExprResult commonRes = UsualUnaryConversions(commonExpr); 6670 if (commonRes.isInvalid()) 6671 return ExprError(); 6672 commonExpr = commonRes.get(); 6673 } 6674 6675 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 6676 commonExpr->getType(), 6677 commonExpr->getValueKind(), 6678 commonExpr->getObjectKind(), 6679 commonExpr); 6680 LHSExpr = CondExpr = opaqueValue; 6681 } 6682 6683 ExprValueKind VK = VK_RValue; 6684 ExprObjectKind OK = OK_Ordinary; 6685 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 6686 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 6687 VK, OK, QuestionLoc); 6688 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 6689 RHS.isInvalid()) 6690 return ExprError(); 6691 6692 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 6693 RHS.get()); 6694 6695 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 6696 6697 if (!commonExpr) 6698 return new (Context) 6699 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 6700 RHS.get(), result, VK, OK); 6701 6702 return new (Context) BinaryConditionalOperator( 6703 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 6704 ColonLoc, result, VK, OK); 6705 } 6706 6707 // checkPointerTypesForAssignment - This is a very tricky routine (despite 6708 // being closely modeled after the C99 spec:-). The odd characteristic of this 6709 // routine is it effectively iqnores the qualifiers on the top level pointee. 6710 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 6711 // FIXME: add a couple examples in this comment. 6712 static Sema::AssignConvertType 6713 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 6714 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6715 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6716 6717 // get the "pointed to" type (ignoring qualifiers at the top level) 6718 const Type *lhptee, *rhptee; 6719 Qualifiers lhq, rhq; 6720 std::tie(lhptee, lhq) = 6721 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 6722 std::tie(rhptee, rhq) = 6723 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 6724 6725 Sema::AssignConvertType ConvTy = Sema::Compatible; 6726 6727 // C99 6.5.16.1p1: This following citation is common to constraints 6728 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 6729 // qualifiers of the type *pointed to* by the right; 6730 6731 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 6732 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 6733 lhq.compatiblyIncludesObjCLifetime(rhq)) { 6734 // Ignore lifetime for further calculation. 6735 lhq.removeObjCLifetime(); 6736 rhq.removeObjCLifetime(); 6737 } 6738 6739 if (!lhq.compatiblyIncludes(rhq)) { 6740 // Treat address-space mismatches as fatal. TODO: address subspaces 6741 if (!lhq.isAddressSpaceSupersetOf(rhq)) 6742 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6743 6744 // It's okay to add or remove GC or lifetime qualifiers when converting to 6745 // and from void*. 6746 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 6747 .compatiblyIncludes( 6748 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 6749 && (lhptee->isVoidType() || rhptee->isVoidType())) 6750 ; // keep old 6751 6752 // Treat lifetime mismatches as fatal. 6753 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 6754 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 6755 6756 // For GCC compatibility, other qualifier mismatches are treated 6757 // as still compatible in C. 6758 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6759 } 6760 6761 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 6762 // incomplete type and the other is a pointer to a qualified or unqualified 6763 // version of void... 6764 if (lhptee->isVoidType()) { 6765 if (rhptee->isIncompleteOrObjectType()) 6766 return ConvTy; 6767 6768 // As an extension, we allow cast to/from void* to function pointer. 6769 assert(rhptee->isFunctionType()); 6770 return Sema::FunctionVoidPointer; 6771 } 6772 6773 if (rhptee->isVoidType()) { 6774 if (lhptee->isIncompleteOrObjectType()) 6775 return ConvTy; 6776 6777 // As an extension, we allow cast to/from void* to function pointer. 6778 assert(lhptee->isFunctionType()); 6779 return Sema::FunctionVoidPointer; 6780 } 6781 6782 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 6783 // unqualified versions of compatible types, ... 6784 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 6785 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 6786 // Check if the pointee types are compatible ignoring the sign. 6787 // We explicitly check for char so that we catch "char" vs 6788 // "unsigned char" on systems where "char" is unsigned. 6789 if (lhptee->isCharType()) 6790 ltrans = S.Context.UnsignedCharTy; 6791 else if (lhptee->hasSignedIntegerRepresentation()) 6792 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 6793 6794 if (rhptee->isCharType()) 6795 rtrans = S.Context.UnsignedCharTy; 6796 else if (rhptee->hasSignedIntegerRepresentation()) 6797 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 6798 6799 if (ltrans == rtrans) { 6800 // Types are compatible ignoring the sign. Qualifier incompatibility 6801 // takes priority over sign incompatibility because the sign 6802 // warning can be disabled. 6803 if (ConvTy != Sema::Compatible) 6804 return ConvTy; 6805 6806 return Sema::IncompatiblePointerSign; 6807 } 6808 6809 // If we are a multi-level pointer, it's possible that our issue is simply 6810 // one of qualification - e.g. char ** -> const char ** is not allowed. If 6811 // the eventual target type is the same and the pointers have the same 6812 // level of indirection, this must be the issue. 6813 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 6814 do { 6815 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 6816 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 6817 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 6818 6819 if (lhptee == rhptee) 6820 return Sema::IncompatibleNestedPointerQualifiers; 6821 } 6822 6823 // General pointer incompatibility takes priority over qualifiers. 6824 return Sema::IncompatiblePointer; 6825 } 6826 if (!S.getLangOpts().CPlusPlus && 6827 S.IsNoReturnConversion(ltrans, rtrans, ltrans)) 6828 return Sema::IncompatiblePointer; 6829 return ConvTy; 6830 } 6831 6832 /// checkBlockPointerTypesForAssignment - This routine determines whether two 6833 /// block pointer types are compatible or whether a block and normal pointer 6834 /// are compatible. It is more restrict than comparing two function pointer 6835 // types. 6836 static Sema::AssignConvertType 6837 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 6838 QualType RHSType) { 6839 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 6840 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 6841 6842 QualType lhptee, rhptee; 6843 6844 // get the "pointed to" type (ignoring qualifiers at the top level) 6845 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 6846 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 6847 6848 // In C++, the types have to match exactly. 6849 if (S.getLangOpts().CPlusPlus) 6850 return Sema::IncompatibleBlockPointer; 6851 6852 Sema::AssignConvertType ConvTy = Sema::Compatible; 6853 6854 // For blocks we enforce that qualifiers are identical. 6855 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers()) 6856 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 6857 6858 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 6859 return Sema::IncompatibleBlockPointer; 6860 6861 return ConvTy; 6862 } 6863 6864 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 6865 /// for assignment compatibility. 6866 static Sema::AssignConvertType 6867 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 6868 QualType RHSType) { 6869 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 6870 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 6871 6872 if (LHSType->isObjCBuiltinType()) { 6873 // Class is not compatible with ObjC object pointers. 6874 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 6875 !RHSType->isObjCQualifiedClassType()) 6876 return Sema::IncompatiblePointer; 6877 return Sema::Compatible; 6878 } 6879 if (RHSType->isObjCBuiltinType()) { 6880 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 6881 !LHSType->isObjCQualifiedClassType()) 6882 return Sema::IncompatiblePointer; 6883 return Sema::Compatible; 6884 } 6885 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6886 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 6887 6888 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 6889 // make an exception for id<P> 6890 !LHSType->isObjCQualifiedIdType()) 6891 return Sema::CompatiblePointerDiscardsQualifiers; 6892 6893 if (S.Context.typesAreCompatible(LHSType, RHSType)) 6894 return Sema::Compatible; 6895 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 6896 return Sema::IncompatibleObjCQualifiedId; 6897 return Sema::IncompatiblePointer; 6898 } 6899 6900 Sema::AssignConvertType 6901 Sema::CheckAssignmentConstraints(SourceLocation Loc, 6902 QualType LHSType, QualType RHSType) { 6903 // Fake up an opaque expression. We don't actually care about what 6904 // cast operations are required, so if CheckAssignmentConstraints 6905 // adds casts to this they'll be wasted, but fortunately that doesn't 6906 // usually happen on valid code. 6907 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 6908 ExprResult RHSPtr = &RHSExpr; 6909 CastKind K = CK_Invalid; 6910 6911 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 6912 } 6913 6914 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 6915 /// has code to accommodate several GCC extensions when type checking 6916 /// pointers. Here are some objectionable examples that GCC considers warnings: 6917 /// 6918 /// int a, *pint; 6919 /// short *pshort; 6920 /// struct foo *pfoo; 6921 /// 6922 /// pint = pshort; // warning: assignment from incompatible pointer type 6923 /// a = pint; // warning: assignment makes integer from pointer without a cast 6924 /// pint = a; // warning: assignment makes pointer from integer without a cast 6925 /// pint = pfoo; // warning: assignment from incompatible pointer type 6926 /// 6927 /// As a result, the code for dealing with pointers is more complex than the 6928 /// C99 spec dictates. 6929 /// 6930 /// Sets 'Kind' for any result kind except Incompatible. 6931 Sema::AssignConvertType 6932 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 6933 CastKind &Kind, bool ConvertRHS) { 6934 QualType RHSType = RHS.get()->getType(); 6935 QualType OrigLHSType = LHSType; 6936 6937 // Get canonical types. We're not formatting these types, just comparing 6938 // them. 6939 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 6940 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 6941 6942 // Common case: no conversion required. 6943 if (LHSType == RHSType) { 6944 Kind = CK_NoOp; 6945 return Compatible; 6946 } 6947 6948 // If we have an atomic type, try a non-atomic assignment, then just add an 6949 // atomic qualification step. 6950 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 6951 Sema::AssignConvertType result = 6952 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 6953 if (result != Compatible) 6954 return result; 6955 if (Kind != CK_NoOp && ConvertRHS) 6956 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 6957 Kind = CK_NonAtomicToAtomic; 6958 return Compatible; 6959 } 6960 6961 // If the left-hand side is a reference type, then we are in a 6962 // (rare!) case where we've allowed the use of references in C, 6963 // e.g., as a parameter type in a built-in function. In this case, 6964 // just make sure that the type referenced is compatible with the 6965 // right-hand side type. The caller is responsible for adjusting 6966 // LHSType so that the resulting expression does not have reference 6967 // type. 6968 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 6969 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 6970 Kind = CK_LValueBitCast; 6971 return Compatible; 6972 } 6973 return Incompatible; 6974 } 6975 6976 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 6977 // to the same ExtVector type. 6978 if (LHSType->isExtVectorType()) { 6979 if (RHSType->isExtVectorType()) 6980 return Incompatible; 6981 if (RHSType->isArithmeticType()) { 6982 // CK_VectorSplat does T -> vector T, so first cast to the 6983 // element type. 6984 QualType elType = cast<ExtVectorType>(LHSType)->getElementType(); 6985 if (elType != RHSType && ConvertRHS) { 6986 Kind = PrepareScalarCast(RHS, elType); 6987 RHS = ImpCastExprToType(RHS.get(), elType, Kind); 6988 } 6989 Kind = CK_VectorSplat; 6990 return Compatible; 6991 } 6992 } 6993 6994 // Conversions to or from vector type. 6995 if (LHSType->isVectorType() || RHSType->isVectorType()) { 6996 if (LHSType->isVectorType() && RHSType->isVectorType()) { 6997 // Allow assignments of an AltiVec vector type to an equivalent GCC 6998 // vector type and vice versa 6999 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7000 Kind = CK_BitCast; 7001 return Compatible; 7002 } 7003 7004 // If we are allowing lax vector conversions, and LHS and RHS are both 7005 // vectors, the total size only needs to be the same. This is a bitcast; 7006 // no bits are changed but the result type is different. 7007 if (isLaxVectorConversion(RHSType, LHSType)) { 7008 Kind = CK_BitCast; 7009 return IncompatibleVectors; 7010 } 7011 } 7012 return Incompatible; 7013 } 7014 7015 // Arithmetic conversions. 7016 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7017 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7018 if (ConvertRHS) 7019 Kind = PrepareScalarCast(RHS, LHSType); 7020 return Compatible; 7021 } 7022 7023 // Conversions to normal pointers. 7024 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7025 // U* -> T* 7026 if (isa<PointerType>(RHSType)) { 7027 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7028 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7029 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7030 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7031 } 7032 7033 // int -> T* 7034 if (RHSType->isIntegerType()) { 7035 Kind = CK_IntegralToPointer; // FIXME: null? 7036 return IntToPointer; 7037 } 7038 7039 // C pointers are not compatible with ObjC object pointers, 7040 // with two exceptions: 7041 if (isa<ObjCObjectPointerType>(RHSType)) { 7042 // - conversions to void* 7043 if (LHSPointer->getPointeeType()->isVoidType()) { 7044 Kind = CK_BitCast; 7045 return Compatible; 7046 } 7047 7048 // - conversions from 'Class' to the redefinition type 7049 if (RHSType->isObjCClassType() && 7050 Context.hasSameType(LHSType, 7051 Context.getObjCClassRedefinitionType())) { 7052 Kind = CK_BitCast; 7053 return Compatible; 7054 } 7055 7056 Kind = CK_BitCast; 7057 return IncompatiblePointer; 7058 } 7059 7060 // U^ -> void* 7061 if (RHSType->getAs<BlockPointerType>()) { 7062 if (LHSPointer->getPointeeType()->isVoidType()) { 7063 Kind = CK_BitCast; 7064 return Compatible; 7065 } 7066 } 7067 7068 return Incompatible; 7069 } 7070 7071 // Conversions to block pointers. 7072 if (isa<BlockPointerType>(LHSType)) { 7073 // U^ -> T^ 7074 if (RHSType->isBlockPointerType()) { 7075 Kind = CK_BitCast; 7076 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7077 } 7078 7079 // int or null -> T^ 7080 if (RHSType->isIntegerType()) { 7081 Kind = CK_IntegralToPointer; // FIXME: null 7082 return IntToBlockPointer; 7083 } 7084 7085 // id -> T^ 7086 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) { 7087 Kind = CK_AnyPointerToBlockPointerCast; 7088 return Compatible; 7089 } 7090 7091 // void* -> T^ 7092 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7093 if (RHSPT->getPointeeType()->isVoidType()) { 7094 Kind = CK_AnyPointerToBlockPointerCast; 7095 return Compatible; 7096 } 7097 7098 return Incompatible; 7099 } 7100 7101 // Conversions to Objective-C pointers. 7102 if (isa<ObjCObjectPointerType>(LHSType)) { 7103 // A* -> B* 7104 if (RHSType->isObjCObjectPointerType()) { 7105 Kind = CK_BitCast; 7106 Sema::AssignConvertType result = 7107 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7108 if (getLangOpts().ObjCAutoRefCount && 7109 result == Compatible && 7110 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7111 result = IncompatibleObjCWeakRef; 7112 return result; 7113 } 7114 7115 // int or null -> A* 7116 if (RHSType->isIntegerType()) { 7117 Kind = CK_IntegralToPointer; // FIXME: null 7118 return IntToPointer; 7119 } 7120 7121 // In general, C pointers are not compatible with ObjC object pointers, 7122 // with two exceptions: 7123 if (isa<PointerType>(RHSType)) { 7124 Kind = CK_CPointerToObjCPointerCast; 7125 7126 // - conversions from 'void*' 7127 if (RHSType->isVoidPointerType()) { 7128 return Compatible; 7129 } 7130 7131 // - conversions to 'Class' from its redefinition type 7132 if (LHSType->isObjCClassType() && 7133 Context.hasSameType(RHSType, 7134 Context.getObjCClassRedefinitionType())) { 7135 return Compatible; 7136 } 7137 7138 return IncompatiblePointer; 7139 } 7140 7141 // Only under strict condition T^ is compatible with an Objective-C pointer. 7142 if (RHSType->isBlockPointerType() && 7143 LHSType->isBlockCompatibleObjCPointerType(Context)) { 7144 if (ConvertRHS) 7145 maybeExtendBlockObject(RHS); 7146 Kind = CK_BlockPointerToObjCPointerCast; 7147 return Compatible; 7148 } 7149 7150 return Incompatible; 7151 } 7152 7153 // Conversions from pointers that are not covered by the above. 7154 if (isa<PointerType>(RHSType)) { 7155 // T* -> _Bool 7156 if (LHSType == Context.BoolTy) { 7157 Kind = CK_PointerToBoolean; 7158 return Compatible; 7159 } 7160 7161 // T* -> int 7162 if (LHSType->isIntegerType()) { 7163 Kind = CK_PointerToIntegral; 7164 return PointerToInt; 7165 } 7166 7167 return Incompatible; 7168 } 7169 7170 // Conversions from Objective-C pointers that are not covered by the above. 7171 if (isa<ObjCObjectPointerType>(RHSType)) { 7172 // T* -> _Bool 7173 if (LHSType == Context.BoolTy) { 7174 Kind = CK_PointerToBoolean; 7175 return Compatible; 7176 } 7177 7178 // T* -> int 7179 if (LHSType->isIntegerType()) { 7180 Kind = CK_PointerToIntegral; 7181 return PointerToInt; 7182 } 7183 7184 return Incompatible; 7185 } 7186 7187 // struct A -> struct B 7188 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 7189 if (Context.typesAreCompatible(LHSType, RHSType)) { 7190 Kind = CK_NoOp; 7191 return Compatible; 7192 } 7193 } 7194 7195 return Incompatible; 7196 } 7197 7198 /// \brief Constructs a transparent union from an expression that is 7199 /// used to initialize the transparent union. 7200 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 7201 ExprResult &EResult, QualType UnionType, 7202 FieldDecl *Field) { 7203 // Build an initializer list that designates the appropriate member 7204 // of the transparent union. 7205 Expr *E = EResult.get(); 7206 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 7207 E, SourceLocation()); 7208 Initializer->setType(UnionType); 7209 Initializer->setInitializedFieldInUnion(Field); 7210 7211 // Build a compound literal constructing a value of the transparent 7212 // union type from this initializer list. 7213 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 7214 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 7215 VK_RValue, Initializer, false); 7216 } 7217 7218 Sema::AssignConvertType 7219 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 7220 ExprResult &RHS) { 7221 QualType RHSType = RHS.get()->getType(); 7222 7223 // If the ArgType is a Union type, we want to handle a potential 7224 // transparent_union GCC extension. 7225 const RecordType *UT = ArgType->getAsUnionType(); 7226 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 7227 return Incompatible; 7228 7229 // The field to initialize within the transparent union. 7230 RecordDecl *UD = UT->getDecl(); 7231 FieldDecl *InitField = nullptr; 7232 // It's compatible if the expression matches any of the fields. 7233 for (auto *it : UD->fields()) { 7234 if (it->getType()->isPointerType()) { 7235 // If the transparent union contains a pointer type, we allow: 7236 // 1) void pointer 7237 // 2) null pointer constant 7238 if (RHSType->isPointerType()) 7239 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 7240 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 7241 InitField = it; 7242 break; 7243 } 7244 7245 if (RHS.get()->isNullPointerConstant(Context, 7246 Expr::NPC_ValueDependentIsNull)) { 7247 RHS = ImpCastExprToType(RHS.get(), it->getType(), 7248 CK_NullToPointer); 7249 InitField = it; 7250 break; 7251 } 7252 } 7253 7254 CastKind Kind = CK_Invalid; 7255 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 7256 == Compatible) { 7257 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 7258 InitField = it; 7259 break; 7260 } 7261 } 7262 7263 if (!InitField) 7264 return Incompatible; 7265 7266 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 7267 return Compatible; 7268 } 7269 7270 Sema::AssignConvertType 7271 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 7272 bool Diagnose, 7273 bool DiagnoseCFAudited, 7274 bool ConvertRHS) { 7275 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 7276 // we can't avoid *all* modifications at the moment, so we need some somewhere 7277 // to put the updated value. 7278 ExprResult LocalRHS = CallerRHS; 7279 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 7280 7281 if (getLangOpts().CPlusPlus) { 7282 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 7283 // C++ 5.17p3: If the left operand is not of class type, the 7284 // expression is implicitly converted (C++ 4) to the 7285 // cv-unqualified type of the left operand. 7286 ExprResult Res; 7287 if (Diagnose) { 7288 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7289 AA_Assigning); 7290 } else { 7291 ImplicitConversionSequence ICS = 7292 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7293 /*SuppressUserConversions=*/false, 7294 /*AllowExplicit=*/false, 7295 /*InOverloadResolution=*/false, 7296 /*CStyle=*/false, 7297 /*AllowObjCWritebackConversion=*/false); 7298 if (ICS.isFailure()) 7299 return Incompatible; 7300 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 7301 ICS, AA_Assigning); 7302 } 7303 if (Res.isInvalid()) 7304 return Incompatible; 7305 Sema::AssignConvertType result = Compatible; 7306 if (getLangOpts().ObjCAutoRefCount && 7307 !CheckObjCARCUnavailableWeakConversion(LHSType, 7308 RHS.get()->getType())) 7309 result = IncompatibleObjCWeakRef; 7310 RHS = Res; 7311 return result; 7312 } 7313 7314 // FIXME: Currently, we fall through and treat C++ classes like C 7315 // structures. 7316 // FIXME: We also fall through for atomics; not sure what should 7317 // happen there, though. 7318 } else if (RHS.get()->getType() == Context.OverloadTy) { 7319 // As a set of extensions to C, we support overloading on functions. These 7320 // functions need to be resolved here. 7321 DeclAccessPair DAP; 7322 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 7323 RHS.get(), LHSType, /*Complain=*/false, DAP)) 7324 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 7325 else 7326 return Incompatible; 7327 } 7328 7329 // C99 6.5.16.1p1: the left operand is a pointer and the right is 7330 // a null pointer constant. 7331 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 7332 LHSType->isBlockPointerType()) && 7333 RHS.get()->isNullPointerConstant(Context, 7334 Expr::NPC_ValueDependentIsNull)) { 7335 CastKind Kind; 7336 CXXCastPath Path; 7337 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false); 7338 if (ConvertRHS) 7339 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 7340 return Compatible; 7341 } 7342 7343 // This check seems unnatural, however it is necessary to ensure the proper 7344 // conversion of functions/arrays. If the conversion were done for all 7345 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 7346 // expressions that suppress this implicit conversion (&, sizeof). 7347 // 7348 // Suppress this for references: C++ 8.5.3p5. 7349 if (!LHSType->isReferenceType()) { 7350 // FIXME: We potentially allocate here even if ConvertRHS is false. 7351 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 7352 if (RHS.isInvalid()) 7353 return Incompatible; 7354 } 7355 7356 Expr *PRE = RHS.get()->IgnoreParenCasts(); 7357 if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) { 7358 ObjCProtocolDecl *PDecl = OPE->getProtocol(); 7359 if (PDecl && !PDecl->hasDefinition()) { 7360 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName(); 7361 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 7362 } 7363 } 7364 7365 CastKind Kind = CK_Invalid; 7366 Sema::AssignConvertType result = 7367 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 7368 7369 // C99 6.5.16.1p2: The value of the right operand is converted to the 7370 // type of the assignment expression. 7371 // CheckAssignmentConstraints allows the left-hand side to be a reference, 7372 // so that we can use references in built-in functions even in C. 7373 // The getNonReferenceType() call makes sure that the resulting expression 7374 // does not have reference type. 7375 if (result != Incompatible && RHS.get()->getType() != LHSType) { 7376 QualType Ty = LHSType.getNonLValueExprType(Context); 7377 Expr *E = RHS.get(); 7378 if (getLangOpts().ObjCAutoRefCount) 7379 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 7380 DiagnoseCFAudited); 7381 if (getLangOpts().ObjC1 && 7382 (CheckObjCBridgeRelatedConversions(E->getLocStart(), 7383 LHSType, E->getType(), E) || 7384 ConversionToObjCStringLiteralCheck(LHSType, E))) { 7385 RHS = E; 7386 return Compatible; 7387 } 7388 7389 if (ConvertRHS) 7390 RHS = ImpCastExprToType(E, Ty, Kind); 7391 } 7392 return result; 7393 } 7394 7395 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 7396 ExprResult &RHS) { 7397 Diag(Loc, diag::err_typecheck_invalid_operands) 7398 << LHS.get()->getType() << RHS.get()->getType() 7399 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7400 return QualType(); 7401 } 7402 7403 /// Try to convert a value of non-vector type to a vector type by converting 7404 /// the type to the element type of the vector and then performing a splat. 7405 /// If the language is OpenCL, we only use conversions that promote scalar 7406 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 7407 /// for float->int. 7408 /// 7409 /// \param scalar - if non-null, actually perform the conversions 7410 /// \return true if the operation fails (but without diagnosing the failure) 7411 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 7412 QualType scalarTy, 7413 QualType vectorEltTy, 7414 QualType vectorTy) { 7415 // The conversion to apply to the scalar before splatting it, 7416 // if necessary. 7417 CastKind scalarCast = CK_Invalid; 7418 7419 if (vectorEltTy->isIntegralType(S.Context)) { 7420 if (!scalarTy->isIntegralType(S.Context)) 7421 return true; 7422 if (S.getLangOpts().OpenCL && 7423 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0) 7424 return true; 7425 scalarCast = CK_IntegralCast; 7426 } else if (vectorEltTy->isRealFloatingType()) { 7427 if (scalarTy->isRealFloatingType()) { 7428 if (S.getLangOpts().OpenCL && 7429 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) 7430 return true; 7431 scalarCast = CK_FloatingCast; 7432 } 7433 else if (scalarTy->isIntegralType(S.Context)) 7434 scalarCast = CK_IntegralToFloating; 7435 else 7436 return true; 7437 } else { 7438 return true; 7439 } 7440 7441 // Adjust scalar if desired. 7442 if (scalar) { 7443 if (scalarCast != CK_Invalid) 7444 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 7445 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 7446 } 7447 return false; 7448 } 7449 7450 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 7451 SourceLocation Loc, bool IsCompAssign, 7452 bool AllowBothBool, 7453 bool AllowBoolConversions) { 7454 if (!IsCompAssign) { 7455 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 7456 if (LHS.isInvalid()) 7457 return QualType(); 7458 } 7459 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 7460 if (RHS.isInvalid()) 7461 return QualType(); 7462 7463 // For conversion purposes, we ignore any qualifiers. 7464 // For example, "const float" and "float" are equivalent. 7465 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 7466 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 7467 7468 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 7469 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 7470 assert(LHSVecType || RHSVecType); 7471 7472 // AltiVec-style "vector bool op vector bool" combinations are allowed 7473 // for some operators but not others. 7474 if (!AllowBothBool && 7475 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7476 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 7477 return InvalidOperands(Loc, LHS, RHS); 7478 7479 // If the vector types are identical, return. 7480 if (Context.hasSameType(LHSType, RHSType)) 7481 return LHSType; 7482 7483 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 7484 if (LHSVecType && RHSVecType && 7485 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7486 if (isa<ExtVectorType>(LHSVecType)) { 7487 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7488 return LHSType; 7489 } 7490 7491 if (!IsCompAssign) 7492 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7493 return RHSType; 7494 } 7495 7496 // AllowBoolConversions says that bool and non-bool AltiVec vectors 7497 // can be mixed, with the result being the non-bool type. The non-bool 7498 // operand must have integer element type. 7499 if (AllowBoolConversions && LHSVecType && RHSVecType && 7500 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 7501 (Context.getTypeSize(LHSVecType->getElementType()) == 7502 Context.getTypeSize(RHSVecType->getElementType()))) { 7503 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 7504 LHSVecType->getElementType()->isIntegerType() && 7505 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 7506 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 7507 return LHSType; 7508 } 7509 if (!IsCompAssign && 7510 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 7511 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 7512 RHSVecType->getElementType()->isIntegerType()) { 7513 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 7514 return RHSType; 7515 } 7516 } 7517 7518 // If there's an ext-vector type and a scalar, try to convert the scalar to 7519 // the vector element type and splat. 7520 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) { 7521 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 7522 LHSVecType->getElementType(), LHSType)) 7523 return LHSType; 7524 } 7525 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) { 7526 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 7527 LHSType, RHSVecType->getElementType(), 7528 RHSType)) 7529 return RHSType; 7530 } 7531 7532 // If we're allowing lax vector conversions, only the total (data) size 7533 // needs to be the same. 7534 // FIXME: Should we really be allowing this? 7535 // FIXME: We really just pick the LHS type arbitrarily? 7536 if (isLaxVectorConversion(RHSType, LHSType)) { 7537 QualType resultType = LHSType; 7538 RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast); 7539 return resultType; 7540 } 7541 7542 // Okay, the expression is invalid. 7543 7544 // If there's a non-vector, non-real operand, diagnose that. 7545 if ((!RHSVecType && !RHSType->isRealType()) || 7546 (!LHSVecType && !LHSType->isRealType())) { 7547 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 7548 << LHSType << RHSType 7549 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7550 return QualType(); 7551 } 7552 7553 // OpenCL V1.1 6.2.6.p1: 7554 // If the operands are of more than one vector type, then an error shall 7555 // occur. Implicit conversions between vector types are not permitted, per 7556 // section 6.2.1. 7557 if (getLangOpts().OpenCL && 7558 RHSVecType && isa<ExtVectorType>(RHSVecType) && 7559 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 7560 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 7561 << RHSType; 7562 return QualType(); 7563 } 7564 7565 // Otherwise, use the generic diagnostic. 7566 Diag(Loc, diag::err_typecheck_vector_not_convertable) 7567 << LHSType << RHSType 7568 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7569 return QualType(); 7570 } 7571 7572 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 7573 // expression. These are mainly cases where the null pointer is used as an 7574 // integer instead of a pointer. 7575 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 7576 SourceLocation Loc, bool IsCompare) { 7577 // The canonical way to check for a GNU null is with isNullPointerConstant, 7578 // but we use a bit of a hack here for speed; this is a relatively 7579 // hot path, and isNullPointerConstant is slow. 7580 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 7581 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 7582 7583 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 7584 7585 // Avoid analyzing cases where the result will either be invalid (and 7586 // diagnosed as such) or entirely valid and not something to warn about. 7587 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 7588 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 7589 return; 7590 7591 // Comparison operations would not make sense with a null pointer no matter 7592 // what the other expression is. 7593 if (!IsCompare) { 7594 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 7595 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 7596 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 7597 return; 7598 } 7599 7600 // The rest of the operations only make sense with a null pointer 7601 // if the other expression is a pointer. 7602 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 7603 NonNullType->canDecayToPointerType()) 7604 return; 7605 7606 S.Diag(Loc, diag::warn_null_in_comparison_operation) 7607 << LHSNull /* LHS is NULL */ << NonNullType 7608 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7609 } 7610 7611 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 7612 ExprResult &RHS, 7613 SourceLocation Loc, bool IsDiv) { 7614 // Check for division/remainder by zero. 7615 llvm::APSInt RHSValue; 7616 if (!RHS.get()->isValueDependent() && 7617 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0) 7618 S.DiagRuntimeBehavior(Loc, RHS.get(), 7619 S.PDiag(diag::warn_remainder_division_by_zero) 7620 << IsDiv << RHS.get()->getSourceRange()); 7621 } 7622 7623 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 7624 SourceLocation Loc, 7625 bool IsCompAssign, bool IsDiv) { 7626 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7627 7628 if (LHS.get()->getType()->isVectorType() || 7629 RHS.get()->getType()->isVectorType()) 7630 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 7631 /*AllowBothBool*/getLangOpts().AltiVec, 7632 /*AllowBoolConversions*/false); 7633 7634 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 7635 if (LHS.isInvalid() || RHS.isInvalid()) 7636 return QualType(); 7637 7638 7639 if (compType.isNull() || !compType->isArithmeticType()) 7640 return InvalidOperands(Loc, LHS, RHS); 7641 if (IsDiv) 7642 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 7643 return compType; 7644 } 7645 7646 QualType Sema::CheckRemainderOperands( 7647 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 7648 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7649 7650 if (LHS.get()->getType()->isVectorType() || 7651 RHS.get()->getType()->isVectorType()) { 7652 if (LHS.get()->getType()->hasIntegerRepresentation() && 7653 RHS.get()->getType()->hasIntegerRepresentation()) 7654 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 7655 /*AllowBothBool*/getLangOpts().AltiVec, 7656 /*AllowBoolConversions*/false); 7657 return InvalidOperands(Loc, LHS, RHS); 7658 } 7659 7660 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 7661 if (LHS.isInvalid() || RHS.isInvalid()) 7662 return QualType(); 7663 7664 if (compType.isNull() || !compType->isIntegerType()) 7665 return InvalidOperands(Loc, LHS, RHS); 7666 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 7667 return compType; 7668 } 7669 7670 /// \brief Diagnose invalid arithmetic on two void pointers. 7671 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 7672 Expr *LHSExpr, Expr *RHSExpr) { 7673 S.Diag(Loc, S.getLangOpts().CPlusPlus 7674 ? diag::err_typecheck_pointer_arith_void_type 7675 : diag::ext_gnu_void_ptr) 7676 << 1 /* two pointers */ << LHSExpr->getSourceRange() 7677 << RHSExpr->getSourceRange(); 7678 } 7679 7680 /// \brief Diagnose invalid arithmetic on a void pointer. 7681 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 7682 Expr *Pointer) { 7683 S.Diag(Loc, S.getLangOpts().CPlusPlus 7684 ? diag::err_typecheck_pointer_arith_void_type 7685 : diag::ext_gnu_void_ptr) 7686 << 0 /* one pointer */ << Pointer->getSourceRange(); 7687 } 7688 7689 /// \brief Diagnose invalid arithmetic on two function pointers. 7690 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 7691 Expr *LHS, Expr *RHS) { 7692 assert(LHS->getType()->isAnyPointerType()); 7693 assert(RHS->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 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 7698 // We only show the second type if it differs from the first. 7699 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 7700 RHS->getType()) 7701 << RHS->getType()->getPointeeType() 7702 << LHS->getSourceRange() << RHS->getSourceRange(); 7703 } 7704 7705 /// \brief Diagnose invalid arithmetic on a function pointer. 7706 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 7707 Expr *Pointer) { 7708 assert(Pointer->getType()->isAnyPointerType()); 7709 S.Diag(Loc, S.getLangOpts().CPlusPlus 7710 ? diag::err_typecheck_pointer_arith_function_type 7711 : diag::ext_gnu_ptr_func_arith) 7712 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 7713 << 0 /* one pointer, so only one type */ 7714 << Pointer->getSourceRange(); 7715 } 7716 7717 /// \brief Emit error if Operand is incomplete pointer type 7718 /// 7719 /// \returns True if pointer has incomplete type 7720 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 7721 Expr *Operand) { 7722 QualType ResType = Operand->getType(); 7723 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7724 ResType = ResAtomicType->getValueType(); 7725 7726 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 7727 QualType PointeeTy = ResType->getPointeeType(); 7728 return S.RequireCompleteType(Loc, PointeeTy, 7729 diag::err_typecheck_arithmetic_incomplete_type, 7730 PointeeTy, Operand->getSourceRange()); 7731 } 7732 7733 /// \brief Check the validity of an arithmetic pointer operand. 7734 /// 7735 /// If the operand has pointer type, this code will check for pointer types 7736 /// which are invalid in arithmetic operations. These will be diagnosed 7737 /// appropriately, including whether or not the use is supported as an 7738 /// extension. 7739 /// 7740 /// \returns True when the operand is valid to use (even if as an extension). 7741 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 7742 Expr *Operand) { 7743 QualType ResType = Operand->getType(); 7744 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 7745 ResType = ResAtomicType->getValueType(); 7746 7747 if (!ResType->isAnyPointerType()) return true; 7748 7749 QualType PointeeTy = ResType->getPointeeType(); 7750 if (PointeeTy->isVoidType()) { 7751 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 7752 return !S.getLangOpts().CPlusPlus; 7753 } 7754 if (PointeeTy->isFunctionType()) { 7755 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 7756 return !S.getLangOpts().CPlusPlus; 7757 } 7758 7759 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 7760 7761 return true; 7762 } 7763 7764 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer 7765 /// operands. 7766 /// 7767 /// This routine will diagnose any invalid arithmetic on pointer operands much 7768 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 7769 /// for emitting a single diagnostic even for operations where both LHS and RHS 7770 /// are (potentially problematic) pointers. 7771 /// 7772 /// \returns True when the operand is valid to use (even if as an extension). 7773 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 7774 Expr *LHSExpr, Expr *RHSExpr) { 7775 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 7776 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 7777 if (!isLHSPointer && !isRHSPointer) return true; 7778 7779 QualType LHSPointeeTy, RHSPointeeTy; 7780 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 7781 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 7782 7783 // if both are pointers check if operation is valid wrt address spaces 7784 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 7785 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 7786 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 7787 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 7788 S.Diag(Loc, 7789 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 7790 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 7791 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 7792 return false; 7793 } 7794 } 7795 7796 // Check for arithmetic on pointers to incomplete types. 7797 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 7798 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 7799 if (isLHSVoidPtr || isRHSVoidPtr) { 7800 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 7801 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 7802 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 7803 7804 return !S.getLangOpts().CPlusPlus; 7805 } 7806 7807 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 7808 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 7809 if (isLHSFuncPtr || isRHSFuncPtr) { 7810 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 7811 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 7812 RHSExpr); 7813 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 7814 7815 return !S.getLangOpts().CPlusPlus; 7816 } 7817 7818 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 7819 return false; 7820 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 7821 return false; 7822 7823 return true; 7824 } 7825 7826 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 7827 /// literal. 7828 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 7829 Expr *LHSExpr, Expr *RHSExpr) { 7830 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 7831 Expr* IndexExpr = RHSExpr; 7832 if (!StrExpr) { 7833 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 7834 IndexExpr = LHSExpr; 7835 } 7836 7837 bool IsStringPlusInt = StrExpr && 7838 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 7839 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 7840 return; 7841 7842 llvm::APSInt index; 7843 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) { 7844 unsigned StrLenWithNull = StrExpr->getLength() + 1; 7845 if (index.isNonNegative() && 7846 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 7847 index.isUnsigned())) 7848 return; 7849 } 7850 7851 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7852 Self.Diag(OpLoc, diag::warn_string_plus_int) 7853 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 7854 7855 // Only print a fixit for "str" + int, not for int + "str". 7856 if (IndexExpr == RHSExpr) { 7857 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 7858 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7859 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7860 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7861 << FixItHint::CreateInsertion(EndLoc, "]"); 7862 } else 7863 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7864 } 7865 7866 /// \brief Emit a warning when adding a char literal to a string. 7867 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 7868 Expr *LHSExpr, Expr *RHSExpr) { 7869 const Expr *StringRefExpr = LHSExpr; 7870 const CharacterLiteral *CharExpr = 7871 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 7872 7873 if (!CharExpr) { 7874 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 7875 StringRefExpr = RHSExpr; 7876 } 7877 7878 if (!CharExpr || !StringRefExpr) 7879 return; 7880 7881 const QualType StringType = StringRefExpr->getType(); 7882 7883 // Return if not a PointerType. 7884 if (!StringType->isAnyPointerType()) 7885 return; 7886 7887 // Return if not a CharacterType. 7888 if (!StringType->getPointeeType()->isAnyCharacterType()) 7889 return; 7890 7891 ASTContext &Ctx = Self.getASTContext(); 7892 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 7893 7894 const QualType CharType = CharExpr->getType(); 7895 if (!CharType->isAnyCharacterType() && 7896 CharType->isIntegerType() && 7897 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 7898 Self.Diag(OpLoc, diag::warn_string_plus_char) 7899 << DiagRange << Ctx.CharTy; 7900 } else { 7901 Self.Diag(OpLoc, diag::warn_string_plus_char) 7902 << DiagRange << CharExpr->getType(); 7903 } 7904 7905 // Only print a fixit for str + char, not for char + str. 7906 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 7907 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd()); 7908 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 7909 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&") 7910 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 7911 << FixItHint::CreateInsertion(EndLoc, "]"); 7912 } else { 7913 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 7914 } 7915 } 7916 7917 /// \brief Emit error when two pointers are incompatible. 7918 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 7919 Expr *LHSExpr, Expr *RHSExpr) { 7920 assert(LHSExpr->getType()->isAnyPointerType()); 7921 assert(RHSExpr->getType()->isAnyPointerType()); 7922 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 7923 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 7924 << RHSExpr->getSourceRange(); 7925 } 7926 7927 // C99 6.5.6 7928 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 7929 SourceLocation Loc, BinaryOperatorKind Opc, 7930 QualType* CompLHSTy) { 7931 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 7932 7933 if (LHS.get()->getType()->isVectorType() || 7934 RHS.get()->getType()->isVectorType()) { 7935 QualType compType = CheckVectorOperands( 7936 LHS, RHS, Loc, CompLHSTy, 7937 /*AllowBothBool*/getLangOpts().AltiVec, 7938 /*AllowBoolConversions*/getLangOpts().ZVector); 7939 if (CompLHSTy) *CompLHSTy = compType; 7940 return compType; 7941 } 7942 7943 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 7944 if (LHS.isInvalid() || RHS.isInvalid()) 7945 return QualType(); 7946 7947 // Diagnose "string literal" '+' int and string '+' "char literal". 7948 if (Opc == BO_Add) { 7949 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 7950 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 7951 } 7952 7953 // handle the common case first (both operands are arithmetic). 7954 if (!compType.isNull() && compType->isArithmeticType()) { 7955 if (CompLHSTy) *CompLHSTy = compType; 7956 return compType; 7957 } 7958 7959 // Type-checking. Ultimately the pointer's going to be in PExp; 7960 // note that we bias towards the LHS being the pointer. 7961 Expr *PExp = LHS.get(), *IExp = RHS.get(); 7962 7963 bool isObjCPointer; 7964 if (PExp->getType()->isPointerType()) { 7965 isObjCPointer = false; 7966 } else if (PExp->getType()->isObjCObjectPointerType()) { 7967 isObjCPointer = true; 7968 } else { 7969 std::swap(PExp, IExp); 7970 if (PExp->getType()->isPointerType()) { 7971 isObjCPointer = false; 7972 } else if (PExp->getType()->isObjCObjectPointerType()) { 7973 isObjCPointer = true; 7974 } else { 7975 return InvalidOperands(Loc, LHS, RHS); 7976 } 7977 } 7978 assert(PExp->getType()->isAnyPointerType()); 7979 7980 if (!IExp->getType()->isIntegerType()) 7981 return InvalidOperands(Loc, LHS, RHS); 7982 7983 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 7984 return QualType(); 7985 7986 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 7987 return QualType(); 7988 7989 // Check array bounds for pointer arithemtic 7990 CheckArrayAccess(PExp, IExp); 7991 7992 if (CompLHSTy) { 7993 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 7994 if (LHSTy.isNull()) { 7995 LHSTy = LHS.get()->getType(); 7996 if (LHSTy->isPromotableIntegerType()) 7997 LHSTy = Context.getPromotedIntegerType(LHSTy); 7998 } 7999 *CompLHSTy = LHSTy; 8000 } 8001 8002 return PExp->getType(); 8003 } 8004 8005 // C99 6.5.6 8006 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 8007 SourceLocation Loc, 8008 QualType* CompLHSTy) { 8009 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8010 8011 if (LHS.get()->getType()->isVectorType() || 8012 RHS.get()->getType()->isVectorType()) { 8013 QualType compType = CheckVectorOperands( 8014 LHS, RHS, Loc, CompLHSTy, 8015 /*AllowBothBool*/getLangOpts().AltiVec, 8016 /*AllowBoolConversions*/getLangOpts().ZVector); 8017 if (CompLHSTy) *CompLHSTy = compType; 8018 return compType; 8019 } 8020 8021 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 8022 if (LHS.isInvalid() || RHS.isInvalid()) 8023 return QualType(); 8024 8025 // Enforce type constraints: C99 6.5.6p3. 8026 8027 // Handle the common case first (both operands are arithmetic). 8028 if (!compType.isNull() && compType->isArithmeticType()) { 8029 if (CompLHSTy) *CompLHSTy = compType; 8030 return compType; 8031 } 8032 8033 // Either ptr - int or ptr - ptr. 8034 if (LHS.get()->getType()->isAnyPointerType()) { 8035 QualType lpointee = LHS.get()->getType()->getPointeeType(); 8036 8037 // Diagnose bad cases where we step over interface counts. 8038 if (LHS.get()->getType()->isObjCObjectPointerType() && 8039 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 8040 return QualType(); 8041 8042 // The result type of a pointer-int computation is the pointer type. 8043 if (RHS.get()->getType()->isIntegerType()) { 8044 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 8045 return QualType(); 8046 8047 // Check array bounds for pointer arithemtic 8048 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 8049 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 8050 8051 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8052 return LHS.get()->getType(); 8053 } 8054 8055 // Handle pointer-pointer subtractions. 8056 if (const PointerType *RHSPTy 8057 = RHS.get()->getType()->getAs<PointerType>()) { 8058 QualType rpointee = RHSPTy->getPointeeType(); 8059 8060 if (getLangOpts().CPlusPlus) { 8061 // Pointee types must be the same: C++ [expr.add] 8062 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 8063 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8064 } 8065 } else { 8066 // Pointee types must be compatible C99 6.5.6p3 8067 if (!Context.typesAreCompatible( 8068 Context.getCanonicalType(lpointee).getUnqualifiedType(), 8069 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 8070 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 8071 return QualType(); 8072 } 8073 } 8074 8075 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 8076 LHS.get(), RHS.get())) 8077 return QualType(); 8078 8079 // The pointee type may have zero size. As an extension, a structure or 8080 // union may have zero size or an array may have zero length. In this 8081 // case subtraction does not make sense. 8082 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 8083 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 8084 if (ElementSize.isZero()) { 8085 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 8086 << rpointee.getUnqualifiedType() 8087 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8088 } 8089 } 8090 8091 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 8092 return Context.getPointerDiffType(); 8093 } 8094 } 8095 8096 return InvalidOperands(Loc, LHS, RHS); 8097 } 8098 8099 static bool isScopedEnumerationType(QualType T) { 8100 if (const EnumType *ET = T->getAs<EnumType>()) 8101 return ET->getDecl()->isScoped(); 8102 return false; 8103 } 8104 8105 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 8106 SourceLocation Loc, BinaryOperatorKind Opc, 8107 QualType LHSType) { 8108 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 8109 // so skip remaining warnings as we don't want to modify values within Sema. 8110 if (S.getLangOpts().OpenCL) 8111 return; 8112 8113 llvm::APSInt Right; 8114 // Check right/shifter operand 8115 if (RHS.get()->isValueDependent() || 8116 !RHS.get()->EvaluateAsInt(Right, S.Context)) 8117 return; 8118 8119 if (Right.isNegative()) { 8120 S.DiagRuntimeBehavior(Loc, RHS.get(), 8121 S.PDiag(diag::warn_shift_negative) 8122 << RHS.get()->getSourceRange()); 8123 return; 8124 } 8125 llvm::APInt LeftBits(Right.getBitWidth(), 8126 S.Context.getTypeSize(LHS.get()->getType())); 8127 if (Right.uge(LeftBits)) { 8128 S.DiagRuntimeBehavior(Loc, RHS.get(), 8129 S.PDiag(diag::warn_shift_gt_typewidth) 8130 << RHS.get()->getSourceRange()); 8131 return; 8132 } 8133 if (Opc != BO_Shl) 8134 return; 8135 8136 // When left shifting an ICE which is signed, we can check for overflow which 8137 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 8138 // integers have defined behavior modulo one more than the maximum value 8139 // representable in the result type, so never warn for those. 8140 llvm::APSInt Left; 8141 if (LHS.get()->isValueDependent() || 8142 LHSType->hasUnsignedIntegerRepresentation() || 8143 !LHS.get()->EvaluateAsInt(Left, S.Context)) 8144 return; 8145 8146 // If LHS does not have a signed type and non-negative value 8147 // then, the behavior is undefined. Warn about it. 8148 if (Left.isNegative()) { 8149 S.DiagRuntimeBehavior(Loc, LHS.get(), 8150 S.PDiag(diag::warn_shift_lhs_negative) 8151 << LHS.get()->getSourceRange()); 8152 return; 8153 } 8154 8155 llvm::APInt ResultBits = 8156 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 8157 if (LeftBits.uge(ResultBits)) 8158 return; 8159 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 8160 Result = Result.shl(Right); 8161 8162 // Print the bit representation of the signed integer as an unsigned 8163 // hexadecimal number. 8164 SmallString<40> HexResult; 8165 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 8166 8167 // If we are only missing a sign bit, this is less likely to result in actual 8168 // bugs -- if the result is cast back to an unsigned type, it will have the 8169 // expected value. Thus we place this behind a different warning that can be 8170 // turned off separately if needed. 8171 if (LeftBits == ResultBits - 1) { 8172 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 8173 << HexResult << LHSType 8174 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8175 return; 8176 } 8177 8178 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 8179 << HexResult.str() << Result.getMinSignedBits() << LHSType 8180 << Left.getBitWidth() << LHS.get()->getSourceRange() 8181 << RHS.get()->getSourceRange(); 8182 } 8183 8184 /// \brief Return the resulting type when an OpenCL vector is shifted 8185 /// by a scalar or vector shift amount. 8186 static QualType checkOpenCLVectorShift(Sema &S, 8187 ExprResult &LHS, ExprResult &RHS, 8188 SourceLocation Loc, bool IsCompAssign) { 8189 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 8190 if (!LHS.get()->getType()->isVectorType()) { 8191 S.Diag(Loc, diag::err_shift_rhs_only_vector) 8192 << RHS.get()->getType() << LHS.get()->getType() 8193 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8194 return QualType(); 8195 } 8196 8197 if (!IsCompAssign) { 8198 LHS = S.UsualUnaryConversions(LHS.get()); 8199 if (LHS.isInvalid()) return QualType(); 8200 } 8201 8202 RHS = S.UsualUnaryConversions(RHS.get()); 8203 if (RHS.isInvalid()) return QualType(); 8204 8205 QualType LHSType = LHS.get()->getType(); 8206 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 8207 QualType LHSEleType = LHSVecTy->getElementType(); 8208 8209 // Note that RHS might not be a vector. 8210 QualType RHSType = RHS.get()->getType(); 8211 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 8212 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 8213 8214 // OpenCL v1.1 s6.3.j says that the operands need to be integers. 8215 if (!LHSEleType->isIntegerType()) { 8216 S.Diag(Loc, diag::err_typecheck_expect_int) 8217 << LHS.get()->getType() << LHS.get()->getSourceRange(); 8218 return QualType(); 8219 } 8220 8221 if (!RHSEleType->isIntegerType()) { 8222 S.Diag(Loc, diag::err_typecheck_expect_int) 8223 << RHS.get()->getType() << RHS.get()->getSourceRange(); 8224 return QualType(); 8225 } 8226 8227 if (RHSVecTy) { 8228 // OpenCL v1.1 s6.3.j says that for vector types, the operators 8229 // are applied component-wise. So if RHS is a vector, then ensure 8230 // that the number of elements is the same as LHS... 8231 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 8232 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 8233 << LHS.get()->getType() << RHS.get()->getType() 8234 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8235 return QualType(); 8236 } 8237 } else { 8238 // ...else expand RHS to match the number of elements in LHS. 8239 QualType VecTy = 8240 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 8241 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 8242 } 8243 8244 return LHSType; 8245 } 8246 8247 // C99 6.5.7 8248 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 8249 SourceLocation Loc, BinaryOperatorKind Opc, 8250 bool IsCompAssign) { 8251 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8252 8253 // Vector shifts promote their scalar inputs to vector type. 8254 if (LHS.get()->getType()->isVectorType() || 8255 RHS.get()->getType()->isVectorType()) { 8256 if (LangOpts.OpenCL) 8257 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8258 if (LangOpts.ZVector) { 8259 // The shift operators for the z vector extensions work basically 8260 // like OpenCL shifts, except that neither the LHS nor the RHS is 8261 // allowed to be a "vector bool". 8262 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 8263 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 8264 return InvalidOperands(Loc, LHS, RHS); 8265 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 8266 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8267 return InvalidOperands(Loc, LHS, RHS); 8268 return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 8269 } 8270 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8271 /*AllowBothBool*/true, 8272 /*AllowBoolConversions*/false); 8273 } 8274 8275 // Shifts don't perform usual arithmetic conversions, they just do integer 8276 // promotions on each operand. C99 6.5.7p3 8277 8278 // For the LHS, do usual unary conversions, but then reset them away 8279 // if this is a compound assignment. 8280 ExprResult OldLHS = LHS; 8281 LHS = UsualUnaryConversions(LHS.get()); 8282 if (LHS.isInvalid()) 8283 return QualType(); 8284 QualType LHSType = LHS.get()->getType(); 8285 if (IsCompAssign) LHS = OldLHS; 8286 8287 // The RHS is simpler. 8288 RHS = UsualUnaryConversions(RHS.get()); 8289 if (RHS.isInvalid()) 8290 return QualType(); 8291 QualType RHSType = RHS.get()->getType(); 8292 8293 // C99 6.5.7p2: Each of the operands shall have integer type. 8294 if (!LHSType->hasIntegerRepresentation() || 8295 !RHSType->hasIntegerRepresentation()) 8296 return InvalidOperands(Loc, LHS, RHS); 8297 8298 // C++0x: Don't allow scoped enums. FIXME: Use something better than 8299 // hasIntegerRepresentation() above instead of this. 8300 if (isScopedEnumerationType(LHSType) || 8301 isScopedEnumerationType(RHSType)) { 8302 return InvalidOperands(Loc, LHS, RHS); 8303 } 8304 // Sanity-check shift operands 8305 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 8306 8307 // "The type of the result is that of the promoted left operand." 8308 return LHSType; 8309 } 8310 8311 static bool IsWithinTemplateSpecialization(Decl *D) { 8312 if (DeclContext *DC = D->getDeclContext()) { 8313 if (isa<ClassTemplateSpecializationDecl>(DC)) 8314 return true; 8315 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 8316 return FD->isFunctionTemplateSpecialization(); 8317 } 8318 return false; 8319 } 8320 8321 /// If two different enums are compared, raise a warning. 8322 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 8323 Expr *RHS) { 8324 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 8325 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 8326 8327 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 8328 if (!LHSEnumType) 8329 return; 8330 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 8331 if (!RHSEnumType) 8332 return; 8333 8334 // Ignore anonymous enums. 8335 if (!LHSEnumType->getDecl()->getIdentifier()) 8336 return; 8337 if (!RHSEnumType->getDecl()->getIdentifier()) 8338 return; 8339 8340 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 8341 return; 8342 8343 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 8344 << LHSStrippedType << RHSStrippedType 8345 << LHS->getSourceRange() << RHS->getSourceRange(); 8346 } 8347 8348 /// \brief Diagnose bad pointer comparisons. 8349 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 8350 ExprResult &LHS, ExprResult &RHS, 8351 bool IsError) { 8352 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 8353 : diag::ext_typecheck_comparison_of_distinct_pointers) 8354 << LHS.get()->getType() << RHS.get()->getType() 8355 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8356 } 8357 8358 /// \brief Returns false if the pointers are converted to a composite type, 8359 /// true otherwise. 8360 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 8361 ExprResult &LHS, ExprResult &RHS) { 8362 // C++ [expr.rel]p2: 8363 // [...] Pointer conversions (4.10) and qualification 8364 // conversions (4.4) are performed on pointer operands (or on 8365 // a pointer operand and a null pointer constant) to bring 8366 // them to their composite pointer type. [...] 8367 // 8368 // C++ [expr.eq]p1 uses the same notion for (in)equality 8369 // comparisons of pointers. 8370 8371 // C++ [expr.eq]p2: 8372 // In addition, pointers to members can be compared, or a pointer to 8373 // member and a null pointer constant. Pointer to member conversions 8374 // (4.11) and qualification conversions (4.4) are performed to bring 8375 // them to a common type. If one operand is a null pointer constant, 8376 // the common type is the type of the other operand. Otherwise, the 8377 // common type is a pointer to member type similar (4.4) to the type 8378 // of one of the operands, with a cv-qualification signature (4.4) 8379 // that is the union of the cv-qualification signatures of the operand 8380 // types. 8381 8382 QualType LHSType = LHS.get()->getType(); 8383 QualType RHSType = RHS.get()->getType(); 8384 assert((LHSType->isPointerType() && RHSType->isPointerType()) || 8385 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType())); 8386 8387 bool NonStandardCompositeType = false; 8388 bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType; 8389 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr); 8390 if (T.isNull()) { 8391 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 8392 return true; 8393 } 8394 8395 if (NonStandardCompositeType) 8396 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard) 8397 << LHSType << RHSType << T << LHS.get()->getSourceRange() 8398 << RHS.get()->getSourceRange(); 8399 8400 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 8401 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 8402 return false; 8403 } 8404 8405 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 8406 ExprResult &LHS, 8407 ExprResult &RHS, 8408 bool IsError) { 8409 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 8410 : diag::ext_typecheck_comparison_of_fptr_to_void) 8411 << LHS.get()->getType() << RHS.get()->getType() 8412 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8413 } 8414 8415 static bool isObjCObjectLiteral(ExprResult &E) { 8416 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 8417 case Stmt::ObjCArrayLiteralClass: 8418 case Stmt::ObjCDictionaryLiteralClass: 8419 case Stmt::ObjCStringLiteralClass: 8420 case Stmt::ObjCBoxedExprClass: 8421 return true; 8422 default: 8423 // Note that ObjCBoolLiteral is NOT an object literal! 8424 return false; 8425 } 8426 } 8427 8428 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 8429 const ObjCObjectPointerType *Type = 8430 LHS->getType()->getAs<ObjCObjectPointerType>(); 8431 8432 // If this is not actually an Objective-C object, bail out. 8433 if (!Type) 8434 return false; 8435 8436 // Get the LHS object's interface type. 8437 QualType InterfaceType = Type->getPointeeType(); 8438 8439 // If the RHS isn't an Objective-C object, bail out. 8440 if (!RHS->getType()->isObjCObjectPointerType()) 8441 return false; 8442 8443 // Try to find the -isEqual: method. 8444 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 8445 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 8446 InterfaceType, 8447 /*instance=*/true); 8448 if (!Method) { 8449 if (Type->isObjCIdType()) { 8450 // For 'id', just check the global pool. 8451 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 8452 /*receiverId=*/true); 8453 } else { 8454 // Check protocols. 8455 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 8456 /*instance=*/true); 8457 } 8458 } 8459 8460 if (!Method) 8461 return false; 8462 8463 QualType T = Method->parameters()[0]->getType(); 8464 if (!T->isObjCObjectPointerType()) 8465 return false; 8466 8467 QualType R = Method->getReturnType(); 8468 if (!R->isScalarType()) 8469 return false; 8470 8471 return true; 8472 } 8473 8474 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 8475 FromE = FromE->IgnoreParenImpCasts(); 8476 switch (FromE->getStmtClass()) { 8477 default: 8478 break; 8479 case Stmt::ObjCStringLiteralClass: 8480 // "string literal" 8481 return LK_String; 8482 case Stmt::ObjCArrayLiteralClass: 8483 // "array literal" 8484 return LK_Array; 8485 case Stmt::ObjCDictionaryLiteralClass: 8486 // "dictionary literal" 8487 return LK_Dictionary; 8488 case Stmt::BlockExprClass: 8489 return LK_Block; 8490 case Stmt::ObjCBoxedExprClass: { 8491 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 8492 switch (Inner->getStmtClass()) { 8493 case Stmt::IntegerLiteralClass: 8494 case Stmt::FloatingLiteralClass: 8495 case Stmt::CharacterLiteralClass: 8496 case Stmt::ObjCBoolLiteralExprClass: 8497 case Stmt::CXXBoolLiteralExprClass: 8498 // "numeric literal" 8499 return LK_Numeric; 8500 case Stmt::ImplicitCastExprClass: { 8501 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 8502 // Boolean literals can be represented by implicit casts. 8503 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 8504 return LK_Numeric; 8505 break; 8506 } 8507 default: 8508 break; 8509 } 8510 return LK_Boxed; 8511 } 8512 } 8513 return LK_None; 8514 } 8515 8516 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 8517 ExprResult &LHS, ExprResult &RHS, 8518 BinaryOperator::Opcode Opc){ 8519 Expr *Literal; 8520 Expr *Other; 8521 if (isObjCObjectLiteral(LHS)) { 8522 Literal = LHS.get(); 8523 Other = RHS.get(); 8524 } else { 8525 Literal = RHS.get(); 8526 Other = LHS.get(); 8527 } 8528 8529 // Don't warn on comparisons against nil. 8530 Other = Other->IgnoreParenCasts(); 8531 if (Other->isNullPointerConstant(S.getASTContext(), 8532 Expr::NPC_ValueDependentIsNotNull)) 8533 return; 8534 8535 // This should be kept in sync with warn_objc_literal_comparison. 8536 // LK_String should always be after the other literals, since it has its own 8537 // warning flag. 8538 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 8539 assert(LiteralKind != Sema::LK_Block); 8540 if (LiteralKind == Sema::LK_None) { 8541 llvm_unreachable("Unknown Objective-C object literal kind"); 8542 } 8543 8544 if (LiteralKind == Sema::LK_String) 8545 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 8546 << Literal->getSourceRange(); 8547 else 8548 S.Diag(Loc, diag::warn_objc_literal_comparison) 8549 << LiteralKind << Literal->getSourceRange(); 8550 8551 if (BinaryOperator::isEqualityOp(Opc) && 8552 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 8553 SourceLocation Start = LHS.get()->getLocStart(); 8554 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd()); 8555 CharSourceRange OpRange = 8556 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 8557 8558 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 8559 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 8560 << FixItHint::CreateReplacement(OpRange, " isEqual:") 8561 << FixItHint::CreateInsertion(End, "]"); 8562 } 8563 } 8564 8565 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS, 8566 ExprResult &RHS, 8567 SourceLocation Loc, 8568 BinaryOperatorKind Opc) { 8569 // Check that left hand side is !something. 8570 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 8571 if (!UO || UO->getOpcode() != UO_LNot) return; 8572 8573 // Only check if the right hand side is non-bool arithmetic type. 8574 if (RHS.get()->isKnownToHaveBooleanValue()) return; 8575 8576 // Make sure that the something in !something is not bool. 8577 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 8578 if (SubExpr->isKnownToHaveBooleanValue()) return; 8579 8580 // Emit warning. 8581 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison) 8582 << Loc; 8583 8584 // First note suggest !(x < y) 8585 SourceLocation FirstOpen = SubExpr->getLocStart(); 8586 SourceLocation FirstClose = RHS.get()->getLocEnd(); 8587 FirstClose = S.getLocForEndOfToken(FirstClose); 8588 if (FirstClose.isInvalid()) 8589 FirstOpen = SourceLocation(); 8590 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 8591 << FixItHint::CreateInsertion(FirstOpen, "(") 8592 << FixItHint::CreateInsertion(FirstClose, ")"); 8593 8594 // Second note suggests (!x) < y 8595 SourceLocation SecondOpen = LHS.get()->getLocStart(); 8596 SourceLocation SecondClose = LHS.get()->getLocEnd(); 8597 SecondClose = S.getLocForEndOfToken(SecondClose); 8598 if (SecondClose.isInvalid()) 8599 SecondOpen = SourceLocation(); 8600 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 8601 << FixItHint::CreateInsertion(SecondOpen, "(") 8602 << FixItHint::CreateInsertion(SecondClose, ")"); 8603 } 8604 8605 // Get the decl for a simple expression: a reference to a variable, 8606 // an implicit C++ field reference, or an implicit ObjC ivar reference. 8607 static ValueDecl *getCompareDecl(Expr *E) { 8608 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E)) 8609 return DR->getDecl(); 8610 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 8611 if (Ivar->isFreeIvar()) 8612 return Ivar->getDecl(); 8613 } 8614 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) { 8615 if (Mem->isImplicitAccess()) 8616 return Mem->getMemberDecl(); 8617 } 8618 return nullptr; 8619 } 8620 8621 // C99 6.5.8, C++ [expr.rel] 8622 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 8623 SourceLocation Loc, BinaryOperatorKind Opc, 8624 bool IsRelational) { 8625 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 8626 8627 // Handle vector comparisons separately. 8628 if (LHS.get()->getType()->isVectorType() || 8629 RHS.get()->getType()->isVectorType()) 8630 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational); 8631 8632 QualType LHSType = LHS.get()->getType(); 8633 QualType RHSType = RHS.get()->getType(); 8634 8635 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts(); 8636 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts(); 8637 8638 checkEnumComparison(*this, Loc, LHS.get(), RHS.get()); 8639 diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc); 8640 8641 if (!LHSType->hasFloatingRepresentation() && 8642 !(LHSType->isBlockPointerType() && IsRelational) && 8643 !LHS.get()->getLocStart().isMacroID() && 8644 !RHS.get()->getLocStart().isMacroID() && 8645 ActiveTemplateInstantiations.empty()) { 8646 // For non-floating point types, check for self-comparisons of the form 8647 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 8648 // often indicate logic errors in the program. 8649 // 8650 // NOTE: Don't warn about comparison expressions resulting from macro 8651 // expansion. Also don't warn about comparisons which are only self 8652 // comparisons within a template specialization. The warnings should catch 8653 // obvious cases in the definition of the template anyways. The idea is to 8654 // warn when the typed comparison operator will always evaluate to the same 8655 // result. 8656 ValueDecl *DL = getCompareDecl(LHSStripped); 8657 ValueDecl *DR = getCompareDecl(RHSStripped); 8658 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) { 8659 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 8660 << 0 // self- 8661 << (Opc == BO_EQ 8662 || Opc == BO_LE 8663 || Opc == BO_GE)); 8664 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() && 8665 !DL->getType()->isReferenceType() && 8666 !DR->getType()->isReferenceType()) { 8667 // what is it always going to eval to? 8668 char always_evals_to; 8669 switch(Opc) { 8670 case BO_EQ: // e.g. array1 == array2 8671 always_evals_to = 0; // false 8672 break; 8673 case BO_NE: // e.g. array1 != array2 8674 always_evals_to = 1; // true 8675 break; 8676 default: 8677 // best we can say is 'a constant' 8678 always_evals_to = 2; // e.g. array1 <= array2 8679 break; 8680 } 8681 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always) 8682 << 1 // array 8683 << always_evals_to); 8684 } 8685 8686 if (isa<CastExpr>(LHSStripped)) 8687 LHSStripped = LHSStripped->IgnoreParenCasts(); 8688 if (isa<CastExpr>(RHSStripped)) 8689 RHSStripped = RHSStripped->IgnoreParenCasts(); 8690 8691 // Warn about comparisons against a string constant (unless the other 8692 // operand is null), the user probably wants strcmp. 8693 Expr *literalString = nullptr; 8694 Expr *literalStringStripped = nullptr; 8695 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 8696 !RHSStripped->isNullPointerConstant(Context, 8697 Expr::NPC_ValueDependentIsNull)) { 8698 literalString = LHS.get(); 8699 literalStringStripped = LHSStripped; 8700 } else if ((isa<StringLiteral>(RHSStripped) || 8701 isa<ObjCEncodeExpr>(RHSStripped)) && 8702 !LHSStripped->isNullPointerConstant(Context, 8703 Expr::NPC_ValueDependentIsNull)) { 8704 literalString = RHS.get(); 8705 literalStringStripped = RHSStripped; 8706 } 8707 8708 if (literalString) { 8709 DiagRuntimeBehavior(Loc, nullptr, 8710 PDiag(diag::warn_stringcompare) 8711 << isa<ObjCEncodeExpr>(literalStringStripped) 8712 << literalString->getSourceRange()); 8713 } 8714 } 8715 8716 // C99 6.5.8p3 / C99 6.5.9p4 8717 UsualArithmeticConversions(LHS, RHS); 8718 if (LHS.isInvalid() || RHS.isInvalid()) 8719 return QualType(); 8720 8721 LHSType = LHS.get()->getType(); 8722 RHSType = RHS.get()->getType(); 8723 8724 // The result of comparisons is 'bool' in C++, 'int' in C. 8725 QualType ResultTy = Context.getLogicalOperationType(); 8726 8727 if (IsRelational) { 8728 if (LHSType->isRealType() && RHSType->isRealType()) 8729 return ResultTy; 8730 } else { 8731 // Check for comparisons of floating point operands using != and ==. 8732 if (LHSType->hasFloatingRepresentation()) 8733 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 8734 8735 if (LHSType->isArithmeticType() && RHSType->isArithmeticType()) 8736 return ResultTy; 8737 } 8738 8739 const Expr::NullPointerConstantKind LHSNullKind = 8740 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 8741 const Expr::NullPointerConstantKind RHSNullKind = 8742 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 8743 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 8744 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 8745 8746 if (!IsRelational && LHSIsNull != RHSIsNull) { 8747 bool IsEquality = Opc == BO_EQ; 8748 if (RHSIsNull) 8749 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 8750 RHS.get()->getSourceRange()); 8751 else 8752 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 8753 LHS.get()->getSourceRange()); 8754 } 8755 8756 // All of the following pointer-related warnings are GCC extensions, except 8757 // when handling null pointer constants. 8758 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2 8759 QualType LCanPointeeTy = 8760 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 8761 QualType RCanPointeeTy = 8762 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 8763 8764 if (getLangOpts().CPlusPlus) { 8765 if (LCanPointeeTy == RCanPointeeTy) 8766 return ResultTy; 8767 if (!IsRelational && 8768 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 8769 // Valid unless comparison between non-null pointer and function pointer 8770 // This is a gcc extension compatibility comparison. 8771 // In a SFINAE context, we treat this as a hard error to maintain 8772 // conformance with the C++ standard. 8773 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 8774 && !LHSIsNull && !RHSIsNull) { 8775 diagnoseFunctionPointerToVoidComparison( 8776 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 8777 8778 if (isSFINAEContext()) 8779 return QualType(); 8780 8781 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8782 return ResultTy; 8783 } 8784 } 8785 8786 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 8787 return QualType(); 8788 else 8789 return ResultTy; 8790 } 8791 // C99 6.5.9p2 and C99 6.5.8p2 8792 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 8793 RCanPointeeTy.getUnqualifiedType())) { 8794 // Valid unless a relational comparison of function pointers 8795 if (IsRelational && LCanPointeeTy->isFunctionType()) { 8796 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 8797 << LHSType << RHSType << LHS.get()->getSourceRange() 8798 << RHS.get()->getSourceRange(); 8799 } 8800 } else if (!IsRelational && 8801 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 8802 // Valid unless comparison between non-null pointer and function pointer 8803 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 8804 && !LHSIsNull && !RHSIsNull) 8805 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 8806 /*isError*/false); 8807 } else { 8808 // Invalid 8809 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 8810 } 8811 if (LCanPointeeTy != RCanPointeeTy) { 8812 // Treat NULL constant as a special case in OpenCL. 8813 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 8814 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 8815 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 8816 Diag(Loc, 8817 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 8818 << LHSType << RHSType << 0 /* comparison */ 8819 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8820 } 8821 } 8822 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace(); 8823 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace(); 8824 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 8825 : CK_BitCast; 8826 if (LHSIsNull && !RHSIsNull) 8827 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 8828 else 8829 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 8830 } 8831 return ResultTy; 8832 } 8833 8834 if (getLangOpts().CPlusPlus) { 8835 // Comparison of nullptr_t with itself. 8836 if (LHSType->isNullPtrType() && RHSType->isNullPtrType()) 8837 return ResultTy; 8838 8839 // Comparison of pointers with null pointer constants and equality 8840 // comparisons of member pointers to null pointer constants. 8841 if (RHSIsNull && 8842 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) || 8843 (!IsRelational && 8844 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) { 8845 RHS = ImpCastExprToType(RHS.get(), LHSType, 8846 LHSType->isMemberPointerType() 8847 ? CK_NullToMemberPointer 8848 : CK_NullToPointer); 8849 return ResultTy; 8850 } 8851 if (LHSIsNull && 8852 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) || 8853 (!IsRelational && 8854 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) { 8855 LHS = ImpCastExprToType(LHS.get(), RHSType, 8856 RHSType->isMemberPointerType() 8857 ? CK_NullToMemberPointer 8858 : CK_NullToPointer); 8859 return ResultTy; 8860 } 8861 8862 // Comparison of member pointers. 8863 if (!IsRelational && 8864 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) { 8865 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 8866 return QualType(); 8867 else 8868 return ResultTy; 8869 } 8870 8871 // Handle scoped enumeration types specifically, since they don't promote 8872 // to integers. 8873 if (LHS.get()->getType()->isEnumeralType() && 8874 Context.hasSameUnqualifiedType(LHS.get()->getType(), 8875 RHS.get()->getType())) 8876 return ResultTy; 8877 } 8878 8879 // Handle block pointer types. 8880 if (!IsRelational && LHSType->isBlockPointerType() && 8881 RHSType->isBlockPointerType()) { 8882 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 8883 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 8884 8885 if (!LHSIsNull && !RHSIsNull && 8886 !Context.typesAreCompatible(lpointee, rpointee)) { 8887 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8888 << LHSType << RHSType << LHS.get()->getSourceRange() 8889 << RHS.get()->getSourceRange(); 8890 } 8891 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8892 return ResultTy; 8893 } 8894 8895 // Allow block pointers to be compared with null pointer constants. 8896 if (!IsRelational 8897 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 8898 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 8899 if (!LHSIsNull && !RHSIsNull) { 8900 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 8901 ->getPointeeType()->isVoidType()) 8902 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 8903 ->getPointeeType()->isVoidType()))) 8904 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 8905 << LHSType << RHSType << LHS.get()->getSourceRange() 8906 << RHS.get()->getSourceRange(); 8907 } 8908 if (LHSIsNull && !RHSIsNull) 8909 LHS = ImpCastExprToType(LHS.get(), RHSType, 8910 RHSType->isPointerType() ? CK_BitCast 8911 : CK_AnyPointerToBlockPointerCast); 8912 else 8913 RHS = ImpCastExprToType(RHS.get(), LHSType, 8914 LHSType->isPointerType() ? CK_BitCast 8915 : CK_AnyPointerToBlockPointerCast); 8916 return ResultTy; 8917 } 8918 8919 if (LHSType->isObjCObjectPointerType() || 8920 RHSType->isObjCObjectPointerType()) { 8921 const PointerType *LPT = LHSType->getAs<PointerType>(); 8922 const PointerType *RPT = RHSType->getAs<PointerType>(); 8923 if (LPT || RPT) { 8924 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 8925 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 8926 8927 if (!LPtrToVoid && !RPtrToVoid && 8928 !Context.typesAreCompatible(LHSType, RHSType)) { 8929 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8930 /*isError*/false); 8931 } 8932 if (LHSIsNull && !RHSIsNull) { 8933 Expr *E = LHS.get(); 8934 if (getLangOpts().ObjCAutoRefCount) 8935 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion); 8936 LHS = ImpCastExprToType(E, RHSType, 8937 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8938 } 8939 else { 8940 Expr *E = RHS.get(); 8941 if (getLangOpts().ObjCAutoRefCount) 8942 CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false, 8943 Opc); 8944 RHS = ImpCastExprToType(E, LHSType, 8945 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 8946 } 8947 return ResultTy; 8948 } 8949 if (LHSType->isObjCObjectPointerType() && 8950 RHSType->isObjCObjectPointerType()) { 8951 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 8952 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 8953 /*isError*/false); 8954 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 8955 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 8956 8957 if (LHSIsNull && !RHSIsNull) 8958 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8959 else 8960 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8961 return ResultTy; 8962 } 8963 } 8964 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 8965 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 8966 unsigned DiagID = 0; 8967 bool isError = false; 8968 if (LangOpts.DebuggerSupport) { 8969 // Under a debugger, allow the comparison of pointers to integers, 8970 // since users tend to want to compare addresses. 8971 } else if ((LHSIsNull && LHSType->isIntegerType()) || 8972 (RHSIsNull && RHSType->isIntegerType())) { 8973 if (IsRelational && !getLangOpts().CPlusPlus) 8974 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 8975 } else if (IsRelational && !getLangOpts().CPlusPlus) 8976 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 8977 else if (getLangOpts().CPlusPlus) { 8978 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 8979 isError = true; 8980 } else 8981 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 8982 8983 if (DiagID) { 8984 Diag(Loc, DiagID) 8985 << LHSType << RHSType << LHS.get()->getSourceRange() 8986 << RHS.get()->getSourceRange(); 8987 if (isError) 8988 return QualType(); 8989 } 8990 8991 if (LHSType->isIntegerType()) 8992 LHS = ImpCastExprToType(LHS.get(), RHSType, 8993 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8994 else 8995 RHS = ImpCastExprToType(RHS.get(), LHSType, 8996 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 8997 return ResultTy; 8998 } 8999 9000 // Handle block pointers. 9001 if (!IsRelational && RHSIsNull 9002 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 9003 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 9004 return ResultTy; 9005 } 9006 if (!IsRelational && LHSIsNull 9007 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 9008 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 9009 return ResultTy; 9010 } 9011 9012 return InvalidOperands(Loc, LHS, RHS); 9013 } 9014 9015 9016 // Return a signed type that is of identical size and number of elements. 9017 // For floating point vectors, return an integer type of identical size 9018 // and number of elements. 9019 QualType Sema::GetSignedVectorType(QualType V) { 9020 const VectorType *VTy = V->getAs<VectorType>(); 9021 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 9022 if (TypeSize == Context.getTypeSize(Context.CharTy)) 9023 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 9024 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 9025 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 9026 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 9027 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 9028 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 9029 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 9030 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 9031 "Unhandled vector element size in vector compare"); 9032 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 9033 } 9034 9035 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 9036 /// operates on extended vector types. Instead of producing an IntTy result, 9037 /// like a scalar comparison, a vector comparison produces a vector of integer 9038 /// types. 9039 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 9040 SourceLocation Loc, 9041 bool IsRelational) { 9042 // Check to make sure we're operating on vectors of the same type and width, 9043 // Allowing one side to be a scalar of element type. 9044 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 9045 /*AllowBothBool*/true, 9046 /*AllowBoolConversions*/getLangOpts().ZVector); 9047 if (vType.isNull()) 9048 return vType; 9049 9050 QualType LHSType = LHS.get()->getType(); 9051 9052 // If AltiVec, the comparison results in a numeric type, i.e. 9053 // bool for C++, int for C 9054 if (getLangOpts().AltiVec && 9055 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 9056 return Context.getLogicalOperationType(); 9057 9058 // For non-floating point types, check for self-comparisons of the form 9059 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9060 // often indicate logic errors in the program. 9061 if (!LHSType->hasFloatingRepresentation() && 9062 ActiveTemplateInstantiations.empty()) { 9063 if (DeclRefExpr* DRL 9064 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts())) 9065 if (DeclRefExpr* DRR 9066 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts())) 9067 if (DRL->getDecl() == DRR->getDecl()) 9068 DiagRuntimeBehavior(Loc, nullptr, 9069 PDiag(diag::warn_comparison_always) 9070 << 0 // self- 9071 << 2 // "a constant" 9072 ); 9073 } 9074 9075 // Check for comparisons of floating point operands using != and ==. 9076 if (!IsRelational && LHSType->hasFloatingRepresentation()) { 9077 assert (RHS.get()->getType()->hasFloatingRepresentation()); 9078 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 9079 } 9080 9081 // Return a signed type for the vector. 9082 return GetSignedVectorType(LHSType); 9083 } 9084 9085 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9086 SourceLocation Loc) { 9087 // Ensure that either both operands are of the same vector type, or 9088 // one operand is of a vector type and the other is of its element type. 9089 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 9090 /*AllowBothBool*/true, 9091 /*AllowBoolConversions*/false); 9092 if (vType.isNull()) 9093 return InvalidOperands(Loc, LHS, RHS); 9094 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 9095 vType->hasFloatingRepresentation()) 9096 return InvalidOperands(Loc, LHS, RHS); 9097 9098 return GetSignedVectorType(LHS.get()->getType()); 9099 } 9100 9101 inline QualType Sema::CheckBitwiseOperands( 9102 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 9103 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9104 9105 if (LHS.get()->getType()->isVectorType() || 9106 RHS.get()->getType()->isVectorType()) { 9107 if (LHS.get()->getType()->hasIntegerRepresentation() && 9108 RHS.get()->getType()->hasIntegerRepresentation()) 9109 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 9110 /*AllowBothBool*/true, 9111 /*AllowBoolConversions*/getLangOpts().ZVector); 9112 return InvalidOperands(Loc, LHS, RHS); 9113 } 9114 9115 ExprResult LHSResult = LHS, RHSResult = RHS; 9116 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 9117 IsCompAssign); 9118 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 9119 return QualType(); 9120 LHS = LHSResult.get(); 9121 RHS = RHSResult.get(); 9122 9123 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 9124 return compType; 9125 return InvalidOperands(Loc, LHS, RHS); 9126 } 9127 9128 // C99 6.5.[13,14] 9129 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 9130 SourceLocation Loc, 9131 BinaryOperatorKind Opc) { 9132 // Check vector operands differently. 9133 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 9134 return CheckVectorLogicalOperands(LHS, RHS, Loc); 9135 9136 // Diagnose cases where the user write a logical and/or but probably meant a 9137 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 9138 // is a constant. 9139 if (LHS.get()->getType()->isIntegerType() && 9140 !LHS.get()->getType()->isBooleanType() && 9141 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 9142 // Don't warn in macros or template instantiations. 9143 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) { 9144 // If the RHS can be constant folded, and if it constant folds to something 9145 // that isn't 0 or 1 (which indicate a potential logical operation that 9146 // happened to fold to true/false) then warn. 9147 // Parens on the RHS are ignored. 9148 llvm::APSInt Result; 9149 if (RHS.get()->EvaluateAsInt(Result, Context)) 9150 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 9151 !RHS.get()->getExprLoc().isMacroID()) || 9152 (Result != 0 && Result != 1)) { 9153 Diag(Loc, diag::warn_logical_instead_of_bitwise) 9154 << RHS.get()->getSourceRange() 9155 << (Opc == BO_LAnd ? "&&" : "||"); 9156 // Suggest replacing the logical operator with the bitwise version 9157 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 9158 << (Opc == BO_LAnd ? "&" : "|") 9159 << FixItHint::CreateReplacement(SourceRange( 9160 Loc, getLocForEndOfToken(Loc)), 9161 Opc == BO_LAnd ? "&" : "|"); 9162 if (Opc == BO_LAnd) 9163 // Suggest replacing "Foo() && kNonZero" with "Foo()" 9164 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 9165 << FixItHint::CreateRemoval( 9166 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()), 9167 RHS.get()->getLocEnd())); 9168 } 9169 } 9170 9171 if (!Context.getLangOpts().CPlusPlus) { 9172 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 9173 // not operate on the built-in scalar and vector float types. 9174 if (Context.getLangOpts().OpenCL && 9175 Context.getLangOpts().OpenCLVersion < 120) { 9176 if (LHS.get()->getType()->isFloatingType() || 9177 RHS.get()->getType()->isFloatingType()) 9178 return InvalidOperands(Loc, LHS, RHS); 9179 } 9180 9181 LHS = UsualUnaryConversions(LHS.get()); 9182 if (LHS.isInvalid()) 9183 return QualType(); 9184 9185 RHS = UsualUnaryConversions(RHS.get()); 9186 if (RHS.isInvalid()) 9187 return QualType(); 9188 9189 if (!LHS.get()->getType()->isScalarType() || 9190 !RHS.get()->getType()->isScalarType()) 9191 return InvalidOperands(Loc, LHS, RHS); 9192 9193 return Context.IntTy; 9194 } 9195 9196 // The following is safe because we only use this method for 9197 // non-overloadable operands. 9198 9199 // C++ [expr.log.and]p1 9200 // C++ [expr.log.or]p1 9201 // The operands are both contextually converted to type bool. 9202 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 9203 if (LHSRes.isInvalid()) 9204 return InvalidOperands(Loc, LHS, RHS); 9205 LHS = LHSRes; 9206 9207 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 9208 if (RHSRes.isInvalid()) 9209 return InvalidOperands(Loc, LHS, RHS); 9210 RHS = RHSRes; 9211 9212 // C++ [expr.log.and]p2 9213 // C++ [expr.log.or]p2 9214 // The result is a bool. 9215 return Context.BoolTy; 9216 } 9217 9218 static bool IsReadonlyMessage(Expr *E, Sema &S) { 9219 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 9220 if (!ME) return false; 9221 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 9222 ObjCMessageExpr *Base = 9223 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts()); 9224 if (!Base) return false; 9225 return Base->getMethodDecl() != nullptr; 9226 } 9227 9228 /// Is the given expression (which must be 'const') a reference to a 9229 /// variable which was originally non-const, but which has become 9230 /// 'const' due to being captured within a block? 9231 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 9232 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 9233 assert(E->isLValue() && E->getType().isConstQualified()); 9234 E = E->IgnoreParens(); 9235 9236 // Must be a reference to a declaration from an enclosing scope. 9237 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 9238 if (!DRE) return NCCK_None; 9239 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 9240 9241 // The declaration must be a variable which is not declared 'const'. 9242 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 9243 if (!var) return NCCK_None; 9244 if (var->getType().isConstQualified()) return NCCK_None; 9245 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 9246 9247 // Decide whether the first capture was for a block or a lambda. 9248 DeclContext *DC = S.CurContext, *Prev = nullptr; 9249 while (DC != var->getDeclContext()) { 9250 Prev = DC; 9251 DC = DC->getParent(); 9252 } 9253 // Unless we have an init-capture, we've gone one step too far. 9254 if (!var->isInitCapture()) 9255 DC = Prev; 9256 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 9257 } 9258 9259 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 9260 Ty = Ty.getNonReferenceType(); 9261 if (IsDereference && Ty->isPointerType()) 9262 Ty = Ty->getPointeeType(); 9263 return !Ty.isConstQualified(); 9264 } 9265 9266 /// Emit the "read-only variable not assignable" error and print notes to give 9267 /// more information about why the variable is not assignable, such as pointing 9268 /// to the declaration of a const variable, showing that a method is const, or 9269 /// that the function is returning a const reference. 9270 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 9271 SourceLocation Loc) { 9272 // Update err_typecheck_assign_const and note_typecheck_assign_const 9273 // when this enum is changed. 9274 enum { 9275 ConstFunction, 9276 ConstVariable, 9277 ConstMember, 9278 ConstMethod, 9279 ConstUnknown, // Keep as last element 9280 }; 9281 9282 SourceRange ExprRange = E->getSourceRange(); 9283 9284 // Only emit one error on the first const found. All other consts will emit 9285 // a note to the error. 9286 bool DiagnosticEmitted = false; 9287 9288 // Track if the current expression is the result of a derefence, and if the 9289 // next checked expression is the result of a derefence. 9290 bool IsDereference = false; 9291 bool NextIsDereference = false; 9292 9293 // Loop to process MemberExpr chains. 9294 while (true) { 9295 IsDereference = NextIsDereference; 9296 NextIsDereference = false; 9297 9298 E = E->IgnoreParenImpCasts(); 9299 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 9300 NextIsDereference = ME->isArrow(); 9301 const ValueDecl *VD = ME->getMemberDecl(); 9302 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 9303 // Mutable fields can be modified even if the class is const. 9304 if (Field->isMutable()) { 9305 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 9306 break; 9307 } 9308 9309 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 9310 if (!DiagnosticEmitted) { 9311 S.Diag(Loc, diag::err_typecheck_assign_const) 9312 << ExprRange << ConstMember << false /*static*/ << Field 9313 << Field->getType(); 9314 DiagnosticEmitted = true; 9315 } 9316 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9317 << ConstMember << false /*static*/ << Field << Field->getType() 9318 << Field->getSourceRange(); 9319 } 9320 E = ME->getBase(); 9321 continue; 9322 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 9323 if (VDecl->getType().isConstQualified()) { 9324 if (!DiagnosticEmitted) { 9325 S.Diag(Loc, diag::err_typecheck_assign_const) 9326 << ExprRange << ConstMember << true /*static*/ << VDecl 9327 << VDecl->getType(); 9328 DiagnosticEmitted = true; 9329 } 9330 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9331 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 9332 << VDecl->getSourceRange(); 9333 } 9334 // Static fields do not inherit constness from parents. 9335 break; 9336 } 9337 break; 9338 } // End MemberExpr 9339 break; 9340 } 9341 9342 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9343 // Function calls 9344 const FunctionDecl *FD = CE->getDirectCallee(); 9345 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 9346 if (!DiagnosticEmitted) { 9347 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9348 << ConstFunction << FD; 9349 DiagnosticEmitted = true; 9350 } 9351 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 9352 diag::note_typecheck_assign_const) 9353 << ConstFunction << FD << FD->getReturnType() 9354 << FD->getReturnTypeSourceRange(); 9355 } 9356 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 9357 // Point to variable declaration. 9358 if (const ValueDecl *VD = DRE->getDecl()) { 9359 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 9360 if (!DiagnosticEmitted) { 9361 S.Diag(Loc, diag::err_typecheck_assign_const) 9362 << ExprRange << ConstVariable << VD << VD->getType(); 9363 DiagnosticEmitted = true; 9364 } 9365 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 9366 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 9367 } 9368 } 9369 } else if (isa<CXXThisExpr>(E)) { 9370 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 9371 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 9372 if (MD->isConst()) { 9373 if (!DiagnosticEmitted) { 9374 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 9375 << ConstMethod << MD; 9376 DiagnosticEmitted = true; 9377 } 9378 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 9379 << ConstMethod << MD << MD->getSourceRange(); 9380 } 9381 } 9382 } 9383 } 9384 9385 if (DiagnosticEmitted) 9386 return; 9387 9388 // Can't determine a more specific message, so display the generic error. 9389 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 9390 } 9391 9392 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 9393 /// emit an error and return true. If so, return false. 9394 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 9395 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 9396 SourceLocation OrigLoc = Loc; 9397 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 9398 &Loc); 9399 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 9400 IsLV = Expr::MLV_InvalidMessageExpression; 9401 if (IsLV == Expr::MLV_Valid) 9402 return false; 9403 9404 unsigned DiagID = 0; 9405 bool NeedType = false; 9406 switch (IsLV) { // C99 6.5.16p2 9407 case Expr::MLV_ConstQualified: 9408 // Use a specialized diagnostic when we're assigning to an object 9409 // from an enclosing function or block. 9410 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 9411 if (NCCK == NCCK_Block) 9412 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 9413 else 9414 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 9415 break; 9416 } 9417 9418 // In ARC, use some specialized diagnostics for occasions where we 9419 // infer 'const'. These are always pseudo-strong variables. 9420 if (S.getLangOpts().ObjCAutoRefCount) { 9421 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 9422 if (declRef && isa<VarDecl>(declRef->getDecl())) { 9423 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 9424 9425 // Use the normal diagnostic if it's pseudo-__strong but the 9426 // user actually wrote 'const'. 9427 if (var->isARCPseudoStrong() && 9428 (!var->getTypeSourceInfo() || 9429 !var->getTypeSourceInfo()->getType().isConstQualified())) { 9430 // There are two pseudo-strong cases: 9431 // - self 9432 ObjCMethodDecl *method = S.getCurMethodDecl(); 9433 if (method && var == method->getSelfDecl()) 9434 DiagID = method->isClassMethod() 9435 ? diag::err_typecheck_arc_assign_self_class_method 9436 : diag::err_typecheck_arc_assign_self; 9437 9438 // - fast enumeration variables 9439 else 9440 DiagID = diag::err_typecheck_arr_assign_enumeration; 9441 9442 SourceRange Assign; 9443 if (Loc != OrigLoc) 9444 Assign = SourceRange(OrigLoc, OrigLoc); 9445 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9446 // We need to preserve the AST regardless, so migration tool 9447 // can do its job. 9448 return false; 9449 } 9450 } 9451 } 9452 9453 // If none of the special cases above are triggered, then this is a 9454 // simple const assignment. 9455 if (DiagID == 0) { 9456 DiagnoseConstAssignment(S, E, Loc); 9457 return true; 9458 } 9459 9460 break; 9461 case Expr::MLV_ConstAddrSpace: 9462 DiagnoseConstAssignment(S, E, Loc); 9463 return true; 9464 case Expr::MLV_ArrayType: 9465 case Expr::MLV_ArrayTemporary: 9466 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 9467 NeedType = true; 9468 break; 9469 case Expr::MLV_NotObjectType: 9470 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 9471 NeedType = true; 9472 break; 9473 case Expr::MLV_LValueCast: 9474 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 9475 break; 9476 case Expr::MLV_Valid: 9477 llvm_unreachable("did not take early return for MLV_Valid"); 9478 case Expr::MLV_InvalidExpression: 9479 case Expr::MLV_MemberFunction: 9480 case Expr::MLV_ClassTemporary: 9481 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 9482 break; 9483 case Expr::MLV_IncompleteType: 9484 case Expr::MLV_IncompleteVoidType: 9485 return S.RequireCompleteType(Loc, E->getType(), 9486 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 9487 case Expr::MLV_DuplicateVectorComponents: 9488 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 9489 break; 9490 case Expr::MLV_NoSetterProperty: 9491 llvm_unreachable("readonly properties should be processed differently"); 9492 case Expr::MLV_InvalidMessageExpression: 9493 DiagID = diag::error_readonly_message_assignment; 9494 break; 9495 case Expr::MLV_SubObjCPropertySetting: 9496 DiagID = diag::error_no_subobject_property_setting; 9497 break; 9498 } 9499 9500 SourceRange Assign; 9501 if (Loc != OrigLoc) 9502 Assign = SourceRange(OrigLoc, OrigLoc); 9503 if (NeedType) 9504 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 9505 else 9506 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 9507 return true; 9508 } 9509 9510 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 9511 SourceLocation Loc, 9512 Sema &Sema) { 9513 // C / C++ fields 9514 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 9515 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 9516 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) { 9517 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())) 9518 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 9519 } 9520 9521 // Objective-C instance variables 9522 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 9523 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 9524 if (OL && OR && OL->getDecl() == OR->getDecl()) { 9525 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 9526 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 9527 if (RL && RR && RL->getDecl() == RR->getDecl()) 9528 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 9529 } 9530 } 9531 9532 // C99 6.5.16.1 9533 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 9534 SourceLocation Loc, 9535 QualType CompoundType) { 9536 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 9537 9538 // Verify that LHS is a modifiable lvalue, and emit error if not. 9539 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 9540 return QualType(); 9541 9542 QualType LHSType = LHSExpr->getType(); 9543 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 9544 CompoundType; 9545 AssignConvertType ConvTy; 9546 if (CompoundType.isNull()) { 9547 Expr *RHSCheck = RHS.get(); 9548 9549 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 9550 9551 QualType LHSTy(LHSType); 9552 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 9553 if (RHS.isInvalid()) 9554 return QualType(); 9555 // Special case of NSObject attributes on c-style pointer types. 9556 if (ConvTy == IncompatiblePointer && 9557 ((Context.isObjCNSObjectType(LHSType) && 9558 RHSType->isObjCObjectPointerType()) || 9559 (Context.isObjCNSObjectType(RHSType) && 9560 LHSType->isObjCObjectPointerType()))) 9561 ConvTy = Compatible; 9562 9563 if (ConvTy == Compatible && 9564 LHSType->isObjCObjectType()) 9565 Diag(Loc, diag::err_objc_object_assignment) 9566 << LHSType; 9567 9568 // If the RHS is a unary plus or minus, check to see if they = and + are 9569 // right next to each other. If so, the user may have typo'd "x =+ 4" 9570 // instead of "x += 4". 9571 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 9572 RHSCheck = ICE->getSubExpr(); 9573 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 9574 if ((UO->getOpcode() == UO_Plus || 9575 UO->getOpcode() == UO_Minus) && 9576 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 9577 // Only if the two operators are exactly adjacent. 9578 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 9579 // And there is a space or other character before the subexpr of the 9580 // unary +/-. We don't want to warn on "x=-1". 9581 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() && 9582 UO->getSubExpr()->getLocStart().isFileID()) { 9583 Diag(Loc, diag::warn_not_compound_assign) 9584 << (UO->getOpcode() == UO_Plus ? "+" : "-") 9585 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 9586 } 9587 } 9588 9589 if (ConvTy == Compatible) { 9590 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 9591 // Warn about retain cycles where a block captures the LHS, but 9592 // not if the LHS is a simple variable into which the block is 9593 // being stored...unless that variable can be captured by reference! 9594 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 9595 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 9596 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 9597 checkRetainCycles(LHSExpr, RHS.get()); 9598 9599 // It is safe to assign a weak reference into a strong variable. 9600 // Although this code can still have problems: 9601 // id x = self.weakProp; 9602 // id y = self.weakProp; 9603 // we do not warn to warn spuriously when 'x' and 'y' are on separate 9604 // paths through the function. This should be revisited if 9605 // -Wrepeated-use-of-weak is made flow-sensitive. 9606 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 9607 RHS.get()->getLocStart())) 9608 getCurFunction()->markSafeWeakUse(RHS.get()); 9609 9610 } else if (getLangOpts().ObjCAutoRefCount) { 9611 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 9612 } 9613 } 9614 } else { 9615 // Compound assignment "x += y" 9616 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 9617 } 9618 9619 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 9620 RHS.get(), AA_Assigning)) 9621 return QualType(); 9622 9623 CheckForNullPointerDereference(*this, LHSExpr); 9624 9625 // C99 6.5.16p3: The type of an assignment expression is the type of the 9626 // left operand unless the left operand has qualified type, in which case 9627 // it is the unqualified version of the type of the left operand. 9628 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 9629 // is converted to the type of the assignment expression (above). 9630 // C++ 5.17p1: the type of the assignment expression is that of its left 9631 // operand. 9632 return (getLangOpts().CPlusPlus 9633 ? LHSType : LHSType.getUnqualifiedType()); 9634 } 9635 9636 // C99 6.5.17 9637 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 9638 SourceLocation Loc) { 9639 LHS = S.CheckPlaceholderExpr(LHS.get()); 9640 RHS = S.CheckPlaceholderExpr(RHS.get()); 9641 if (LHS.isInvalid() || RHS.isInvalid()) 9642 return QualType(); 9643 9644 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 9645 // operands, but not unary promotions. 9646 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 9647 9648 // So we treat the LHS as a ignored value, and in C++ we allow the 9649 // containing site to determine what should be done with the RHS. 9650 LHS = S.IgnoredValueConversions(LHS.get()); 9651 if (LHS.isInvalid()) 9652 return QualType(); 9653 9654 S.DiagnoseUnusedExprResult(LHS.get()); 9655 9656 if (!S.getLangOpts().CPlusPlus) { 9657 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 9658 if (RHS.isInvalid()) 9659 return QualType(); 9660 if (!RHS.get()->getType()->isVoidType()) 9661 S.RequireCompleteType(Loc, RHS.get()->getType(), 9662 diag::err_incomplete_type); 9663 } 9664 9665 return RHS.get()->getType(); 9666 } 9667 9668 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 9669 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 9670 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 9671 ExprValueKind &VK, 9672 ExprObjectKind &OK, 9673 SourceLocation OpLoc, 9674 bool IsInc, bool IsPrefix) { 9675 if (Op->isTypeDependent()) 9676 return S.Context.DependentTy; 9677 9678 QualType ResType = Op->getType(); 9679 // Atomic types can be used for increment / decrement where the non-atomic 9680 // versions can, so ignore the _Atomic() specifier for the purpose of 9681 // checking. 9682 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 9683 ResType = ResAtomicType->getValueType(); 9684 9685 assert(!ResType.isNull() && "no type for increment/decrement expression"); 9686 9687 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 9688 // Decrement of bool is not allowed. 9689 if (!IsInc) { 9690 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 9691 return QualType(); 9692 } 9693 // Increment of bool sets it to true, but is deprecated. 9694 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool 9695 : diag::warn_increment_bool) 9696 << Op->getSourceRange(); 9697 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 9698 // Error on enum increments and decrements in C++ mode 9699 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 9700 return QualType(); 9701 } else if (ResType->isRealType()) { 9702 // OK! 9703 } else if (ResType->isPointerType()) { 9704 // C99 6.5.2.4p2, 6.5.6p2 9705 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 9706 return QualType(); 9707 } else if (ResType->isObjCObjectPointerType()) { 9708 // On modern runtimes, ObjC pointer arithmetic is forbidden. 9709 // Otherwise, we just need a complete type. 9710 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 9711 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 9712 return QualType(); 9713 } else if (ResType->isAnyComplexType()) { 9714 // C99 does not support ++/-- on complex types, we allow as an extension. 9715 S.Diag(OpLoc, diag::ext_integer_increment_complex) 9716 << ResType << Op->getSourceRange(); 9717 } else if (ResType->isPlaceholderType()) { 9718 ExprResult PR = S.CheckPlaceholderExpr(Op); 9719 if (PR.isInvalid()) return QualType(); 9720 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 9721 IsInc, IsPrefix); 9722 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 9723 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 9724 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 9725 (ResType->getAs<VectorType>()->getVectorKind() != 9726 VectorType::AltiVecBool)) { 9727 // The z vector extensions allow ++ and -- for non-bool vectors. 9728 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 9729 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 9730 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 9731 } else { 9732 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 9733 << ResType << int(IsInc) << Op->getSourceRange(); 9734 return QualType(); 9735 } 9736 // At this point, we know we have a real, complex or pointer type. 9737 // Now make sure the operand is a modifiable lvalue. 9738 if (CheckForModifiableLvalue(Op, OpLoc, S)) 9739 return QualType(); 9740 // In C++, a prefix increment is the same type as the operand. Otherwise 9741 // (in C or with postfix), the increment is the unqualified type of the 9742 // operand. 9743 if (IsPrefix && S.getLangOpts().CPlusPlus) { 9744 VK = VK_LValue; 9745 OK = Op->getObjectKind(); 9746 return ResType; 9747 } else { 9748 VK = VK_RValue; 9749 return ResType.getUnqualifiedType(); 9750 } 9751 } 9752 9753 9754 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 9755 /// This routine allows us to typecheck complex/recursive expressions 9756 /// where the declaration is needed for type checking. We only need to 9757 /// handle cases when the expression references a function designator 9758 /// or is an lvalue. Here are some examples: 9759 /// - &(x) => x 9760 /// - &*****f => f for f a function designator. 9761 /// - &s.xx => s 9762 /// - &s.zz[1].yy -> s, if zz is an array 9763 /// - *(x + 1) -> x, if x is an array 9764 /// - &"123"[2] -> 0 9765 /// - & __real__ x -> x 9766 static ValueDecl *getPrimaryDecl(Expr *E) { 9767 switch (E->getStmtClass()) { 9768 case Stmt::DeclRefExprClass: 9769 return cast<DeclRefExpr>(E)->getDecl(); 9770 case Stmt::MemberExprClass: 9771 // If this is an arrow operator, the address is an offset from 9772 // the base's value, so the object the base refers to is 9773 // irrelevant. 9774 if (cast<MemberExpr>(E)->isArrow()) 9775 return nullptr; 9776 // Otherwise, the expression refers to a part of the base 9777 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 9778 case Stmt::ArraySubscriptExprClass: { 9779 // FIXME: This code shouldn't be necessary! We should catch the implicit 9780 // promotion of register arrays earlier. 9781 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 9782 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 9783 if (ICE->getSubExpr()->getType()->isArrayType()) 9784 return getPrimaryDecl(ICE->getSubExpr()); 9785 } 9786 return nullptr; 9787 } 9788 case Stmt::UnaryOperatorClass: { 9789 UnaryOperator *UO = cast<UnaryOperator>(E); 9790 9791 switch(UO->getOpcode()) { 9792 case UO_Real: 9793 case UO_Imag: 9794 case UO_Extension: 9795 return getPrimaryDecl(UO->getSubExpr()); 9796 default: 9797 return nullptr; 9798 } 9799 } 9800 case Stmt::ParenExprClass: 9801 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 9802 case Stmt::ImplicitCastExprClass: 9803 // If the result of an implicit cast is an l-value, we care about 9804 // the sub-expression; otherwise, the result here doesn't matter. 9805 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 9806 default: 9807 return nullptr; 9808 } 9809 } 9810 9811 namespace { 9812 enum { 9813 AO_Bit_Field = 0, 9814 AO_Vector_Element = 1, 9815 AO_Property_Expansion = 2, 9816 AO_Register_Variable = 3, 9817 AO_No_Error = 4 9818 }; 9819 } 9820 /// \brief Diagnose invalid operand for address of operations. 9821 /// 9822 /// \param Type The type of operand which cannot have its address taken. 9823 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 9824 Expr *E, unsigned Type) { 9825 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 9826 } 9827 9828 /// CheckAddressOfOperand - The operand of & must be either a function 9829 /// designator or an lvalue designating an object. If it is an lvalue, the 9830 /// object cannot be declared with storage class register or be a bit field. 9831 /// Note: The usual conversions are *not* applied to the operand of the & 9832 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 9833 /// In C++, the operand might be an overloaded function name, in which case 9834 /// we allow the '&' but retain the overloaded-function type. 9835 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 9836 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 9837 if (PTy->getKind() == BuiltinType::Overload) { 9838 Expr *E = OrigOp.get()->IgnoreParens(); 9839 if (!isa<OverloadExpr>(E)) { 9840 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 9841 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 9842 << OrigOp.get()->getSourceRange(); 9843 return QualType(); 9844 } 9845 9846 OverloadExpr *Ovl = cast<OverloadExpr>(E); 9847 if (isa<UnresolvedMemberExpr>(Ovl)) 9848 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 9849 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 9850 << OrigOp.get()->getSourceRange(); 9851 return QualType(); 9852 } 9853 9854 return Context.OverloadTy; 9855 } 9856 9857 if (PTy->getKind() == BuiltinType::UnknownAny) 9858 return Context.UnknownAnyTy; 9859 9860 if (PTy->getKind() == BuiltinType::BoundMember) { 9861 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 9862 << OrigOp.get()->getSourceRange(); 9863 return QualType(); 9864 } 9865 9866 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 9867 if (OrigOp.isInvalid()) return QualType(); 9868 } 9869 9870 if (OrigOp.get()->isTypeDependent()) 9871 return Context.DependentTy; 9872 9873 assert(!OrigOp.get()->getType()->isPlaceholderType()); 9874 9875 // Make sure to ignore parentheses in subsequent checks 9876 Expr *op = OrigOp.get()->IgnoreParens(); 9877 9878 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 9879 if (LangOpts.OpenCL && op->getType()->isFunctionType()) { 9880 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address); 9881 return QualType(); 9882 } 9883 9884 if (getLangOpts().C99) { 9885 // Implement C99-only parts of addressof rules. 9886 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 9887 if (uOp->getOpcode() == UO_Deref) 9888 // Per C99 6.5.3.2, the address of a deref always returns a valid result 9889 // (assuming the deref expression is valid). 9890 return uOp->getSubExpr()->getType(); 9891 } 9892 // Technically, there should be a check for array subscript 9893 // expressions here, but the result of one is always an lvalue anyway. 9894 } 9895 ValueDecl *dcl = getPrimaryDecl(op); 9896 9897 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 9898 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 9899 op->getLocStart())) 9900 return QualType(); 9901 9902 Expr::LValueClassification lval = op->ClassifyLValue(Context); 9903 unsigned AddressOfError = AO_No_Error; 9904 9905 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 9906 bool sfinae = (bool)isSFINAEContext(); 9907 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 9908 : diag::ext_typecheck_addrof_temporary) 9909 << op->getType() << op->getSourceRange(); 9910 if (sfinae) 9911 return QualType(); 9912 // Materialize the temporary as an lvalue so that we can take its address. 9913 OrigOp = op = new (Context) 9914 MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 9915 } else if (isa<ObjCSelectorExpr>(op)) { 9916 return Context.getPointerType(op->getType()); 9917 } else if (lval == Expr::LV_MemberFunction) { 9918 // If it's an instance method, make a member pointer. 9919 // The expression must have exactly the form &A::foo. 9920 9921 // If the underlying expression isn't a decl ref, give up. 9922 if (!isa<DeclRefExpr>(op)) { 9923 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 9924 << OrigOp.get()->getSourceRange(); 9925 return QualType(); 9926 } 9927 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 9928 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 9929 9930 // The id-expression was parenthesized. 9931 if (OrigOp.get() != DRE) { 9932 Diag(OpLoc, diag::err_parens_pointer_member_function) 9933 << OrigOp.get()->getSourceRange(); 9934 9935 // The method was named without a qualifier. 9936 } else if (!DRE->getQualifier()) { 9937 if (MD->getParent()->getName().empty()) 9938 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 9939 << op->getSourceRange(); 9940 else { 9941 SmallString<32> Str; 9942 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 9943 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 9944 << op->getSourceRange() 9945 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 9946 } 9947 } 9948 9949 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 9950 if (isa<CXXDestructorDecl>(MD)) 9951 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 9952 9953 QualType MPTy = Context.getMemberPointerType( 9954 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 9955 // Under the MS ABI, lock down the inheritance model now. 9956 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 9957 (void)isCompleteType(OpLoc, MPTy); 9958 return MPTy; 9959 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 9960 // C99 6.5.3.2p1 9961 // The operand must be either an l-value or a function designator 9962 if (!op->getType()->isFunctionType()) { 9963 // Use a special diagnostic for loads from property references. 9964 if (isa<PseudoObjectExpr>(op)) { 9965 AddressOfError = AO_Property_Expansion; 9966 } else { 9967 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 9968 << op->getType() << op->getSourceRange(); 9969 return QualType(); 9970 } 9971 } 9972 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 9973 // The operand cannot be a bit-field 9974 AddressOfError = AO_Bit_Field; 9975 } else if (op->getObjectKind() == OK_VectorComponent) { 9976 // The operand cannot be an element of a vector 9977 AddressOfError = AO_Vector_Element; 9978 } else if (dcl) { // C99 6.5.3.2p1 9979 // We have an lvalue with a decl. Make sure the decl is not declared 9980 // with the register storage-class specifier. 9981 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 9982 // in C++ it is not error to take address of a register 9983 // variable (c++03 7.1.1P3) 9984 if (vd->getStorageClass() == SC_Register && 9985 !getLangOpts().CPlusPlus) { 9986 AddressOfError = AO_Register_Variable; 9987 } 9988 } else if (isa<MSPropertyDecl>(dcl)) { 9989 AddressOfError = AO_Property_Expansion; 9990 } else if (isa<FunctionTemplateDecl>(dcl)) { 9991 return Context.OverloadTy; 9992 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 9993 // Okay: we can take the address of a field. 9994 // Could be a pointer to member, though, if there is an explicit 9995 // scope qualifier for the class. 9996 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 9997 DeclContext *Ctx = dcl->getDeclContext(); 9998 if (Ctx && Ctx->isRecord()) { 9999 if (dcl->getType()->isReferenceType()) { 10000 Diag(OpLoc, 10001 diag::err_cannot_form_pointer_to_member_of_reference_type) 10002 << dcl->getDeclName() << dcl->getType(); 10003 return QualType(); 10004 } 10005 10006 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 10007 Ctx = Ctx->getParent(); 10008 10009 QualType MPTy = Context.getMemberPointerType( 10010 op->getType(), 10011 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 10012 // Under the MS ABI, lock down the inheritance model now. 10013 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 10014 (void)isCompleteType(OpLoc, MPTy); 10015 return MPTy; 10016 } 10017 } 10018 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl)) 10019 llvm_unreachable("Unknown/unexpected decl type"); 10020 } 10021 10022 if (AddressOfError != AO_No_Error) { 10023 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 10024 return QualType(); 10025 } 10026 10027 if (lval == Expr::LV_IncompleteVoidType) { 10028 // Taking the address of a void variable is technically illegal, but we 10029 // allow it in cases which are otherwise valid. 10030 // Example: "extern void x; void* y = &x;". 10031 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 10032 } 10033 10034 // If the operand has type "type", the result has type "pointer to type". 10035 if (op->getType()->isObjCObjectType()) 10036 return Context.getObjCObjectPointerType(op->getType()); 10037 return Context.getPointerType(op->getType()); 10038 } 10039 10040 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 10041 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 10042 if (!DRE) 10043 return; 10044 const Decl *D = DRE->getDecl(); 10045 if (!D) 10046 return; 10047 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 10048 if (!Param) 10049 return; 10050 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 10051 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 10052 return; 10053 if (FunctionScopeInfo *FD = S.getCurFunction()) 10054 if (!FD->ModifiedNonNullParams.count(Param)) 10055 FD->ModifiedNonNullParams.insert(Param); 10056 } 10057 10058 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 10059 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 10060 SourceLocation OpLoc) { 10061 if (Op->isTypeDependent()) 10062 return S.Context.DependentTy; 10063 10064 ExprResult ConvResult = S.UsualUnaryConversions(Op); 10065 if (ConvResult.isInvalid()) 10066 return QualType(); 10067 Op = ConvResult.get(); 10068 QualType OpTy = Op->getType(); 10069 QualType Result; 10070 10071 if (isa<CXXReinterpretCastExpr>(Op)) { 10072 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 10073 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 10074 Op->getSourceRange()); 10075 } 10076 10077 if (const PointerType *PT = OpTy->getAs<PointerType>()) 10078 Result = PT->getPointeeType(); 10079 else if (const ObjCObjectPointerType *OPT = 10080 OpTy->getAs<ObjCObjectPointerType>()) 10081 Result = OPT->getPointeeType(); 10082 else { 10083 ExprResult PR = S.CheckPlaceholderExpr(Op); 10084 if (PR.isInvalid()) return QualType(); 10085 if (PR.get() != Op) 10086 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 10087 } 10088 10089 if (Result.isNull()) { 10090 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 10091 << OpTy << Op->getSourceRange(); 10092 return QualType(); 10093 } 10094 10095 // Note that per both C89 and C99, indirection is always legal, even if Result 10096 // is an incomplete type or void. It would be possible to warn about 10097 // dereferencing a void pointer, but it's completely well-defined, and such a 10098 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 10099 // for pointers to 'void' but is fine for any other pointer type: 10100 // 10101 // C++ [expr.unary.op]p1: 10102 // [...] the expression to which [the unary * operator] is applied shall 10103 // be a pointer to an object type, or a pointer to a function type 10104 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 10105 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 10106 << OpTy << Op->getSourceRange(); 10107 10108 // Dereferences are usually l-values... 10109 VK = VK_LValue; 10110 10111 // ...except that certain expressions are never l-values in C. 10112 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 10113 VK = VK_RValue; 10114 10115 return Result; 10116 } 10117 10118 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 10119 BinaryOperatorKind Opc; 10120 switch (Kind) { 10121 default: llvm_unreachable("Unknown binop!"); 10122 case tok::periodstar: Opc = BO_PtrMemD; break; 10123 case tok::arrowstar: Opc = BO_PtrMemI; break; 10124 case tok::star: Opc = BO_Mul; break; 10125 case tok::slash: Opc = BO_Div; break; 10126 case tok::percent: Opc = BO_Rem; break; 10127 case tok::plus: Opc = BO_Add; break; 10128 case tok::minus: Opc = BO_Sub; break; 10129 case tok::lessless: Opc = BO_Shl; break; 10130 case tok::greatergreater: Opc = BO_Shr; break; 10131 case tok::lessequal: Opc = BO_LE; break; 10132 case tok::less: Opc = BO_LT; break; 10133 case tok::greaterequal: Opc = BO_GE; break; 10134 case tok::greater: Opc = BO_GT; break; 10135 case tok::exclaimequal: Opc = BO_NE; break; 10136 case tok::equalequal: Opc = BO_EQ; break; 10137 case tok::amp: Opc = BO_And; break; 10138 case tok::caret: Opc = BO_Xor; break; 10139 case tok::pipe: Opc = BO_Or; break; 10140 case tok::ampamp: Opc = BO_LAnd; break; 10141 case tok::pipepipe: Opc = BO_LOr; break; 10142 case tok::equal: Opc = BO_Assign; break; 10143 case tok::starequal: Opc = BO_MulAssign; break; 10144 case tok::slashequal: Opc = BO_DivAssign; break; 10145 case tok::percentequal: Opc = BO_RemAssign; break; 10146 case tok::plusequal: Opc = BO_AddAssign; break; 10147 case tok::minusequal: Opc = BO_SubAssign; break; 10148 case tok::lesslessequal: Opc = BO_ShlAssign; break; 10149 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 10150 case tok::ampequal: Opc = BO_AndAssign; break; 10151 case tok::caretequal: Opc = BO_XorAssign; break; 10152 case tok::pipeequal: Opc = BO_OrAssign; break; 10153 case tok::comma: Opc = BO_Comma; break; 10154 } 10155 return Opc; 10156 } 10157 10158 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 10159 tok::TokenKind Kind) { 10160 UnaryOperatorKind Opc; 10161 switch (Kind) { 10162 default: llvm_unreachable("Unknown unary op!"); 10163 case tok::plusplus: Opc = UO_PreInc; break; 10164 case tok::minusminus: Opc = UO_PreDec; break; 10165 case tok::amp: Opc = UO_AddrOf; break; 10166 case tok::star: Opc = UO_Deref; break; 10167 case tok::plus: Opc = UO_Plus; break; 10168 case tok::minus: Opc = UO_Minus; break; 10169 case tok::tilde: Opc = UO_Not; break; 10170 case tok::exclaim: Opc = UO_LNot; break; 10171 case tok::kw___real: Opc = UO_Real; break; 10172 case tok::kw___imag: Opc = UO_Imag; break; 10173 case tok::kw___extension__: Opc = UO_Extension; break; 10174 } 10175 return Opc; 10176 } 10177 10178 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 10179 /// This warning is only emitted for builtin assignment operations. It is also 10180 /// suppressed in the event of macro expansions. 10181 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 10182 SourceLocation OpLoc) { 10183 if (!S.ActiveTemplateInstantiations.empty()) 10184 return; 10185 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 10186 return; 10187 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 10188 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 10189 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 10190 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 10191 if (!LHSDeclRef || !RHSDeclRef || 10192 LHSDeclRef->getLocation().isMacroID() || 10193 RHSDeclRef->getLocation().isMacroID()) 10194 return; 10195 const ValueDecl *LHSDecl = 10196 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 10197 const ValueDecl *RHSDecl = 10198 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 10199 if (LHSDecl != RHSDecl) 10200 return; 10201 if (LHSDecl->getType().isVolatileQualified()) 10202 return; 10203 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 10204 if (RefTy->getPointeeType().isVolatileQualified()) 10205 return; 10206 10207 S.Diag(OpLoc, diag::warn_self_assignment) 10208 << LHSDeclRef->getType() 10209 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 10210 } 10211 10212 /// Check if a bitwise-& is performed on an Objective-C pointer. This 10213 /// is usually indicative of introspection within the Objective-C pointer. 10214 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 10215 SourceLocation OpLoc) { 10216 if (!S.getLangOpts().ObjC1) 10217 return; 10218 10219 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 10220 const Expr *LHS = L.get(); 10221 const Expr *RHS = R.get(); 10222 10223 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10224 ObjCPointerExpr = LHS; 10225 OtherExpr = RHS; 10226 } 10227 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 10228 ObjCPointerExpr = RHS; 10229 OtherExpr = LHS; 10230 } 10231 10232 // This warning is deliberately made very specific to reduce false 10233 // positives with logic that uses '&' for hashing. This logic mainly 10234 // looks for code trying to introspect into tagged pointers, which 10235 // code should generally never do. 10236 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 10237 unsigned Diag = diag::warn_objc_pointer_masking; 10238 // Determine if we are introspecting the result of performSelectorXXX. 10239 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 10240 // Special case messages to -performSelector and friends, which 10241 // can return non-pointer values boxed in a pointer value. 10242 // Some clients may wish to silence warnings in this subcase. 10243 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 10244 Selector S = ME->getSelector(); 10245 StringRef SelArg0 = S.getNameForSlot(0); 10246 if (SelArg0.startswith("performSelector")) 10247 Diag = diag::warn_objc_pointer_masking_performSelector; 10248 } 10249 10250 S.Diag(OpLoc, Diag) 10251 << ObjCPointerExpr->getSourceRange(); 10252 } 10253 } 10254 10255 static NamedDecl *getDeclFromExpr(Expr *E) { 10256 if (!E) 10257 return nullptr; 10258 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 10259 return DRE->getDecl(); 10260 if (auto *ME = dyn_cast<MemberExpr>(E)) 10261 return ME->getMemberDecl(); 10262 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 10263 return IRE->getDecl(); 10264 return nullptr; 10265 } 10266 10267 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 10268 /// operator @p Opc at location @c TokLoc. This routine only supports 10269 /// built-in operations; ActOnBinOp handles overloaded operators. 10270 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 10271 BinaryOperatorKind Opc, 10272 Expr *LHSExpr, Expr *RHSExpr) { 10273 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 10274 // The syntax only allows initializer lists on the RHS of assignment, 10275 // so we don't need to worry about accepting invalid code for 10276 // non-assignment operators. 10277 // C++11 5.17p9: 10278 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 10279 // of x = {} is x = T(). 10280 InitializationKind Kind = 10281 InitializationKind::CreateDirectList(RHSExpr->getLocStart()); 10282 InitializedEntity Entity = 10283 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 10284 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 10285 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 10286 if (Init.isInvalid()) 10287 return Init; 10288 RHSExpr = Init.get(); 10289 } 10290 10291 ExprResult LHS = LHSExpr, RHS = RHSExpr; 10292 QualType ResultTy; // Result type of the binary operator. 10293 // The following two variables are used for compound assignment operators 10294 QualType CompLHSTy; // Type of LHS after promotions for computation 10295 QualType CompResultTy; // Type of computation result 10296 ExprValueKind VK = VK_RValue; 10297 ExprObjectKind OK = OK_Ordinary; 10298 10299 if (!getLangOpts().CPlusPlus) { 10300 // C cannot handle TypoExpr nodes on either side of a binop because it 10301 // doesn't handle dependent types properly, so make sure any TypoExprs have 10302 // been dealt with before checking the operands. 10303 LHS = CorrectDelayedTyposInExpr(LHSExpr); 10304 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) { 10305 if (Opc != BO_Assign) 10306 return ExprResult(E); 10307 // Avoid correcting the RHS to the same Expr as the LHS. 10308 Decl *D = getDeclFromExpr(E); 10309 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 10310 }); 10311 if (!LHS.isUsable() || !RHS.isUsable()) 10312 return ExprError(); 10313 } 10314 10315 if (getLangOpts().OpenCL) { 10316 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 10317 // the ATOMIC_VAR_INIT macro. 10318 if (LHSExpr->getType()->isAtomicType() || 10319 RHSExpr->getType()->isAtomicType()) { 10320 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd()); 10321 if (BO_Assign == Opc) 10322 Diag(OpLoc, diag::err_atomic_init_constant) << SR; 10323 else 10324 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 10325 return ExprError(); 10326 } 10327 } 10328 10329 switch (Opc) { 10330 case BO_Assign: 10331 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 10332 if (getLangOpts().CPlusPlus && 10333 LHS.get()->getObjectKind() != OK_ObjCProperty) { 10334 VK = LHS.get()->getValueKind(); 10335 OK = LHS.get()->getObjectKind(); 10336 } 10337 if (!ResultTy.isNull()) { 10338 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10339 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 10340 } 10341 RecordModifiableNonNullParam(*this, LHS.get()); 10342 break; 10343 case BO_PtrMemD: 10344 case BO_PtrMemI: 10345 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 10346 Opc == BO_PtrMemI); 10347 break; 10348 case BO_Mul: 10349 case BO_Div: 10350 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 10351 Opc == BO_Div); 10352 break; 10353 case BO_Rem: 10354 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 10355 break; 10356 case BO_Add: 10357 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 10358 break; 10359 case BO_Sub: 10360 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 10361 break; 10362 case BO_Shl: 10363 case BO_Shr: 10364 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 10365 break; 10366 case BO_LE: 10367 case BO_LT: 10368 case BO_GE: 10369 case BO_GT: 10370 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true); 10371 break; 10372 case BO_EQ: 10373 case BO_NE: 10374 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false); 10375 break; 10376 case BO_And: 10377 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 10378 case BO_Xor: 10379 case BO_Or: 10380 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc); 10381 break; 10382 case BO_LAnd: 10383 case BO_LOr: 10384 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 10385 break; 10386 case BO_MulAssign: 10387 case BO_DivAssign: 10388 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 10389 Opc == BO_DivAssign); 10390 CompLHSTy = CompResultTy; 10391 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10392 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10393 break; 10394 case BO_RemAssign: 10395 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 10396 CompLHSTy = CompResultTy; 10397 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10398 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10399 break; 10400 case BO_AddAssign: 10401 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 10402 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10403 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10404 break; 10405 case BO_SubAssign: 10406 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 10407 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10408 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10409 break; 10410 case BO_ShlAssign: 10411 case BO_ShrAssign: 10412 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 10413 CompLHSTy = CompResultTy; 10414 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10415 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10416 break; 10417 case BO_AndAssign: 10418 case BO_OrAssign: // fallthrough 10419 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc); 10420 case BO_XorAssign: 10421 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true); 10422 CompLHSTy = CompResultTy; 10423 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 10424 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 10425 break; 10426 case BO_Comma: 10427 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 10428 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 10429 VK = RHS.get()->getValueKind(); 10430 OK = RHS.get()->getObjectKind(); 10431 } 10432 break; 10433 } 10434 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 10435 return ExprError(); 10436 10437 // Check for array bounds violations for both sides of the BinaryOperator 10438 CheckArrayAccess(LHS.get()); 10439 CheckArrayAccess(RHS.get()); 10440 10441 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 10442 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 10443 &Context.Idents.get("object_setClass"), 10444 SourceLocation(), LookupOrdinaryName); 10445 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 10446 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd()); 10447 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) << 10448 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") << 10449 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") << 10450 FixItHint::CreateInsertion(RHSLocEnd, ")"); 10451 } 10452 else 10453 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 10454 } 10455 else if (const ObjCIvarRefExpr *OIRE = 10456 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 10457 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 10458 10459 if (CompResultTy.isNull()) 10460 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 10461 OK, OpLoc, FPFeatures.fp_contract); 10462 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 10463 OK_ObjCProperty) { 10464 VK = VK_LValue; 10465 OK = LHS.get()->getObjectKind(); 10466 } 10467 return new (Context) CompoundAssignOperator( 10468 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 10469 OpLoc, FPFeatures.fp_contract); 10470 } 10471 10472 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 10473 /// operators are mixed in a way that suggests that the programmer forgot that 10474 /// comparison operators have higher precedence. The most typical example of 10475 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 10476 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 10477 SourceLocation OpLoc, Expr *LHSExpr, 10478 Expr *RHSExpr) { 10479 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 10480 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 10481 10482 // Check that one of the sides is a comparison operator and the other isn't. 10483 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 10484 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 10485 if (isLeftComp == isRightComp) 10486 return; 10487 10488 // Bitwise operations are sometimes used as eager logical ops. 10489 // Don't diagnose this. 10490 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 10491 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 10492 if (isLeftBitwise || isRightBitwise) 10493 return; 10494 10495 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(), 10496 OpLoc) 10497 : SourceRange(OpLoc, RHSExpr->getLocEnd()); 10498 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 10499 SourceRange ParensRange = isLeftComp ? 10500 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd()) 10501 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd()); 10502 10503 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 10504 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 10505 SuggestParentheses(Self, OpLoc, 10506 Self.PDiag(diag::note_precedence_silence) << OpStr, 10507 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 10508 SuggestParentheses(Self, OpLoc, 10509 Self.PDiag(diag::note_precedence_bitwise_first) 10510 << BinaryOperator::getOpcodeStr(Opc), 10511 ParensRange); 10512 } 10513 10514 /// \brief It accepts a '&&' expr that is inside a '||' one. 10515 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 10516 /// in parentheses. 10517 static void 10518 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 10519 BinaryOperator *Bop) { 10520 assert(Bop->getOpcode() == BO_LAnd); 10521 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 10522 << Bop->getSourceRange() << OpLoc; 10523 SuggestParentheses(Self, Bop->getOperatorLoc(), 10524 Self.PDiag(diag::note_precedence_silence) 10525 << Bop->getOpcodeStr(), 10526 Bop->getSourceRange()); 10527 } 10528 10529 /// \brief Returns true if the given expression can be evaluated as a constant 10530 /// 'true'. 10531 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 10532 bool Res; 10533 return !E->isValueDependent() && 10534 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 10535 } 10536 10537 /// \brief Returns true if the given expression can be evaluated as a constant 10538 /// 'false'. 10539 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 10540 bool Res; 10541 return !E->isValueDependent() && 10542 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 10543 } 10544 10545 /// \brief Look for '&&' in the left hand of a '||' expr. 10546 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 10547 Expr *LHSExpr, Expr *RHSExpr) { 10548 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 10549 if (Bop->getOpcode() == BO_LAnd) { 10550 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 10551 if (EvaluatesAsFalse(S, RHSExpr)) 10552 return; 10553 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 10554 if (!EvaluatesAsTrue(S, Bop->getLHS())) 10555 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 10556 } else if (Bop->getOpcode() == BO_LOr) { 10557 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 10558 // If it's "a || b && 1 || c" we didn't warn earlier for 10559 // "a || b && 1", but warn now. 10560 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 10561 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 10562 } 10563 } 10564 } 10565 } 10566 10567 /// \brief Look for '&&' in the right hand of a '||' expr. 10568 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 10569 Expr *LHSExpr, Expr *RHSExpr) { 10570 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 10571 if (Bop->getOpcode() == BO_LAnd) { 10572 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 10573 if (EvaluatesAsFalse(S, LHSExpr)) 10574 return; 10575 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 10576 if (!EvaluatesAsTrue(S, Bop->getRHS())) 10577 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 10578 } 10579 } 10580 } 10581 10582 /// \brief Look for bitwise op in the left or right hand of a bitwise op with 10583 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 10584 /// the '&' expression in parentheses. 10585 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 10586 SourceLocation OpLoc, Expr *SubExpr) { 10587 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 10588 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 10589 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 10590 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 10591 << Bop->getSourceRange() << OpLoc; 10592 SuggestParentheses(S, Bop->getOperatorLoc(), 10593 S.PDiag(diag::note_precedence_silence) 10594 << Bop->getOpcodeStr(), 10595 Bop->getSourceRange()); 10596 } 10597 } 10598 } 10599 10600 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 10601 Expr *SubExpr, StringRef Shift) { 10602 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 10603 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 10604 StringRef Op = Bop->getOpcodeStr(); 10605 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 10606 << Bop->getSourceRange() << OpLoc << Shift << Op; 10607 SuggestParentheses(S, Bop->getOperatorLoc(), 10608 S.PDiag(diag::note_precedence_silence) << Op, 10609 Bop->getSourceRange()); 10610 } 10611 } 10612 } 10613 10614 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 10615 Expr *LHSExpr, Expr *RHSExpr) { 10616 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 10617 if (!OCE) 10618 return; 10619 10620 FunctionDecl *FD = OCE->getDirectCallee(); 10621 if (!FD || !FD->isOverloadedOperator()) 10622 return; 10623 10624 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 10625 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 10626 return; 10627 10628 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 10629 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 10630 << (Kind == OO_LessLess); 10631 SuggestParentheses(S, OCE->getOperatorLoc(), 10632 S.PDiag(diag::note_precedence_silence) 10633 << (Kind == OO_LessLess ? "<<" : ">>"), 10634 OCE->getSourceRange()); 10635 SuggestParentheses(S, OpLoc, 10636 S.PDiag(diag::note_evaluate_comparison_first), 10637 SourceRange(OCE->getArg(1)->getLocStart(), 10638 RHSExpr->getLocEnd())); 10639 } 10640 10641 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 10642 /// precedence. 10643 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 10644 SourceLocation OpLoc, Expr *LHSExpr, 10645 Expr *RHSExpr){ 10646 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 10647 if (BinaryOperator::isBitwiseOp(Opc)) 10648 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 10649 10650 // Diagnose "arg1 & arg2 | arg3" 10651 if ((Opc == BO_Or || Opc == BO_Xor) && 10652 !OpLoc.isMacroID()/* Don't warn in macros. */) { 10653 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 10654 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 10655 } 10656 10657 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 10658 // We don't warn for 'assert(a || b && "bad")' since this is safe. 10659 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 10660 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 10661 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 10662 } 10663 10664 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 10665 || Opc == BO_Shr) { 10666 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 10667 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 10668 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 10669 } 10670 10671 // Warn on overloaded shift operators and comparisons, such as: 10672 // cout << 5 == 4; 10673 if (BinaryOperator::isComparisonOp(Opc)) 10674 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 10675 } 10676 10677 // Binary Operators. 'Tok' is the token for the operator. 10678 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 10679 tok::TokenKind Kind, 10680 Expr *LHSExpr, Expr *RHSExpr) { 10681 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 10682 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 10683 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 10684 10685 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 10686 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 10687 10688 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 10689 } 10690 10691 /// Build an overloaded binary operator expression in the given scope. 10692 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 10693 BinaryOperatorKind Opc, 10694 Expr *LHS, Expr *RHS) { 10695 // Find all of the overloaded operators visible from this 10696 // point. We perform both an operator-name lookup from the local 10697 // scope and an argument-dependent lookup based on the types of 10698 // the arguments. 10699 UnresolvedSet<16> Functions; 10700 OverloadedOperatorKind OverOp 10701 = BinaryOperator::getOverloadedOperator(Opc); 10702 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 10703 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 10704 RHS->getType(), Functions); 10705 10706 // Build the (potentially-overloaded, potentially-dependent) 10707 // binary operation. 10708 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 10709 } 10710 10711 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 10712 BinaryOperatorKind Opc, 10713 Expr *LHSExpr, Expr *RHSExpr) { 10714 // We want to end up calling one of checkPseudoObjectAssignment 10715 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 10716 // both expressions are overloadable or either is type-dependent), 10717 // or CreateBuiltinBinOp (in any other case). We also want to get 10718 // any placeholder types out of the way. 10719 10720 // Handle pseudo-objects in the LHS. 10721 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 10722 // Assignments with a pseudo-object l-value need special analysis. 10723 if (pty->getKind() == BuiltinType::PseudoObject && 10724 BinaryOperator::isAssignmentOp(Opc)) 10725 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 10726 10727 // Don't resolve overloads if the other type is overloadable. 10728 if (pty->getKind() == BuiltinType::Overload) { 10729 // We can't actually test that if we still have a placeholder, 10730 // though. Fortunately, none of the exceptions we see in that 10731 // code below are valid when the LHS is an overload set. Note 10732 // that an overload set can be dependently-typed, but it never 10733 // instantiates to having an overloadable type. 10734 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 10735 if (resolvedRHS.isInvalid()) return ExprError(); 10736 RHSExpr = resolvedRHS.get(); 10737 10738 if (RHSExpr->isTypeDependent() || 10739 RHSExpr->getType()->isOverloadableType()) 10740 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10741 } 10742 10743 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 10744 if (LHS.isInvalid()) return ExprError(); 10745 LHSExpr = LHS.get(); 10746 } 10747 10748 // Handle pseudo-objects in the RHS. 10749 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 10750 // An overload in the RHS can potentially be resolved by the type 10751 // being assigned to. 10752 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 10753 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 10754 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10755 10756 if (LHSExpr->getType()->isOverloadableType()) 10757 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10758 10759 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 10760 } 10761 10762 // Don't resolve overloads if the other type is overloadable. 10763 if (pty->getKind() == BuiltinType::Overload && 10764 LHSExpr->getType()->isOverloadableType()) 10765 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10766 10767 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 10768 if (!resolvedRHS.isUsable()) return ExprError(); 10769 RHSExpr = resolvedRHS.get(); 10770 } 10771 10772 if (getLangOpts().CPlusPlus) { 10773 // If either expression is type-dependent, always build an 10774 // overloaded op. 10775 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 10776 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10777 10778 // Otherwise, build an overloaded op if either expression has an 10779 // overloadable type. 10780 if (LHSExpr->getType()->isOverloadableType() || 10781 RHSExpr->getType()->isOverloadableType()) 10782 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 10783 } 10784 10785 // Build a built-in binary operation. 10786 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 10787 } 10788 10789 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 10790 UnaryOperatorKind Opc, 10791 Expr *InputExpr) { 10792 ExprResult Input = InputExpr; 10793 ExprValueKind VK = VK_RValue; 10794 ExprObjectKind OK = OK_Ordinary; 10795 QualType resultType; 10796 if (getLangOpts().OpenCL) { 10797 // The only legal unary operation for atomics is '&'. 10798 if (Opc != UO_AddrOf && InputExpr->getType()->isAtomicType()) { 10799 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10800 << InputExpr->getType() 10801 << Input.get()->getSourceRange()); 10802 } 10803 } 10804 switch (Opc) { 10805 case UO_PreInc: 10806 case UO_PreDec: 10807 case UO_PostInc: 10808 case UO_PostDec: 10809 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 10810 OpLoc, 10811 Opc == UO_PreInc || 10812 Opc == UO_PostInc, 10813 Opc == UO_PreInc || 10814 Opc == UO_PreDec); 10815 break; 10816 case UO_AddrOf: 10817 resultType = CheckAddressOfOperand(Input, OpLoc); 10818 RecordModifiableNonNullParam(*this, InputExpr); 10819 break; 10820 case UO_Deref: { 10821 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 10822 if (Input.isInvalid()) return ExprError(); 10823 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 10824 break; 10825 } 10826 case UO_Plus: 10827 case UO_Minus: 10828 Input = UsualUnaryConversions(Input.get()); 10829 if (Input.isInvalid()) return ExprError(); 10830 resultType = Input.get()->getType(); 10831 if (resultType->isDependentType()) 10832 break; 10833 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 10834 break; 10835 else if (resultType->isVectorType() && 10836 // The z vector extensions don't allow + or - with bool vectors. 10837 (!Context.getLangOpts().ZVector || 10838 resultType->getAs<VectorType>()->getVectorKind() != 10839 VectorType::AltiVecBool)) 10840 break; 10841 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 10842 Opc == UO_Plus && 10843 resultType->isPointerType()) 10844 break; 10845 10846 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10847 << resultType << Input.get()->getSourceRange()); 10848 10849 case UO_Not: // bitwise complement 10850 Input = UsualUnaryConversions(Input.get()); 10851 if (Input.isInvalid()) 10852 return ExprError(); 10853 resultType = Input.get()->getType(); 10854 if (resultType->isDependentType()) 10855 break; 10856 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 10857 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 10858 // C99 does not support '~' for complex conjugation. 10859 Diag(OpLoc, diag::ext_integer_complement_complex) 10860 << resultType << Input.get()->getSourceRange(); 10861 else if (resultType->hasIntegerRepresentation()) 10862 break; 10863 else if (resultType->isExtVectorType()) { 10864 if (Context.getLangOpts().OpenCL) { 10865 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 10866 // on vector float types. 10867 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 10868 if (!T->isIntegerType()) 10869 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10870 << resultType << Input.get()->getSourceRange()); 10871 } 10872 break; 10873 } else { 10874 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10875 << resultType << Input.get()->getSourceRange()); 10876 } 10877 break; 10878 10879 case UO_LNot: // logical negation 10880 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 10881 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 10882 if (Input.isInvalid()) return ExprError(); 10883 resultType = Input.get()->getType(); 10884 10885 // Though we still have to promote half FP to float... 10886 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 10887 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 10888 resultType = Context.FloatTy; 10889 } 10890 10891 if (resultType->isDependentType()) 10892 break; 10893 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 10894 // C99 6.5.3.3p1: ok, fallthrough; 10895 if (Context.getLangOpts().CPlusPlus) { 10896 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 10897 // operand contextually converted to bool. 10898 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 10899 ScalarTypeToBooleanCastKind(resultType)); 10900 } else if (Context.getLangOpts().OpenCL && 10901 Context.getLangOpts().OpenCLVersion < 120) { 10902 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 10903 // operate on scalar float types. 10904 if (!resultType->isIntegerType()) 10905 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10906 << resultType << Input.get()->getSourceRange()); 10907 } 10908 } else if (resultType->isExtVectorType()) { 10909 if (Context.getLangOpts().OpenCL && 10910 Context.getLangOpts().OpenCLVersion < 120) { 10911 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 10912 // operate on vector float types. 10913 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 10914 if (!T->isIntegerType()) 10915 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10916 << resultType << Input.get()->getSourceRange()); 10917 } 10918 // Vector logical not returns the signed variant of the operand type. 10919 resultType = GetSignedVectorType(resultType); 10920 break; 10921 } else { 10922 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 10923 << resultType << Input.get()->getSourceRange()); 10924 } 10925 10926 // LNot always has type int. C99 6.5.3.3p5. 10927 // In C++, it's bool. C++ 5.3.1p8 10928 resultType = Context.getLogicalOperationType(); 10929 break; 10930 case UO_Real: 10931 case UO_Imag: 10932 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 10933 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 10934 // complex l-values to ordinary l-values and all other values to r-values. 10935 if (Input.isInvalid()) return ExprError(); 10936 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 10937 if (Input.get()->getValueKind() != VK_RValue && 10938 Input.get()->getObjectKind() == OK_Ordinary) 10939 VK = Input.get()->getValueKind(); 10940 } else if (!getLangOpts().CPlusPlus) { 10941 // In C, a volatile scalar is read by __imag. In C++, it is not. 10942 Input = DefaultLvalueConversion(Input.get()); 10943 } 10944 break; 10945 case UO_Extension: 10946 case UO_Coawait: 10947 resultType = Input.get()->getType(); 10948 VK = Input.get()->getValueKind(); 10949 OK = Input.get()->getObjectKind(); 10950 break; 10951 } 10952 if (resultType.isNull() || Input.isInvalid()) 10953 return ExprError(); 10954 10955 // Check for array bounds violations in the operand of the UnaryOperator, 10956 // except for the '*' and '&' operators that have to be handled specially 10957 // by CheckArrayAccess (as there are special cases like &array[arraysize] 10958 // that are explicitly defined as valid by the standard). 10959 if (Opc != UO_AddrOf && Opc != UO_Deref) 10960 CheckArrayAccess(Input.get()); 10961 10962 return new (Context) 10963 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc); 10964 } 10965 10966 /// \brief Determine whether the given expression is a qualified member 10967 /// access expression, of a form that could be turned into a pointer to member 10968 /// with the address-of operator. 10969 static bool isQualifiedMemberAccess(Expr *E) { 10970 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 10971 if (!DRE->getQualifier()) 10972 return false; 10973 10974 ValueDecl *VD = DRE->getDecl(); 10975 if (!VD->isCXXClassMember()) 10976 return false; 10977 10978 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 10979 return true; 10980 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 10981 return Method->isInstance(); 10982 10983 return false; 10984 } 10985 10986 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 10987 if (!ULE->getQualifier()) 10988 return false; 10989 10990 for (NamedDecl *D : ULE->decls()) { 10991 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 10992 if (Method->isInstance()) 10993 return true; 10994 } else { 10995 // Overload set does not contain methods. 10996 break; 10997 } 10998 } 10999 11000 return false; 11001 } 11002 11003 return false; 11004 } 11005 11006 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 11007 UnaryOperatorKind Opc, Expr *Input) { 11008 // First things first: handle placeholders so that the 11009 // overloaded-operator check considers the right type. 11010 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 11011 // Increment and decrement of pseudo-object references. 11012 if (pty->getKind() == BuiltinType::PseudoObject && 11013 UnaryOperator::isIncrementDecrementOp(Opc)) 11014 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 11015 11016 // extension is always a builtin operator. 11017 if (Opc == UO_Extension) 11018 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11019 11020 // & gets special logic for several kinds of placeholder. 11021 // The builtin code knows what to do. 11022 if (Opc == UO_AddrOf && 11023 (pty->getKind() == BuiltinType::Overload || 11024 pty->getKind() == BuiltinType::UnknownAny || 11025 pty->getKind() == BuiltinType::BoundMember)) 11026 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11027 11028 // Anything else needs to be handled now. 11029 ExprResult Result = CheckPlaceholderExpr(Input); 11030 if (Result.isInvalid()) return ExprError(); 11031 Input = Result.get(); 11032 } 11033 11034 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 11035 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 11036 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 11037 // Find all of the overloaded operators visible from this 11038 // point. We perform both an operator-name lookup from the local 11039 // scope and an argument-dependent lookup based on the types of 11040 // the arguments. 11041 UnresolvedSet<16> Functions; 11042 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 11043 if (S && OverOp != OO_None) 11044 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 11045 Functions); 11046 11047 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 11048 } 11049 11050 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11051 } 11052 11053 // Unary Operators. 'Tok' is the token for the operator. 11054 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 11055 tok::TokenKind Op, Expr *Input) { 11056 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 11057 } 11058 11059 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 11060 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 11061 LabelDecl *TheDecl) { 11062 TheDecl->markUsed(Context); 11063 // Create the AST node. The address of a label always has type 'void*'. 11064 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 11065 Context.getPointerType(Context.VoidTy)); 11066 } 11067 11068 /// Given the last statement in a statement-expression, check whether 11069 /// the result is a producing expression (like a call to an 11070 /// ns_returns_retained function) and, if so, rebuild it to hoist the 11071 /// release out of the full-expression. Otherwise, return null. 11072 /// Cannot fail. 11073 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 11074 // Should always be wrapped with one of these. 11075 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 11076 if (!cleanups) return nullptr; 11077 11078 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 11079 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 11080 return nullptr; 11081 11082 // Splice out the cast. This shouldn't modify any interesting 11083 // features of the statement. 11084 Expr *producer = cast->getSubExpr(); 11085 assert(producer->getType() == cast->getType()); 11086 assert(producer->getValueKind() == cast->getValueKind()); 11087 cleanups->setSubExpr(producer); 11088 return cleanups; 11089 } 11090 11091 void Sema::ActOnStartStmtExpr() { 11092 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 11093 } 11094 11095 void Sema::ActOnStmtExprError() { 11096 // Note that function is also called by TreeTransform when leaving a 11097 // StmtExpr scope without rebuilding anything. 11098 11099 DiscardCleanupsInEvaluationContext(); 11100 PopExpressionEvaluationContext(); 11101 } 11102 11103 ExprResult 11104 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 11105 SourceLocation RPLoc) { // "({..})" 11106 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 11107 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 11108 11109 if (hasAnyUnrecoverableErrorsInThisFunction()) 11110 DiscardCleanupsInEvaluationContext(); 11111 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!"); 11112 PopExpressionEvaluationContext(); 11113 11114 // FIXME: there are a variety of strange constraints to enforce here, for 11115 // example, it is not possible to goto into a stmt expression apparently. 11116 // More semantic analysis is needed. 11117 11118 // If there are sub-stmts in the compound stmt, take the type of the last one 11119 // as the type of the stmtexpr. 11120 QualType Ty = Context.VoidTy; 11121 bool StmtExprMayBindToTemp = false; 11122 if (!Compound->body_empty()) { 11123 Stmt *LastStmt = Compound->body_back(); 11124 LabelStmt *LastLabelStmt = nullptr; 11125 // If LastStmt is a label, skip down through into the body. 11126 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 11127 LastLabelStmt = Label; 11128 LastStmt = Label->getSubStmt(); 11129 } 11130 11131 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 11132 // Do function/array conversion on the last expression, but not 11133 // lvalue-to-rvalue. However, initialize an unqualified type. 11134 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 11135 if (LastExpr.isInvalid()) 11136 return ExprError(); 11137 Ty = LastExpr.get()->getType().getUnqualifiedType(); 11138 11139 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 11140 // In ARC, if the final expression ends in a consume, splice 11141 // the consume out and bind it later. In the alternate case 11142 // (when dealing with a retainable type), the result 11143 // initialization will create a produce. In both cases the 11144 // result will be +1, and we'll need to balance that out with 11145 // a bind. 11146 if (Expr *rebuiltLastStmt 11147 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 11148 LastExpr = rebuiltLastStmt; 11149 } else { 11150 LastExpr = PerformCopyInitialization( 11151 InitializedEntity::InitializeResult(LPLoc, 11152 Ty, 11153 false), 11154 SourceLocation(), 11155 LastExpr); 11156 } 11157 11158 if (LastExpr.isInvalid()) 11159 return ExprError(); 11160 if (LastExpr.get() != nullptr) { 11161 if (!LastLabelStmt) 11162 Compound->setLastStmt(LastExpr.get()); 11163 else 11164 LastLabelStmt->setSubStmt(LastExpr.get()); 11165 StmtExprMayBindToTemp = true; 11166 } 11167 } 11168 } 11169 } 11170 11171 // FIXME: Check that expression type is complete/non-abstract; statement 11172 // expressions are not lvalues. 11173 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 11174 if (StmtExprMayBindToTemp) 11175 return MaybeBindToTemporary(ResStmtExpr); 11176 return ResStmtExpr; 11177 } 11178 11179 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 11180 TypeSourceInfo *TInfo, 11181 ArrayRef<OffsetOfComponent> Components, 11182 SourceLocation RParenLoc) { 11183 QualType ArgTy = TInfo->getType(); 11184 bool Dependent = ArgTy->isDependentType(); 11185 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 11186 11187 // We must have at least one component that refers to the type, and the first 11188 // one is known to be a field designator. Verify that the ArgTy represents 11189 // a struct/union/class. 11190 if (!Dependent && !ArgTy->isRecordType()) 11191 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 11192 << ArgTy << TypeRange); 11193 11194 // Type must be complete per C99 7.17p3 because a declaring a variable 11195 // with an incomplete type would be ill-formed. 11196 if (!Dependent 11197 && RequireCompleteType(BuiltinLoc, ArgTy, 11198 diag::err_offsetof_incomplete_type, TypeRange)) 11199 return ExprError(); 11200 11201 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a 11202 // GCC extension, diagnose them. 11203 // FIXME: This diagnostic isn't actually visible because the location is in 11204 // a system header! 11205 if (Components.size() != 1) 11206 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator) 11207 << SourceRange(Components[1].LocStart, Components.back().LocEnd); 11208 11209 bool DidWarnAboutNonPOD = false; 11210 QualType CurrentType = ArgTy; 11211 SmallVector<OffsetOfNode, 4> Comps; 11212 SmallVector<Expr*, 4> Exprs; 11213 for (const OffsetOfComponent &OC : Components) { 11214 if (OC.isBrackets) { 11215 // Offset of an array sub-field. TODO: Should we allow vector elements? 11216 if (!CurrentType->isDependentType()) { 11217 const ArrayType *AT = Context.getAsArrayType(CurrentType); 11218 if(!AT) 11219 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 11220 << CurrentType); 11221 CurrentType = AT->getElementType(); 11222 } else 11223 CurrentType = Context.DependentTy; 11224 11225 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 11226 if (IdxRval.isInvalid()) 11227 return ExprError(); 11228 Expr *Idx = IdxRval.get(); 11229 11230 // The expression must be an integral expression. 11231 // FIXME: An integral constant expression? 11232 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 11233 !Idx->getType()->isIntegerType()) 11234 return ExprError(Diag(Idx->getLocStart(), 11235 diag::err_typecheck_subscript_not_integer) 11236 << Idx->getSourceRange()); 11237 11238 // Record this array index. 11239 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 11240 Exprs.push_back(Idx); 11241 continue; 11242 } 11243 11244 // Offset of a field. 11245 if (CurrentType->isDependentType()) { 11246 // We have the offset of a field, but we can't look into the dependent 11247 // type. Just record the identifier of the field. 11248 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 11249 CurrentType = Context.DependentTy; 11250 continue; 11251 } 11252 11253 // We need to have a complete type to look into. 11254 if (RequireCompleteType(OC.LocStart, CurrentType, 11255 diag::err_offsetof_incomplete_type)) 11256 return ExprError(); 11257 11258 // Look for the designated field. 11259 const RecordType *RC = CurrentType->getAs<RecordType>(); 11260 if (!RC) 11261 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 11262 << CurrentType); 11263 RecordDecl *RD = RC->getDecl(); 11264 11265 // C++ [lib.support.types]p5: 11266 // The macro offsetof accepts a restricted set of type arguments in this 11267 // International Standard. type shall be a POD structure or a POD union 11268 // (clause 9). 11269 // C++11 [support.types]p4: 11270 // If type is not a standard-layout class (Clause 9), the results are 11271 // undefined. 11272 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 11273 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 11274 unsigned DiagID = 11275 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 11276 : diag::ext_offsetof_non_pod_type; 11277 11278 if (!IsSafe && !DidWarnAboutNonPOD && 11279 DiagRuntimeBehavior(BuiltinLoc, nullptr, 11280 PDiag(DiagID) 11281 << SourceRange(Components[0].LocStart, OC.LocEnd) 11282 << CurrentType)) 11283 DidWarnAboutNonPOD = true; 11284 } 11285 11286 // Look for the field. 11287 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 11288 LookupQualifiedName(R, RD); 11289 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 11290 IndirectFieldDecl *IndirectMemberDecl = nullptr; 11291 if (!MemberDecl) { 11292 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 11293 MemberDecl = IndirectMemberDecl->getAnonField(); 11294 } 11295 11296 if (!MemberDecl) 11297 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 11298 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 11299 OC.LocEnd)); 11300 11301 // C99 7.17p3: 11302 // (If the specified member is a bit-field, the behavior is undefined.) 11303 // 11304 // We diagnose this as an error. 11305 if (MemberDecl->isBitField()) { 11306 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 11307 << MemberDecl->getDeclName() 11308 << SourceRange(BuiltinLoc, RParenLoc); 11309 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 11310 return ExprError(); 11311 } 11312 11313 RecordDecl *Parent = MemberDecl->getParent(); 11314 if (IndirectMemberDecl) 11315 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 11316 11317 // If the member was found in a base class, introduce OffsetOfNodes for 11318 // the base class indirections. 11319 CXXBasePaths Paths; 11320 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 11321 Paths)) { 11322 if (Paths.getDetectedVirtual()) { 11323 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 11324 << MemberDecl->getDeclName() 11325 << SourceRange(BuiltinLoc, RParenLoc); 11326 return ExprError(); 11327 } 11328 11329 CXXBasePath &Path = Paths.front(); 11330 for (const CXXBasePathElement &B : Path) 11331 Comps.push_back(OffsetOfNode(B.Base)); 11332 } 11333 11334 if (IndirectMemberDecl) { 11335 for (auto *FI : IndirectMemberDecl->chain()) { 11336 assert(isa<FieldDecl>(FI)); 11337 Comps.push_back(OffsetOfNode(OC.LocStart, 11338 cast<FieldDecl>(FI), OC.LocEnd)); 11339 } 11340 } else 11341 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 11342 11343 CurrentType = MemberDecl->getType().getNonReferenceType(); 11344 } 11345 11346 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 11347 Comps, Exprs, RParenLoc); 11348 } 11349 11350 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 11351 SourceLocation BuiltinLoc, 11352 SourceLocation TypeLoc, 11353 ParsedType ParsedArgTy, 11354 ArrayRef<OffsetOfComponent> Components, 11355 SourceLocation RParenLoc) { 11356 11357 TypeSourceInfo *ArgTInfo; 11358 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 11359 if (ArgTy.isNull()) 11360 return ExprError(); 11361 11362 if (!ArgTInfo) 11363 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 11364 11365 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 11366 } 11367 11368 11369 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 11370 Expr *CondExpr, 11371 Expr *LHSExpr, Expr *RHSExpr, 11372 SourceLocation RPLoc) { 11373 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 11374 11375 ExprValueKind VK = VK_RValue; 11376 ExprObjectKind OK = OK_Ordinary; 11377 QualType resType; 11378 bool ValueDependent = false; 11379 bool CondIsTrue = false; 11380 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 11381 resType = Context.DependentTy; 11382 ValueDependent = true; 11383 } else { 11384 // The conditional expression is required to be a constant expression. 11385 llvm::APSInt condEval(32); 11386 ExprResult CondICE 11387 = VerifyIntegerConstantExpression(CondExpr, &condEval, 11388 diag::err_typecheck_choose_expr_requires_constant, false); 11389 if (CondICE.isInvalid()) 11390 return ExprError(); 11391 CondExpr = CondICE.get(); 11392 CondIsTrue = condEval.getZExtValue(); 11393 11394 // If the condition is > zero, then the AST type is the same as the LSHExpr. 11395 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 11396 11397 resType = ActiveExpr->getType(); 11398 ValueDependent = ActiveExpr->isValueDependent(); 11399 VK = ActiveExpr->getValueKind(); 11400 OK = ActiveExpr->getObjectKind(); 11401 } 11402 11403 return new (Context) 11404 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 11405 CondIsTrue, resType->isDependentType(), ValueDependent); 11406 } 11407 11408 //===----------------------------------------------------------------------===// 11409 // Clang Extensions. 11410 //===----------------------------------------------------------------------===// 11411 11412 /// ActOnBlockStart - This callback is invoked when a block literal is started. 11413 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 11414 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 11415 11416 if (LangOpts.CPlusPlus) { 11417 Decl *ManglingContextDecl; 11418 if (MangleNumberingContext *MCtx = 11419 getCurrentMangleNumberContext(Block->getDeclContext(), 11420 ManglingContextDecl)) { 11421 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 11422 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 11423 } 11424 } 11425 11426 PushBlockScope(CurScope, Block); 11427 CurContext->addDecl(Block); 11428 if (CurScope) 11429 PushDeclContext(CurScope, Block); 11430 else 11431 CurContext = Block; 11432 11433 getCurBlock()->HasImplicitReturnType = true; 11434 11435 // Enter a new evaluation context to insulate the block from any 11436 // cleanups from the enclosing full-expression. 11437 PushExpressionEvaluationContext(PotentiallyEvaluated); 11438 } 11439 11440 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 11441 Scope *CurScope) { 11442 assert(ParamInfo.getIdentifier() == nullptr && 11443 "block-id should have no identifier!"); 11444 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext); 11445 BlockScopeInfo *CurBlock = getCurBlock(); 11446 11447 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 11448 QualType T = Sig->getType(); 11449 11450 // FIXME: We should allow unexpanded parameter packs here, but that would, 11451 // in turn, make the block expression contain unexpanded parameter packs. 11452 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 11453 // Drop the parameters. 11454 FunctionProtoType::ExtProtoInfo EPI; 11455 EPI.HasTrailingReturn = false; 11456 EPI.TypeQuals |= DeclSpec::TQ_const; 11457 T = Context.getFunctionType(Context.DependentTy, None, EPI); 11458 Sig = Context.getTrivialTypeSourceInfo(T); 11459 } 11460 11461 // GetTypeForDeclarator always produces a function type for a block 11462 // literal signature. Furthermore, it is always a FunctionProtoType 11463 // unless the function was written with a typedef. 11464 assert(T->isFunctionType() && 11465 "GetTypeForDeclarator made a non-function block signature"); 11466 11467 // Look for an explicit signature in that function type. 11468 FunctionProtoTypeLoc ExplicitSignature; 11469 11470 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens(); 11471 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) { 11472 11473 // Check whether that explicit signature was synthesized by 11474 // GetTypeForDeclarator. If so, don't save that as part of the 11475 // written signature. 11476 if (ExplicitSignature.getLocalRangeBegin() == 11477 ExplicitSignature.getLocalRangeEnd()) { 11478 // This would be much cheaper if we stored TypeLocs instead of 11479 // TypeSourceInfos. 11480 TypeLoc Result = ExplicitSignature.getReturnLoc(); 11481 unsigned Size = Result.getFullDataSize(); 11482 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 11483 Sig->getTypeLoc().initializeFullCopy(Result, Size); 11484 11485 ExplicitSignature = FunctionProtoTypeLoc(); 11486 } 11487 } 11488 11489 CurBlock->TheDecl->setSignatureAsWritten(Sig); 11490 CurBlock->FunctionType = T; 11491 11492 const FunctionType *Fn = T->getAs<FunctionType>(); 11493 QualType RetTy = Fn->getReturnType(); 11494 bool isVariadic = 11495 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 11496 11497 CurBlock->TheDecl->setIsVariadic(isVariadic); 11498 11499 // Context.DependentTy is used as a placeholder for a missing block 11500 // return type. TODO: what should we do with declarators like: 11501 // ^ * { ... } 11502 // If the answer is "apply template argument deduction".... 11503 if (RetTy != Context.DependentTy) { 11504 CurBlock->ReturnType = RetTy; 11505 CurBlock->TheDecl->setBlockMissingReturnType(false); 11506 CurBlock->HasImplicitReturnType = false; 11507 } 11508 11509 // Push block parameters from the declarator if we had them. 11510 SmallVector<ParmVarDecl*, 8> Params; 11511 if (ExplicitSignature) { 11512 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 11513 ParmVarDecl *Param = ExplicitSignature.getParam(I); 11514 if (Param->getIdentifier() == nullptr && 11515 !Param->isImplicit() && 11516 !Param->isInvalidDecl() && 11517 !getLangOpts().CPlusPlus) 11518 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 11519 Params.push_back(Param); 11520 } 11521 11522 // Fake up parameter variables if we have a typedef, like 11523 // ^ fntype { ... } 11524 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 11525 for (const auto &I : Fn->param_types()) { 11526 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 11527 CurBlock->TheDecl, ParamInfo.getLocStart(), I); 11528 Params.push_back(Param); 11529 } 11530 } 11531 11532 // Set the parameters on the block decl. 11533 if (!Params.empty()) { 11534 CurBlock->TheDecl->setParams(Params); 11535 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(), 11536 CurBlock->TheDecl->param_end(), 11537 /*CheckParameterNames=*/false); 11538 } 11539 11540 // Finally we can process decl attributes. 11541 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 11542 11543 // Put the parameter variables in scope. 11544 for (auto AI : CurBlock->TheDecl->params()) { 11545 AI->setOwningFunction(CurBlock->TheDecl); 11546 11547 // If this has an identifier, add it to the scope stack. 11548 if (AI->getIdentifier()) { 11549 CheckShadow(CurBlock->TheScope, AI); 11550 11551 PushOnScopeChains(AI, CurBlock->TheScope); 11552 } 11553 } 11554 } 11555 11556 /// ActOnBlockError - If there is an error parsing a block, this callback 11557 /// is invoked to pop the information about the block from the action impl. 11558 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 11559 // Leave the expression-evaluation context. 11560 DiscardCleanupsInEvaluationContext(); 11561 PopExpressionEvaluationContext(); 11562 11563 // Pop off CurBlock, handle nested blocks. 11564 PopDeclContext(); 11565 PopFunctionScopeInfo(); 11566 } 11567 11568 /// ActOnBlockStmtExpr - This is called when the body of a block statement 11569 /// literal was successfully completed. ^(int x){...} 11570 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 11571 Stmt *Body, Scope *CurScope) { 11572 // If blocks are disabled, emit an error. 11573 if (!LangOpts.Blocks) 11574 Diag(CaretLoc, diag::err_blocks_disable); 11575 11576 // Leave the expression-evaluation context. 11577 if (hasAnyUnrecoverableErrorsInThisFunction()) 11578 DiscardCleanupsInEvaluationContext(); 11579 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!"); 11580 PopExpressionEvaluationContext(); 11581 11582 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 11583 11584 if (BSI->HasImplicitReturnType) 11585 deduceClosureReturnType(*BSI); 11586 11587 PopDeclContext(); 11588 11589 QualType RetTy = Context.VoidTy; 11590 if (!BSI->ReturnType.isNull()) 11591 RetTy = BSI->ReturnType; 11592 11593 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>(); 11594 QualType BlockTy; 11595 11596 // Set the captured variables on the block. 11597 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 11598 SmallVector<BlockDecl::Capture, 4> Captures; 11599 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) { 11600 if (Cap.isThisCapture()) 11601 continue; 11602 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 11603 Cap.isNested(), Cap.getInitExpr()); 11604 Captures.push_back(NewCap); 11605 } 11606 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 11607 11608 // If the user wrote a function type in some form, try to use that. 11609 if (!BSI->FunctionType.isNull()) { 11610 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 11611 11612 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 11613 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 11614 11615 // Turn protoless block types into nullary block types. 11616 if (isa<FunctionNoProtoType>(FTy)) { 11617 FunctionProtoType::ExtProtoInfo EPI; 11618 EPI.ExtInfo = Ext; 11619 BlockTy = Context.getFunctionType(RetTy, None, EPI); 11620 11621 // Otherwise, if we don't need to change anything about the function type, 11622 // preserve its sugar structure. 11623 } else if (FTy->getReturnType() == RetTy && 11624 (!NoReturn || FTy->getNoReturnAttr())) { 11625 BlockTy = BSI->FunctionType; 11626 11627 // Otherwise, make the minimal modifications to the function type. 11628 } else { 11629 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 11630 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11631 EPI.TypeQuals = 0; // FIXME: silently? 11632 EPI.ExtInfo = Ext; 11633 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 11634 } 11635 11636 // If we don't have a function type, just build one from nothing. 11637 } else { 11638 FunctionProtoType::ExtProtoInfo EPI; 11639 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 11640 BlockTy = Context.getFunctionType(RetTy, None, EPI); 11641 } 11642 11643 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(), 11644 BSI->TheDecl->param_end()); 11645 BlockTy = Context.getBlockPointerType(BlockTy); 11646 11647 // If needed, diagnose invalid gotos and switches in the block. 11648 if (getCurFunction()->NeedsScopeChecking() && 11649 !PP.isCodeCompletionEnabled()) 11650 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 11651 11652 BSI->TheDecl->setBody(cast<CompoundStmt>(Body)); 11653 11654 // Try to apply the named return value optimization. We have to check again 11655 // if we can do this, though, because blocks keep return statements around 11656 // to deduce an implicit return type. 11657 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 11658 !BSI->TheDecl->isDependentContext()) 11659 computeNRVO(Body, BSI); 11660 11661 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy); 11662 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 11663 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 11664 11665 // If the block isn't obviously global, i.e. it captures anything at 11666 // all, then we need to do a few things in the surrounding context: 11667 if (Result->getBlockDecl()->hasCaptures()) { 11668 // First, this expression has a new cleanup object. 11669 ExprCleanupObjects.push_back(Result->getBlockDecl()); 11670 ExprNeedsCleanups = true; 11671 11672 // It also gets a branch-protected scope if any of the captured 11673 // variables needs destruction. 11674 for (const auto &CI : Result->getBlockDecl()->captures()) { 11675 const VarDecl *var = CI.getVariable(); 11676 if (var->getType().isDestructedType() != QualType::DK_none) { 11677 getCurFunction()->setHasBranchProtectedScope(); 11678 break; 11679 } 11680 } 11681 } 11682 11683 return Result; 11684 } 11685 11686 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, 11687 Expr *E, ParsedType Ty, 11688 SourceLocation RPLoc) { 11689 TypeSourceInfo *TInfo; 11690 GetTypeFromParser(Ty, &TInfo); 11691 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 11692 } 11693 11694 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 11695 Expr *E, TypeSourceInfo *TInfo, 11696 SourceLocation RPLoc) { 11697 Expr *OrigExpr = E; 11698 bool IsMS = false; 11699 11700 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 11701 // as Microsoft ABI on an actual Microsoft platform, where 11702 // __builtin_ms_va_list and __builtin_va_list are the same.) 11703 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 11704 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 11705 QualType MSVaListType = Context.getBuiltinMSVaListType(); 11706 if (Context.hasSameType(MSVaListType, E->getType())) { 11707 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 11708 return ExprError(); 11709 IsMS = true; 11710 } 11711 } 11712 11713 // Get the va_list type 11714 QualType VaListType = Context.getBuiltinVaListType(); 11715 if (!IsMS) { 11716 if (VaListType->isArrayType()) { 11717 // Deal with implicit array decay; for example, on x86-64, 11718 // va_list is an array, but it's supposed to decay to 11719 // a pointer for va_arg. 11720 VaListType = Context.getArrayDecayedType(VaListType); 11721 // Make sure the input expression also decays appropriately. 11722 ExprResult Result = UsualUnaryConversions(E); 11723 if (Result.isInvalid()) 11724 return ExprError(); 11725 E = Result.get(); 11726 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 11727 // If va_list is a record type and we are compiling in C++ mode, 11728 // check the argument using reference binding. 11729 InitializedEntity Entity = InitializedEntity::InitializeParameter( 11730 Context, Context.getLValueReferenceType(VaListType), false); 11731 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 11732 if (Init.isInvalid()) 11733 return ExprError(); 11734 E = Init.getAs<Expr>(); 11735 } else { 11736 // Otherwise, the va_list argument must be an l-value because 11737 // it is modified by va_arg. 11738 if (!E->isTypeDependent() && 11739 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 11740 return ExprError(); 11741 } 11742 } 11743 11744 if (!IsMS && !E->isTypeDependent() && 11745 !Context.hasSameType(VaListType, E->getType())) 11746 return ExprError(Diag(E->getLocStart(), 11747 diag::err_first_argument_to_va_arg_not_of_type_va_list) 11748 << OrigExpr->getType() << E->getSourceRange()); 11749 11750 if (!TInfo->getType()->isDependentType()) { 11751 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 11752 diag::err_second_parameter_to_va_arg_incomplete, 11753 TInfo->getTypeLoc())) 11754 return ExprError(); 11755 11756 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 11757 TInfo->getType(), 11758 diag::err_second_parameter_to_va_arg_abstract, 11759 TInfo->getTypeLoc())) 11760 return ExprError(); 11761 11762 if (!TInfo->getType().isPODType(Context)) { 11763 Diag(TInfo->getTypeLoc().getBeginLoc(), 11764 TInfo->getType()->isObjCLifetimeType() 11765 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 11766 : diag::warn_second_parameter_to_va_arg_not_pod) 11767 << TInfo->getType() 11768 << TInfo->getTypeLoc().getSourceRange(); 11769 } 11770 11771 // Check for va_arg where arguments of the given type will be promoted 11772 // (i.e. this va_arg is guaranteed to have undefined behavior). 11773 QualType PromoteType; 11774 if (TInfo->getType()->isPromotableIntegerType()) { 11775 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 11776 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 11777 PromoteType = QualType(); 11778 } 11779 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 11780 PromoteType = Context.DoubleTy; 11781 if (!PromoteType.isNull()) 11782 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 11783 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 11784 << TInfo->getType() 11785 << PromoteType 11786 << TInfo->getTypeLoc().getSourceRange()); 11787 } 11788 11789 QualType T = TInfo->getType().getNonLValueExprType(Context); 11790 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 11791 } 11792 11793 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 11794 // The type of __null will be int or long, depending on the size of 11795 // pointers on the target. 11796 QualType Ty; 11797 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 11798 if (pw == Context.getTargetInfo().getIntWidth()) 11799 Ty = Context.IntTy; 11800 else if (pw == Context.getTargetInfo().getLongWidth()) 11801 Ty = Context.LongTy; 11802 else if (pw == Context.getTargetInfo().getLongLongWidth()) 11803 Ty = Context.LongLongTy; 11804 else { 11805 llvm_unreachable("I don't know size of pointer!"); 11806 } 11807 11808 return new (Context) GNUNullExpr(Ty, TokenLoc); 11809 } 11810 11811 bool 11812 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) { 11813 if (!getLangOpts().ObjC1) 11814 return false; 11815 11816 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 11817 if (!PT) 11818 return false; 11819 11820 if (!PT->isObjCIdType()) { 11821 // Check if the destination is the 'NSString' interface. 11822 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 11823 if (!ID || !ID->getIdentifier()->isStr("NSString")) 11824 return false; 11825 } 11826 11827 // Ignore any parens, implicit casts (should only be 11828 // array-to-pointer decays), and not-so-opaque values. The last is 11829 // important for making this trigger for property assignments. 11830 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 11831 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 11832 if (OV->getSourceExpr()) 11833 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 11834 11835 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 11836 if (!SL || !SL->isAscii()) 11837 return false; 11838 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix) 11839 << FixItHint::CreateInsertion(SL->getLocStart(), "@"); 11840 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get(); 11841 return true; 11842 } 11843 11844 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 11845 const Expr *SrcExpr) { 11846 if (!DstType->isFunctionPointerType() || 11847 !SrcExpr->getType()->isFunctionType()) 11848 return false; 11849 11850 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 11851 if (!DRE) 11852 return false; 11853 11854 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 11855 if (!FD) 11856 return false; 11857 11858 return !S.checkAddressOfFunctionIsAvailable(FD, 11859 /*Complain=*/true, 11860 SrcExpr->getLocStart()); 11861 } 11862 11863 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 11864 SourceLocation Loc, 11865 QualType DstType, QualType SrcType, 11866 Expr *SrcExpr, AssignmentAction Action, 11867 bool *Complained) { 11868 if (Complained) 11869 *Complained = false; 11870 11871 // Decode the result (notice that AST's are still created for extensions). 11872 bool CheckInferredResultType = false; 11873 bool isInvalid = false; 11874 unsigned DiagKind = 0; 11875 FixItHint Hint; 11876 ConversionFixItGenerator ConvHints; 11877 bool MayHaveConvFixit = false; 11878 bool MayHaveFunctionDiff = false; 11879 const ObjCInterfaceDecl *IFace = nullptr; 11880 const ObjCProtocolDecl *PDecl = nullptr; 11881 11882 switch (ConvTy) { 11883 case Compatible: 11884 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 11885 return false; 11886 11887 case PointerToInt: 11888 DiagKind = diag::ext_typecheck_convert_pointer_int; 11889 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11890 MayHaveConvFixit = true; 11891 break; 11892 case IntToPointer: 11893 DiagKind = diag::ext_typecheck_convert_int_pointer; 11894 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11895 MayHaveConvFixit = true; 11896 break; 11897 case IncompatiblePointer: 11898 DiagKind = 11899 (Action == AA_Passing_CFAudited ? 11900 diag::err_arc_typecheck_convert_incompatible_pointer : 11901 diag::ext_typecheck_convert_incompatible_pointer); 11902 CheckInferredResultType = DstType->isObjCObjectPointerType() && 11903 SrcType->isObjCObjectPointerType(); 11904 if (Hint.isNull() && !CheckInferredResultType) { 11905 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 11906 } 11907 else if (CheckInferredResultType) { 11908 SrcType = SrcType.getUnqualifiedType(); 11909 DstType = DstType.getUnqualifiedType(); 11910 } 11911 MayHaveConvFixit = true; 11912 break; 11913 case IncompatiblePointerSign: 11914 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 11915 break; 11916 case FunctionVoidPointer: 11917 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 11918 break; 11919 case IncompatiblePointerDiscardsQualifiers: { 11920 // Perform array-to-pointer decay if necessary. 11921 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 11922 11923 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 11924 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 11925 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 11926 DiagKind = diag::err_typecheck_incompatible_address_space; 11927 break; 11928 11929 11930 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 11931 DiagKind = diag::err_typecheck_incompatible_ownership; 11932 break; 11933 } 11934 11935 llvm_unreachable("unknown error case for discarding qualifiers!"); 11936 // fallthrough 11937 } 11938 case CompatiblePointerDiscardsQualifiers: 11939 // If the qualifiers lost were because we were applying the 11940 // (deprecated) C++ conversion from a string literal to a char* 11941 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 11942 // Ideally, this check would be performed in 11943 // checkPointerTypesForAssignment. However, that would require a 11944 // bit of refactoring (so that the second argument is an 11945 // expression, rather than a type), which should be done as part 11946 // of a larger effort to fix checkPointerTypesForAssignment for 11947 // C++ semantics. 11948 if (getLangOpts().CPlusPlus && 11949 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 11950 return false; 11951 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 11952 break; 11953 case IncompatibleNestedPointerQualifiers: 11954 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 11955 break; 11956 case IntToBlockPointer: 11957 DiagKind = diag::err_int_to_block_pointer; 11958 break; 11959 case IncompatibleBlockPointer: 11960 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 11961 break; 11962 case IncompatibleObjCQualifiedId: { 11963 if (SrcType->isObjCQualifiedIdType()) { 11964 const ObjCObjectPointerType *srcOPT = 11965 SrcType->getAs<ObjCObjectPointerType>(); 11966 for (auto *srcProto : srcOPT->quals()) { 11967 PDecl = srcProto; 11968 break; 11969 } 11970 if (const ObjCInterfaceType *IFaceT = 11971 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 11972 IFace = IFaceT->getDecl(); 11973 } 11974 else if (DstType->isObjCQualifiedIdType()) { 11975 const ObjCObjectPointerType *dstOPT = 11976 DstType->getAs<ObjCObjectPointerType>(); 11977 for (auto *dstProto : dstOPT->quals()) { 11978 PDecl = dstProto; 11979 break; 11980 } 11981 if (const ObjCInterfaceType *IFaceT = 11982 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 11983 IFace = IFaceT->getDecl(); 11984 } 11985 DiagKind = diag::warn_incompatible_qualified_id; 11986 break; 11987 } 11988 case IncompatibleVectors: 11989 DiagKind = diag::warn_incompatible_vectors; 11990 break; 11991 case IncompatibleObjCWeakRef: 11992 DiagKind = diag::err_arc_weak_unavailable_assign; 11993 break; 11994 case Incompatible: 11995 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 11996 if (Complained) 11997 *Complained = true; 11998 return true; 11999 } 12000 12001 DiagKind = diag::err_typecheck_convert_incompatible; 12002 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 12003 MayHaveConvFixit = true; 12004 isInvalid = true; 12005 MayHaveFunctionDiff = true; 12006 break; 12007 } 12008 12009 QualType FirstType, SecondType; 12010 switch (Action) { 12011 case AA_Assigning: 12012 case AA_Initializing: 12013 // The destination type comes first. 12014 FirstType = DstType; 12015 SecondType = SrcType; 12016 break; 12017 12018 case AA_Returning: 12019 case AA_Passing: 12020 case AA_Passing_CFAudited: 12021 case AA_Converting: 12022 case AA_Sending: 12023 case AA_Casting: 12024 // The source type comes first. 12025 FirstType = SrcType; 12026 SecondType = DstType; 12027 break; 12028 } 12029 12030 PartialDiagnostic FDiag = PDiag(DiagKind); 12031 if (Action == AA_Passing_CFAudited) 12032 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 12033 else 12034 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 12035 12036 // If we can fix the conversion, suggest the FixIts. 12037 assert(ConvHints.isNull() || Hint.isNull()); 12038 if (!ConvHints.isNull()) { 12039 for (FixItHint &H : ConvHints.Hints) 12040 FDiag << H; 12041 } else { 12042 FDiag << Hint; 12043 } 12044 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 12045 12046 if (MayHaveFunctionDiff) 12047 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 12048 12049 Diag(Loc, FDiag); 12050 if (DiagKind == diag::warn_incompatible_qualified_id && 12051 PDecl && IFace && !IFace->hasDefinition()) 12052 Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id) 12053 << IFace->getName() << PDecl->getName(); 12054 12055 if (SecondType == Context.OverloadTy) 12056 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 12057 FirstType, /*TakingAddress=*/true); 12058 12059 if (CheckInferredResultType) 12060 EmitRelatedResultTypeNote(SrcExpr); 12061 12062 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 12063 EmitRelatedResultTypeNoteForReturn(DstType); 12064 12065 if (Complained) 12066 *Complained = true; 12067 return isInvalid; 12068 } 12069 12070 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12071 llvm::APSInt *Result) { 12072 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 12073 public: 12074 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12075 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 12076 } 12077 } Diagnoser; 12078 12079 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 12080 } 12081 12082 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 12083 llvm::APSInt *Result, 12084 unsigned DiagID, 12085 bool AllowFold) { 12086 class IDDiagnoser : public VerifyICEDiagnoser { 12087 unsigned DiagID; 12088 12089 public: 12090 IDDiagnoser(unsigned DiagID) 12091 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 12092 12093 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 12094 S.Diag(Loc, DiagID) << SR; 12095 } 12096 } Diagnoser(DiagID); 12097 12098 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 12099 } 12100 12101 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 12102 SourceRange SR) { 12103 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 12104 } 12105 12106 ExprResult 12107 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 12108 VerifyICEDiagnoser &Diagnoser, 12109 bool AllowFold) { 12110 SourceLocation DiagLoc = E->getLocStart(); 12111 12112 if (getLangOpts().CPlusPlus11) { 12113 // C++11 [expr.const]p5: 12114 // If an expression of literal class type is used in a context where an 12115 // integral constant expression is required, then that class type shall 12116 // have a single non-explicit conversion function to an integral or 12117 // unscoped enumeration type 12118 ExprResult Converted; 12119 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 12120 public: 12121 CXX11ConvertDiagnoser(bool Silent) 12122 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 12123 Silent, true) {} 12124 12125 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 12126 QualType T) override { 12127 return S.Diag(Loc, diag::err_ice_not_integral) << T; 12128 } 12129 12130 SemaDiagnosticBuilder diagnoseIncomplete( 12131 Sema &S, SourceLocation Loc, QualType T) override { 12132 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 12133 } 12134 12135 SemaDiagnosticBuilder diagnoseExplicitConv( 12136 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12137 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 12138 } 12139 12140 SemaDiagnosticBuilder noteExplicitConv( 12141 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12142 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12143 << ConvTy->isEnumeralType() << ConvTy; 12144 } 12145 12146 SemaDiagnosticBuilder diagnoseAmbiguous( 12147 Sema &S, SourceLocation Loc, QualType T) override { 12148 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 12149 } 12150 12151 SemaDiagnosticBuilder noteAmbiguous( 12152 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 12153 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 12154 << ConvTy->isEnumeralType() << ConvTy; 12155 } 12156 12157 SemaDiagnosticBuilder diagnoseConversion( 12158 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 12159 llvm_unreachable("conversion functions are permitted"); 12160 } 12161 } ConvertDiagnoser(Diagnoser.Suppress); 12162 12163 Converted = PerformContextualImplicitConversion(DiagLoc, E, 12164 ConvertDiagnoser); 12165 if (Converted.isInvalid()) 12166 return Converted; 12167 E = Converted.get(); 12168 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 12169 return ExprError(); 12170 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 12171 // An ICE must be of integral or unscoped enumeration type. 12172 if (!Diagnoser.Suppress) 12173 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12174 return ExprError(); 12175 } 12176 12177 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 12178 // in the non-ICE case. 12179 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 12180 if (Result) 12181 *Result = E->EvaluateKnownConstInt(Context); 12182 return E; 12183 } 12184 12185 Expr::EvalResult EvalResult; 12186 SmallVector<PartialDiagnosticAt, 8> Notes; 12187 EvalResult.Diag = &Notes; 12188 12189 // Try to evaluate the expression, and produce diagnostics explaining why it's 12190 // not a constant expression as a side-effect. 12191 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 12192 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 12193 12194 // In C++11, we can rely on diagnostics being produced for any expression 12195 // which is not a constant expression. If no diagnostics were produced, then 12196 // this is a constant expression. 12197 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 12198 if (Result) 12199 *Result = EvalResult.Val.getInt(); 12200 return E; 12201 } 12202 12203 // If our only note is the usual "invalid subexpression" note, just point 12204 // the caret at its location rather than producing an essentially 12205 // redundant note. 12206 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12207 diag::note_invalid_subexpr_in_const_expr) { 12208 DiagLoc = Notes[0].first; 12209 Notes.clear(); 12210 } 12211 12212 if (!Folded || !AllowFold) { 12213 if (!Diagnoser.Suppress) { 12214 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 12215 for (const PartialDiagnosticAt &Note : Notes) 12216 Diag(Note.first, Note.second); 12217 } 12218 12219 return ExprError(); 12220 } 12221 12222 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 12223 for (const PartialDiagnosticAt &Note : Notes) 12224 Diag(Note.first, Note.second); 12225 12226 if (Result) 12227 *Result = EvalResult.Val.getInt(); 12228 return E; 12229 } 12230 12231 namespace { 12232 // Handle the case where we conclude a expression which we speculatively 12233 // considered to be unevaluated is actually evaluated. 12234 class TransformToPE : public TreeTransform<TransformToPE> { 12235 typedef TreeTransform<TransformToPE> BaseTransform; 12236 12237 public: 12238 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 12239 12240 // Make sure we redo semantic analysis 12241 bool AlwaysRebuild() { return true; } 12242 12243 // Make sure we handle LabelStmts correctly. 12244 // FIXME: This does the right thing, but maybe we need a more general 12245 // fix to TreeTransform? 12246 StmtResult TransformLabelStmt(LabelStmt *S) { 12247 S->getDecl()->setStmt(nullptr); 12248 return BaseTransform::TransformLabelStmt(S); 12249 } 12250 12251 // We need to special-case DeclRefExprs referring to FieldDecls which 12252 // are not part of a member pointer formation; normal TreeTransforming 12253 // doesn't catch this case because of the way we represent them in the AST. 12254 // FIXME: This is a bit ugly; is it really the best way to handle this 12255 // case? 12256 // 12257 // Error on DeclRefExprs referring to FieldDecls. 12258 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 12259 if (isa<FieldDecl>(E->getDecl()) && 12260 !SemaRef.isUnevaluatedContext()) 12261 return SemaRef.Diag(E->getLocation(), 12262 diag::err_invalid_non_static_member_use) 12263 << E->getDecl() << E->getSourceRange(); 12264 12265 return BaseTransform::TransformDeclRefExpr(E); 12266 } 12267 12268 // Exception: filter out member pointer formation 12269 ExprResult TransformUnaryOperator(UnaryOperator *E) { 12270 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 12271 return E; 12272 12273 return BaseTransform::TransformUnaryOperator(E); 12274 } 12275 12276 ExprResult TransformLambdaExpr(LambdaExpr *E) { 12277 // Lambdas never need to be transformed. 12278 return E; 12279 } 12280 }; 12281 } 12282 12283 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 12284 assert(isUnevaluatedContext() && 12285 "Should only transform unevaluated expressions"); 12286 ExprEvalContexts.back().Context = 12287 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 12288 if (isUnevaluatedContext()) 12289 return E; 12290 return TransformToPE(*this).TransformExpr(E); 12291 } 12292 12293 void 12294 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12295 Decl *LambdaContextDecl, 12296 bool IsDecltype) { 12297 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), 12298 ExprNeedsCleanups, LambdaContextDecl, 12299 IsDecltype); 12300 ExprNeedsCleanups = false; 12301 if (!MaybeODRUseExprs.empty()) 12302 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 12303 } 12304 12305 void 12306 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 12307 ReuseLambdaContextDecl_t, 12308 bool IsDecltype) { 12309 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 12310 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype); 12311 } 12312 12313 void Sema::PopExpressionEvaluationContext() { 12314 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 12315 unsigned NumTypos = Rec.NumTypos; 12316 12317 if (!Rec.Lambdas.empty()) { 12318 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12319 unsigned D; 12320 if (Rec.isUnevaluated()) { 12321 // C++11 [expr.prim.lambda]p2: 12322 // A lambda-expression shall not appear in an unevaluated operand 12323 // (Clause 5). 12324 D = diag::err_lambda_unevaluated_operand; 12325 } else { 12326 // C++1y [expr.const]p2: 12327 // A conditional-expression e is a core constant expression unless the 12328 // evaluation of e, following the rules of the abstract machine, would 12329 // evaluate [...] a lambda-expression. 12330 D = diag::err_lambda_in_constant_expression; 12331 } 12332 for (const auto *L : Rec.Lambdas) 12333 Diag(L->getLocStart(), D); 12334 } else { 12335 // Mark the capture expressions odr-used. This was deferred 12336 // during lambda expression creation. 12337 for (auto *Lambda : Rec.Lambdas) { 12338 for (auto *C : Lambda->capture_inits()) 12339 MarkDeclarationsReferencedInExpr(C); 12340 } 12341 } 12342 } 12343 12344 // When are coming out of an unevaluated context, clear out any 12345 // temporaries that we may have created as part of the evaluation of 12346 // the expression in that context: they aren't relevant because they 12347 // will never be constructed. 12348 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) { 12349 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 12350 ExprCleanupObjects.end()); 12351 ExprNeedsCleanups = Rec.ParentNeedsCleanups; 12352 CleanupVarDeclMarking(); 12353 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 12354 // Otherwise, merge the contexts together. 12355 } else { 12356 ExprNeedsCleanups |= Rec.ParentNeedsCleanups; 12357 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 12358 Rec.SavedMaybeODRUseExprs.end()); 12359 } 12360 12361 // Pop the current expression evaluation context off the stack. 12362 ExprEvalContexts.pop_back(); 12363 12364 if (!ExprEvalContexts.empty()) 12365 ExprEvalContexts.back().NumTypos += NumTypos; 12366 else 12367 assert(NumTypos == 0 && "There are outstanding typos after popping the " 12368 "last ExpressionEvaluationContextRecord"); 12369 } 12370 12371 void Sema::DiscardCleanupsInEvaluationContext() { 12372 ExprCleanupObjects.erase( 12373 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 12374 ExprCleanupObjects.end()); 12375 ExprNeedsCleanups = false; 12376 MaybeODRUseExprs.clear(); 12377 } 12378 12379 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 12380 if (!E->getType()->isVariablyModifiedType()) 12381 return E; 12382 return TransformToPotentiallyEvaluated(E); 12383 } 12384 12385 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) { 12386 // Do not mark anything as "used" within a dependent context; wait for 12387 // an instantiation. 12388 if (SemaRef.CurContext->isDependentContext()) 12389 return false; 12390 12391 switch (SemaRef.ExprEvalContexts.back().Context) { 12392 case Sema::Unevaluated: 12393 case Sema::UnevaluatedAbstract: 12394 // We are in an expression that is not potentially evaluated; do nothing. 12395 // (Depending on how you read the standard, we actually do need to do 12396 // something here for null pointer constants, but the standard's 12397 // definition of a null pointer constant is completely crazy.) 12398 return false; 12399 12400 case Sema::ConstantEvaluated: 12401 case Sema::PotentiallyEvaluated: 12402 // We are in a potentially evaluated expression (or a constant-expression 12403 // in C++03); we need to do implicit template instantiation, implicitly 12404 // define class members, and mark most declarations as used. 12405 return true; 12406 12407 case Sema::PotentiallyEvaluatedIfUsed: 12408 // Referenced declarations will only be used if the construct in the 12409 // containing expression is used. 12410 return false; 12411 } 12412 llvm_unreachable("Invalid context"); 12413 } 12414 12415 /// \brief Mark a function referenced, and check whether it is odr-used 12416 /// (C++ [basic.def.odr]p2, C99 6.9p3) 12417 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 12418 bool OdrUse) { 12419 assert(Func && "No function?"); 12420 12421 Func->setReferenced(); 12422 12423 // C++11 [basic.def.odr]p3: 12424 // A function whose name appears as a potentially-evaluated expression is 12425 // odr-used if it is the unique lookup result or the selected member of a 12426 // set of overloaded functions [...]. 12427 // 12428 // We (incorrectly) mark overload resolution as an unevaluated context, so we 12429 // can just check that here. Skip the rest of this function if we've already 12430 // marked the function as used. 12431 if (Func->isUsed(/*CheckUsedAttr=*/false) || 12432 !IsPotentiallyEvaluatedContext(*this)) { 12433 // C++11 [temp.inst]p3: 12434 // Unless a function template specialization has been explicitly 12435 // instantiated or explicitly specialized, the function template 12436 // specialization is implicitly instantiated when the specialization is 12437 // referenced in a context that requires a function definition to exist. 12438 // 12439 // We consider constexpr function templates to be referenced in a context 12440 // that requires a definition to exist whenever they are referenced. 12441 // 12442 // FIXME: This instantiates constexpr functions too frequently. If this is 12443 // really an unevaluated context (and we're not just in the definition of a 12444 // function template or overload resolution or other cases which we 12445 // incorrectly consider to be unevaluated contexts), and we're not in a 12446 // subexpression which we actually need to evaluate (for instance, a 12447 // template argument, array bound or an expression in a braced-init-list), 12448 // we are not permitted to instantiate this constexpr function definition. 12449 // 12450 // FIXME: This also implicitly defines special members too frequently. They 12451 // are only supposed to be implicitly defined if they are odr-used, but they 12452 // are not odr-used from constant expressions in unevaluated contexts. 12453 // However, they cannot be referenced if they are deleted, and they are 12454 // deleted whenever the implicit definition of the special member would 12455 // fail. 12456 if (!Func->isConstexpr() || Func->getBody()) 12457 return; 12458 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 12459 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided())) 12460 return; 12461 } 12462 12463 // Note that this declaration has been used. 12464 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 12465 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 12466 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 12467 if (Constructor->isDefaultConstructor()) { 12468 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 12469 return; 12470 DefineImplicitDefaultConstructor(Loc, Constructor); 12471 } else if (Constructor->isCopyConstructor()) { 12472 DefineImplicitCopyConstructor(Loc, Constructor); 12473 } else if (Constructor->isMoveConstructor()) { 12474 DefineImplicitMoveConstructor(Loc, Constructor); 12475 } 12476 } else if (Constructor->getInheritedConstructor()) { 12477 DefineInheritingConstructor(Loc, Constructor); 12478 } 12479 } else if (CXXDestructorDecl *Destructor = 12480 dyn_cast<CXXDestructorDecl>(Func)) { 12481 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 12482 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 12483 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 12484 return; 12485 DefineImplicitDestructor(Loc, Destructor); 12486 } 12487 if (Destructor->isVirtual() && getLangOpts().AppleKext) 12488 MarkVTableUsed(Loc, Destructor->getParent()); 12489 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 12490 if (MethodDecl->isOverloadedOperator() && 12491 MethodDecl->getOverloadedOperator() == OO_Equal) { 12492 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 12493 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 12494 if (MethodDecl->isCopyAssignmentOperator()) 12495 DefineImplicitCopyAssignment(Loc, MethodDecl); 12496 else 12497 DefineImplicitMoveAssignment(Loc, MethodDecl); 12498 } 12499 } else if (isa<CXXConversionDecl>(MethodDecl) && 12500 MethodDecl->getParent()->isLambda()) { 12501 CXXConversionDecl *Conversion = 12502 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 12503 if (Conversion->isLambdaToBlockPointerConversion()) 12504 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 12505 else 12506 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 12507 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 12508 MarkVTableUsed(Loc, MethodDecl->getParent()); 12509 } 12510 12511 // Recursive functions should be marked when used from another function. 12512 // FIXME: Is this really right? 12513 if (CurContext == Func) return; 12514 12515 // Resolve the exception specification for any function which is 12516 // used: CodeGen will need it. 12517 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 12518 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 12519 ResolveExceptionSpec(Loc, FPT); 12520 12521 if (!OdrUse) return; 12522 12523 // Implicit instantiation of function templates and member functions of 12524 // class templates. 12525 if (Func->isImplicitlyInstantiable()) { 12526 bool AlreadyInstantiated = false; 12527 SourceLocation PointOfInstantiation = Loc; 12528 if (FunctionTemplateSpecializationInfo *SpecInfo 12529 = Func->getTemplateSpecializationInfo()) { 12530 if (SpecInfo->getPointOfInstantiation().isInvalid()) 12531 SpecInfo->setPointOfInstantiation(Loc); 12532 else if (SpecInfo->getTemplateSpecializationKind() 12533 == TSK_ImplicitInstantiation) { 12534 AlreadyInstantiated = true; 12535 PointOfInstantiation = SpecInfo->getPointOfInstantiation(); 12536 } 12537 } else if (MemberSpecializationInfo *MSInfo 12538 = Func->getMemberSpecializationInfo()) { 12539 if (MSInfo->getPointOfInstantiation().isInvalid()) 12540 MSInfo->setPointOfInstantiation(Loc); 12541 else if (MSInfo->getTemplateSpecializationKind() 12542 == TSK_ImplicitInstantiation) { 12543 AlreadyInstantiated = true; 12544 PointOfInstantiation = MSInfo->getPointOfInstantiation(); 12545 } 12546 } 12547 12548 if (!AlreadyInstantiated || Func->isConstexpr()) { 12549 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 12550 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 12551 ActiveTemplateInstantiations.size()) 12552 PendingLocalImplicitInstantiations.push_back( 12553 std::make_pair(Func, PointOfInstantiation)); 12554 else if (Func->isConstexpr()) 12555 // Do not defer instantiations of constexpr functions, to avoid the 12556 // expression evaluator needing to call back into Sema if it sees a 12557 // call to such a function. 12558 InstantiateFunctionDefinition(PointOfInstantiation, Func); 12559 else { 12560 PendingInstantiations.push_back(std::make_pair(Func, 12561 PointOfInstantiation)); 12562 // Notify the consumer that a function was implicitly instantiated. 12563 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 12564 } 12565 } 12566 } else { 12567 // Walk redefinitions, as some of them may be instantiable. 12568 for (auto i : Func->redecls()) { 12569 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 12570 MarkFunctionReferenced(Loc, i); 12571 } 12572 } 12573 12574 // Keep track of used but undefined functions. 12575 if (!Func->isDefined()) { 12576 if (mightHaveNonExternalLinkage(Func)) 12577 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 12578 else if (Func->getMostRecentDecl()->isInlined() && 12579 !LangOpts.GNUInline && 12580 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 12581 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 12582 } 12583 12584 // Normally the most current decl is marked used while processing the use and 12585 // any subsequent decls are marked used by decl merging. This fails with 12586 // template instantiation since marking can happen at the end of the file 12587 // and, because of the two phase lookup, this function is called with at 12588 // decl in the middle of a decl chain. We loop to maintain the invariant 12589 // that once a decl is used, all decls after it are also used. 12590 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) { 12591 F->markUsed(Context); 12592 if (F == Func) 12593 break; 12594 } 12595 } 12596 12597 static void 12598 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 12599 VarDecl *var, DeclContext *DC) { 12600 DeclContext *VarDC = var->getDeclContext(); 12601 12602 // If the parameter still belongs to the translation unit, then 12603 // we're actually just using one parameter in the declaration of 12604 // the next. 12605 if (isa<ParmVarDecl>(var) && 12606 isa<TranslationUnitDecl>(VarDC)) 12607 return; 12608 12609 // For C code, don't diagnose about capture if we're not actually in code 12610 // right now; it's impossible to write a non-constant expression outside of 12611 // function context, so we'll get other (more useful) diagnostics later. 12612 // 12613 // For C++, things get a bit more nasty... it would be nice to suppress this 12614 // diagnostic for certain cases like using a local variable in an array bound 12615 // for a member of a local class, but the correct predicate is not obvious. 12616 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 12617 return; 12618 12619 if (isa<CXXMethodDecl>(VarDC) && 12620 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 12621 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda) 12622 << var->getIdentifier(); 12623 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) { 12624 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function) 12625 << var->getIdentifier() << fn->getDeclName(); 12626 } else if (isa<BlockDecl>(VarDC)) { 12627 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block) 12628 << var->getIdentifier(); 12629 } else { 12630 // FIXME: Is there any other context where a local variable can be 12631 // declared? 12632 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context) 12633 << var->getIdentifier(); 12634 } 12635 12636 S.Diag(var->getLocation(), diag::note_entity_declared_at) 12637 << var->getIdentifier(); 12638 12639 // FIXME: Add additional diagnostic info about class etc. which prevents 12640 // capture. 12641 } 12642 12643 12644 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 12645 bool &SubCapturesAreNested, 12646 QualType &CaptureType, 12647 QualType &DeclRefType) { 12648 // Check whether we've already captured it. 12649 if (CSI->CaptureMap.count(Var)) { 12650 // If we found a capture, any subcaptures are nested. 12651 SubCapturesAreNested = true; 12652 12653 // Retrieve the capture type for this variable. 12654 CaptureType = CSI->getCapture(Var).getCaptureType(); 12655 12656 // Compute the type of an expression that refers to this variable. 12657 DeclRefType = CaptureType.getNonReferenceType(); 12658 12659 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 12660 // are mutable in the sense that user can change their value - they are 12661 // private instances of the captured declarations. 12662 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var); 12663 if (Cap.isCopyCapture() && 12664 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 12665 !(isa<CapturedRegionScopeInfo>(CSI) && 12666 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 12667 DeclRefType.addConst(); 12668 return true; 12669 } 12670 return false; 12671 } 12672 12673 // Only block literals, captured statements, and lambda expressions can 12674 // capture; other scopes don't work. 12675 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 12676 SourceLocation Loc, 12677 const bool Diagnose, Sema &S) { 12678 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 12679 return getLambdaAwareParentOfDeclContext(DC); 12680 else if (Var->hasLocalStorage()) { 12681 if (Diagnose) 12682 diagnoseUncapturableValueReference(S, Loc, Var, DC); 12683 } 12684 return nullptr; 12685 } 12686 12687 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 12688 // certain types of variables (unnamed, variably modified types etc.) 12689 // so check for eligibility. 12690 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 12691 SourceLocation Loc, 12692 const bool Diagnose, Sema &S) { 12693 12694 bool IsBlock = isa<BlockScopeInfo>(CSI); 12695 bool IsLambda = isa<LambdaScopeInfo>(CSI); 12696 12697 // Lambdas are not allowed to capture unnamed variables 12698 // (e.g. anonymous unions). 12699 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 12700 // assuming that's the intent. 12701 if (IsLambda && !Var->getDeclName()) { 12702 if (Diagnose) { 12703 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 12704 S.Diag(Var->getLocation(), diag::note_declared_at); 12705 } 12706 return false; 12707 } 12708 12709 // Prohibit variably-modified types in blocks; they're difficult to deal with. 12710 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 12711 if (Diagnose) { 12712 S.Diag(Loc, diag::err_ref_vm_type); 12713 S.Diag(Var->getLocation(), diag::note_previous_decl) 12714 << Var->getDeclName(); 12715 } 12716 return false; 12717 } 12718 // Prohibit structs with flexible array members too. 12719 // We cannot capture what is in the tail end of the struct. 12720 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 12721 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 12722 if (Diagnose) { 12723 if (IsBlock) 12724 S.Diag(Loc, diag::err_ref_flexarray_type); 12725 else 12726 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 12727 << Var->getDeclName(); 12728 S.Diag(Var->getLocation(), diag::note_previous_decl) 12729 << Var->getDeclName(); 12730 } 12731 return false; 12732 } 12733 } 12734 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 12735 // Lambdas and captured statements are not allowed to capture __block 12736 // variables; they don't support the expected semantics. 12737 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 12738 if (Diagnose) { 12739 S.Diag(Loc, diag::err_capture_block_variable) 12740 << Var->getDeclName() << !IsLambda; 12741 S.Diag(Var->getLocation(), diag::note_previous_decl) 12742 << Var->getDeclName(); 12743 } 12744 return false; 12745 } 12746 12747 return true; 12748 } 12749 12750 // Returns true if the capture by block was successful. 12751 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 12752 SourceLocation Loc, 12753 const bool BuildAndDiagnose, 12754 QualType &CaptureType, 12755 QualType &DeclRefType, 12756 const bool Nested, 12757 Sema &S) { 12758 Expr *CopyExpr = nullptr; 12759 bool ByRef = false; 12760 12761 // Blocks are not allowed to capture arrays. 12762 if (CaptureType->isArrayType()) { 12763 if (BuildAndDiagnose) { 12764 S.Diag(Loc, diag::err_ref_array_type); 12765 S.Diag(Var->getLocation(), diag::note_previous_decl) 12766 << Var->getDeclName(); 12767 } 12768 return false; 12769 } 12770 12771 // Forbid the block-capture of autoreleasing variables. 12772 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 12773 if (BuildAndDiagnose) { 12774 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 12775 << /*block*/ 0; 12776 S.Diag(Var->getLocation(), diag::note_previous_decl) 12777 << Var->getDeclName(); 12778 } 12779 return false; 12780 } 12781 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 12782 if (HasBlocksAttr || CaptureType->isReferenceType()) { 12783 // Block capture by reference does not change the capture or 12784 // declaration reference types. 12785 ByRef = true; 12786 } else { 12787 // Block capture by copy introduces 'const'. 12788 CaptureType = CaptureType.getNonReferenceType().withConst(); 12789 DeclRefType = CaptureType; 12790 12791 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 12792 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 12793 // The capture logic needs the destructor, so make sure we mark it. 12794 // Usually this is unnecessary because most local variables have 12795 // their destructors marked at declaration time, but parameters are 12796 // an exception because it's technically only the call site that 12797 // actually requires the destructor. 12798 if (isa<ParmVarDecl>(Var)) 12799 S.FinalizeVarWithDestructor(Var, Record); 12800 12801 // Enter a new evaluation context to insulate the copy 12802 // full-expression. 12803 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated); 12804 12805 // According to the blocks spec, the capture of a variable from 12806 // the stack requires a const copy constructor. This is not true 12807 // of the copy/move done to move a __block variable to the heap. 12808 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 12809 DeclRefType.withConst(), 12810 VK_LValue, Loc); 12811 12812 ExprResult Result 12813 = S.PerformCopyInitialization( 12814 InitializedEntity::InitializeBlock(Var->getLocation(), 12815 CaptureType, false), 12816 Loc, DeclRef); 12817 12818 // Build a full-expression copy expression if initialization 12819 // succeeded and used a non-trivial constructor. Recover from 12820 // errors by pretending that the copy isn't necessary. 12821 if (!Result.isInvalid() && 12822 !cast<CXXConstructExpr>(Result.get())->getConstructor() 12823 ->isTrivial()) { 12824 Result = S.MaybeCreateExprWithCleanups(Result); 12825 CopyExpr = Result.get(); 12826 } 12827 } 12828 } 12829 } 12830 12831 // Actually capture the variable. 12832 if (BuildAndDiagnose) 12833 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 12834 SourceLocation(), CaptureType, CopyExpr); 12835 12836 return true; 12837 12838 } 12839 12840 12841 /// \brief Capture the given variable in the captured region. 12842 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 12843 VarDecl *Var, 12844 SourceLocation Loc, 12845 const bool BuildAndDiagnose, 12846 QualType &CaptureType, 12847 QualType &DeclRefType, 12848 const bool RefersToCapturedVariable, 12849 Sema &S) { 12850 12851 // By default, capture variables by reference. 12852 bool ByRef = true; 12853 // Using an LValue reference type is consistent with Lambdas (see below). 12854 if (S.getLangOpts().OpenMP) { 12855 ByRef = S.IsOpenMPCapturedByRef(Var, RSI); 12856 if (S.IsOpenMPCapturedVar(Var)) 12857 DeclRefType = DeclRefType.getUnqualifiedType(); 12858 } 12859 12860 if (ByRef) 12861 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 12862 else 12863 CaptureType = DeclRefType; 12864 12865 Expr *CopyExpr = nullptr; 12866 if (BuildAndDiagnose) { 12867 // The current implementation assumes that all variables are captured 12868 // by references. Since there is no capture by copy, no expression 12869 // evaluation will be needed. 12870 RecordDecl *RD = RSI->TheRecordDecl; 12871 12872 FieldDecl *Field 12873 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 12874 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 12875 nullptr, false, ICIS_NoInit); 12876 Field->setImplicit(true); 12877 Field->setAccess(AS_private); 12878 RD->addDecl(Field); 12879 12880 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 12881 DeclRefType, VK_LValue, Loc); 12882 Var->setReferenced(true); 12883 Var->markUsed(S.Context); 12884 } 12885 12886 // Actually capture the variable. 12887 if (BuildAndDiagnose) 12888 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 12889 SourceLocation(), CaptureType, CopyExpr); 12890 12891 12892 return true; 12893 } 12894 12895 /// \brief Create a field within the lambda class for the variable 12896 /// being captured. 12897 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, VarDecl *Var, 12898 QualType FieldType, QualType DeclRefType, 12899 SourceLocation Loc, 12900 bool RefersToCapturedVariable) { 12901 CXXRecordDecl *Lambda = LSI->Lambda; 12902 12903 // Build the non-static data member. 12904 FieldDecl *Field 12905 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 12906 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 12907 nullptr, false, ICIS_NoInit); 12908 Field->setImplicit(true); 12909 Field->setAccess(AS_private); 12910 Lambda->addDecl(Field); 12911 } 12912 12913 /// \brief Capture the given variable in the lambda. 12914 static bool captureInLambda(LambdaScopeInfo *LSI, 12915 VarDecl *Var, 12916 SourceLocation Loc, 12917 const bool BuildAndDiagnose, 12918 QualType &CaptureType, 12919 QualType &DeclRefType, 12920 const bool RefersToCapturedVariable, 12921 const Sema::TryCaptureKind Kind, 12922 SourceLocation EllipsisLoc, 12923 const bool IsTopScope, 12924 Sema &S) { 12925 12926 // Determine whether we are capturing by reference or by value. 12927 bool ByRef = false; 12928 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 12929 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 12930 } else { 12931 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 12932 } 12933 12934 // Compute the type of the field that will capture this variable. 12935 if (ByRef) { 12936 // C++11 [expr.prim.lambda]p15: 12937 // An entity is captured by reference if it is implicitly or 12938 // explicitly captured but not captured by copy. It is 12939 // unspecified whether additional unnamed non-static data 12940 // members are declared in the closure type for entities 12941 // captured by reference. 12942 // 12943 // FIXME: It is not clear whether we want to build an lvalue reference 12944 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 12945 // to do the former, while EDG does the latter. Core issue 1249 will 12946 // clarify, but for now we follow GCC because it's a more permissive and 12947 // easily defensible position. 12948 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 12949 } else { 12950 // C++11 [expr.prim.lambda]p14: 12951 // For each entity captured by copy, an unnamed non-static 12952 // data member is declared in the closure type. The 12953 // declaration order of these members is unspecified. The type 12954 // of such a data member is the type of the corresponding 12955 // captured entity if the entity is not a reference to an 12956 // object, or the referenced type otherwise. [Note: If the 12957 // captured entity is a reference to a function, the 12958 // corresponding data member is also a reference to a 12959 // function. - end note ] 12960 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 12961 if (!RefType->getPointeeType()->isFunctionType()) 12962 CaptureType = RefType->getPointeeType(); 12963 } 12964 12965 // Forbid the lambda copy-capture of autoreleasing variables. 12966 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 12967 if (BuildAndDiagnose) { 12968 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 12969 S.Diag(Var->getLocation(), diag::note_previous_decl) 12970 << Var->getDeclName(); 12971 } 12972 return false; 12973 } 12974 12975 // Make sure that by-copy captures are of a complete and non-abstract type. 12976 if (BuildAndDiagnose) { 12977 if (!CaptureType->isDependentType() && 12978 S.RequireCompleteType(Loc, CaptureType, 12979 diag::err_capture_of_incomplete_type, 12980 Var->getDeclName())) 12981 return false; 12982 12983 if (S.RequireNonAbstractType(Loc, CaptureType, 12984 diag::err_capture_of_abstract_type)) 12985 return false; 12986 } 12987 } 12988 12989 // Capture this variable in the lambda. 12990 if (BuildAndDiagnose) 12991 addAsFieldToClosureType(S, LSI, Var, CaptureType, DeclRefType, Loc, 12992 RefersToCapturedVariable); 12993 12994 // Compute the type of a reference to this captured variable. 12995 if (ByRef) 12996 DeclRefType = CaptureType.getNonReferenceType(); 12997 else { 12998 // C++ [expr.prim.lambda]p5: 12999 // The closure type for a lambda-expression has a public inline 13000 // function call operator [...]. This function call operator is 13001 // declared const (9.3.1) if and only if the lambda-expression’s 13002 // parameter-declaration-clause is not followed by mutable. 13003 DeclRefType = CaptureType.getNonReferenceType(); 13004 if (!LSI->Mutable && !CaptureType->isReferenceType()) 13005 DeclRefType.addConst(); 13006 } 13007 13008 // Add the capture. 13009 if (BuildAndDiagnose) 13010 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 13011 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 13012 13013 return true; 13014 } 13015 13016 bool Sema::tryCaptureVariable( 13017 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 13018 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 13019 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 13020 // An init-capture is notionally from the context surrounding its 13021 // declaration, but its parent DC is the lambda class. 13022 DeclContext *VarDC = Var->getDeclContext(); 13023 if (Var->isInitCapture()) 13024 VarDC = VarDC->getParent(); 13025 13026 DeclContext *DC = CurContext; 13027 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 13028 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 13029 // We need to sync up the Declaration Context with the 13030 // FunctionScopeIndexToStopAt 13031 if (FunctionScopeIndexToStopAt) { 13032 unsigned FSIndex = FunctionScopes.size() - 1; 13033 while (FSIndex != MaxFunctionScopesIndex) { 13034 DC = getLambdaAwareParentOfDeclContext(DC); 13035 --FSIndex; 13036 } 13037 } 13038 13039 13040 // If the variable is declared in the current context, there is no need to 13041 // capture it. 13042 if (VarDC == DC) return true; 13043 13044 // Capture global variables if it is required to use private copy of this 13045 // variable. 13046 bool IsGlobal = !Var->hasLocalStorage(); 13047 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedVar(Var))) 13048 return true; 13049 13050 // Walk up the stack to determine whether we can capture the variable, 13051 // performing the "simple" checks that don't depend on type. We stop when 13052 // we've either hit the declared scope of the variable or find an existing 13053 // capture of that variable. We start from the innermost capturing-entity 13054 // (the DC) and ensure that all intervening capturing-entities 13055 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 13056 // declcontext can either capture the variable or have already captured 13057 // the variable. 13058 CaptureType = Var->getType(); 13059 DeclRefType = CaptureType.getNonReferenceType(); 13060 bool Nested = false; 13061 bool Explicit = (Kind != TryCapture_Implicit); 13062 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 13063 unsigned OpenMPLevel = 0; 13064 do { 13065 // Only block literals, captured statements, and lambda expressions can 13066 // capture; other scopes don't work. 13067 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 13068 ExprLoc, 13069 BuildAndDiagnose, 13070 *this); 13071 // We need to check for the parent *first* because, if we *have* 13072 // private-captured a global variable, we need to recursively capture it in 13073 // intermediate blocks, lambdas, etc. 13074 if (!ParentDC) { 13075 if (IsGlobal) { 13076 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 13077 break; 13078 } 13079 return true; 13080 } 13081 13082 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 13083 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 13084 13085 13086 // Check whether we've already captured it. 13087 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 13088 DeclRefType)) 13089 break; 13090 // If we are instantiating a generic lambda call operator body, 13091 // we do not want to capture new variables. What was captured 13092 // during either a lambdas transformation or initial parsing 13093 // should be used. 13094 if (isGenericLambdaCallOperatorSpecialization(DC)) { 13095 if (BuildAndDiagnose) { 13096 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13097 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 13098 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13099 Diag(Var->getLocation(), diag::note_previous_decl) 13100 << Var->getDeclName(); 13101 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl); 13102 } else 13103 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 13104 } 13105 return true; 13106 } 13107 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 13108 // certain types of variables (unnamed, variably modified types etc.) 13109 // so check for eligibility. 13110 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 13111 return true; 13112 13113 // Try to capture variable-length arrays types. 13114 if (Var->getType()->isVariablyModifiedType()) { 13115 // We're going to walk down into the type and look for VLA 13116 // expressions. 13117 QualType QTy = Var->getType(); 13118 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 13119 QTy = PVD->getOriginalType(); 13120 do { 13121 const Type *Ty = QTy.getTypePtr(); 13122 switch (Ty->getTypeClass()) { 13123 #define TYPE(Class, Base) 13124 #define ABSTRACT_TYPE(Class, Base) 13125 #define NON_CANONICAL_TYPE(Class, Base) 13126 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 13127 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 13128 #include "clang/AST/TypeNodes.def" 13129 QTy = QualType(); 13130 break; 13131 // These types are never variably-modified. 13132 case Type::Builtin: 13133 case Type::Complex: 13134 case Type::Vector: 13135 case Type::ExtVector: 13136 case Type::Record: 13137 case Type::Enum: 13138 case Type::Elaborated: 13139 case Type::TemplateSpecialization: 13140 case Type::ObjCObject: 13141 case Type::ObjCInterface: 13142 case Type::ObjCObjectPointer: 13143 case Type::Pipe: 13144 llvm_unreachable("type class is never variably-modified!"); 13145 case Type::Adjusted: 13146 QTy = cast<AdjustedType>(Ty)->getOriginalType(); 13147 break; 13148 case Type::Decayed: 13149 QTy = cast<DecayedType>(Ty)->getPointeeType(); 13150 break; 13151 case Type::Pointer: 13152 QTy = cast<PointerType>(Ty)->getPointeeType(); 13153 break; 13154 case Type::BlockPointer: 13155 QTy = cast<BlockPointerType>(Ty)->getPointeeType(); 13156 break; 13157 case Type::LValueReference: 13158 case Type::RValueReference: 13159 QTy = cast<ReferenceType>(Ty)->getPointeeType(); 13160 break; 13161 case Type::MemberPointer: 13162 QTy = cast<MemberPointerType>(Ty)->getPointeeType(); 13163 break; 13164 case Type::ConstantArray: 13165 case Type::IncompleteArray: 13166 // Losing element qualification here is fine. 13167 QTy = cast<ArrayType>(Ty)->getElementType(); 13168 break; 13169 case Type::VariableArray: { 13170 // Losing element qualification here is fine. 13171 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 13172 13173 // Unknown size indication requires no size computation. 13174 // Otherwise, evaluate and record it. 13175 if (auto Size = VAT->getSizeExpr()) { 13176 if (!CSI->isVLATypeCaptured(VAT)) { 13177 RecordDecl *CapRecord = nullptr; 13178 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 13179 CapRecord = LSI->Lambda; 13180 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13181 CapRecord = CRSI->TheRecordDecl; 13182 } 13183 if (CapRecord) { 13184 auto ExprLoc = Size->getExprLoc(); 13185 auto SizeType = Context.getSizeType(); 13186 // Build the non-static data member. 13187 auto Field = FieldDecl::Create( 13188 Context, CapRecord, ExprLoc, ExprLoc, 13189 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 13190 /*BW*/ nullptr, /*Mutable*/ false, 13191 /*InitStyle*/ ICIS_NoInit); 13192 Field->setImplicit(true); 13193 Field->setAccess(AS_private); 13194 Field->setCapturedVLAType(VAT); 13195 CapRecord->addDecl(Field); 13196 13197 CSI->addVLATypeCapture(ExprLoc, SizeType); 13198 } 13199 } 13200 } 13201 QTy = VAT->getElementType(); 13202 break; 13203 } 13204 case Type::FunctionProto: 13205 case Type::FunctionNoProto: 13206 QTy = cast<FunctionType>(Ty)->getReturnType(); 13207 break; 13208 case Type::Paren: 13209 case Type::TypeOf: 13210 case Type::UnaryTransform: 13211 case Type::Attributed: 13212 case Type::SubstTemplateTypeParm: 13213 case Type::PackExpansion: 13214 // Keep walking after single level desugaring. 13215 QTy = QTy.getSingleStepDesugaredType(getASTContext()); 13216 break; 13217 case Type::Typedef: 13218 QTy = cast<TypedefType>(Ty)->desugar(); 13219 break; 13220 case Type::Decltype: 13221 QTy = cast<DecltypeType>(Ty)->desugar(); 13222 break; 13223 case Type::Auto: 13224 QTy = cast<AutoType>(Ty)->getDeducedType(); 13225 break; 13226 case Type::TypeOfExpr: 13227 QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 13228 break; 13229 case Type::Atomic: 13230 QTy = cast<AtomicType>(Ty)->getValueType(); 13231 break; 13232 } 13233 } while (!QTy.isNull() && QTy->isVariablyModifiedType()); 13234 } 13235 13236 if (getLangOpts().OpenMP) { 13237 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13238 // OpenMP private variables should not be captured in outer scope, so 13239 // just break here. Similarly, global variables that are captured in a 13240 // target region should not be captured outside the scope of the region. 13241 if (RSI->CapRegionKind == CR_OpenMP) { 13242 auto isTargetCap = isOpenMPTargetCapturedVar(Var, OpenMPLevel); 13243 // When we detect target captures we are looking from inside the 13244 // target region, therefore we need to propagate the capture from the 13245 // enclosing region. Therefore, the capture is not initially nested. 13246 if (isTargetCap) 13247 FunctionScopesIndex--; 13248 13249 if (isTargetCap || isOpenMPPrivateVar(Var, OpenMPLevel)) { 13250 Nested = !isTargetCap; 13251 DeclRefType = DeclRefType.getUnqualifiedType(); 13252 CaptureType = Context.getLValueReferenceType(DeclRefType); 13253 break; 13254 } 13255 ++OpenMPLevel; 13256 } 13257 } 13258 } 13259 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 13260 // No capture-default, and this is not an explicit capture 13261 // so cannot capture this variable. 13262 if (BuildAndDiagnose) { 13263 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 13264 Diag(Var->getLocation(), diag::note_previous_decl) 13265 << Var->getDeclName(); 13266 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(), 13267 diag::note_lambda_decl); 13268 // FIXME: If we error out because an outer lambda can not implicitly 13269 // capture a variable that an inner lambda explicitly captures, we 13270 // should have the inner lambda do the explicit capture - because 13271 // it makes for cleaner diagnostics later. This would purely be done 13272 // so that the diagnostic does not misleadingly claim that a variable 13273 // can not be captured by a lambda implicitly even though it is captured 13274 // explicitly. Suggestion: 13275 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 13276 // at the function head 13277 // - cache the StartingDeclContext - this must be a lambda 13278 // - captureInLambda in the innermost lambda the variable. 13279 } 13280 return true; 13281 } 13282 13283 FunctionScopesIndex--; 13284 DC = ParentDC; 13285 Explicit = false; 13286 } while (!VarDC->Equals(DC)); 13287 13288 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 13289 // computing the type of the capture at each step, checking type-specific 13290 // requirements, and adding captures if requested. 13291 // If the variable had already been captured previously, we start capturing 13292 // at the lambda nested within that one. 13293 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 13294 ++I) { 13295 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 13296 13297 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 13298 if (!captureInBlock(BSI, Var, ExprLoc, 13299 BuildAndDiagnose, CaptureType, 13300 DeclRefType, Nested, *this)) 13301 return true; 13302 Nested = true; 13303 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 13304 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 13305 BuildAndDiagnose, CaptureType, 13306 DeclRefType, Nested, *this)) 13307 return true; 13308 Nested = true; 13309 } else { 13310 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 13311 if (!captureInLambda(LSI, Var, ExprLoc, 13312 BuildAndDiagnose, CaptureType, 13313 DeclRefType, Nested, Kind, EllipsisLoc, 13314 /*IsTopScope*/I == N - 1, *this)) 13315 return true; 13316 Nested = true; 13317 } 13318 } 13319 return false; 13320 } 13321 13322 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 13323 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 13324 QualType CaptureType; 13325 QualType DeclRefType; 13326 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 13327 /*BuildAndDiagnose=*/true, CaptureType, 13328 DeclRefType, nullptr); 13329 } 13330 13331 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 13332 QualType CaptureType; 13333 QualType DeclRefType; 13334 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13335 /*BuildAndDiagnose=*/false, CaptureType, 13336 DeclRefType, nullptr); 13337 } 13338 13339 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 13340 QualType CaptureType; 13341 QualType DeclRefType; 13342 13343 // Determine whether we can capture this variable. 13344 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 13345 /*BuildAndDiagnose=*/false, CaptureType, 13346 DeclRefType, nullptr)) 13347 return QualType(); 13348 13349 return DeclRefType; 13350 } 13351 13352 13353 13354 // If either the type of the variable or the initializer is dependent, 13355 // return false. Otherwise, determine whether the variable is a constant 13356 // expression. Use this if you need to know if a variable that might or 13357 // might not be dependent is truly a constant expression. 13358 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 13359 ASTContext &Context) { 13360 13361 if (Var->getType()->isDependentType()) 13362 return false; 13363 const VarDecl *DefVD = nullptr; 13364 Var->getAnyInitializer(DefVD); 13365 if (!DefVD) 13366 return false; 13367 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 13368 Expr *Init = cast<Expr>(Eval->Value); 13369 if (Init->isValueDependent()) 13370 return false; 13371 return IsVariableAConstantExpression(Var, Context); 13372 } 13373 13374 13375 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 13376 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 13377 // an object that satisfies the requirements for appearing in a 13378 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 13379 // is immediately applied." This function handles the lvalue-to-rvalue 13380 // conversion part. 13381 MaybeODRUseExprs.erase(E->IgnoreParens()); 13382 13383 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 13384 // to a variable that is a constant expression, and if so, identify it as 13385 // a reference to a variable that does not involve an odr-use of that 13386 // variable. 13387 if (LambdaScopeInfo *LSI = getCurLambda()) { 13388 Expr *SansParensExpr = E->IgnoreParens(); 13389 VarDecl *Var = nullptr; 13390 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 13391 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 13392 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 13393 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 13394 13395 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 13396 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 13397 } 13398 } 13399 13400 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 13401 Res = CorrectDelayedTyposInExpr(Res); 13402 13403 if (!Res.isUsable()) 13404 return Res; 13405 13406 // If a constant-expression is a reference to a variable where we delay 13407 // deciding whether it is an odr-use, just assume we will apply the 13408 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 13409 // (a non-type template argument), we have special handling anyway. 13410 UpdateMarkingForLValueToRValue(Res.get()); 13411 return Res; 13412 } 13413 13414 void Sema::CleanupVarDeclMarking() { 13415 for (Expr *E : MaybeODRUseExprs) { 13416 VarDecl *Var; 13417 SourceLocation Loc; 13418 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13419 Var = cast<VarDecl>(DRE->getDecl()); 13420 Loc = DRE->getLocation(); 13421 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13422 Var = cast<VarDecl>(ME->getMemberDecl()); 13423 Loc = ME->getMemberLoc(); 13424 } else { 13425 llvm_unreachable("Unexpected expression"); 13426 } 13427 13428 MarkVarDeclODRUsed(Var, Loc, *this, 13429 /*MaxFunctionScopeIndex Pointer*/ nullptr); 13430 } 13431 13432 MaybeODRUseExprs.clear(); 13433 } 13434 13435 13436 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 13437 VarDecl *Var, Expr *E) { 13438 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 13439 "Invalid Expr argument to DoMarkVarDeclReferenced"); 13440 Var->setReferenced(); 13441 13442 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 13443 bool MarkODRUsed = true; 13444 13445 // If the context is not potentially evaluated, this is not an odr-use and 13446 // does not trigger instantiation. 13447 if (!IsPotentiallyEvaluatedContext(SemaRef)) { 13448 if (SemaRef.isUnevaluatedContext()) 13449 return; 13450 13451 // If we don't yet know whether this context is going to end up being an 13452 // evaluated context, and we're referencing a variable from an enclosing 13453 // scope, add a potential capture. 13454 // 13455 // FIXME: Is this necessary? These contexts are only used for default 13456 // arguments, where local variables can't be used. 13457 const bool RefersToEnclosingScope = 13458 (SemaRef.CurContext != Var->getDeclContext() && 13459 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 13460 if (RefersToEnclosingScope) { 13461 if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) { 13462 // If a variable could potentially be odr-used, defer marking it so 13463 // until we finish analyzing the full expression for any 13464 // lvalue-to-rvalue 13465 // or discarded value conversions that would obviate odr-use. 13466 // Add it to the list of potential captures that will be analyzed 13467 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 13468 // unless the variable is a reference that was initialized by a constant 13469 // expression (this will never need to be captured or odr-used). 13470 assert(E && "Capture variable should be used in an expression."); 13471 if (!Var->getType()->isReferenceType() || 13472 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 13473 LSI->addPotentialCapture(E->IgnoreParens()); 13474 } 13475 } 13476 13477 if (!isTemplateInstantiation(TSK)) 13478 return; 13479 13480 // Instantiate, but do not mark as odr-used, variable templates. 13481 MarkODRUsed = false; 13482 } 13483 13484 VarTemplateSpecializationDecl *VarSpec = 13485 dyn_cast<VarTemplateSpecializationDecl>(Var); 13486 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 13487 "Can't instantiate a partial template specialization."); 13488 13489 // Perform implicit instantiation of static data members, static data member 13490 // templates of class templates, and variable template specializations. Delay 13491 // instantiations of variable templates, except for those that could be used 13492 // in a constant expression. 13493 if (isTemplateInstantiation(TSK)) { 13494 bool TryInstantiating = TSK == TSK_ImplicitInstantiation; 13495 13496 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) { 13497 if (Var->getPointOfInstantiation().isInvalid()) { 13498 // This is a modification of an existing AST node. Notify listeners. 13499 if (ASTMutationListener *L = SemaRef.getASTMutationListener()) 13500 L->StaticDataMemberInstantiated(Var); 13501 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context)) 13502 // Don't bother trying to instantiate it again, unless we might need 13503 // its initializer before we get to the end of the TU. 13504 TryInstantiating = false; 13505 } 13506 13507 if (Var->getPointOfInstantiation().isInvalid()) 13508 Var->setTemplateSpecializationKind(TSK, Loc); 13509 13510 if (TryInstantiating) { 13511 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 13512 bool InstantiationDependent = false; 13513 bool IsNonDependent = 13514 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 13515 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 13516 : true; 13517 13518 // Do not instantiate specializations that are still type-dependent. 13519 if (IsNonDependent) { 13520 if (Var->isUsableInConstantExpressions(SemaRef.Context)) { 13521 // Do not defer instantiations of variables which could be used in a 13522 // constant expression. 13523 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 13524 } else { 13525 SemaRef.PendingInstantiations 13526 .push_back(std::make_pair(Var, PointOfInstantiation)); 13527 } 13528 } 13529 } 13530 } 13531 13532 if(!MarkODRUsed) return; 13533 13534 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 13535 // the requirements for appearing in a constant expression (5.19) and, if 13536 // it is an object, the lvalue-to-rvalue conversion (4.1) 13537 // is immediately applied." We check the first part here, and 13538 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 13539 // Note that we use the C++11 definition everywhere because nothing in 13540 // C++03 depends on whether we get the C++03 version correct. The second 13541 // part does not apply to references, since they are not objects. 13542 if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) { 13543 // A reference initialized by a constant expression can never be 13544 // odr-used, so simply ignore it. 13545 if (!Var->getType()->isReferenceType()) 13546 SemaRef.MaybeODRUseExprs.insert(E); 13547 } else 13548 MarkVarDeclODRUsed(Var, Loc, SemaRef, 13549 /*MaxFunctionScopeIndex ptr*/ nullptr); 13550 } 13551 13552 /// \brief Mark a variable referenced, and check whether it is odr-used 13553 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 13554 /// used directly for normal expressions referring to VarDecl. 13555 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 13556 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 13557 } 13558 13559 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 13560 Decl *D, Expr *E, bool OdrUse) { 13561 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 13562 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 13563 return; 13564 } 13565 13566 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse); 13567 13568 // If this is a call to a method via a cast, also mark the method in the 13569 // derived class used in case codegen can devirtualize the call. 13570 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 13571 if (!ME) 13572 return; 13573 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 13574 if (!MD) 13575 return; 13576 // Only attempt to devirtualize if this is truly a virtual call. 13577 bool IsVirtualCall = MD->isVirtual() && 13578 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 13579 if (!IsVirtualCall) 13580 return; 13581 const Expr *Base = ME->getBase(); 13582 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType(); 13583 if (!MostDerivedClassDecl) 13584 return; 13585 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl); 13586 if (!DM || DM->isPure()) 13587 return; 13588 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse); 13589 } 13590 13591 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr. 13592 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) { 13593 // TODO: update this with DR# once a defect report is filed. 13594 // C++11 defect. The address of a pure member should not be an ODR use, even 13595 // if it's a qualified reference. 13596 bool OdrUse = true; 13597 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 13598 if (Method->isVirtual()) 13599 OdrUse = false; 13600 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 13601 } 13602 13603 /// \brief Perform reference-marking and odr-use handling for a MemberExpr. 13604 void Sema::MarkMemberReferenced(MemberExpr *E) { 13605 // C++11 [basic.def.odr]p2: 13606 // A non-overloaded function whose name appears as a potentially-evaluated 13607 // expression or a member of a set of candidate functions, if selected by 13608 // overload resolution when referred to from a potentially-evaluated 13609 // expression, is odr-used, unless it is a pure virtual function and its 13610 // name is not explicitly qualified. 13611 bool OdrUse = true; 13612 if (E->performsVirtualDispatch(getLangOpts())) { 13613 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 13614 if (Method->isPure()) 13615 OdrUse = false; 13616 } 13617 SourceLocation Loc = E->getMemberLoc().isValid() ? 13618 E->getMemberLoc() : E->getLocStart(); 13619 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse); 13620 } 13621 13622 /// \brief Perform marking for a reference to an arbitrary declaration. It 13623 /// marks the declaration referenced, and performs odr-use checking for 13624 /// functions and variables. This method should not be used when building a 13625 /// normal expression which refers to a variable. 13626 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) { 13627 if (OdrUse) { 13628 if (auto *VD = dyn_cast<VarDecl>(D)) { 13629 MarkVariableReferenced(Loc, VD); 13630 return; 13631 } 13632 } 13633 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 13634 MarkFunctionReferenced(Loc, FD, OdrUse); 13635 return; 13636 } 13637 D->setReferenced(); 13638 } 13639 13640 namespace { 13641 // Mark all of the declarations referenced 13642 // FIXME: Not fully implemented yet! We need to have a better understanding 13643 // of when we're entering 13644 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 13645 Sema &S; 13646 SourceLocation Loc; 13647 13648 public: 13649 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 13650 13651 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 13652 13653 bool TraverseTemplateArgument(const TemplateArgument &Arg); 13654 bool TraverseRecordType(RecordType *T); 13655 }; 13656 } 13657 13658 bool MarkReferencedDecls::TraverseTemplateArgument( 13659 const TemplateArgument &Arg) { 13660 if (Arg.getKind() == TemplateArgument::Declaration) { 13661 if (Decl *D = Arg.getAsDecl()) 13662 S.MarkAnyDeclReferenced(Loc, D, true); 13663 } 13664 13665 return Inherited::TraverseTemplateArgument(Arg); 13666 } 13667 13668 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) { 13669 if (ClassTemplateSpecializationDecl *Spec 13670 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) { 13671 const TemplateArgumentList &Args = Spec->getTemplateArgs(); 13672 return TraverseTemplateArguments(Args.data(), Args.size()); 13673 } 13674 13675 return true; 13676 } 13677 13678 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 13679 MarkReferencedDecls Marker(*this, Loc); 13680 Marker.TraverseType(Context.getCanonicalType(T)); 13681 } 13682 13683 namespace { 13684 /// \brief Helper class that marks all of the declarations referenced by 13685 /// potentially-evaluated subexpressions as "referenced". 13686 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 13687 Sema &S; 13688 bool SkipLocalVariables; 13689 13690 public: 13691 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 13692 13693 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 13694 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 13695 13696 void VisitDeclRefExpr(DeclRefExpr *E) { 13697 // If we were asked not to visit local variables, don't. 13698 if (SkipLocalVariables) { 13699 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 13700 if (VD->hasLocalStorage()) 13701 return; 13702 } 13703 13704 S.MarkDeclRefReferenced(E); 13705 } 13706 13707 void VisitMemberExpr(MemberExpr *E) { 13708 S.MarkMemberReferenced(E); 13709 Inherited::VisitMemberExpr(E); 13710 } 13711 13712 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 13713 S.MarkFunctionReferenced(E->getLocStart(), 13714 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor())); 13715 Visit(E->getSubExpr()); 13716 } 13717 13718 void VisitCXXNewExpr(CXXNewExpr *E) { 13719 if (E->getOperatorNew()) 13720 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew()); 13721 if (E->getOperatorDelete()) 13722 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 13723 Inherited::VisitCXXNewExpr(E); 13724 } 13725 13726 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 13727 if (E->getOperatorDelete()) 13728 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete()); 13729 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 13730 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 13731 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 13732 S.MarkFunctionReferenced(E->getLocStart(), 13733 S.LookupDestructor(Record)); 13734 } 13735 13736 Inherited::VisitCXXDeleteExpr(E); 13737 } 13738 13739 void VisitCXXConstructExpr(CXXConstructExpr *E) { 13740 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor()); 13741 Inherited::VisitCXXConstructExpr(E); 13742 } 13743 13744 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 13745 Visit(E->getExpr()); 13746 } 13747 13748 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 13749 Inherited::VisitImplicitCastExpr(E); 13750 13751 if (E->getCastKind() == CK_LValueToRValue) 13752 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 13753 } 13754 }; 13755 } 13756 13757 /// \brief Mark any declarations that appear within this expression or any 13758 /// potentially-evaluated subexpressions as "referenced". 13759 /// 13760 /// \param SkipLocalVariables If true, don't mark local variables as 13761 /// 'referenced'. 13762 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 13763 bool SkipLocalVariables) { 13764 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 13765 } 13766 13767 /// \brief Emit a diagnostic that describes an effect on the run-time behavior 13768 /// of the program being compiled. 13769 /// 13770 /// This routine emits the given diagnostic when the code currently being 13771 /// type-checked is "potentially evaluated", meaning that there is a 13772 /// possibility that the code will actually be executable. Code in sizeof() 13773 /// expressions, code used only during overload resolution, etc., are not 13774 /// potentially evaluated. This routine will suppress such diagnostics or, 13775 /// in the absolutely nutty case of potentially potentially evaluated 13776 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 13777 /// later. 13778 /// 13779 /// This routine should be used for all diagnostics that describe the run-time 13780 /// behavior of a program, such as passing a non-POD value through an ellipsis. 13781 /// Failure to do so will likely result in spurious diagnostics or failures 13782 /// during overload resolution or within sizeof/alignof/typeof/typeid. 13783 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 13784 const PartialDiagnostic &PD) { 13785 switch (ExprEvalContexts.back().Context) { 13786 case Unevaluated: 13787 case UnevaluatedAbstract: 13788 // The argument will never be evaluated, so don't complain. 13789 break; 13790 13791 case ConstantEvaluated: 13792 // Relevant diagnostics should be produced by constant evaluation. 13793 break; 13794 13795 case PotentiallyEvaluated: 13796 case PotentiallyEvaluatedIfUsed: 13797 if (Statement && getCurFunctionOrMethodDecl()) { 13798 FunctionScopes.back()->PossiblyUnreachableDiags. 13799 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 13800 } 13801 else 13802 Diag(Loc, PD); 13803 13804 return true; 13805 } 13806 13807 return false; 13808 } 13809 13810 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 13811 CallExpr *CE, FunctionDecl *FD) { 13812 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 13813 return false; 13814 13815 // If we're inside a decltype's expression, don't check for a valid return 13816 // type or construct temporaries until we know whether this is the last call. 13817 if (ExprEvalContexts.back().IsDecltype) { 13818 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 13819 return false; 13820 } 13821 13822 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 13823 FunctionDecl *FD; 13824 CallExpr *CE; 13825 13826 public: 13827 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 13828 : FD(FD), CE(CE) { } 13829 13830 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 13831 if (!FD) { 13832 S.Diag(Loc, diag::err_call_incomplete_return) 13833 << T << CE->getSourceRange(); 13834 return; 13835 } 13836 13837 S.Diag(Loc, diag::err_call_function_incomplete_return) 13838 << CE->getSourceRange() << FD->getDeclName() << T; 13839 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 13840 << FD->getDeclName(); 13841 } 13842 } Diagnoser(FD, CE); 13843 13844 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 13845 return true; 13846 13847 return false; 13848 } 13849 13850 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 13851 // will prevent this condition from triggering, which is what we want. 13852 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 13853 SourceLocation Loc; 13854 13855 unsigned diagnostic = diag::warn_condition_is_assignment; 13856 bool IsOrAssign = false; 13857 13858 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 13859 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 13860 return; 13861 13862 IsOrAssign = Op->getOpcode() == BO_OrAssign; 13863 13864 // Greylist some idioms by putting them into a warning subcategory. 13865 if (ObjCMessageExpr *ME 13866 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 13867 Selector Sel = ME->getSelector(); 13868 13869 // self = [<foo> init...] 13870 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 13871 diagnostic = diag::warn_condition_is_idiomatic_assignment; 13872 13873 // <foo> = [<bar> nextObject] 13874 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 13875 diagnostic = diag::warn_condition_is_idiomatic_assignment; 13876 } 13877 13878 Loc = Op->getOperatorLoc(); 13879 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 13880 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 13881 return; 13882 13883 IsOrAssign = Op->getOperator() == OO_PipeEqual; 13884 Loc = Op->getOperatorLoc(); 13885 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 13886 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 13887 else { 13888 // Not an assignment. 13889 return; 13890 } 13891 13892 Diag(Loc, diagnostic) << E->getSourceRange(); 13893 13894 SourceLocation Open = E->getLocStart(); 13895 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 13896 Diag(Loc, diag::note_condition_assign_silence) 13897 << FixItHint::CreateInsertion(Open, "(") 13898 << FixItHint::CreateInsertion(Close, ")"); 13899 13900 if (IsOrAssign) 13901 Diag(Loc, diag::note_condition_or_assign_to_comparison) 13902 << FixItHint::CreateReplacement(Loc, "!="); 13903 else 13904 Diag(Loc, diag::note_condition_assign_to_comparison) 13905 << FixItHint::CreateReplacement(Loc, "=="); 13906 } 13907 13908 /// \brief Redundant parentheses over an equality comparison can indicate 13909 /// that the user intended an assignment used as condition. 13910 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 13911 // Don't warn if the parens came from a macro. 13912 SourceLocation parenLoc = ParenE->getLocStart(); 13913 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 13914 return; 13915 // Don't warn for dependent expressions. 13916 if (ParenE->isTypeDependent()) 13917 return; 13918 13919 Expr *E = ParenE->IgnoreParens(); 13920 13921 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 13922 if (opE->getOpcode() == BO_EQ && 13923 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 13924 == Expr::MLV_Valid) { 13925 SourceLocation Loc = opE->getOperatorLoc(); 13926 13927 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 13928 SourceRange ParenERange = ParenE->getSourceRange(); 13929 Diag(Loc, diag::note_equality_comparison_silence) 13930 << FixItHint::CreateRemoval(ParenERange.getBegin()) 13931 << FixItHint::CreateRemoval(ParenERange.getEnd()); 13932 Diag(Loc, diag::note_equality_comparison_to_assign) 13933 << FixItHint::CreateReplacement(Loc, "="); 13934 } 13935 } 13936 13937 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) { 13938 DiagnoseAssignmentAsCondition(E); 13939 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 13940 DiagnoseEqualityWithExtraParens(parenE); 13941 13942 ExprResult result = CheckPlaceholderExpr(E); 13943 if (result.isInvalid()) return ExprError(); 13944 E = result.get(); 13945 13946 if (!E->isTypeDependent()) { 13947 if (getLangOpts().CPlusPlus) 13948 return CheckCXXBooleanCondition(E); // C++ 6.4p4 13949 13950 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 13951 if (ERes.isInvalid()) 13952 return ExprError(); 13953 E = ERes.get(); 13954 13955 QualType T = E->getType(); 13956 if (!T->isScalarType()) { // C99 6.8.4.1p1 13957 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 13958 << T << E->getSourceRange(); 13959 return ExprError(); 13960 } 13961 CheckBoolLikeConversion(E, Loc); 13962 } 13963 13964 return E; 13965 } 13966 13967 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc, 13968 Expr *SubExpr) { 13969 if (!SubExpr) 13970 return ExprError(); 13971 13972 return CheckBooleanCondition(SubExpr, Loc); 13973 } 13974 13975 namespace { 13976 /// A visitor for rebuilding a call to an __unknown_any expression 13977 /// to have an appropriate type. 13978 struct RebuildUnknownAnyFunction 13979 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 13980 13981 Sema &S; 13982 13983 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 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_call) 13991 << E->getSourceRange(); 13992 return ExprError(); 13993 } 13994 13995 /// Rebuild an expression which simply semantically wraps another 13996 /// expression which it shares the type and value kind of. 13997 template <class T> ExprResult rebuildSugarExpr(T *E) { 13998 ExprResult SubResult = Visit(E->getSubExpr()); 13999 if (SubResult.isInvalid()) return ExprError(); 14000 14001 Expr *SubExpr = SubResult.get(); 14002 E->setSubExpr(SubExpr); 14003 E->setType(SubExpr->getType()); 14004 E->setValueKind(SubExpr->getValueKind()); 14005 assert(E->getObjectKind() == OK_Ordinary); 14006 return E; 14007 } 14008 14009 ExprResult VisitParenExpr(ParenExpr *E) { 14010 return rebuildSugarExpr(E); 14011 } 14012 14013 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14014 return rebuildSugarExpr(E); 14015 } 14016 14017 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14018 ExprResult SubResult = Visit(E->getSubExpr()); 14019 if (SubResult.isInvalid()) return ExprError(); 14020 14021 Expr *SubExpr = SubResult.get(); 14022 E->setSubExpr(SubExpr); 14023 E->setType(S.Context.getPointerType(SubExpr->getType())); 14024 assert(E->getValueKind() == VK_RValue); 14025 assert(E->getObjectKind() == OK_Ordinary); 14026 return E; 14027 } 14028 14029 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 14030 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 14031 14032 E->setType(VD->getType()); 14033 14034 assert(E->getValueKind() == VK_RValue); 14035 if (S.getLangOpts().CPlusPlus && 14036 !(isa<CXXMethodDecl>(VD) && 14037 cast<CXXMethodDecl>(VD)->isInstance())) 14038 E->setValueKind(VK_LValue); 14039 14040 return E; 14041 } 14042 14043 ExprResult VisitMemberExpr(MemberExpr *E) { 14044 return resolveDecl(E, E->getMemberDecl()); 14045 } 14046 14047 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14048 return resolveDecl(E, E->getDecl()); 14049 } 14050 }; 14051 } 14052 14053 /// Given a function expression of unknown-any type, try to rebuild it 14054 /// to have a function type. 14055 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 14056 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 14057 if (Result.isInvalid()) return ExprError(); 14058 return S.DefaultFunctionArrayConversion(Result.get()); 14059 } 14060 14061 namespace { 14062 /// A visitor for rebuilding an expression of type __unknown_anytype 14063 /// into one which resolves the type directly on the referring 14064 /// expression. Strict preservation of the original source 14065 /// structure is not a goal. 14066 struct RebuildUnknownAnyExpr 14067 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 14068 14069 Sema &S; 14070 14071 /// The current destination type. 14072 QualType DestType; 14073 14074 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 14075 : S(S), DestType(CastType) {} 14076 14077 ExprResult VisitStmt(Stmt *S) { 14078 llvm_unreachable("unexpected statement!"); 14079 } 14080 14081 ExprResult VisitExpr(Expr *E) { 14082 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14083 << E->getSourceRange(); 14084 return ExprError(); 14085 } 14086 14087 ExprResult VisitCallExpr(CallExpr *E); 14088 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 14089 14090 /// Rebuild an expression which simply semantically wraps another 14091 /// expression which it shares the type and value kind of. 14092 template <class T> ExprResult rebuildSugarExpr(T *E) { 14093 ExprResult SubResult = Visit(E->getSubExpr()); 14094 if (SubResult.isInvalid()) return ExprError(); 14095 Expr *SubExpr = SubResult.get(); 14096 E->setSubExpr(SubExpr); 14097 E->setType(SubExpr->getType()); 14098 E->setValueKind(SubExpr->getValueKind()); 14099 assert(E->getObjectKind() == OK_Ordinary); 14100 return E; 14101 } 14102 14103 ExprResult VisitParenExpr(ParenExpr *E) { 14104 return rebuildSugarExpr(E); 14105 } 14106 14107 ExprResult VisitUnaryExtension(UnaryOperator *E) { 14108 return rebuildSugarExpr(E); 14109 } 14110 14111 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 14112 const PointerType *Ptr = DestType->getAs<PointerType>(); 14113 if (!Ptr) { 14114 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 14115 << E->getSourceRange(); 14116 return ExprError(); 14117 } 14118 assert(E->getValueKind() == VK_RValue); 14119 assert(E->getObjectKind() == OK_Ordinary); 14120 E->setType(DestType); 14121 14122 // Build the sub-expression as if it were an object of the pointee type. 14123 DestType = Ptr->getPointeeType(); 14124 ExprResult SubResult = Visit(E->getSubExpr()); 14125 if (SubResult.isInvalid()) return ExprError(); 14126 E->setSubExpr(SubResult.get()); 14127 return E; 14128 } 14129 14130 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 14131 14132 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 14133 14134 ExprResult VisitMemberExpr(MemberExpr *E) { 14135 return resolveDecl(E, E->getMemberDecl()); 14136 } 14137 14138 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 14139 return resolveDecl(E, E->getDecl()); 14140 } 14141 }; 14142 } 14143 14144 /// Rebuilds a call expression which yielded __unknown_anytype. 14145 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 14146 Expr *CalleeExpr = E->getCallee(); 14147 14148 enum FnKind { 14149 FK_MemberFunction, 14150 FK_FunctionPointer, 14151 FK_BlockPointer 14152 }; 14153 14154 FnKind Kind; 14155 QualType CalleeType = CalleeExpr->getType(); 14156 if (CalleeType == S.Context.BoundMemberTy) { 14157 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 14158 Kind = FK_MemberFunction; 14159 CalleeType = Expr::findBoundMemberType(CalleeExpr); 14160 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 14161 CalleeType = Ptr->getPointeeType(); 14162 Kind = FK_FunctionPointer; 14163 } else { 14164 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 14165 Kind = FK_BlockPointer; 14166 } 14167 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 14168 14169 // Verify that this is a legal result type of a function. 14170 if (DestType->isArrayType() || DestType->isFunctionType()) { 14171 unsigned diagID = diag::err_func_returning_array_function; 14172 if (Kind == FK_BlockPointer) 14173 diagID = diag::err_block_returning_array_function; 14174 14175 S.Diag(E->getExprLoc(), diagID) 14176 << DestType->isFunctionType() << DestType; 14177 return ExprError(); 14178 } 14179 14180 // Otherwise, go ahead and set DestType as the call's result. 14181 E->setType(DestType.getNonLValueExprType(S.Context)); 14182 E->setValueKind(Expr::getValueKindForType(DestType)); 14183 assert(E->getObjectKind() == OK_Ordinary); 14184 14185 // Rebuild the function type, replacing the result type with DestType. 14186 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 14187 if (Proto) { 14188 // __unknown_anytype(...) is a special case used by the debugger when 14189 // it has no idea what a function's signature is. 14190 // 14191 // We want to build this call essentially under the K&R 14192 // unprototyped rules, but making a FunctionNoProtoType in C++ 14193 // would foul up all sorts of assumptions. However, we cannot 14194 // simply pass all arguments as variadic arguments, nor can we 14195 // portably just call the function under a non-variadic type; see 14196 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 14197 // However, it turns out that in practice it is generally safe to 14198 // call a function declared as "A foo(B,C,D);" under the prototype 14199 // "A foo(B,C,D,...);". The only known exception is with the 14200 // Windows ABI, where any variadic function is implicitly cdecl 14201 // regardless of its normal CC. Therefore we change the parameter 14202 // types to match the types of the arguments. 14203 // 14204 // This is a hack, but it is far superior to moving the 14205 // corresponding target-specific code from IR-gen to Sema/AST. 14206 14207 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 14208 SmallVector<QualType, 8> ArgTypes; 14209 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 14210 ArgTypes.reserve(E->getNumArgs()); 14211 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 14212 Expr *Arg = E->getArg(i); 14213 QualType ArgType = Arg->getType(); 14214 if (E->isLValue()) { 14215 ArgType = S.Context.getLValueReferenceType(ArgType); 14216 } else if (E->isXValue()) { 14217 ArgType = S.Context.getRValueReferenceType(ArgType); 14218 } 14219 ArgTypes.push_back(ArgType); 14220 } 14221 ParamTypes = ArgTypes; 14222 } 14223 DestType = S.Context.getFunctionType(DestType, ParamTypes, 14224 Proto->getExtProtoInfo()); 14225 } else { 14226 DestType = S.Context.getFunctionNoProtoType(DestType, 14227 FnType->getExtInfo()); 14228 } 14229 14230 // Rebuild the appropriate pointer-to-function type. 14231 switch (Kind) { 14232 case FK_MemberFunction: 14233 // Nothing to do. 14234 break; 14235 14236 case FK_FunctionPointer: 14237 DestType = S.Context.getPointerType(DestType); 14238 break; 14239 14240 case FK_BlockPointer: 14241 DestType = S.Context.getBlockPointerType(DestType); 14242 break; 14243 } 14244 14245 // Finally, we can recurse. 14246 ExprResult CalleeResult = Visit(CalleeExpr); 14247 if (!CalleeResult.isUsable()) return ExprError(); 14248 E->setCallee(CalleeResult.get()); 14249 14250 // Bind a temporary if necessary. 14251 return S.MaybeBindToTemporary(E); 14252 } 14253 14254 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 14255 // Verify that this is a legal result type of a call. 14256 if (DestType->isArrayType() || DestType->isFunctionType()) { 14257 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 14258 << DestType->isFunctionType() << DestType; 14259 return ExprError(); 14260 } 14261 14262 // Rewrite the method result type if available. 14263 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 14264 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 14265 Method->setReturnType(DestType); 14266 } 14267 14268 // Change the type of the message. 14269 E->setType(DestType.getNonReferenceType()); 14270 E->setValueKind(Expr::getValueKindForType(DestType)); 14271 14272 return S.MaybeBindToTemporary(E); 14273 } 14274 14275 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 14276 // The only case we should ever see here is a function-to-pointer decay. 14277 if (E->getCastKind() == CK_FunctionToPointerDecay) { 14278 assert(E->getValueKind() == VK_RValue); 14279 assert(E->getObjectKind() == OK_Ordinary); 14280 14281 E->setType(DestType); 14282 14283 // Rebuild the sub-expression as the pointee (function) type. 14284 DestType = DestType->castAs<PointerType>()->getPointeeType(); 14285 14286 ExprResult Result = Visit(E->getSubExpr()); 14287 if (!Result.isUsable()) return ExprError(); 14288 14289 E->setSubExpr(Result.get()); 14290 return E; 14291 } else if (E->getCastKind() == CK_LValueToRValue) { 14292 assert(E->getValueKind() == VK_RValue); 14293 assert(E->getObjectKind() == OK_Ordinary); 14294 14295 assert(isa<BlockPointerType>(E->getType())); 14296 14297 E->setType(DestType); 14298 14299 // The sub-expression has to be a lvalue reference, so rebuild it as such. 14300 DestType = S.Context.getLValueReferenceType(DestType); 14301 14302 ExprResult Result = Visit(E->getSubExpr()); 14303 if (!Result.isUsable()) return ExprError(); 14304 14305 E->setSubExpr(Result.get()); 14306 return E; 14307 } else { 14308 llvm_unreachable("Unhandled cast type!"); 14309 } 14310 } 14311 14312 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 14313 ExprValueKind ValueKind = VK_LValue; 14314 QualType Type = DestType; 14315 14316 // We know how to make this work for certain kinds of decls: 14317 14318 // - functions 14319 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 14320 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 14321 DestType = Ptr->getPointeeType(); 14322 ExprResult Result = resolveDecl(E, VD); 14323 if (Result.isInvalid()) return ExprError(); 14324 return S.ImpCastExprToType(Result.get(), Type, 14325 CK_FunctionToPointerDecay, VK_RValue); 14326 } 14327 14328 if (!Type->isFunctionType()) { 14329 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 14330 << VD << E->getSourceRange(); 14331 return ExprError(); 14332 } 14333 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 14334 // We must match the FunctionDecl's type to the hack introduced in 14335 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 14336 // type. See the lengthy commentary in that routine. 14337 QualType FDT = FD->getType(); 14338 const FunctionType *FnType = FDT->castAs<FunctionType>(); 14339 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 14340 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 14341 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 14342 SourceLocation Loc = FD->getLocation(); 14343 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 14344 FD->getDeclContext(), 14345 Loc, Loc, FD->getNameInfo().getName(), 14346 DestType, FD->getTypeSourceInfo(), 14347 SC_None, false/*isInlineSpecified*/, 14348 FD->hasPrototype(), 14349 false/*isConstexprSpecified*/); 14350 14351 if (FD->getQualifier()) 14352 NewFD->setQualifierInfo(FD->getQualifierLoc()); 14353 14354 SmallVector<ParmVarDecl*, 16> Params; 14355 for (const auto &AI : FT->param_types()) { 14356 ParmVarDecl *Param = 14357 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 14358 Param->setScopeInfo(0, Params.size()); 14359 Params.push_back(Param); 14360 } 14361 NewFD->setParams(Params); 14362 DRE->setDecl(NewFD); 14363 VD = DRE->getDecl(); 14364 } 14365 } 14366 14367 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 14368 if (MD->isInstance()) { 14369 ValueKind = VK_RValue; 14370 Type = S.Context.BoundMemberTy; 14371 } 14372 14373 // Function references aren't l-values in C. 14374 if (!S.getLangOpts().CPlusPlus) 14375 ValueKind = VK_RValue; 14376 14377 // - variables 14378 } else if (isa<VarDecl>(VD)) { 14379 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 14380 Type = RefTy->getPointeeType(); 14381 } else if (Type->isFunctionType()) { 14382 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 14383 << VD << E->getSourceRange(); 14384 return ExprError(); 14385 } 14386 14387 // - nothing else 14388 } else { 14389 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 14390 << VD << E->getSourceRange(); 14391 return ExprError(); 14392 } 14393 14394 // Modifying the declaration like this is friendly to IR-gen but 14395 // also really dangerous. 14396 VD->setType(DestType); 14397 E->setType(Type); 14398 E->setValueKind(ValueKind); 14399 return E; 14400 } 14401 14402 /// Check a cast of an unknown-any type. We intentionally only 14403 /// trigger this for C-style casts. 14404 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 14405 Expr *CastExpr, CastKind &CastKind, 14406 ExprValueKind &VK, CXXCastPath &Path) { 14407 // Rewrite the casted expression from scratch. 14408 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 14409 if (!result.isUsable()) return ExprError(); 14410 14411 CastExpr = result.get(); 14412 VK = CastExpr->getValueKind(); 14413 CastKind = CK_NoOp; 14414 14415 return CastExpr; 14416 } 14417 14418 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 14419 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 14420 } 14421 14422 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 14423 Expr *arg, QualType ¶mType) { 14424 // If the syntactic form of the argument is not an explicit cast of 14425 // any sort, just do default argument promotion. 14426 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 14427 if (!castArg) { 14428 ExprResult result = DefaultArgumentPromotion(arg); 14429 if (result.isInvalid()) return ExprError(); 14430 paramType = result.get()->getType(); 14431 return result; 14432 } 14433 14434 // Otherwise, use the type that was written in the explicit cast. 14435 assert(!arg->hasPlaceholderType()); 14436 paramType = castArg->getTypeAsWritten(); 14437 14438 // Copy-initialize a parameter of that type. 14439 InitializedEntity entity = 14440 InitializedEntity::InitializeParameter(Context, paramType, 14441 /*consumed*/ false); 14442 return PerformCopyInitialization(entity, callLoc, arg); 14443 } 14444 14445 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 14446 Expr *orig = E; 14447 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 14448 while (true) { 14449 E = E->IgnoreParenImpCasts(); 14450 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 14451 E = call->getCallee(); 14452 diagID = diag::err_uncasted_call_of_unknown_any; 14453 } else { 14454 break; 14455 } 14456 } 14457 14458 SourceLocation loc; 14459 NamedDecl *d; 14460 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 14461 loc = ref->getLocation(); 14462 d = ref->getDecl(); 14463 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 14464 loc = mem->getMemberLoc(); 14465 d = mem->getMemberDecl(); 14466 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 14467 diagID = diag::err_uncasted_call_of_unknown_any; 14468 loc = msg->getSelectorStartLoc(); 14469 d = msg->getMethodDecl(); 14470 if (!d) { 14471 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 14472 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 14473 << orig->getSourceRange(); 14474 return ExprError(); 14475 } 14476 } else { 14477 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 14478 << E->getSourceRange(); 14479 return ExprError(); 14480 } 14481 14482 S.Diag(loc, diagID) << d << orig->getSourceRange(); 14483 14484 // Never recoverable. 14485 return ExprError(); 14486 } 14487 14488 /// Check for operands with placeholder types and complain if found. 14489 /// Returns true if there was an error and no recovery was possible. 14490 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 14491 if (!getLangOpts().CPlusPlus) { 14492 // C cannot handle TypoExpr nodes on either side of a binop because it 14493 // doesn't handle dependent types properly, so make sure any TypoExprs have 14494 // been dealt with before checking the operands. 14495 ExprResult Result = CorrectDelayedTyposInExpr(E); 14496 if (!Result.isUsable()) return ExprError(); 14497 E = Result.get(); 14498 } 14499 14500 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 14501 if (!placeholderType) return E; 14502 14503 switch (placeholderType->getKind()) { 14504 14505 // Overloaded expressions. 14506 case BuiltinType::Overload: { 14507 // Try to resolve a single function template specialization. 14508 // This is obligatory. 14509 ExprResult result = E; 14510 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) { 14511 return result; 14512 14513 // If that failed, try to recover with a call. 14514 } else { 14515 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable), 14516 /*complain*/ true); 14517 return result; 14518 } 14519 } 14520 14521 // Bound member functions. 14522 case BuiltinType::BoundMember: { 14523 ExprResult result = E; 14524 const Expr *BME = E->IgnoreParens(); 14525 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 14526 // Try to give a nicer diagnostic if it is a bound member that we recognize. 14527 if (isa<CXXPseudoDestructorExpr>(BME)) { 14528 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 14529 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 14530 if (ME->getMemberNameInfo().getName().getNameKind() == 14531 DeclarationName::CXXDestructorName) 14532 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 14533 } 14534 tryToRecoverWithCall(result, PD, 14535 /*complain*/ true); 14536 return result; 14537 } 14538 14539 // ARC unbridged casts. 14540 case BuiltinType::ARCUnbridgedCast: { 14541 Expr *realCast = stripARCUnbridgedCast(E); 14542 diagnoseARCUnbridgedCast(realCast); 14543 return realCast; 14544 } 14545 14546 // Expressions of unknown type. 14547 case BuiltinType::UnknownAny: 14548 return diagnoseUnknownAnyExpr(*this, E); 14549 14550 // Pseudo-objects. 14551 case BuiltinType::PseudoObject: 14552 return checkPseudoObjectRValue(E); 14553 14554 case BuiltinType::BuiltinFn: { 14555 // Accept __noop without parens by implicitly converting it to a call expr. 14556 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 14557 if (DRE) { 14558 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 14559 if (FD->getBuiltinID() == Builtin::BI__noop) { 14560 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 14561 CK_BuiltinFnToFnPtr).get(); 14562 return new (Context) CallExpr(Context, E, None, Context.IntTy, 14563 VK_RValue, SourceLocation()); 14564 } 14565 } 14566 14567 Diag(E->getLocStart(), diag::err_builtin_fn_use); 14568 return ExprError(); 14569 } 14570 14571 // Expressions of unknown type. 14572 case BuiltinType::OMPArraySection: 14573 Diag(E->getLocStart(), diag::err_omp_array_section_use); 14574 return ExprError(); 14575 14576 // Everything else should be impossible. 14577 #define BUILTIN_TYPE(Id, SingletonId) \ 14578 case BuiltinType::Id: 14579 #define PLACEHOLDER_TYPE(Id, SingletonId) 14580 #include "clang/AST/BuiltinTypes.def" 14581 break; 14582 } 14583 14584 llvm_unreachable("invalid placeholder type!"); 14585 } 14586 14587 bool Sema::CheckCaseExpression(Expr *E) { 14588 if (E->isTypeDependent()) 14589 return true; 14590 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 14591 return E->getType()->isIntegralOrEnumerationType(); 14592 return false; 14593 } 14594 14595 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 14596 ExprResult 14597 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 14598 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 14599 "Unknown Objective-C Boolean value!"); 14600 QualType BoolT = Context.ObjCBuiltinBoolTy; 14601 if (!Context.getBOOLDecl()) { 14602 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 14603 Sema::LookupOrdinaryName); 14604 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 14605 NamedDecl *ND = Result.getFoundDecl(); 14606 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 14607 Context.setBOOLDecl(TD); 14608 } 14609 } 14610 if (Context.getBOOLDecl()) 14611 BoolT = Context.getBOOLType(); 14612 return new (Context) 14613 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 14614 } 14615