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 "TreeTransform.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/ASTMutationListener.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/DeclTemplate.h" 22 #include "clang/AST/EvaluatedExprVisitor.h" 23 #include "clang/AST/Expr.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/ExprObjC.h" 26 #include "clang/AST/ExprOpenMP.h" 27 #include "clang/AST/RecursiveASTVisitor.h" 28 #include "clang/AST/TypeLoc.h" 29 #include "clang/Basic/FixedPoint.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/Overload.h" 42 #include "clang/Sema/ParsedTemplate.h" 43 #include "clang/Sema/Scope.h" 44 #include "clang/Sema/ScopeInfo.h" 45 #include "clang/Sema/SemaFixItUtils.h" 46 #include "clang/Sema/SemaInternal.h" 47 #include "clang/Sema/Template.h" 48 #include "llvm/Support/ConvertUTF.h" 49 using namespace clang; 50 using namespace sema; 51 52 /// Determine whether the use of this declaration is valid, without 53 /// emitting diagnostics. 54 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) { 55 // See if this is an auto-typed variable whose initializer we are parsing. 56 if (ParsingInitForAutoVars.count(D)) 57 return false; 58 59 // See if this is a deleted function. 60 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 61 if (FD->isDeleted()) 62 return false; 63 64 // If the function has a deduced return type, and we can't deduce it, 65 // then we can't use it either. 66 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 67 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false)) 68 return false; 69 } 70 71 // See if this function is unavailable. 72 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable && 73 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable) 74 return false; 75 76 return true; 77 } 78 79 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) { 80 // Warn if this is used but marked unused. 81 if (const auto *A = D->getAttr<UnusedAttr>()) { 82 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused)) 83 // should diagnose them. 84 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused && 85 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) { 86 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext()); 87 if (DC && !DC->hasAttr<UnusedAttr>()) 88 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName(); 89 } 90 } 91 } 92 93 /// Emit a note explaining that this function is deleted. 94 void Sema::NoteDeletedFunction(FunctionDecl *Decl) { 95 assert(Decl->isDeleted()); 96 97 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl); 98 99 if (Method && Method->isDeleted() && Method->isDefaulted()) { 100 // If the method was explicitly defaulted, point at that declaration. 101 if (!Method->isImplicit()) 102 Diag(Decl->getLocation(), diag::note_implicitly_deleted); 103 104 // Try to diagnose why this special member function was implicitly 105 // deleted. This might fail, if that reason no longer applies. 106 CXXSpecialMember CSM = getSpecialMember(Method); 107 if (CSM != CXXInvalid) 108 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true); 109 110 return; 111 } 112 113 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl); 114 if (Ctor && Ctor->isInheritingConstructor()) 115 return NoteDeletedInheritingConstructor(Ctor); 116 117 Diag(Decl->getLocation(), diag::note_availability_specified_here) 118 << Decl << true; 119 } 120 121 /// Determine whether a FunctionDecl was ever declared with an 122 /// explicit storage class. 123 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) { 124 for (auto I : D->redecls()) { 125 if (I->getStorageClass() != SC_None) 126 return true; 127 } 128 return false; 129 } 130 131 /// Check whether we're in an extern inline function and referring to a 132 /// variable or function with internal linkage (C11 6.7.4p3). 133 /// 134 /// This is only a warning because we used to silently accept this code, but 135 /// in many cases it will not behave correctly. This is not enabled in C++ mode 136 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6) 137 /// and so while there may still be user mistakes, most of the time we can't 138 /// prove that there are errors. 139 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, 140 const NamedDecl *D, 141 SourceLocation Loc) { 142 // This is disabled under C++; there are too many ways for this to fire in 143 // contexts where the warning is a false positive, or where it is technically 144 // correct but benign. 145 if (S.getLangOpts().CPlusPlus) 146 return; 147 148 // Check if this is an inlined function or method. 149 FunctionDecl *Current = S.getCurFunctionDecl(); 150 if (!Current) 151 return; 152 if (!Current->isInlined()) 153 return; 154 if (!Current->isExternallyVisible()) 155 return; 156 157 // Check if the decl has internal linkage. 158 if (D->getFormalLinkage() != InternalLinkage) 159 return; 160 161 // Downgrade from ExtWarn to Extension if 162 // (1) the supposedly external inline function is in the main file, 163 // and probably won't be included anywhere else. 164 // (2) the thing we're referencing is a pure function. 165 // (3) the thing we're referencing is another inline function. 166 // This last can give us false negatives, but it's better than warning on 167 // wrappers for simple C library functions. 168 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D); 169 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc); 170 if (!DowngradeWarning && UsedFn) 171 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>(); 172 173 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet 174 : diag::ext_internal_in_extern_inline) 175 << /*IsVar=*/!UsedFn << D; 176 177 S.MaybeSuggestAddingStaticToDecl(Current); 178 179 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at) 180 << D; 181 } 182 183 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) { 184 const FunctionDecl *First = Cur->getFirstDecl(); 185 186 // Suggest "static" on the function, if possible. 187 if (!hasAnyExplicitStorageClass(First)) { 188 SourceLocation DeclBegin = First->getSourceRange().getBegin(); 189 Diag(DeclBegin, diag::note_convert_inline_to_static) 190 << Cur << FixItHint::CreateInsertion(DeclBegin, "static "); 191 } 192 } 193 194 /// Determine whether the use of this declaration is valid, and 195 /// emit any corresponding diagnostics. 196 /// 197 /// This routine diagnoses various problems with referencing 198 /// declarations that can occur when using a declaration. For example, 199 /// it might warn if a deprecated or unavailable declaration is being 200 /// used, or produce an error (and return true) if a C++0x deleted 201 /// function is being used. 202 /// 203 /// \returns true if there was an error (this declaration cannot be 204 /// referenced), false otherwise. 205 /// 206 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, 207 const ObjCInterfaceDecl *UnknownObjCClass, 208 bool ObjCPropertyAccess, 209 bool AvoidPartialAvailabilityChecks, 210 ObjCInterfaceDecl *ClassReceiver) { 211 SourceLocation Loc = Locs.front(); 212 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) { 213 // If there were any diagnostics suppressed by template argument deduction, 214 // emit them now. 215 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl()); 216 if (Pos != SuppressedDiagnostics.end()) { 217 for (const PartialDiagnosticAt &Suppressed : Pos->second) 218 Diag(Suppressed.first, Suppressed.second); 219 220 // Clear out the list of suppressed diagnostics, so that we don't emit 221 // them again for this specialization. However, we don't obsolete this 222 // entry from the table, because we want to avoid ever emitting these 223 // diagnostics again. 224 Pos->second.clear(); 225 } 226 227 // C++ [basic.start.main]p3: 228 // The function 'main' shall not be used within a program. 229 if (cast<FunctionDecl>(D)->isMain()) 230 Diag(Loc, diag::ext_main_used); 231 } 232 233 // See if this is an auto-typed variable whose initializer we are parsing. 234 if (ParsingInitForAutoVars.count(D)) { 235 if (isa<BindingDecl>(D)) { 236 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer) 237 << D->getDeclName(); 238 } else { 239 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer) 240 << D->getDeclName() << cast<VarDecl>(D)->getType(); 241 } 242 return true; 243 } 244 245 // See if this is a deleted function. 246 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 247 if (FD->isDeleted()) { 248 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD); 249 if (Ctor && Ctor->isInheritingConstructor()) 250 Diag(Loc, diag::err_deleted_inherited_ctor_use) 251 << Ctor->getParent() 252 << Ctor->getInheritedConstructor().getConstructor()->getParent(); 253 else 254 Diag(Loc, diag::err_deleted_function_use); 255 NoteDeletedFunction(FD); 256 return true; 257 } 258 259 // If the function has a deduced return type, and we can't deduce it, 260 // then we can't use it either. 261 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 262 DeduceReturnType(FD, Loc)) 263 return true; 264 265 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD)) 266 return true; 267 } 268 269 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 270 // Lambdas are only default-constructible or assignable in C++2a onwards. 271 if (MD->getParent()->isLambda() && 272 ((isa<CXXConstructorDecl>(MD) && 273 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) || 274 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) { 275 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign) 276 << !isa<CXXConstructorDecl>(MD); 277 } 278 } 279 280 auto getReferencedObjCProp = [](const NamedDecl *D) -> 281 const ObjCPropertyDecl * { 282 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 283 return MD->findPropertyDecl(); 284 return nullptr; 285 }; 286 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) { 287 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc)) 288 return true; 289 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) { 290 return true; 291 } 292 293 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 294 // Only the variables omp_in and omp_out are allowed in the combiner. 295 // Only the variables omp_priv and omp_orig are allowed in the 296 // initializer-clause. 297 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext); 298 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) && 299 isa<VarDecl>(D)) { 300 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction) 301 << getCurFunction()->HasOMPDeclareReductionCombiner; 302 Diag(D->getLocation(), diag::note_entity_declared_at) << D; 303 return true; 304 } 305 306 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess, 307 AvoidPartialAvailabilityChecks, ClassReceiver); 308 309 DiagnoseUnusedOfDecl(*this, D, Loc); 310 311 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc); 312 313 return false; 314 } 315 316 /// Retrieve the message suffix that should be added to a 317 /// diagnostic complaining about the given function being deleted or 318 /// unavailable. 319 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) { 320 std::string Message; 321 if (FD->getAvailability(&Message)) 322 return ": " + Message; 323 324 return std::string(); 325 } 326 327 /// DiagnoseSentinelCalls - This routine checks whether a call or 328 /// message-send is to a declaration with the sentinel attribute, and 329 /// if so, it checks that the requirements of the sentinel are 330 /// satisfied. 331 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 332 ArrayRef<Expr *> Args) { 333 const SentinelAttr *attr = D->getAttr<SentinelAttr>(); 334 if (!attr) 335 return; 336 337 // The number of formal parameters of the declaration. 338 unsigned numFormalParams; 339 340 // The kind of declaration. This is also an index into a %select in 341 // the diagnostic. 342 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType; 343 344 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 345 numFormalParams = MD->param_size(); 346 calleeType = CT_Method; 347 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 348 numFormalParams = FD->param_size(); 349 calleeType = CT_Function; 350 } else if (isa<VarDecl>(D)) { 351 QualType type = cast<ValueDecl>(D)->getType(); 352 const FunctionType *fn = nullptr; 353 if (const PointerType *ptr = type->getAs<PointerType>()) { 354 fn = ptr->getPointeeType()->getAs<FunctionType>(); 355 if (!fn) return; 356 calleeType = CT_Function; 357 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) { 358 fn = ptr->getPointeeType()->castAs<FunctionType>(); 359 calleeType = CT_Block; 360 } else { 361 return; 362 } 363 364 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) { 365 numFormalParams = proto->getNumParams(); 366 } else { 367 numFormalParams = 0; 368 } 369 } else { 370 return; 371 } 372 373 // "nullPos" is the number of formal parameters at the end which 374 // effectively count as part of the variadic arguments. This is 375 // useful if you would prefer to not have *any* formal parameters, 376 // but the language forces you to have at least one. 377 unsigned nullPos = attr->getNullPos(); 378 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"); 379 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos); 380 381 // The number of arguments which should follow the sentinel. 382 unsigned numArgsAfterSentinel = attr->getSentinel(); 383 384 // If there aren't enough arguments for all the formal parameters, 385 // the sentinel, and the args after the sentinel, complain. 386 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) { 387 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName(); 388 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 389 return; 390 } 391 392 // Otherwise, find the sentinel expression. 393 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1]; 394 if (!sentinelExpr) return; 395 if (sentinelExpr->isValueDependent()) return; 396 if (Context.isSentinelNullExpr(sentinelExpr)) return; 397 398 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr', 399 // or 'NULL' if those are actually defined in the context. Only use 400 // 'nil' for ObjC methods, where it's much more likely that the 401 // variadic arguments form a list of object pointers. 402 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc()); 403 std::string NullValue; 404 if (calleeType == CT_Method && PP.isMacroDefined("nil")) 405 NullValue = "nil"; 406 else if (getLangOpts().CPlusPlus11) 407 NullValue = "nullptr"; 408 else if (PP.isMacroDefined("NULL")) 409 NullValue = "NULL"; 410 else 411 NullValue = "(void*) 0"; 412 413 if (MissingNilLoc.isInvalid()) 414 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType); 415 else 416 Diag(MissingNilLoc, diag::warn_missing_sentinel) 417 << int(calleeType) 418 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue); 419 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType); 420 } 421 422 SourceRange Sema::getExprRange(Expr *E) const { 423 return E ? E->getSourceRange() : SourceRange(); 424 } 425 426 //===----------------------------------------------------------------------===// 427 // Standard Promotions and Conversions 428 //===----------------------------------------------------------------------===// 429 430 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4). 431 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) { 432 // Handle any placeholder expressions which made it here. 433 if (E->getType()->isPlaceholderType()) { 434 ExprResult result = CheckPlaceholderExpr(E); 435 if (result.isInvalid()) return ExprError(); 436 E = result.get(); 437 } 438 439 QualType Ty = E->getType(); 440 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"); 441 442 if (Ty->isFunctionType()) { 443 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts())) 444 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 445 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc())) 446 return ExprError(); 447 448 E = ImpCastExprToType(E, Context.getPointerType(Ty), 449 CK_FunctionToPointerDecay).get(); 450 } else if (Ty->isArrayType()) { 451 // In C90 mode, arrays only promote to pointers if the array expression is 452 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has 453 // type 'array of type' is converted to an expression that has type 'pointer 454 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression 455 // that has type 'array of type' ...". The relevant change is "an lvalue" 456 // (C90) to "an expression" (C99). 457 // 458 // C++ 4.2p1: 459 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of 460 // T" can be converted to an rvalue of type "pointer to T". 461 // 462 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) 463 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty), 464 CK_ArrayToPointerDecay).get(); 465 } 466 return E; 467 } 468 469 static void CheckForNullPointerDereference(Sema &S, Expr *E) { 470 // Check to see if we are dereferencing a null pointer. If so, 471 // and if not volatile-qualified, this is undefined behavior that the 472 // optimizer will delete, so warn about it. People sometimes try to use this 473 // to get a deterministic trap and are surprised by clang's behavior. This 474 // only handles the pattern "*null", which is a very syntactic check. 475 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts())) 476 if (UO->getOpcode() == UO_Deref && 477 UO->getSubExpr()->IgnoreParenCasts()-> 478 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) && 479 !UO->getType().isVolatileQualified()) { 480 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 481 S.PDiag(diag::warn_indirection_through_null) 482 << UO->getSubExpr()->getSourceRange()); 483 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO, 484 S.PDiag(diag::note_indirection_through_null)); 485 } 486 } 487 488 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, 489 SourceLocation AssignLoc, 490 const Expr* RHS) { 491 const ObjCIvarDecl *IV = OIRE->getDecl(); 492 if (!IV) 493 return; 494 495 DeclarationName MemberName = IV->getDeclName(); 496 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 497 if (!Member || !Member->isStr("isa")) 498 return; 499 500 const Expr *Base = OIRE->getBase(); 501 QualType BaseType = Base->getType(); 502 if (OIRE->isArrow()) 503 BaseType = BaseType->getPointeeType(); 504 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) 505 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) { 506 ObjCInterfaceDecl *ClassDeclared = nullptr; 507 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 508 if (!ClassDeclared->getSuperClass() 509 && (*ClassDeclared->ivar_begin()) == IV) { 510 if (RHS) { 511 NamedDecl *ObjectSetClass = 512 S.LookupSingleName(S.TUScope, 513 &S.Context.Idents.get("object_setClass"), 514 SourceLocation(), S.LookupOrdinaryName); 515 if (ObjectSetClass) { 516 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc()); 517 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) 518 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 519 "object_setClass(") 520 << FixItHint::CreateReplacement( 521 SourceRange(OIRE->getOpLoc(), AssignLoc), ",") 522 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 523 } 524 else 525 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign); 526 } else { 527 NamedDecl *ObjectGetClass = 528 S.LookupSingleName(S.TUScope, 529 &S.Context.Idents.get("object_getClass"), 530 SourceLocation(), S.LookupOrdinaryName); 531 if (ObjectGetClass) 532 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) 533 << FixItHint::CreateInsertion(OIRE->getBeginLoc(), 534 "object_getClass(") 535 << FixItHint::CreateReplacement( 536 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")"); 537 else 538 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use); 539 } 540 S.Diag(IV->getLocation(), diag::note_ivar_decl); 541 } 542 } 543 } 544 545 ExprResult Sema::DefaultLvalueConversion(Expr *E) { 546 // Handle any placeholder expressions which made it here. 547 if (E->getType()->isPlaceholderType()) { 548 ExprResult result = CheckPlaceholderExpr(E); 549 if (result.isInvalid()) return ExprError(); 550 E = result.get(); 551 } 552 553 // C++ [conv.lval]p1: 554 // A glvalue of a non-function, non-array type T can be 555 // converted to a prvalue. 556 if (!E->isGLValue()) return E; 557 558 QualType T = E->getType(); 559 assert(!T.isNull() && "r-value conversion on typeless expression?"); 560 561 // We don't want to throw lvalue-to-rvalue casts on top of 562 // expressions of certain types in C++. 563 if (getLangOpts().CPlusPlus && 564 (E->getType() == Context.OverloadTy || 565 T->isDependentType() || 566 T->isRecordType())) 567 return E; 568 569 // The C standard is actually really unclear on this point, and 570 // DR106 tells us what the result should be but not why. It's 571 // generally best to say that void types just doesn't undergo 572 // lvalue-to-rvalue at all. Note that expressions of unqualified 573 // 'void' type are never l-values, but qualified void can be. 574 if (T->isVoidType()) 575 return E; 576 577 // OpenCL usually rejects direct accesses to values of 'half' type. 578 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 579 T->isHalfType()) { 580 Diag(E->getExprLoc(), diag::err_opencl_half_load_store) 581 << 0 << T; 582 return ExprError(); 583 } 584 585 CheckForNullPointerDereference(*this, E); 586 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) { 587 NamedDecl *ObjectGetClass = LookupSingleName(TUScope, 588 &Context.Idents.get("object_getClass"), 589 SourceLocation(), LookupOrdinaryName); 590 if (ObjectGetClass) 591 Diag(E->getExprLoc(), diag::warn_objc_isa_use) 592 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(") 593 << FixItHint::CreateReplacement( 594 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")"); 595 else 596 Diag(E->getExprLoc(), diag::warn_objc_isa_use); 597 } 598 else if (const ObjCIvarRefExpr *OIRE = 599 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts())) 600 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr); 601 602 // C++ [conv.lval]p1: 603 // [...] If T is a non-class type, the type of the prvalue is the 604 // cv-unqualified version of T. Otherwise, the type of the 605 // rvalue is T. 606 // 607 // C99 6.3.2.1p2: 608 // If the lvalue has qualified type, the value has the unqualified 609 // version of the type of the lvalue; otherwise, the value has the 610 // type of the lvalue. 611 if (T.hasQualifiers()) 612 T = T.getUnqualifiedType(); 613 614 // Under the MS ABI, lock down the inheritance model now. 615 if (T->isMemberPointerType() && 616 Context.getTargetInfo().getCXXABI().isMicrosoft()) 617 (void)isCompleteType(E->getExprLoc(), T); 618 619 UpdateMarkingForLValueToRValue(E); 620 621 // Loading a __weak object implicitly retains the value, so we need a cleanup to 622 // balance that. 623 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak) 624 Cleanup.setExprNeedsCleanups(true); 625 626 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E, 627 nullptr, VK_RValue); 628 629 // C11 6.3.2.1p2: 630 // ... if the lvalue has atomic type, the value has the non-atomic version 631 // of the type of the lvalue ... 632 if (const AtomicType *Atomic = T->getAs<AtomicType>()) { 633 T = Atomic->getValueType().getUnqualifiedType(); 634 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(), 635 nullptr, VK_RValue); 636 } 637 638 return Res; 639 } 640 641 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) { 642 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose); 643 if (Res.isInvalid()) 644 return ExprError(); 645 Res = DefaultLvalueConversion(Res.get()); 646 if (Res.isInvalid()) 647 return ExprError(); 648 return Res; 649 } 650 651 /// CallExprUnaryConversions - a special case of an unary conversion 652 /// performed on a function designator of a call expression. 653 ExprResult Sema::CallExprUnaryConversions(Expr *E) { 654 QualType Ty = E->getType(); 655 ExprResult Res = E; 656 // Only do implicit cast for a function type, but not for a pointer 657 // to function type. 658 if (Ty->isFunctionType()) { 659 Res = ImpCastExprToType(E, Context.getPointerType(Ty), 660 CK_FunctionToPointerDecay).get(); 661 if (Res.isInvalid()) 662 return ExprError(); 663 } 664 Res = DefaultLvalueConversion(Res.get()); 665 if (Res.isInvalid()) 666 return ExprError(); 667 return Res.get(); 668 } 669 670 /// UsualUnaryConversions - Performs various conversions that are common to most 671 /// operators (C99 6.3). The conversions of array and function types are 672 /// sometimes suppressed. For example, the array->pointer conversion doesn't 673 /// apply if the array is an argument to the sizeof or address (&) operators. 674 /// In these instances, this routine should *not* be called. 675 ExprResult Sema::UsualUnaryConversions(Expr *E) { 676 // First, convert to an r-value. 677 ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 678 if (Res.isInvalid()) 679 return ExprError(); 680 E = Res.get(); 681 682 QualType Ty = E->getType(); 683 assert(!Ty.isNull() && "UsualUnaryConversions - missing type"); 684 685 // Half FP have to be promoted to float unless it is natively supported 686 if (Ty->isHalfType() && !getLangOpts().NativeHalfType) 687 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast); 688 689 // Try to perform integral promotions if the object has a theoretically 690 // promotable type. 691 if (Ty->isIntegralOrUnscopedEnumerationType()) { 692 // C99 6.3.1.1p2: 693 // 694 // The following may be used in an expression wherever an int or 695 // unsigned int may be used: 696 // - an object or expression with an integer type whose integer 697 // conversion rank is less than or equal to the rank of int 698 // and unsigned int. 699 // - A bit-field of type _Bool, int, signed int, or unsigned int. 700 // 701 // If an int can represent all values of the original type, the 702 // value is converted to an int; otherwise, it is converted to an 703 // unsigned int. These are called the integer promotions. All 704 // other types are unchanged by the integer promotions. 705 706 QualType PTy = Context.isPromotableBitField(E); 707 if (!PTy.isNull()) { 708 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get(); 709 return E; 710 } 711 if (Ty->isPromotableIntegerType()) { 712 QualType PT = Context.getPromotedIntegerType(Ty); 713 E = ImpCastExprToType(E, PT, CK_IntegralCast).get(); 714 return E; 715 } 716 } 717 return E; 718 } 719 720 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 721 /// do not have a prototype. Arguments that have type float or __fp16 722 /// are promoted to double. All other argument types are converted by 723 /// UsualUnaryConversions(). 724 ExprResult Sema::DefaultArgumentPromotion(Expr *E) { 725 QualType Ty = E->getType(); 726 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type"); 727 728 ExprResult Res = UsualUnaryConversions(E); 729 if (Res.isInvalid()) 730 return ExprError(); 731 E = Res.get(); 732 733 QualType ScalarTy = Ty; 734 unsigned NumElts = 0; 735 if (const ExtVectorType *VecTy = Ty->getAs<ExtVectorType>()) { 736 NumElts = VecTy->getNumElements(); 737 ScalarTy = VecTy->getElementType(); 738 } 739 740 // If this is a 'float' or '__fp16' (CVR qualified or typedef) 741 // promote to double. 742 // Note that default argument promotion applies only to float (and 743 // half/fp16); it does not apply to _Float16. 744 const BuiltinType *BTy = ScalarTy->getAs<BuiltinType>(); 745 if (BTy && (BTy->getKind() == BuiltinType::Half || 746 BTy->getKind() == BuiltinType::Float)) { 747 if (getLangOpts().OpenCL && 748 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 749 if (BTy->getKind() == BuiltinType::Half) { 750 QualType Ty = Context.FloatTy; 751 if (NumElts != 0) 752 Ty = Context.getExtVectorType(Ty, NumElts); 753 E = ImpCastExprToType(E, Ty, CK_FloatingCast).get(); 754 } 755 } else { 756 QualType Ty = Context.DoubleTy; 757 if (NumElts != 0) 758 Ty = Context.getExtVectorType(Ty, NumElts); 759 E = ImpCastExprToType(E, Ty, CK_FloatingCast).get(); 760 } 761 } 762 763 // C++ performs lvalue-to-rvalue conversion as a default argument 764 // promotion, even on class types, but note: 765 // C++11 [conv.lval]p2: 766 // When an lvalue-to-rvalue conversion occurs in an unevaluated 767 // operand or a subexpression thereof the value contained in the 768 // referenced object is not accessed. Otherwise, if the glvalue 769 // has a class type, the conversion copy-initializes a temporary 770 // of type T from the glvalue and the result of the conversion 771 // is a prvalue for the temporary. 772 // FIXME: add some way to gate this entire thing for correctness in 773 // potentially potentially evaluated contexts. 774 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) { 775 ExprResult Temp = PerformCopyInitialization( 776 InitializedEntity::InitializeTemporary(E->getType()), 777 E->getExprLoc(), E); 778 if (Temp.isInvalid()) 779 return ExprError(); 780 E = Temp.get(); 781 } 782 783 return E; 784 } 785 786 /// Determine the degree of POD-ness for an expression. 787 /// Incomplete types are considered POD, since this check can be performed 788 /// when we're in an unevaluated context. 789 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) { 790 if (Ty->isIncompleteType()) { 791 // C++11 [expr.call]p7: 792 // After these conversions, if the argument does not have arithmetic, 793 // enumeration, pointer, pointer to member, or class type, the program 794 // is ill-formed. 795 // 796 // Since we've already performed array-to-pointer and function-to-pointer 797 // decay, the only such type in C++ is cv void. This also handles 798 // initializer lists as variadic arguments. 799 if (Ty->isVoidType()) 800 return VAK_Invalid; 801 802 if (Ty->isObjCObjectType()) 803 return VAK_Invalid; 804 return VAK_Valid; 805 } 806 807 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 808 return VAK_Invalid; 809 810 if (Ty.isCXX98PODType(Context)) 811 return VAK_Valid; 812 813 // C++11 [expr.call]p7: 814 // Passing a potentially-evaluated argument of class type (Clause 9) 815 // having a non-trivial copy constructor, a non-trivial move constructor, 816 // or a non-trivial destructor, with no corresponding parameter, 817 // is conditionally-supported with implementation-defined semantics. 818 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType()) 819 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl()) 820 if (!Record->hasNonTrivialCopyConstructor() && 821 !Record->hasNonTrivialMoveConstructor() && 822 !Record->hasNonTrivialDestructor()) 823 return VAK_ValidInCXX11; 824 825 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType()) 826 return VAK_Valid; 827 828 if (Ty->isObjCObjectType()) 829 return VAK_Invalid; 830 831 if (getLangOpts().MSVCCompat) 832 return VAK_MSVCUndefined; 833 834 // FIXME: In C++11, these cases are conditionally-supported, meaning we're 835 // permitted to reject them. We should consider doing so. 836 return VAK_Undefined; 837 } 838 839 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) { 840 // Don't allow one to pass an Objective-C interface to a vararg. 841 const QualType &Ty = E->getType(); 842 VarArgKind VAK = isValidVarArgType(Ty); 843 844 // Complain about passing non-POD types through varargs. 845 switch (VAK) { 846 case VAK_ValidInCXX11: 847 DiagRuntimeBehavior( 848 E->getBeginLoc(), nullptr, 849 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT); 850 LLVM_FALLTHROUGH; 851 case VAK_Valid: 852 if (Ty->isRecordType()) { 853 // This is unlikely to be what the user intended. If the class has a 854 // 'c_str' member function, the user probably meant to call that. 855 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 856 PDiag(diag::warn_pass_class_arg_to_vararg) 857 << Ty << CT << hasCStrMethod(E) << ".c_str()"); 858 } 859 break; 860 861 case VAK_Undefined: 862 case VAK_MSVCUndefined: 863 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 864 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg) 865 << getLangOpts().CPlusPlus11 << Ty << CT); 866 break; 867 868 case VAK_Invalid: 869 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct) 870 Diag(E->getBeginLoc(), 871 diag::err_cannot_pass_non_trivial_c_struct_to_vararg) 872 << Ty << CT; 873 else if (Ty->isObjCObjectType()) 874 DiagRuntimeBehavior(E->getBeginLoc(), nullptr, 875 PDiag(diag::err_cannot_pass_objc_interface_to_vararg) 876 << Ty << CT); 877 else 878 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg) 879 << isa<InitListExpr>(E) << Ty << CT; 880 break; 881 } 882 } 883 884 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 885 /// will create a trap if the resulting type is not a POD type. 886 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 887 FunctionDecl *FDecl) { 888 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) { 889 // Strip the unbridged-cast placeholder expression off, if applicable. 890 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast && 891 (CT == VariadicMethod || 892 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) { 893 E = stripARCUnbridgedCast(E); 894 895 // Otherwise, do normal placeholder checking. 896 } else { 897 ExprResult ExprRes = CheckPlaceholderExpr(E); 898 if (ExprRes.isInvalid()) 899 return ExprError(); 900 E = ExprRes.get(); 901 } 902 } 903 904 ExprResult ExprRes = DefaultArgumentPromotion(E); 905 if (ExprRes.isInvalid()) 906 return ExprError(); 907 E = ExprRes.get(); 908 909 // Diagnostics regarding non-POD argument types are 910 // emitted along with format string checking in Sema::CheckFunctionCall(). 911 if (isValidVarArgType(E->getType()) == VAK_Undefined) { 912 // Turn this into a trap. 913 CXXScopeSpec SS; 914 SourceLocation TemplateKWLoc; 915 UnqualifiedId Name; 916 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"), 917 E->getBeginLoc()); 918 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, 919 Name, true, false); 920 if (TrapFn.isInvalid()) 921 return ExprError(); 922 923 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), 924 None, E->getEndLoc()); 925 if (Call.isInvalid()) 926 return ExprError(); 927 928 ExprResult Comma = 929 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E); 930 if (Comma.isInvalid()) 931 return ExprError(); 932 return Comma.get(); 933 } 934 935 if (!getLangOpts().CPlusPlus && 936 RequireCompleteType(E->getExprLoc(), E->getType(), 937 diag::err_call_incomplete_argument)) 938 return ExprError(); 939 940 return E; 941 } 942 943 /// Converts an integer to complex float type. Helper function of 944 /// UsualArithmeticConversions() 945 /// 946 /// \return false if the integer expression is an integer type and is 947 /// successfully converted to the complex type. 948 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr, 949 ExprResult &ComplexExpr, 950 QualType IntTy, 951 QualType ComplexTy, 952 bool SkipCast) { 953 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true; 954 if (SkipCast) return false; 955 if (IntTy->isIntegerType()) { 956 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType(); 957 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating); 958 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 959 CK_FloatingRealToComplex); 960 } else { 961 assert(IntTy->isComplexIntegerType()); 962 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy, 963 CK_IntegralComplexToFloatingComplex); 964 } 965 return false; 966 } 967 968 /// Handle arithmetic conversion with complex types. Helper function of 969 /// UsualArithmeticConversions() 970 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS, 971 ExprResult &RHS, QualType LHSType, 972 QualType RHSType, 973 bool IsCompAssign) { 974 // if we have an integer operand, the result is the complex type. 975 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType, 976 /*skipCast*/false)) 977 return LHSType; 978 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType, 979 /*skipCast*/IsCompAssign)) 980 return RHSType; 981 982 // This handles complex/complex, complex/float, or float/complex. 983 // When both operands are complex, the shorter operand is converted to the 984 // type of the longer, and that is the type of the result. This corresponds 985 // to what is done when combining two real floating-point operands. 986 // The fun begins when size promotion occur across type domains. 987 // From H&S 6.3.4: When one operand is complex and the other is a real 988 // floating-point type, the less precise type is converted, within it's 989 // real or complex domain, to the precision of the other type. For example, 990 // when combining a "long double" with a "double _Complex", the 991 // "double _Complex" is promoted to "long double _Complex". 992 993 // Compute the rank of the two types, regardless of whether they are complex. 994 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 995 996 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType); 997 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType); 998 QualType LHSElementType = 999 LHSComplexType ? LHSComplexType->getElementType() : LHSType; 1000 QualType RHSElementType = 1001 RHSComplexType ? RHSComplexType->getElementType() : RHSType; 1002 1003 QualType ResultType = S.Context.getComplexType(LHSElementType); 1004 if (Order < 0) { 1005 // Promote the precision of the LHS if not an assignment. 1006 ResultType = S.Context.getComplexType(RHSElementType); 1007 if (!IsCompAssign) { 1008 if (LHSComplexType) 1009 LHS = 1010 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast); 1011 else 1012 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast); 1013 } 1014 } else if (Order > 0) { 1015 // Promote the precision of the RHS. 1016 if (RHSComplexType) 1017 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast); 1018 else 1019 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast); 1020 } 1021 return ResultType; 1022 } 1023 1024 /// Handle arithmetic conversion from integer to float. Helper function 1025 /// of UsualArithmeticConversions() 1026 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, 1027 ExprResult &IntExpr, 1028 QualType FloatTy, QualType IntTy, 1029 bool ConvertFloat, bool ConvertInt) { 1030 if (IntTy->isIntegerType()) { 1031 if (ConvertInt) 1032 // Convert intExpr to the lhs floating point type. 1033 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy, 1034 CK_IntegralToFloating); 1035 return FloatTy; 1036 } 1037 1038 // Convert both sides to the appropriate complex float. 1039 assert(IntTy->isComplexIntegerType()); 1040 QualType result = S.Context.getComplexType(FloatTy); 1041 1042 // _Complex int -> _Complex float 1043 if (ConvertInt) 1044 IntExpr = S.ImpCastExprToType(IntExpr.get(), result, 1045 CK_IntegralComplexToFloatingComplex); 1046 1047 // float -> _Complex float 1048 if (ConvertFloat) 1049 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result, 1050 CK_FloatingRealToComplex); 1051 1052 return result; 1053 } 1054 1055 /// Handle arithmethic conversion with floating point types. Helper 1056 /// function of UsualArithmeticConversions() 1057 static QualType handleFloatConversion(Sema &S, ExprResult &LHS, 1058 ExprResult &RHS, QualType LHSType, 1059 QualType RHSType, bool IsCompAssign) { 1060 bool LHSFloat = LHSType->isRealFloatingType(); 1061 bool RHSFloat = RHSType->isRealFloatingType(); 1062 1063 // If we have two real floating types, convert the smaller operand 1064 // to the bigger result. 1065 if (LHSFloat && RHSFloat) { 1066 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType); 1067 if (order > 0) { 1068 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast); 1069 return LHSType; 1070 } 1071 1072 assert(order < 0 && "illegal float comparison"); 1073 if (!IsCompAssign) 1074 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast); 1075 return RHSType; 1076 } 1077 1078 if (LHSFloat) { 1079 // Half FP has to be promoted to float unless it is natively supported 1080 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType) 1081 LHSType = S.Context.FloatTy; 1082 1083 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType, 1084 /*convertFloat=*/!IsCompAssign, 1085 /*convertInt=*/ true); 1086 } 1087 assert(RHSFloat); 1088 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType, 1089 /*convertInt=*/ true, 1090 /*convertFloat=*/!IsCompAssign); 1091 } 1092 1093 /// Diagnose attempts to convert between __float128 and long double if 1094 /// there is no support for such conversion. Helper function of 1095 /// UsualArithmeticConversions(). 1096 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, 1097 QualType RHSType) { 1098 /* No issue converting if at least one of the types is not a floating point 1099 type or the two types have the same rank. 1100 */ 1101 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() || 1102 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0) 1103 return false; 1104 1105 assert(LHSType->isFloatingType() && RHSType->isFloatingType() && 1106 "The remaining types must be floating point types."); 1107 1108 auto *LHSComplex = LHSType->getAs<ComplexType>(); 1109 auto *RHSComplex = RHSType->getAs<ComplexType>(); 1110 1111 QualType LHSElemType = LHSComplex ? 1112 LHSComplex->getElementType() : LHSType; 1113 QualType RHSElemType = RHSComplex ? 1114 RHSComplex->getElementType() : RHSType; 1115 1116 // No issue if the two types have the same representation 1117 if (&S.Context.getFloatTypeSemantics(LHSElemType) == 1118 &S.Context.getFloatTypeSemantics(RHSElemType)) 1119 return false; 1120 1121 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty && 1122 RHSElemType == S.Context.LongDoubleTy); 1123 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy && 1124 RHSElemType == S.Context.Float128Ty); 1125 1126 // We've handled the situation where __float128 and long double have the same 1127 // representation. We allow all conversions for all possible long double types 1128 // except PPC's double double. 1129 return Float128AndLongDouble && 1130 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1131 &llvm::APFloat::PPCDoubleDouble()); 1132 } 1133 1134 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType); 1135 1136 namespace { 1137 /// These helper callbacks are placed in an anonymous namespace to 1138 /// permit their use as function template parameters. 1139 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) { 1140 return S.ImpCastExprToType(op, toType, CK_IntegralCast); 1141 } 1142 1143 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) { 1144 return S.ImpCastExprToType(op, S.Context.getComplexType(toType), 1145 CK_IntegralComplexCast); 1146 } 1147 } 1148 1149 /// Handle integer arithmetic conversions. Helper function of 1150 /// UsualArithmeticConversions() 1151 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast> 1152 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, 1153 ExprResult &RHS, QualType LHSType, 1154 QualType RHSType, bool IsCompAssign) { 1155 // The rules for this case are in C99 6.3.1.8 1156 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType); 1157 bool LHSSigned = LHSType->hasSignedIntegerRepresentation(); 1158 bool RHSSigned = RHSType->hasSignedIntegerRepresentation(); 1159 if (LHSSigned == RHSSigned) { 1160 // Same signedness; use the higher-ranked type 1161 if (order >= 0) { 1162 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1163 return LHSType; 1164 } else if (!IsCompAssign) 1165 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1166 return RHSType; 1167 } else if (order != (LHSSigned ? 1 : -1)) { 1168 // The unsigned type has greater than or equal rank to the 1169 // signed type, so use the unsigned type 1170 if (RHSSigned) { 1171 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1172 return LHSType; 1173 } else if (!IsCompAssign) 1174 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1175 return RHSType; 1176 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) { 1177 // The two types are different widths; if we are here, that 1178 // means the signed type is larger than the unsigned type, so 1179 // use the signed type. 1180 if (LHSSigned) { 1181 RHS = (*doRHSCast)(S, RHS.get(), LHSType); 1182 return LHSType; 1183 } else if (!IsCompAssign) 1184 LHS = (*doLHSCast)(S, LHS.get(), RHSType); 1185 return RHSType; 1186 } else { 1187 // The signed type is higher-ranked than the unsigned type, 1188 // but isn't actually any bigger (like unsigned int and long 1189 // on most 32-bit systems). Use the unsigned type corresponding 1190 // to the signed type. 1191 QualType result = 1192 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType); 1193 RHS = (*doRHSCast)(S, RHS.get(), result); 1194 if (!IsCompAssign) 1195 LHS = (*doLHSCast)(S, LHS.get(), result); 1196 return result; 1197 } 1198 } 1199 1200 /// Handle conversions with GCC complex int extension. Helper function 1201 /// of UsualArithmeticConversions() 1202 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, 1203 ExprResult &RHS, QualType LHSType, 1204 QualType RHSType, 1205 bool IsCompAssign) { 1206 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType(); 1207 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType(); 1208 1209 if (LHSComplexInt && RHSComplexInt) { 1210 QualType LHSEltType = LHSComplexInt->getElementType(); 1211 QualType RHSEltType = RHSComplexInt->getElementType(); 1212 QualType ScalarType = 1213 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast> 1214 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign); 1215 1216 return S.Context.getComplexType(ScalarType); 1217 } 1218 1219 if (LHSComplexInt) { 1220 QualType LHSEltType = LHSComplexInt->getElementType(); 1221 QualType ScalarType = 1222 handleIntegerConversion<doComplexIntegralCast, doIntegralCast> 1223 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign); 1224 QualType ComplexType = S.Context.getComplexType(ScalarType); 1225 RHS = S.ImpCastExprToType(RHS.get(), ComplexType, 1226 CK_IntegralRealToComplex); 1227 1228 return ComplexType; 1229 } 1230 1231 assert(RHSComplexInt); 1232 1233 QualType RHSEltType = RHSComplexInt->getElementType(); 1234 QualType ScalarType = 1235 handleIntegerConversion<doIntegralCast, doComplexIntegralCast> 1236 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign); 1237 QualType ComplexType = S.Context.getComplexType(ScalarType); 1238 1239 if (!IsCompAssign) 1240 LHS = S.ImpCastExprToType(LHS.get(), ComplexType, 1241 CK_IntegralRealToComplex); 1242 return ComplexType; 1243 } 1244 1245 /// UsualArithmeticConversions - Performs various conversions that are common to 1246 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this 1247 /// routine returns the first non-arithmetic type found. The client is 1248 /// responsible for emitting appropriate error diagnostics. 1249 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 1250 bool IsCompAssign) { 1251 if (!IsCompAssign) { 1252 LHS = UsualUnaryConversions(LHS.get()); 1253 if (LHS.isInvalid()) 1254 return QualType(); 1255 } 1256 1257 RHS = UsualUnaryConversions(RHS.get()); 1258 if (RHS.isInvalid()) 1259 return QualType(); 1260 1261 // For conversion purposes, we ignore any qualifiers. 1262 // For example, "const float" and "float" are equivalent. 1263 QualType LHSType = 1264 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 1265 QualType RHSType = 1266 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 1267 1268 // For conversion purposes, we ignore any atomic qualifier on the LHS. 1269 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>()) 1270 LHSType = AtomicLHS->getValueType(); 1271 1272 // If both types are identical, no conversion is needed. 1273 if (LHSType == RHSType) 1274 return LHSType; 1275 1276 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 1277 // The caller can deal with this (e.g. pointer + int). 1278 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType()) 1279 return QualType(); 1280 1281 // Apply unary and bitfield promotions to the LHS's type. 1282 QualType LHSUnpromotedType = LHSType; 1283 if (LHSType->isPromotableIntegerType()) 1284 LHSType = Context.getPromotedIntegerType(LHSType); 1285 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get()); 1286 if (!LHSBitfieldPromoteTy.isNull()) 1287 LHSType = LHSBitfieldPromoteTy; 1288 if (LHSType != LHSUnpromotedType && !IsCompAssign) 1289 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast); 1290 1291 // If both types are identical, no conversion is needed. 1292 if (LHSType == RHSType) 1293 return LHSType; 1294 1295 // At this point, we have two different arithmetic types. 1296 1297 // Diagnose attempts to convert between __float128 and long double where 1298 // such conversions currently can't be handled. 1299 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 1300 return QualType(); 1301 1302 // Handle complex types first (C99 6.3.1.8p1). 1303 if (LHSType->isComplexType() || RHSType->isComplexType()) 1304 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1305 IsCompAssign); 1306 1307 // Now handle "real" floating types (i.e. float, double, long double). 1308 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 1309 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType, 1310 IsCompAssign); 1311 1312 // Handle GCC complex int extension. 1313 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType()) 1314 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType, 1315 IsCompAssign); 1316 1317 // Finally, we have two differing integer types. 1318 return handleIntegerConversion<doIntegralCast, doIntegralCast> 1319 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign); 1320 } 1321 1322 1323 //===----------------------------------------------------------------------===// 1324 // Semantic Analysis for various Expression Types 1325 //===----------------------------------------------------------------------===// 1326 1327 1328 ExprResult 1329 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc, 1330 SourceLocation DefaultLoc, 1331 SourceLocation RParenLoc, 1332 Expr *ControllingExpr, 1333 ArrayRef<ParsedType> ArgTypes, 1334 ArrayRef<Expr *> ArgExprs) { 1335 unsigned NumAssocs = ArgTypes.size(); 1336 assert(NumAssocs == ArgExprs.size()); 1337 1338 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs]; 1339 for (unsigned i = 0; i < NumAssocs; ++i) { 1340 if (ArgTypes[i]) 1341 (void) GetTypeFromParser(ArgTypes[i], &Types[i]); 1342 else 1343 Types[i] = nullptr; 1344 } 1345 1346 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc, 1347 ControllingExpr, 1348 llvm::makeArrayRef(Types, NumAssocs), 1349 ArgExprs); 1350 delete [] Types; 1351 return ER; 1352 } 1353 1354 ExprResult 1355 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc, 1356 SourceLocation DefaultLoc, 1357 SourceLocation RParenLoc, 1358 Expr *ControllingExpr, 1359 ArrayRef<TypeSourceInfo *> Types, 1360 ArrayRef<Expr *> Exprs) { 1361 unsigned NumAssocs = Types.size(); 1362 assert(NumAssocs == Exprs.size()); 1363 1364 // Decay and strip qualifiers for the controlling expression type, and handle 1365 // placeholder type replacement. See committee discussion from WG14 DR423. 1366 { 1367 EnterExpressionEvaluationContext Unevaluated( 1368 *this, Sema::ExpressionEvaluationContext::Unevaluated); 1369 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr); 1370 if (R.isInvalid()) 1371 return ExprError(); 1372 ControllingExpr = R.get(); 1373 } 1374 1375 // The controlling expression is an unevaluated operand, so side effects are 1376 // likely unintended. 1377 if (!inTemplateInstantiation() && 1378 ControllingExpr->HasSideEffects(Context, false)) 1379 Diag(ControllingExpr->getExprLoc(), 1380 diag::warn_side_effects_unevaluated_context); 1381 1382 bool TypeErrorFound = false, 1383 IsResultDependent = ControllingExpr->isTypeDependent(), 1384 ContainsUnexpandedParameterPack 1385 = ControllingExpr->containsUnexpandedParameterPack(); 1386 1387 for (unsigned i = 0; i < NumAssocs; ++i) { 1388 if (Exprs[i]->containsUnexpandedParameterPack()) 1389 ContainsUnexpandedParameterPack = true; 1390 1391 if (Types[i]) { 1392 if (Types[i]->getType()->containsUnexpandedParameterPack()) 1393 ContainsUnexpandedParameterPack = true; 1394 1395 if (Types[i]->getType()->isDependentType()) { 1396 IsResultDependent = true; 1397 } else { 1398 // C11 6.5.1.1p2 "The type name in a generic association shall specify a 1399 // complete object type other than a variably modified type." 1400 unsigned D = 0; 1401 if (Types[i]->getType()->isIncompleteType()) 1402 D = diag::err_assoc_type_incomplete; 1403 else if (!Types[i]->getType()->isObjectType()) 1404 D = diag::err_assoc_type_nonobject; 1405 else if (Types[i]->getType()->isVariablyModifiedType()) 1406 D = diag::err_assoc_type_variably_modified; 1407 1408 if (D != 0) { 1409 Diag(Types[i]->getTypeLoc().getBeginLoc(), D) 1410 << Types[i]->getTypeLoc().getSourceRange() 1411 << Types[i]->getType(); 1412 TypeErrorFound = true; 1413 } 1414 1415 // C11 6.5.1.1p2 "No two generic associations in the same generic 1416 // selection shall specify compatible types." 1417 for (unsigned j = i+1; j < NumAssocs; ++j) 1418 if (Types[j] && !Types[j]->getType()->isDependentType() && 1419 Context.typesAreCompatible(Types[i]->getType(), 1420 Types[j]->getType())) { 1421 Diag(Types[j]->getTypeLoc().getBeginLoc(), 1422 diag::err_assoc_compatible_types) 1423 << Types[j]->getTypeLoc().getSourceRange() 1424 << Types[j]->getType() 1425 << Types[i]->getType(); 1426 Diag(Types[i]->getTypeLoc().getBeginLoc(), 1427 diag::note_compat_assoc) 1428 << Types[i]->getTypeLoc().getSourceRange() 1429 << Types[i]->getType(); 1430 TypeErrorFound = true; 1431 } 1432 } 1433 } 1434 } 1435 if (TypeErrorFound) 1436 return ExprError(); 1437 1438 // If we determined that the generic selection is result-dependent, don't 1439 // try to compute the result expression. 1440 if (IsResultDependent) 1441 return new (Context) GenericSelectionExpr( 1442 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1443 ContainsUnexpandedParameterPack); 1444 1445 SmallVector<unsigned, 1> CompatIndices; 1446 unsigned DefaultIndex = -1U; 1447 for (unsigned i = 0; i < NumAssocs; ++i) { 1448 if (!Types[i]) 1449 DefaultIndex = i; 1450 else if (Context.typesAreCompatible(ControllingExpr->getType(), 1451 Types[i]->getType())) 1452 CompatIndices.push_back(i); 1453 } 1454 1455 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have 1456 // type compatible with at most one of the types named in its generic 1457 // association list." 1458 if (CompatIndices.size() > 1) { 1459 // We strip parens here because the controlling expression is typically 1460 // parenthesized in macro definitions. 1461 ControllingExpr = ControllingExpr->IgnoreParens(); 1462 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match) 1463 << ControllingExpr->getSourceRange() << ControllingExpr->getType() 1464 << (unsigned)CompatIndices.size(); 1465 for (unsigned I : CompatIndices) { 1466 Diag(Types[I]->getTypeLoc().getBeginLoc(), 1467 diag::note_compat_assoc) 1468 << Types[I]->getTypeLoc().getSourceRange() 1469 << Types[I]->getType(); 1470 } 1471 return ExprError(); 1472 } 1473 1474 // C11 6.5.1.1p2 "If a generic selection has no default generic association, 1475 // its controlling expression shall have type compatible with exactly one of 1476 // the types named in its generic association list." 1477 if (DefaultIndex == -1U && CompatIndices.size() == 0) { 1478 // We strip parens here because the controlling expression is typically 1479 // parenthesized in macro definitions. 1480 ControllingExpr = ControllingExpr->IgnoreParens(); 1481 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match) 1482 << ControllingExpr->getSourceRange() << ControllingExpr->getType(); 1483 return ExprError(); 1484 } 1485 1486 // C11 6.5.1.1p3 "If a generic selection has a generic association with a 1487 // type name that is compatible with the type of the controlling expression, 1488 // then the result expression of the generic selection is the expression 1489 // in that generic association. Otherwise, the result expression of the 1490 // generic selection is the expression in the default generic association." 1491 unsigned ResultIndex = 1492 CompatIndices.size() ? CompatIndices[0] : DefaultIndex; 1493 1494 return new (Context) GenericSelectionExpr( 1495 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc, 1496 ContainsUnexpandedParameterPack, ResultIndex); 1497 } 1498 1499 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the 1500 /// location of the token and the offset of the ud-suffix within it. 1501 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, 1502 unsigned Offset) { 1503 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(), 1504 S.getLangOpts()); 1505 } 1506 1507 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up 1508 /// the corresponding cooked (non-raw) literal operator, and build a call to it. 1509 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, 1510 IdentifierInfo *UDSuffix, 1511 SourceLocation UDSuffixLoc, 1512 ArrayRef<Expr*> Args, 1513 SourceLocation LitEndLoc) { 1514 assert(Args.size() <= 2 && "too many arguments for literal operator"); 1515 1516 QualType ArgTy[2]; 1517 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 1518 ArgTy[ArgIdx] = Args[ArgIdx]->getType(); 1519 if (ArgTy[ArgIdx]->isArrayType()) 1520 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]); 1521 } 1522 1523 DeclarationName OpName = 1524 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1525 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1526 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1527 1528 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName); 1529 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()), 1530 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1531 /*AllowStringTemplate*/ false, 1532 /*DiagnoseMissing*/ true) == Sema::LOLR_Error) 1533 return ExprError(); 1534 1535 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc); 1536 } 1537 1538 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 1539 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string 1540 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from 1541 /// multiple tokens. However, the common case is that StringToks points to one 1542 /// string. 1543 /// 1544 ExprResult 1545 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) { 1546 assert(!StringToks.empty() && "Must have at least one string!"); 1547 1548 StringLiteralParser Literal(StringToks, PP); 1549 if (Literal.hadError) 1550 return ExprError(); 1551 1552 SmallVector<SourceLocation, 4> StringTokLocs; 1553 for (const Token &Tok : StringToks) 1554 StringTokLocs.push_back(Tok.getLocation()); 1555 1556 QualType CharTy = Context.CharTy; 1557 StringLiteral::StringKind Kind = StringLiteral::Ascii; 1558 if (Literal.isWide()) { 1559 CharTy = Context.getWideCharType(); 1560 Kind = StringLiteral::Wide; 1561 } else if (Literal.isUTF8()) { 1562 if (getLangOpts().Char8) 1563 CharTy = Context.Char8Ty; 1564 Kind = StringLiteral::UTF8; 1565 } else if (Literal.isUTF16()) { 1566 CharTy = Context.Char16Ty; 1567 Kind = StringLiteral::UTF16; 1568 } else if (Literal.isUTF32()) { 1569 CharTy = Context.Char32Ty; 1570 Kind = StringLiteral::UTF32; 1571 } else if (Literal.isPascal()) { 1572 CharTy = Context.UnsignedCharTy; 1573 } 1574 1575 // Warn on initializing an array of char from a u8 string literal; this 1576 // becomes ill-formed in C++2a. 1577 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a && 1578 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) { 1579 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string); 1580 1581 // Create removals for all 'u8' prefixes in the string literal(s). This 1582 // ensures C++2a compatibility (but may change the program behavior when 1583 // built by non-Clang compilers for which the execution character set is 1584 // not always UTF-8). 1585 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8); 1586 SourceLocation RemovalDiagLoc; 1587 for (const Token &Tok : StringToks) { 1588 if (Tok.getKind() == tok::utf8_string_literal) { 1589 if (RemovalDiagLoc.isInvalid()) 1590 RemovalDiagLoc = Tok.getLocation(); 1591 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange( 1592 Tok.getLocation(), 1593 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2, 1594 getSourceManager(), getLangOpts()))); 1595 } 1596 } 1597 Diag(RemovalDiagLoc, RemovalDiag); 1598 } 1599 1600 1601 QualType CharTyConst = CharTy; 1602 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 1603 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 1604 CharTyConst.addConst(); 1605 1606 CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst); 1607 1608 // Get an array type for the string, according to C99 6.4.5. This includes 1609 // the nul terminator character as well as the string length for pascal 1610 // strings. 1611 QualType StrTy = Context.getConstantArrayType( 1612 CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1), 1613 ArrayType::Normal, 0); 1614 1615 // Pass &StringTokLocs[0], StringTokLocs.size() to factory! 1616 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(), 1617 Kind, Literal.Pascal, StrTy, 1618 &StringTokLocs[0], 1619 StringTokLocs.size()); 1620 if (Literal.getUDSuffix().empty()) 1621 return Lit; 1622 1623 // We're building a user-defined literal. 1624 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 1625 SourceLocation UDSuffixLoc = 1626 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()], 1627 Literal.getUDSuffixOffset()); 1628 1629 // Make sure we're allowed user-defined literals here. 1630 if (!UDLScope) 1631 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl)); 1632 1633 // C++11 [lex.ext]p5: The literal L is treated as a call of the form 1634 // operator "" X (str, len) 1635 QualType SizeType = Context.getSizeType(); 1636 1637 DeclarationName OpName = 1638 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 1639 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 1640 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 1641 1642 QualType ArgTy[] = { 1643 Context.getArrayDecayedType(StrTy), SizeType 1644 }; 1645 1646 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 1647 switch (LookupLiteralOperator(UDLScope, R, ArgTy, 1648 /*AllowRaw*/ false, /*AllowTemplate*/ false, 1649 /*AllowStringTemplate*/ true, 1650 /*DiagnoseMissing*/ true)) { 1651 1652 case LOLR_Cooked: { 1653 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars()); 1654 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType, 1655 StringTokLocs[0]); 1656 Expr *Args[] = { Lit, LenArg }; 1657 1658 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back()); 1659 } 1660 1661 case LOLR_StringTemplate: { 1662 TemplateArgumentListInfo ExplicitArgs; 1663 1664 unsigned CharBits = Context.getIntWidth(CharTy); 1665 bool CharIsUnsigned = CharTy->isUnsignedIntegerType(); 1666 llvm::APSInt Value(CharBits, CharIsUnsigned); 1667 1668 TemplateArgument TypeArg(CharTy); 1669 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy)); 1670 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo)); 1671 1672 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) { 1673 Value = Lit->getCodeUnit(I); 1674 TemplateArgument Arg(Context, Value, CharTy); 1675 TemplateArgumentLocInfo ArgInfo; 1676 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 1677 } 1678 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(), 1679 &ExplicitArgs); 1680 } 1681 case LOLR_Raw: 1682 case LOLR_Template: 1683 case LOLR_ErrorNoDiagnostic: 1684 llvm_unreachable("unexpected literal operator lookup result"); 1685 case LOLR_Error: 1686 return ExprError(); 1687 } 1688 llvm_unreachable("unexpected literal operator lookup result"); 1689 } 1690 1691 ExprResult 1692 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1693 SourceLocation Loc, 1694 const CXXScopeSpec *SS) { 1695 DeclarationNameInfo NameInfo(D->getDeclName(), Loc); 1696 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS); 1697 } 1698 1699 /// BuildDeclRefExpr - Build an expression that references a 1700 /// declaration that does not require a closure capture. 1701 ExprResult 1702 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, 1703 const DeclarationNameInfo &NameInfo, 1704 const CXXScopeSpec *SS, NamedDecl *FoundD, 1705 const TemplateArgumentListInfo *TemplateArgs) { 1706 bool RefersToCapturedVariable = 1707 isa<VarDecl>(D) && 1708 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc()); 1709 1710 DeclRefExpr *E; 1711 if (isa<VarTemplateSpecializationDecl>(D)) { 1712 VarTemplateSpecializationDecl *VarSpec = 1713 cast<VarTemplateSpecializationDecl>(D); 1714 1715 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1716 : NestedNameSpecifierLoc(), 1717 VarSpec->getTemplateKeywordLoc(), D, 1718 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK, 1719 FoundD, TemplateArgs); 1720 } else { 1721 assert(!TemplateArgs && "No template arguments for non-variable" 1722 " template specialization references"); 1723 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context) 1724 : NestedNameSpecifierLoc(), 1725 SourceLocation(), D, RefersToCapturedVariable, 1726 NameInfo, Ty, VK, FoundD); 1727 } 1728 1729 MarkDeclRefReferenced(E); 1730 1731 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) && 1732 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() && 1733 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc())) 1734 getCurFunction()->recordUseOfWeak(E); 1735 1736 FieldDecl *FD = dyn_cast<FieldDecl>(D); 1737 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 1738 FD = IFD->getAnonField(); 1739 if (FD) { 1740 UnusedPrivateFields.remove(FD); 1741 // Just in case we're building an illegal pointer-to-member. 1742 if (FD->isBitField()) 1743 E->setObjectKind(OK_BitField); 1744 } 1745 1746 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier 1747 // designates a bit-field. 1748 if (auto *BD = dyn_cast<BindingDecl>(D)) 1749 if (auto *BE = BD->getBinding()) 1750 E->setObjectKind(BE->getObjectKind()); 1751 1752 return E; 1753 } 1754 1755 /// Decomposes the given name into a DeclarationNameInfo, its location, and 1756 /// possibly a list of template arguments. 1757 /// 1758 /// If this produces template arguments, it is permitted to call 1759 /// DecomposeTemplateName. 1760 /// 1761 /// This actually loses a lot of source location information for 1762 /// non-standard name kinds; we should consider preserving that in 1763 /// some way. 1764 void 1765 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id, 1766 TemplateArgumentListInfo &Buffer, 1767 DeclarationNameInfo &NameInfo, 1768 const TemplateArgumentListInfo *&TemplateArgs) { 1769 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) { 1770 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc); 1771 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc); 1772 1773 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(), 1774 Id.TemplateId->NumArgs); 1775 translateTemplateArguments(TemplateArgsPtr, Buffer); 1776 1777 TemplateName TName = Id.TemplateId->Template.get(); 1778 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc; 1779 NameInfo = Context.getNameForTemplate(TName, TNameLoc); 1780 TemplateArgs = &Buffer; 1781 } else { 1782 NameInfo = GetNameFromUnqualifiedId(Id); 1783 TemplateArgs = nullptr; 1784 } 1785 } 1786 1787 static void emitEmptyLookupTypoDiagnostic( 1788 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, 1789 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args, 1790 unsigned DiagnosticID, unsigned DiagnosticSuggestID) { 1791 DeclContext *Ctx = 1792 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false); 1793 if (!TC) { 1794 // Emit a special diagnostic for failed member lookups. 1795 // FIXME: computing the declaration context might fail here (?) 1796 if (Ctx) 1797 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx 1798 << SS.getRange(); 1799 else 1800 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo; 1801 return; 1802 } 1803 1804 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts()); 1805 bool DroppedSpecifier = 1806 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr; 1807 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>() 1808 ? diag::note_implicit_param_decl 1809 : diag::note_previous_decl; 1810 if (!Ctx) 1811 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo, 1812 SemaRef.PDiag(NoteID)); 1813 else 1814 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 1815 << Typo << Ctx << DroppedSpecifier 1816 << SS.getRange(), 1817 SemaRef.PDiag(NoteID)); 1818 } 1819 1820 /// Diagnose an empty lookup. 1821 /// 1822 /// \return false if new lookup candidates were found 1823 bool 1824 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 1825 std::unique_ptr<CorrectionCandidateCallback> CCC, 1826 TemplateArgumentListInfo *ExplicitTemplateArgs, 1827 ArrayRef<Expr *> Args, TypoExpr **Out) { 1828 DeclarationName Name = R.getLookupName(); 1829 1830 unsigned diagnostic = diag::err_undeclared_var_use; 1831 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest; 1832 if (Name.getNameKind() == DeclarationName::CXXOperatorName || 1833 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName || 1834 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 1835 diagnostic = diag::err_undeclared_use; 1836 diagnostic_suggest = diag::err_undeclared_use_suggest; 1837 } 1838 1839 // If the original lookup was an unqualified lookup, fake an 1840 // unqualified lookup. This is useful when (for example) the 1841 // original lookup would not have found something because it was a 1842 // dependent name. 1843 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr; 1844 while (DC) { 1845 if (isa<CXXRecordDecl>(DC)) { 1846 LookupQualifiedName(R, DC); 1847 1848 if (!R.empty()) { 1849 // Don't give errors about ambiguities in this lookup. 1850 R.suppressDiagnostics(); 1851 1852 // During a default argument instantiation the CurContext points 1853 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a 1854 // function parameter list, hence add an explicit check. 1855 bool isDefaultArgument = 1856 !CodeSynthesisContexts.empty() && 1857 CodeSynthesisContexts.back().Kind == 1858 CodeSynthesisContext::DefaultFunctionArgumentInstantiation; 1859 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext); 1860 bool isInstance = CurMethod && 1861 CurMethod->isInstance() && 1862 DC == CurMethod->getParent() && !isDefaultArgument; 1863 1864 // Give a code modification hint to insert 'this->'. 1865 // TODO: fixit for inserting 'Base<T>::' in the other cases. 1866 // Actually quite difficult! 1867 if (getLangOpts().MSVCCompat) 1868 diagnostic = diag::ext_found_via_dependent_bases_lookup; 1869 if (isInstance) { 1870 Diag(R.getNameLoc(), diagnostic) << Name 1871 << FixItHint::CreateInsertion(R.getNameLoc(), "this->"); 1872 CheckCXXThisCapture(R.getNameLoc()); 1873 } else { 1874 Diag(R.getNameLoc(), diagnostic) << Name; 1875 } 1876 1877 // Do we really want to note all of these? 1878 for (NamedDecl *D : R) 1879 Diag(D->getLocation(), diag::note_dependent_var_use); 1880 1881 // Return true if we are inside a default argument instantiation 1882 // and the found name refers to an instance member function, otherwise 1883 // the function calling DiagnoseEmptyLookup will try to create an 1884 // implicit member call and this is wrong for default argument. 1885 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) { 1886 Diag(R.getNameLoc(), diag::err_member_call_without_object); 1887 return true; 1888 } 1889 1890 // Tell the callee to try to recover. 1891 return false; 1892 } 1893 1894 R.clear(); 1895 } 1896 1897 // In Microsoft mode, if we are performing lookup from within a friend 1898 // function definition declared at class scope then we must set 1899 // DC to the lexical parent to be able to search into the parent 1900 // class. 1901 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) && 1902 cast<FunctionDecl>(DC)->getFriendObjectKind() && 1903 DC->getLexicalParent()->isRecord()) 1904 DC = DC->getLexicalParent(); 1905 else 1906 DC = DC->getParent(); 1907 } 1908 1909 // We didn't find anything, so try to correct for a typo. 1910 TypoCorrection Corrected; 1911 if (S && Out) { 1912 SourceLocation TypoLoc = R.getNameLoc(); 1913 assert(!ExplicitTemplateArgs && 1914 "Diagnosing an empty lookup with explicit template args!"); 1915 *Out = CorrectTypoDelayed( 1916 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC), 1917 [=](const TypoCorrection &TC) { 1918 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args, 1919 diagnostic, diagnostic_suggest); 1920 }, 1921 nullptr, CTK_ErrorRecovery); 1922 if (*Out) 1923 return true; 1924 } else if (S && (Corrected = 1925 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, 1926 &SS, std::move(CCC), CTK_ErrorRecovery))) { 1927 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 1928 bool DroppedSpecifier = 1929 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr; 1930 R.setLookupName(Corrected.getCorrection()); 1931 1932 bool AcceptableWithRecovery = false; 1933 bool AcceptableWithoutRecovery = false; 1934 NamedDecl *ND = Corrected.getFoundDecl(); 1935 if (ND) { 1936 if (Corrected.isOverloaded()) { 1937 OverloadCandidateSet OCS(R.getNameLoc(), 1938 OverloadCandidateSet::CSK_Normal); 1939 OverloadCandidateSet::iterator Best; 1940 for (NamedDecl *CD : Corrected) { 1941 if (FunctionTemplateDecl *FTD = 1942 dyn_cast<FunctionTemplateDecl>(CD)) 1943 AddTemplateOverloadCandidate( 1944 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs, 1945 Args, OCS); 1946 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 1947 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0) 1948 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), 1949 Args, OCS); 1950 } 1951 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) { 1952 case OR_Success: 1953 ND = Best->FoundDecl; 1954 Corrected.setCorrectionDecl(ND); 1955 break; 1956 default: 1957 // FIXME: Arbitrarily pick the first declaration for the note. 1958 Corrected.setCorrectionDecl(ND); 1959 break; 1960 } 1961 } 1962 R.addDecl(ND); 1963 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) { 1964 CXXRecordDecl *Record = nullptr; 1965 if (Corrected.getCorrectionSpecifier()) { 1966 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType(); 1967 Record = Ty->getAsCXXRecordDecl(); 1968 } 1969 if (!Record) 1970 Record = cast<CXXRecordDecl>( 1971 ND->getDeclContext()->getRedeclContext()); 1972 R.setNamingClass(Record); 1973 } 1974 1975 auto *UnderlyingND = ND->getUnderlyingDecl(); 1976 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) || 1977 isa<FunctionTemplateDecl>(UnderlyingND); 1978 // FIXME: If we ended up with a typo for a type name or 1979 // Objective-C class name, we're in trouble because the parser 1980 // is in the wrong place to recover. Suggest the typo 1981 // correction, but don't make it a fix-it since we're not going 1982 // to recover well anyway. 1983 AcceptableWithoutRecovery = 1984 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND); 1985 } else { 1986 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it 1987 // because we aren't able to recover. 1988 AcceptableWithoutRecovery = true; 1989 } 1990 1991 if (AcceptableWithRecovery || AcceptableWithoutRecovery) { 1992 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>() 1993 ? diag::note_implicit_param_decl 1994 : diag::note_previous_decl; 1995 if (SS.isEmpty()) 1996 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name, 1997 PDiag(NoteID), AcceptableWithRecovery); 1998 else 1999 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 2000 << Name << computeDeclContext(SS, false) 2001 << DroppedSpecifier << SS.getRange(), 2002 PDiag(NoteID), AcceptableWithRecovery); 2003 2004 // Tell the callee whether to try to recover. 2005 return !AcceptableWithRecovery; 2006 } 2007 } 2008 R.clear(); 2009 2010 // Emit a special diagnostic for failed member lookups. 2011 // FIXME: computing the declaration context might fail here (?) 2012 if (!SS.isEmpty()) { 2013 Diag(R.getNameLoc(), diag::err_no_member) 2014 << Name << computeDeclContext(SS, false) 2015 << SS.getRange(); 2016 return true; 2017 } 2018 2019 // Give up, we can't recover. 2020 Diag(R.getNameLoc(), diagnostic) << Name; 2021 return true; 2022 } 2023 2024 /// In Microsoft mode, if we are inside a template class whose parent class has 2025 /// dependent base classes, and we can't resolve an unqualified identifier, then 2026 /// assume the identifier is a member of a dependent base class. We can only 2027 /// recover successfully in static methods, instance methods, and other contexts 2028 /// where 'this' is available. This doesn't precisely match MSVC's 2029 /// instantiation model, but it's close enough. 2030 static Expr * 2031 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, 2032 DeclarationNameInfo &NameInfo, 2033 SourceLocation TemplateKWLoc, 2034 const TemplateArgumentListInfo *TemplateArgs) { 2035 // Only try to recover from lookup into dependent bases in static methods or 2036 // contexts where 'this' is available. 2037 QualType ThisType = S.getCurrentThisType(); 2038 const CXXRecordDecl *RD = nullptr; 2039 if (!ThisType.isNull()) 2040 RD = ThisType->getPointeeType()->getAsCXXRecordDecl(); 2041 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext)) 2042 RD = MD->getParent(); 2043 if (!RD || !RD->hasAnyDependentBases()) 2044 return nullptr; 2045 2046 // Diagnose this as unqualified lookup into a dependent base class. If 'this' 2047 // is available, suggest inserting 'this->' as a fixit. 2048 SourceLocation Loc = NameInfo.getLoc(); 2049 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base); 2050 DB << NameInfo.getName() << RD; 2051 2052 if (!ThisType.isNull()) { 2053 DB << FixItHint::CreateInsertion(Loc, "this->"); 2054 return CXXDependentScopeMemberExpr::Create( 2055 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true, 2056 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc, 2057 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs); 2058 } 2059 2060 // Synthesize a fake NNS that points to the derived class. This will 2061 // perform name lookup during template instantiation. 2062 CXXScopeSpec SS; 2063 auto *NNS = 2064 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl()); 2065 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc)); 2066 return DependentScopeDeclRefExpr::Create( 2067 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 2068 TemplateArgs); 2069 } 2070 2071 ExprResult 2072 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2073 SourceLocation TemplateKWLoc, UnqualifiedId &Id, 2074 bool HasTrailingLParen, bool IsAddressOfOperand, 2075 std::unique_ptr<CorrectionCandidateCallback> CCC, 2076 bool IsInlineAsmIdentifier, Token *KeywordReplacement) { 2077 assert(!(IsAddressOfOperand && HasTrailingLParen) && 2078 "cannot be direct & operand and have a trailing lparen"); 2079 if (SS.isInvalid()) 2080 return ExprError(); 2081 2082 TemplateArgumentListInfo TemplateArgsBuffer; 2083 2084 // Decompose the UnqualifiedId into the following data. 2085 DeclarationNameInfo NameInfo; 2086 const TemplateArgumentListInfo *TemplateArgs; 2087 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs); 2088 2089 DeclarationName Name = NameInfo.getName(); 2090 IdentifierInfo *II = Name.getAsIdentifierInfo(); 2091 SourceLocation NameLoc = NameInfo.getLoc(); 2092 2093 if (II && II->isEditorPlaceholder()) { 2094 // FIXME: When typed placeholders are supported we can create a typed 2095 // placeholder expression node. 2096 return ExprError(); 2097 } 2098 2099 // C++ [temp.dep.expr]p3: 2100 // An id-expression is type-dependent if it contains: 2101 // -- an identifier that was declared with a dependent type, 2102 // (note: handled after lookup) 2103 // -- a template-id that is dependent, 2104 // (note: handled in BuildTemplateIdExpr) 2105 // -- a conversion-function-id that specifies a dependent type, 2106 // -- a nested-name-specifier that contains a class-name that 2107 // names a dependent type. 2108 // Determine whether this is a member of an unknown specialization; 2109 // we need to handle these differently. 2110 bool DependentID = false; 2111 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName && 2112 Name.getCXXNameType()->isDependentType()) { 2113 DependentID = true; 2114 } else if (SS.isSet()) { 2115 if (DeclContext *DC = computeDeclContext(SS, false)) { 2116 if (RequireCompleteDeclContext(SS, DC)) 2117 return ExprError(); 2118 } else { 2119 DependentID = true; 2120 } 2121 } 2122 2123 if (DependentID) 2124 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2125 IsAddressOfOperand, TemplateArgs); 2126 2127 // Perform the required lookup. 2128 LookupResult R(*this, NameInfo, 2129 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam) 2130 ? LookupObjCImplicitSelfParam 2131 : LookupOrdinaryName); 2132 if (TemplateKWLoc.isValid() || TemplateArgs) { 2133 // Lookup the template name again to correctly establish the context in 2134 // which it was found. This is really unfortunate as we already did the 2135 // lookup to determine that it was a template name in the first place. If 2136 // this becomes a performance hit, we can work harder to preserve those 2137 // results until we get here but it's likely not worth it. 2138 bool MemberOfUnknownSpecialization; 2139 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false, 2140 MemberOfUnknownSpecialization, TemplateKWLoc)) 2141 return ExprError(); 2142 2143 if (MemberOfUnknownSpecialization || 2144 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)) 2145 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2146 IsAddressOfOperand, TemplateArgs); 2147 } else { 2148 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl(); 2149 LookupParsedName(R, S, &SS, !IvarLookupFollowUp); 2150 2151 // If the result might be in a dependent base class, this is a dependent 2152 // id-expression. 2153 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2154 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo, 2155 IsAddressOfOperand, TemplateArgs); 2156 2157 // If this reference is in an Objective-C method, then we need to do 2158 // some special Objective-C lookup, too. 2159 if (IvarLookupFollowUp) { 2160 ExprResult E(LookupInObjCMethod(R, S, II, true)); 2161 if (E.isInvalid()) 2162 return ExprError(); 2163 2164 if (Expr *Ex = E.getAs<Expr>()) 2165 return Ex; 2166 } 2167 } 2168 2169 if (R.isAmbiguous()) 2170 return ExprError(); 2171 2172 // This could be an implicitly declared function reference (legal in C90, 2173 // extension in C99, forbidden in C++). 2174 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) { 2175 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S); 2176 if (D) R.addDecl(D); 2177 } 2178 2179 // Determine whether this name might be a candidate for 2180 // argument-dependent lookup. 2181 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen); 2182 2183 if (R.empty() && !ADL) { 2184 if (SS.isEmpty() && getLangOpts().MSVCCompat) { 2185 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo, 2186 TemplateKWLoc, TemplateArgs)) 2187 return E; 2188 } 2189 2190 // Don't diagnose an empty lookup for inline assembly. 2191 if (IsInlineAsmIdentifier) 2192 return ExprError(); 2193 2194 // If this name wasn't predeclared and if this is not a function 2195 // call, diagnose the problem. 2196 TypoExpr *TE = nullptr; 2197 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>( 2198 II, SS.isValid() ? SS.getScopeRep() : nullptr); 2199 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand; 2200 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && 2201 "Typo correction callback misconfigured"); 2202 if (CCC) { 2203 // Make sure the callback knows what the typo being diagnosed is. 2204 CCC->setTypoName(II); 2205 if (SS.isValid()) 2206 CCC->setTypoNNS(SS.getScopeRep()); 2207 } 2208 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for 2209 // a template name, but we happen to have always already looked up the name 2210 // before we get here if it must be a template name. 2211 if (DiagnoseEmptyLookup(S, SS, R, 2212 CCC ? std::move(CCC) : std::move(DefaultValidator), 2213 nullptr, None, &TE)) { 2214 if (TE && KeywordReplacement) { 2215 auto &State = getTypoExprState(TE); 2216 auto BestTC = State.Consumer->getNextCorrection(); 2217 if (BestTC.isKeyword()) { 2218 auto *II = BestTC.getCorrectionAsIdentifierInfo(); 2219 if (State.DiagHandler) 2220 State.DiagHandler(BestTC); 2221 KeywordReplacement->startToken(); 2222 KeywordReplacement->setKind(II->getTokenID()); 2223 KeywordReplacement->setIdentifierInfo(II); 2224 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin()); 2225 // Clean up the state associated with the TypoExpr, since it has 2226 // now been diagnosed (without a call to CorrectDelayedTyposInExpr). 2227 clearDelayedTypo(TE); 2228 // Signal that a correction to a keyword was performed by returning a 2229 // valid-but-null ExprResult. 2230 return (Expr*)nullptr; 2231 } 2232 State.Consumer->resetCorrectionStream(); 2233 } 2234 return TE ? TE : ExprError(); 2235 } 2236 2237 assert(!R.empty() && 2238 "DiagnoseEmptyLookup returned false but added no results"); 2239 2240 // If we found an Objective-C instance variable, let 2241 // LookupInObjCMethod build the appropriate expression to 2242 // reference the ivar. 2243 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) { 2244 R.clear(); 2245 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier())); 2246 // In a hopelessly buggy code, Objective-C instance variable 2247 // lookup fails and no expression will be built to reference it. 2248 if (!E.isInvalid() && !E.get()) 2249 return ExprError(); 2250 return E; 2251 } 2252 } 2253 2254 // This is guaranteed from this point on. 2255 assert(!R.empty() || ADL); 2256 2257 // Check whether this might be a C++ implicit instance member access. 2258 // C++ [class.mfct.non-static]p3: 2259 // When an id-expression that is not part of a class member access 2260 // syntax and not used to form a pointer to member is used in the 2261 // body of a non-static member function of class X, if name lookup 2262 // resolves the name in the id-expression to a non-static non-type 2263 // member of some class C, the id-expression is transformed into a 2264 // class member access expression using (*this) as the 2265 // postfix-expression to the left of the . operator. 2266 // 2267 // But we don't actually need to do this for '&' operands if R 2268 // resolved to a function or overloaded function set, because the 2269 // expression is ill-formed if it actually works out to be a 2270 // non-static member function: 2271 // 2272 // C++ [expr.ref]p4: 2273 // Otherwise, if E1.E2 refers to a non-static member function. . . 2274 // [t]he expression can be used only as the left-hand operand of a 2275 // member function call. 2276 // 2277 // There are other safeguards against such uses, but it's important 2278 // to get this right here so that we don't end up making a 2279 // spuriously dependent expression if we're inside a dependent 2280 // instance method. 2281 if (!R.empty() && (*R.begin())->isCXXClassMember()) { 2282 bool MightBeImplicitMember; 2283 if (!IsAddressOfOperand) 2284 MightBeImplicitMember = true; 2285 else if (!SS.isEmpty()) 2286 MightBeImplicitMember = false; 2287 else if (R.isOverloadedResult()) 2288 MightBeImplicitMember = false; 2289 else if (R.isUnresolvableResult()) 2290 MightBeImplicitMember = true; 2291 else 2292 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) || 2293 isa<IndirectFieldDecl>(R.getFoundDecl()) || 2294 isa<MSPropertyDecl>(R.getFoundDecl()); 2295 2296 if (MightBeImplicitMember) 2297 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 2298 R, TemplateArgs, S); 2299 } 2300 2301 if (TemplateArgs || TemplateKWLoc.isValid()) { 2302 2303 // In C++1y, if this is a variable template id, then check it 2304 // in BuildTemplateIdExpr(). 2305 // The single lookup result must be a variable template declaration. 2306 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId && 2307 Id.TemplateId->Kind == TNK_Var_template) { 2308 assert(R.getAsSingle<VarTemplateDecl>() && 2309 "There should only be one declaration found."); 2310 } 2311 2312 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs); 2313 } 2314 2315 return BuildDeclarationNameExpr(SS, R, ADL); 2316 } 2317 2318 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified 2319 /// declaration name, generally during template instantiation. 2320 /// There's a large number of things which don't need to be done along 2321 /// this path. 2322 ExprResult Sema::BuildQualifiedDeclarationNameExpr( 2323 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, 2324 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) { 2325 DeclContext *DC = computeDeclContext(SS, false); 2326 if (!DC) 2327 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2328 NameInfo, /*TemplateArgs=*/nullptr); 2329 2330 if (RequireCompleteDeclContext(SS, DC)) 2331 return ExprError(); 2332 2333 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2334 LookupQualifiedName(R, DC); 2335 2336 if (R.isAmbiguous()) 2337 return ExprError(); 2338 2339 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation) 2340 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 2341 NameInfo, /*TemplateArgs=*/nullptr); 2342 2343 if (R.empty()) { 2344 Diag(NameInfo.getLoc(), diag::err_no_member) 2345 << NameInfo.getName() << DC << SS.getRange(); 2346 return ExprError(); 2347 } 2348 2349 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) { 2350 // Diagnose a missing typename if this resolved unambiguously to a type in 2351 // a dependent context. If we can recover with a type, downgrade this to 2352 // a warning in Microsoft compatibility mode. 2353 unsigned DiagID = diag::err_typename_missing; 2354 if (RecoveryTSI && getLangOpts().MSVCCompat) 2355 DiagID = diag::ext_typename_missing; 2356 SourceLocation Loc = SS.getBeginLoc(); 2357 auto D = Diag(Loc, DiagID); 2358 D << SS.getScopeRep() << NameInfo.getName().getAsString() 2359 << SourceRange(Loc, NameInfo.getEndLoc()); 2360 2361 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE 2362 // context. 2363 if (!RecoveryTSI) 2364 return ExprError(); 2365 2366 // Only issue the fixit if we're prepared to recover. 2367 D << FixItHint::CreateInsertion(Loc, "typename "); 2368 2369 // Recover by pretending this was an elaborated type. 2370 QualType Ty = Context.getTypeDeclType(TD); 2371 TypeLocBuilder TLB; 2372 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc()); 2373 2374 QualType ET = getElaboratedType(ETK_None, SS, Ty); 2375 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET); 2376 QTL.setElaboratedKeywordLoc(SourceLocation()); 2377 QTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2378 2379 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET); 2380 2381 return ExprEmpty(); 2382 } 2383 2384 // Defend against this resolving to an implicit member access. We usually 2385 // won't get here if this might be a legitimate a class member (we end up in 2386 // BuildMemberReferenceExpr instead), but this can be valid if we're forming 2387 // a pointer-to-member or in an unevaluated context in C++11. 2388 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand) 2389 return BuildPossibleImplicitMemberExpr(SS, 2390 /*TemplateKWLoc=*/SourceLocation(), 2391 R, /*TemplateArgs=*/nullptr, S); 2392 2393 return BuildDeclarationNameExpr(SS, R, /* ADL */ false); 2394 } 2395 2396 /// LookupInObjCMethod - The parser has read a name in, and Sema has 2397 /// detected that we're currently inside an ObjC method. Perform some 2398 /// additional lookup. 2399 /// 2400 /// Ideally, most of this would be done by lookup, but there's 2401 /// actually quite a lot of extra work involved. 2402 /// 2403 /// Returns a null sentinel to indicate trivial success. 2404 ExprResult 2405 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S, 2406 IdentifierInfo *II, bool AllowBuiltinCreation) { 2407 SourceLocation Loc = Lookup.getNameLoc(); 2408 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 2409 2410 // Check for error condition which is already reported. 2411 if (!CurMethod) 2412 return ExprError(); 2413 2414 // There are two cases to handle here. 1) scoped lookup could have failed, 2415 // in which case we should look for an ivar. 2) scoped lookup could have 2416 // found a decl, but that decl is outside the current instance method (i.e. 2417 // a global variable). In these two cases, we do a lookup for an ivar with 2418 // this name, if the lookup sucedes, we replace it our current decl. 2419 2420 // If we're in a class method, we don't normally want to look for 2421 // ivars. But if we don't find anything else, and there's an 2422 // ivar, that's an error. 2423 bool IsClassMethod = CurMethod->isClassMethod(); 2424 2425 bool LookForIvars; 2426 if (Lookup.empty()) 2427 LookForIvars = true; 2428 else if (IsClassMethod) 2429 LookForIvars = false; 2430 else 2431 LookForIvars = (Lookup.isSingleResult() && 2432 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()); 2433 ObjCInterfaceDecl *IFace = nullptr; 2434 if (LookForIvars) { 2435 IFace = CurMethod->getClassInterface(); 2436 ObjCInterfaceDecl *ClassDeclared; 2437 ObjCIvarDecl *IV = nullptr; 2438 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) { 2439 // Diagnose using an ivar in a class method. 2440 if (IsClassMethod) 2441 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2442 << IV->getDeclName()); 2443 2444 // If we're referencing an invalid decl, just return this as a silent 2445 // error node. The error diagnostic was already emitted on the decl. 2446 if (IV->isInvalidDecl()) 2447 return ExprError(); 2448 2449 // Check if referencing a field with __attribute__((deprecated)). 2450 if (DiagnoseUseOfDecl(IV, Loc)) 2451 return ExprError(); 2452 2453 // Diagnose the use of an ivar outside of the declaring class. 2454 if (IV->getAccessControl() == ObjCIvarDecl::Private && 2455 !declaresSameEntity(ClassDeclared, IFace) && 2456 !getLangOpts().DebuggerSupport) 2457 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName(); 2458 2459 // FIXME: This should use a new expr for a direct reference, don't 2460 // turn this into Self->ivar, just return a BareIVarExpr or something. 2461 IdentifierInfo &II = Context.Idents.get("self"); 2462 UnqualifiedId SelfName; 2463 SelfName.setIdentifier(&II, SourceLocation()); 2464 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam); 2465 CXXScopeSpec SelfScopeSpec; 2466 SourceLocation TemplateKWLoc; 2467 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, 2468 SelfName, false, false); 2469 if (SelfExpr.isInvalid()) 2470 return ExprError(); 2471 2472 SelfExpr = DefaultLvalueConversion(SelfExpr.get()); 2473 if (SelfExpr.isInvalid()) 2474 return ExprError(); 2475 2476 MarkAnyDeclReferenced(Loc, IV, true); 2477 2478 ObjCMethodFamily MF = CurMethod->getMethodFamily(); 2479 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize && 2480 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV)) 2481 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName(); 2482 2483 ObjCIvarRefExpr *Result = new (Context) 2484 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc, 2485 IV->getLocation(), SelfExpr.get(), true, true); 2486 2487 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 2488 if (!isUnevaluatedContext() && 2489 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 2490 getCurFunction()->recordUseOfWeak(Result); 2491 } 2492 if (getLangOpts().ObjCAutoRefCount) { 2493 if (CurContext->isClosure()) 2494 Diag(Loc, diag::warn_implicitly_retains_self) 2495 << FixItHint::CreateInsertion(Loc, "self->"); 2496 } 2497 2498 return Result; 2499 } 2500 } else if (CurMethod->isInstanceMethod()) { 2501 // We should warn if a local variable hides an ivar. 2502 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) { 2503 ObjCInterfaceDecl *ClassDeclared; 2504 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) { 2505 if (IV->getAccessControl() != ObjCIvarDecl::Private || 2506 declaresSameEntity(IFace, ClassDeclared)) 2507 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName(); 2508 } 2509 } 2510 } else if (Lookup.isSingleResult() && 2511 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) { 2512 // If accessing a stand-alone ivar in a class method, this is an error. 2513 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) 2514 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method) 2515 << IV->getDeclName()); 2516 } 2517 2518 if (Lookup.empty() && II && AllowBuiltinCreation) { 2519 // FIXME. Consolidate this with similar code in LookupName. 2520 if (unsigned BuiltinID = II->getBuiltinID()) { 2521 if (!(getLangOpts().CPlusPlus && 2522 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) { 2523 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, 2524 S, Lookup.isForRedeclaration(), 2525 Lookup.getNameLoc()); 2526 if (D) Lookup.addDecl(D); 2527 } 2528 } 2529 } 2530 // Sentinel value saying that we didn't do anything special. 2531 return ExprResult((Expr *)nullptr); 2532 } 2533 2534 /// Cast a base object to a member's actual type. 2535 /// 2536 /// Logically this happens in three phases: 2537 /// 2538 /// * First we cast from the base type to the naming class. 2539 /// The naming class is the class into which we were looking 2540 /// when we found the member; it's the qualifier type if a 2541 /// qualifier was provided, and otherwise it's the base type. 2542 /// 2543 /// * Next we cast from the naming class to the declaring class. 2544 /// If the member we found was brought into a class's scope by 2545 /// a using declaration, this is that class; otherwise it's 2546 /// the class declaring the member. 2547 /// 2548 /// * Finally we cast from the declaring class to the "true" 2549 /// declaring class of the member. This conversion does not 2550 /// obey access control. 2551 ExprResult 2552 Sema::PerformObjectMemberConversion(Expr *From, 2553 NestedNameSpecifier *Qualifier, 2554 NamedDecl *FoundDecl, 2555 NamedDecl *Member) { 2556 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext()); 2557 if (!RD) 2558 return From; 2559 2560 QualType DestRecordType; 2561 QualType DestType; 2562 QualType FromRecordType; 2563 QualType FromType = From->getType(); 2564 bool PointerConversions = false; 2565 if (isa<FieldDecl>(Member)) { 2566 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD)); 2567 2568 if (FromType->getAs<PointerType>()) { 2569 DestType = Context.getPointerType(DestRecordType); 2570 FromRecordType = FromType->getPointeeType(); 2571 PointerConversions = true; 2572 } else { 2573 DestType = DestRecordType; 2574 FromRecordType = FromType; 2575 } 2576 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) { 2577 if (Method->isStatic()) 2578 return From; 2579 2580 DestType = Method->getThisType(Context); 2581 DestRecordType = DestType->getPointeeType(); 2582 2583 if (FromType->getAs<PointerType>()) { 2584 FromRecordType = FromType->getPointeeType(); 2585 PointerConversions = true; 2586 } else { 2587 FromRecordType = FromType; 2588 DestType = DestRecordType; 2589 } 2590 } else { 2591 // No conversion necessary. 2592 return From; 2593 } 2594 2595 if (DestType->isDependentType() || FromType->isDependentType()) 2596 return From; 2597 2598 // If the unqualified types are the same, no conversion is necessary. 2599 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2600 return From; 2601 2602 SourceRange FromRange = From->getSourceRange(); 2603 SourceLocation FromLoc = FromRange.getBegin(); 2604 2605 ExprValueKind VK = From->getValueKind(); 2606 2607 // C++ [class.member.lookup]p8: 2608 // [...] Ambiguities can often be resolved by qualifying a name with its 2609 // class name. 2610 // 2611 // If the member was a qualified name and the qualified referred to a 2612 // specific base subobject type, we'll cast to that intermediate type 2613 // first and then to the object in which the member is declared. That allows 2614 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as: 2615 // 2616 // class Base { public: int x; }; 2617 // class Derived1 : public Base { }; 2618 // class Derived2 : public Base { }; 2619 // class VeryDerived : public Derived1, public Derived2 { void f(); }; 2620 // 2621 // void VeryDerived::f() { 2622 // x = 17; // error: ambiguous base subobjects 2623 // Derived1::x = 17; // okay, pick the Base subobject of Derived1 2624 // } 2625 if (Qualifier && Qualifier->getAsType()) { 2626 QualType QType = QualType(Qualifier->getAsType(), 0); 2627 assert(QType->isRecordType() && "lookup done with non-record type"); 2628 2629 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0); 2630 2631 // In C++98, the qualifier type doesn't actually have to be a base 2632 // type of the object type, in which case we just ignore it. 2633 // Otherwise build the appropriate casts. 2634 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) { 2635 CXXCastPath BasePath; 2636 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType, 2637 FromLoc, FromRange, &BasePath)) 2638 return ExprError(); 2639 2640 if (PointerConversions) 2641 QType = Context.getPointerType(QType); 2642 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase, 2643 VK, &BasePath).get(); 2644 2645 FromType = QType; 2646 FromRecordType = QRecordType; 2647 2648 // If the qualifier type was the same as the destination type, 2649 // we're done. 2650 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType)) 2651 return From; 2652 } 2653 } 2654 2655 bool IgnoreAccess = false; 2656 2657 // If we actually found the member through a using declaration, cast 2658 // down to the using declaration's type. 2659 // 2660 // Pointer equality is fine here because only one declaration of a 2661 // class ever has member declarations. 2662 if (FoundDecl->getDeclContext() != Member->getDeclContext()) { 2663 assert(isa<UsingShadowDecl>(FoundDecl)); 2664 QualType URecordType = Context.getTypeDeclType( 2665 cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 2666 2667 // We only need to do this if the naming-class to declaring-class 2668 // conversion is non-trivial. 2669 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) { 2670 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType)); 2671 CXXCastPath BasePath; 2672 if (CheckDerivedToBaseConversion(FromRecordType, URecordType, 2673 FromLoc, FromRange, &BasePath)) 2674 return ExprError(); 2675 2676 QualType UType = URecordType; 2677 if (PointerConversions) 2678 UType = Context.getPointerType(UType); 2679 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase, 2680 VK, &BasePath).get(); 2681 FromType = UType; 2682 FromRecordType = URecordType; 2683 } 2684 2685 // We don't do access control for the conversion from the 2686 // declaring class to the true declaring class. 2687 IgnoreAccess = true; 2688 } 2689 2690 CXXCastPath BasePath; 2691 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType, 2692 FromLoc, FromRange, &BasePath, 2693 IgnoreAccess)) 2694 return ExprError(); 2695 2696 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, 2697 VK, &BasePath); 2698 } 2699 2700 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS, 2701 const LookupResult &R, 2702 bool HasTrailingLParen) { 2703 // Only when used directly as the postfix-expression of a call. 2704 if (!HasTrailingLParen) 2705 return false; 2706 2707 // Never if a scope specifier was provided. 2708 if (SS.isSet()) 2709 return false; 2710 2711 // Only in C++ or ObjC++. 2712 if (!getLangOpts().CPlusPlus) 2713 return false; 2714 2715 // Turn off ADL when we find certain kinds of declarations during 2716 // normal lookup: 2717 for (NamedDecl *D : R) { 2718 // C++0x [basic.lookup.argdep]p3: 2719 // -- a declaration of a class member 2720 // Since using decls preserve this property, we check this on the 2721 // original decl. 2722 if (D->isCXXClassMember()) 2723 return false; 2724 2725 // C++0x [basic.lookup.argdep]p3: 2726 // -- a block-scope function declaration that is not a 2727 // using-declaration 2728 // NOTE: we also trigger this for function templates (in fact, we 2729 // don't check the decl type at all, since all other decl types 2730 // turn off ADL anyway). 2731 if (isa<UsingShadowDecl>(D)) 2732 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 2733 else if (D->getLexicalDeclContext()->isFunctionOrMethod()) 2734 return false; 2735 2736 // C++0x [basic.lookup.argdep]p3: 2737 // -- a declaration that is neither a function or a function 2738 // template 2739 // And also for builtin functions. 2740 if (isa<FunctionDecl>(D)) { 2741 FunctionDecl *FDecl = cast<FunctionDecl>(D); 2742 2743 // But also builtin functions. 2744 if (FDecl->getBuiltinID() && FDecl->isImplicit()) 2745 return false; 2746 } else if (!isa<FunctionTemplateDecl>(D)) 2747 return false; 2748 } 2749 2750 return true; 2751 } 2752 2753 2754 /// Diagnoses obvious problems with the use of the given declaration 2755 /// as an expression. This is only actually called for lookups that 2756 /// were not overloaded, and it doesn't promise that the declaration 2757 /// will in fact be used. 2758 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) { 2759 if (D->isInvalidDecl()) 2760 return true; 2761 2762 if (isa<TypedefNameDecl>(D)) { 2763 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName(); 2764 return true; 2765 } 2766 2767 if (isa<ObjCInterfaceDecl>(D)) { 2768 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName(); 2769 return true; 2770 } 2771 2772 if (isa<NamespaceDecl>(D)) { 2773 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName(); 2774 return true; 2775 } 2776 2777 return false; 2778 } 2779 2780 // Certain multiversion types should be treated as overloaded even when there is 2781 // only one result. 2782 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) { 2783 assert(R.isSingleResult() && "Expected only a single result"); 2784 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 2785 return FD && 2786 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion()); 2787 } 2788 2789 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2790 LookupResult &R, bool NeedsADL, 2791 bool AcceptInvalidDecl) { 2792 // If this is a single, fully-resolved result and we don't need ADL, 2793 // just build an ordinary singleton decl ref. 2794 if (!NeedsADL && R.isSingleResult() && 2795 !R.getAsSingle<FunctionTemplateDecl>() && 2796 !ShouldLookupResultBeMultiVersionOverload(R)) 2797 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(), 2798 R.getRepresentativeDecl(), nullptr, 2799 AcceptInvalidDecl); 2800 2801 // We only need to check the declaration if there's exactly one 2802 // result, because in the overloaded case the results can only be 2803 // functions and function templates. 2804 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) && 2805 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl())) 2806 return ExprError(); 2807 2808 // Otherwise, just build an unresolved lookup expression. Suppress 2809 // any lookup-related diagnostics; we'll hash these out later, when 2810 // we've picked a target. 2811 R.suppressDiagnostics(); 2812 2813 UnresolvedLookupExpr *ULE 2814 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2815 SS.getWithLocInContext(Context), 2816 R.getLookupNameInfo(), 2817 NeedsADL, R.isOverloadedResult(), 2818 R.begin(), R.end()); 2819 2820 return ULE; 2821 } 2822 2823 static void 2824 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 2825 ValueDecl *var, DeclContext *DC); 2826 2827 /// Complete semantic analysis for a reference to the given declaration. 2828 ExprResult Sema::BuildDeclarationNameExpr( 2829 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, 2830 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs, 2831 bool AcceptInvalidDecl) { 2832 assert(D && "Cannot refer to a NULL declaration"); 2833 assert(!isa<FunctionTemplateDecl>(D) && 2834 "Cannot refer unambiguously to a function template"); 2835 2836 SourceLocation Loc = NameInfo.getLoc(); 2837 if (CheckDeclInExpr(*this, Loc, D)) 2838 return ExprError(); 2839 2840 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 2841 // Specifically diagnose references to class templates that are missing 2842 // a template argument list. 2843 diagnoseMissingTemplateArguments(TemplateName(Template), Loc); 2844 return ExprError(); 2845 } 2846 2847 // Make sure that we're referring to a value. 2848 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2849 if (!VD) { 2850 Diag(Loc, diag::err_ref_non_value) 2851 << D << SS.getRange(); 2852 Diag(D->getLocation(), diag::note_declared_at); 2853 return ExprError(); 2854 } 2855 2856 // Check whether this declaration can be used. Note that we suppress 2857 // this check when we're going to perform argument-dependent lookup 2858 // on this function name, because this might not be the function 2859 // that overload resolution actually selects. 2860 if (DiagnoseUseOfDecl(VD, Loc)) 2861 return ExprError(); 2862 2863 // Only create DeclRefExpr's for valid Decl's. 2864 if (VD->isInvalidDecl() && !AcceptInvalidDecl) 2865 return ExprError(); 2866 2867 // Handle members of anonymous structs and unions. If we got here, 2868 // and the reference is to a class member indirect field, then this 2869 // must be the subject of a pointer-to-member expression. 2870 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD)) 2871 if (!indirectField->isCXXClassMember()) 2872 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(), 2873 indirectField); 2874 2875 { 2876 QualType type = VD->getType(); 2877 if (type.isNull()) 2878 return ExprError(); 2879 if (auto *FPT = type->getAs<FunctionProtoType>()) { 2880 // C++ [except.spec]p17: 2881 // An exception-specification is considered to be needed when: 2882 // - in an expression, the function is the unique lookup result or 2883 // the selected member of a set of overloaded functions. 2884 ResolveExceptionSpec(Loc, FPT); 2885 type = VD->getType(); 2886 } 2887 ExprValueKind valueKind = VK_RValue; 2888 2889 switch (D->getKind()) { 2890 // Ignore all the non-ValueDecl kinds. 2891 #define ABSTRACT_DECL(kind) 2892 #define VALUE(type, base) 2893 #define DECL(type, base) \ 2894 case Decl::type: 2895 #include "clang/AST/DeclNodes.inc" 2896 llvm_unreachable("invalid value decl kind"); 2897 2898 // These shouldn't make it here. 2899 case Decl::ObjCAtDefsField: 2900 case Decl::ObjCIvar: 2901 llvm_unreachable("forming non-member reference to ivar?"); 2902 2903 // Enum constants are always r-values and never references. 2904 // Unresolved using declarations are dependent. 2905 case Decl::EnumConstant: 2906 case Decl::UnresolvedUsingValue: 2907 case Decl::OMPDeclareReduction: 2908 valueKind = VK_RValue; 2909 break; 2910 2911 // Fields and indirect fields that got here must be for 2912 // pointer-to-member expressions; we just call them l-values for 2913 // internal consistency, because this subexpression doesn't really 2914 // exist in the high-level semantics. 2915 case Decl::Field: 2916 case Decl::IndirectField: 2917 assert(getLangOpts().CPlusPlus && 2918 "building reference to field in C?"); 2919 2920 // These can't have reference type in well-formed programs, but 2921 // for internal consistency we do this anyway. 2922 type = type.getNonReferenceType(); 2923 valueKind = VK_LValue; 2924 break; 2925 2926 // Non-type template parameters are either l-values or r-values 2927 // depending on the type. 2928 case Decl::NonTypeTemplateParm: { 2929 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) { 2930 type = reftype->getPointeeType(); 2931 valueKind = VK_LValue; // even if the parameter is an r-value reference 2932 break; 2933 } 2934 2935 // For non-references, we need to strip qualifiers just in case 2936 // the template parameter was declared as 'const int' or whatever. 2937 valueKind = VK_RValue; 2938 type = type.getUnqualifiedType(); 2939 break; 2940 } 2941 2942 case Decl::Var: 2943 case Decl::VarTemplateSpecialization: 2944 case Decl::VarTemplatePartialSpecialization: 2945 case Decl::Decomposition: 2946 case Decl::OMPCapturedExpr: 2947 // In C, "extern void blah;" is valid and is an r-value. 2948 if (!getLangOpts().CPlusPlus && 2949 !type.hasQualifiers() && 2950 type->isVoidType()) { 2951 valueKind = VK_RValue; 2952 break; 2953 } 2954 LLVM_FALLTHROUGH; 2955 2956 case Decl::ImplicitParam: 2957 case Decl::ParmVar: { 2958 // These are always l-values. 2959 valueKind = VK_LValue; 2960 type = type.getNonReferenceType(); 2961 2962 // FIXME: Does the addition of const really only apply in 2963 // potentially-evaluated contexts? Since the variable isn't actually 2964 // captured in an unevaluated context, it seems that the answer is no. 2965 if (!isUnevaluatedContext()) { 2966 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc); 2967 if (!CapturedType.isNull()) 2968 type = CapturedType; 2969 } 2970 2971 break; 2972 } 2973 2974 case Decl::Binding: { 2975 // These are always lvalues. 2976 valueKind = VK_LValue; 2977 type = type.getNonReferenceType(); 2978 // FIXME: Support lambda-capture of BindingDecls, once CWG actually 2979 // decides how that's supposed to work. 2980 auto *BD = cast<BindingDecl>(VD); 2981 if (BD->getDeclContext()->isFunctionOrMethod() && 2982 BD->getDeclContext() != CurContext) 2983 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext); 2984 break; 2985 } 2986 2987 case Decl::Function: { 2988 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) { 2989 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 2990 type = Context.BuiltinFnTy; 2991 valueKind = VK_RValue; 2992 break; 2993 } 2994 } 2995 2996 const FunctionType *fty = type->castAs<FunctionType>(); 2997 2998 // If we're referring to a function with an __unknown_anytype 2999 // result type, make the entire expression __unknown_anytype. 3000 if (fty->getReturnType() == Context.UnknownAnyTy) { 3001 type = Context.UnknownAnyTy; 3002 valueKind = VK_RValue; 3003 break; 3004 } 3005 3006 // Functions are l-values in C++. 3007 if (getLangOpts().CPlusPlus) { 3008 valueKind = VK_LValue; 3009 break; 3010 } 3011 3012 // C99 DR 316 says that, if a function type comes from a 3013 // function definition (without a prototype), that type is only 3014 // used for checking compatibility. Therefore, when referencing 3015 // the function, we pretend that we don't have the full function 3016 // type. 3017 if (!cast<FunctionDecl>(VD)->hasPrototype() && 3018 isa<FunctionProtoType>(fty)) 3019 type = Context.getFunctionNoProtoType(fty->getReturnType(), 3020 fty->getExtInfo()); 3021 3022 // Functions are r-values in C. 3023 valueKind = VK_RValue; 3024 break; 3025 } 3026 3027 case Decl::CXXDeductionGuide: 3028 llvm_unreachable("building reference to deduction guide"); 3029 3030 case Decl::MSProperty: 3031 valueKind = VK_LValue; 3032 break; 3033 3034 case Decl::CXXMethod: 3035 // If we're referring to a method with an __unknown_anytype 3036 // result type, make the entire expression __unknown_anytype. 3037 // This should only be possible with a type written directly. 3038 if (const FunctionProtoType *proto 3039 = dyn_cast<FunctionProtoType>(VD->getType())) 3040 if (proto->getReturnType() == Context.UnknownAnyTy) { 3041 type = Context.UnknownAnyTy; 3042 valueKind = VK_RValue; 3043 break; 3044 } 3045 3046 // C++ methods are l-values if static, r-values if non-static. 3047 if (cast<CXXMethodDecl>(VD)->isStatic()) { 3048 valueKind = VK_LValue; 3049 break; 3050 } 3051 LLVM_FALLTHROUGH; 3052 3053 case Decl::CXXConversion: 3054 case Decl::CXXDestructor: 3055 case Decl::CXXConstructor: 3056 valueKind = VK_RValue; 3057 break; 3058 } 3059 3060 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD, 3061 TemplateArgs); 3062 } 3063 } 3064 3065 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, 3066 SmallString<32> &Target) { 3067 Target.resize(CharByteWidth * (Source.size() + 1)); 3068 char *ResultPtr = &Target[0]; 3069 const llvm::UTF8 *ErrorPtr; 3070 bool success = 3071 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr); 3072 (void)success; 3073 assert(success); 3074 Target.resize(ResultPtr - &Target[0]); 3075 } 3076 3077 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc, 3078 PredefinedExpr::IdentKind IK) { 3079 // Pick the current block, lambda, captured statement or function. 3080 Decl *currentDecl = nullptr; 3081 if (const BlockScopeInfo *BSI = getCurBlock()) 3082 currentDecl = BSI->TheDecl; 3083 else if (const LambdaScopeInfo *LSI = getCurLambda()) 3084 currentDecl = LSI->CallOperator; 3085 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion()) 3086 currentDecl = CSI->TheCapturedDecl; 3087 else 3088 currentDecl = getCurFunctionOrMethodDecl(); 3089 3090 if (!currentDecl) { 3091 Diag(Loc, diag::ext_predef_outside_function); 3092 currentDecl = Context.getTranslationUnitDecl(); 3093 } 3094 3095 QualType ResTy; 3096 StringLiteral *SL = nullptr; 3097 if (cast<DeclContext>(currentDecl)->isDependentContext()) 3098 ResTy = Context.DependentTy; 3099 else { 3100 // Pre-defined identifiers are of type char[x], where x is the length of 3101 // the string. 3102 auto Str = PredefinedExpr::ComputeName(IK, currentDecl); 3103 unsigned Length = Str.length(); 3104 3105 llvm::APInt LengthI(32, Length + 1); 3106 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) { 3107 ResTy = 3108 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst()); 3109 SmallString<32> RawChars; 3110 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(), 3111 Str, RawChars); 3112 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3113 /*IndexTypeQuals*/ 0); 3114 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide, 3115 /*Pascal*/ false, ResTy, Loc); 3116 } else { 3117 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst()); 3118 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 3119 /*IndexTypeQuals*/ 0); 3120 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii, 3121 /*Pascal*/ false, ResTy, Loc); 3122 } 3123 } 3124 3125 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL); 3126 } 3127 3128 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) { 3129 PredefinedExpr::IdentKind IK; 3130 3131 switch (Kind) { 3132 default: llvm_unreachable("Unknown simple primary expr!"); 3133 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2] 3134 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break; 3135 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS] 3136 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS] 3137 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS] 3138 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS] 3139 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break; 3140 } 3141 3142 return BuildPredefinedExpr(Loc, IK); 3143 } 3144 3145 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) { 3146 SmallString<16> CharBuffer; 3147 bool Invalid = false; 3148 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid); 3149 if (Invalid) 3150 return ExprError(); 3151 3152 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(), 3153 PP, Tok.getKind()); 3154 if (Literal.hadError()) 3155 return ExprError(); 3156 3157 QualType Ty; 3158 if (Literal.isWide()) 3159 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++. 3160 else if (Literal.isUTF8() && getLangOpts().Char8) 3161 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists. 3162 else if (Literal.isUTF16()) 3163 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11. 3164 else if (Literal.isUTF32()) 3165 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11. 3166 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar()) 3167 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++. 3168 else 3169 Ty = Context.CharTy; // 'x' -> char in C++ 3170 3171 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii; 3172 if (Literal.isWide()) 3173 Kind = CharacterLiteral::Wide; 3174 else if (Literal.isUTF16()) 3175 Kind = CharacterLiteral::UTF16; 3176 else if (Literal.isUTF32()) 3177 Kind = CharacterLiteral::UTF32; 3178 else if (Literal.isUTF8()) 3179 Kind = CharacterLiteral::UTF8; 3180 3181 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty, 3182 Tok.getLocation()); 3183 3184 if (Literal.getUDSuffix().empty()) 3185 return Lit; 3186 3187 // We're building a user-defined literal. 3188 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3189 SourceLocation UDSuffixLoc = 3190 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3191 3192 // Make sure we're allowed user-defined literals here. 3193 if (!UDLScope) 3194 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl)); 3195 3196 // C++11 [lex.ext]p6: The literal L is treated as a call of the form 3197 // operator "" X (ch) 3198 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc, 3199 Lit, Tok.getLocation()); 3200 } 3201 3202 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) { 3203 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3204 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val), 3205 Context.IntTy, Loc); 3206 } 3207 3208 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, 3209 QualType Ty, SourceLocation Loc) { 3210 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty); 3211 3212 using llvm::APFloat; 3213 APFloat Val(Format); 3214 3215 APFloat::opStatus result = Literal.GetFloatValue(Val); 3216 3217 // Overflow is always an error, but underflow is only an error if 3218 // we underflowed to zero (APFloat reports denormals as underflow). 3219 if ((result & APFloat::opOverflow) || 3220 ((result & APFloat::opUnderflow) && Val.isZero())) { 3221 unsigned diagnostic; 3222 SmallString<20> buffer; 3223 if (result & APFloat::opOverflow) { 3224 diagnostic = diag::warn_float_overflow; 3225 APFloat::getLargest(Format).toString(buffer); 3226 } else { 3227 diagnostic = diag::warn_float_underflow; 3228 APFloat::getSmallest(Format).toString(buffer); 3229 } 3230 3231 S.Diag(Loc, diagnostic) 3232 << Ty 3233 << StringRef(buffer.data(), buffer.size()); 3234 } 3235 3236 bool isExact = (result == APFloat::opOK); 3237 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc); 3238 } 3239 3240 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) { 3241 assert(E && "Invalid expression"); 3242 3243 if (E->isValueDependent()) 3244 return false; 3245 3246 QualType QT = E->getType(); 3247 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) { 3248 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT; 3249 return true; 3250 } 3251 3252 llvm::APSInt ValueAPS; 3253 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS); 3254 3255 if (R.isInvalid()) 3256 return true; 3257 3258 bool ValueIsPositive = ValueAPS.isStrictlyPositive(); 3259 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) { 3260 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value) 3261 << ValueAPS.toString(10) << ValueIsPositive; 3262 return true; 3263 } 3264 3265 return false; 3266 } 3267 3268 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) { 3269 // Fast path for a single digit (which is quite common). A single digit 3270 // cannot have a trigraph, escaped newline, radix prefix, or suffix. 3271 if (Tok.getLength() == 1) { 3272 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok); 3273 return ActOnIntegerConstant(Tok.getLocation(), Val-'0'); 3274 } 3275 3276 SmallString<128> SpellingBuffer; 3277 // NumericLiteralParser wants to overread by one character. Add padding to 3278 // the buffer in case the token is copied to the buffer. If getSpelling() 3279 // returns a StringRef to the memory buffer, it should have a null char at 3280 // the EOF, so it is also safe. 3281 SpellingBuffer.resize(Tok.getLength() + 1); 3282 3283 // Get the spelling of the token, which eliminates trigraphs, etc. 3284 bool Invalid = false; 3285 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid); 3286 if (Invalid) 3287 return ExprError(); 3288 3289 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP); 3290 if (Literal.hadError) 3291 return ExprError(); 3292 3293 if (Literal.hasUDSuffix()) { 3294 // We're building a user-defined literal. 3295 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix()); 3296 SourceLocation UDSuffixLoc = 3297 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset()); 3298 3299 // Make sure we're allowed user-defined literals here. 3300 if (!UDLScope) 3301 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl)); 3302 3303 QualType CookedTy; 3304 if (Literal.isFloatingLiteral()) { 3305 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type 3306 // long double, the literal is treated as a call of the form 3307 // operator "" X (f L) 3308 CookedTy = Context.LongDoubleTy; 3309 } else { 3310 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type 3311 // unsigned long long, the literal is treated as a call of the form 3312 // operator "" X (n ULL) 3313 CookedTy = Context.UnsignedLongLongTy; 3314 } 3315 3316 DeclarationName OpName = 3317 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix); 3318 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc); 3319 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc); 3320 3321 SourceLocation TokLoc = Tok.getLocation(); 3322 3323 // Perform literal operator lookup to determine if we're building a raw 3324 // literal or a cooked one. 3325 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName); 3326 switch (LookupLiteralOperator(UDLScope, R, CookedTy, 3327 /*AllowRaw*/ true, /*AllowTemplate*/ true, 3328 /*AllowStringTemplate*/ false, 3329 /*DiagnoseMissing*/ !Literal.isImaginary)) { 3330 case LOLR_ErrorNoDiagnostic: 3331 // Lookup failure for imaginary constants isn't fatal, there's still the 3332 // GNU extension producing _Complex types. 3333 break; 3334 case LOLR_Error: 3335 return ExprError(); 3336 case LOLR_Cooked: { 3337 Expr *Lit; 3338 if (Literal.isFloatingLiteral()) { 3339 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation()); 3340 } else { 3341 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0); 3342 if (Literal.GetIntegerValue(ResultVal)) 3343 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3344 << /* Unsigned */ 1; 3345 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy, 3346 Tok.getLocation()); 3347 } 3348 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3349 } 3350 3351 case LOLR_Raw: { 3352 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the 3353 // literal is treated as a call of the form 3354 // operator "" X ("n") 3355 unsigned Length = Literal.getUDSuffixOffset(); 3356 QualType StrTy = Context.getConstantArrayType( 3357 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()), 3358 llvm::APInt(32, Length + 1), ArrayType::Normal, 0); 3359 Expr *Lit = StringLiteral::Create( 3360 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii, 3361 /*Pascal*/false, StrTy, &TokLoc, 1); 3362 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc); 3363 } 3364 3365 case LOLR_Template: { 3366 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator 3367 // template), L is treated as a call fo the form 3368 // operator "" X <'c1', 'c2', ... 'ck'>() 3369 // where n is the source character sequence c1 c2 ... ck. 3370 TemplateArgumentListInfo ExplicitArgs; 3371 unsigned CharBits = Context.getIntWidth(Context.CharTy); 3372 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType(); 3373 llvm::APSInt Value(CharBits, CharIsUnsigned); 3374 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) { 3375 Value = TokSpelling[I]; 3376 TemplateArgument Arg(Context, Value, Context.CharTy); 3377 TemplateArgumentLocInfo ArgInfo; 3378 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo)); 3379 } 3380 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc, 3381 &ExplicitArgs); 3382 } 3383 case LOLR_StringTemplate: 3384 llvm_unreachable("unexpected literal operator lookup result"); 3385 } 3386 } 3387 3388 Expr *Res; 3389 3390 if (Literal.isFixedPointLiteral()) { 3391 QualType Ty; 3392 3393 if (Literal.isAccum) { 3394 if (Literal.isHalf) { 3395 Ty = Context.ShortAccumTy; 3396 } else if (Literal.isLong) { 3397 Ty = Context.LongAccumTy; 3398 } else { 3399 Ty = Context.AccumTy; 3400 } 3401 } else if (Literal.isFract) { 3402 if (Literal.isHalf) { 3403 Ty = Context.ShortFractTy; 3404 } else if (Literal.isLong) { 3405 Ty = Context.LongFractTy; 3406 } else { 3407 Ty = Context.FractTy; 3408 } 3409 } 3410 3411 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty); 3412 3413 bool isSigned = !Literal.isUnsigned; 3414 unsigned scale = Context.getFixedPointScale(Ty); 3415 unsigned bit_width = Context.getTypeInfo(Ty).Width; 3416 3417 llvm::APInt Val(bit_width, 0, isSigned); 3418 bool Overflowed = Literal.GetFixedPointValue(Val, scale); 3419 bool ValIsZero = Val.isNullValue() && !Overflowed; 3420 3421 auto MaxVal = Context.getFixedPointMax(Ty).getValue(); 3422 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero) 3423 // Clause 6.4.4 - The value of a constant shall be in the range of 3424 // representable values for its type, with exception for constants of a 3425 // fract type with a value of exactly 1; such a constant shall denote 3426 // the maximal value for the type. 3427 --Val; 3428 else if (Val.ugt(MaxVal) || Overflowed) 3429 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point); 3430 3431 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty, 3432 Tok.getLocation(), scale); 3433 } else if (Literal.isFloatingLiteral()) { 3434 QualType Ty; 3435 if (Literal.isHalf){ 3436 if (getOpenCLOptions().isEnabled("cl_khr_fp16")) 3437 Ty = Context.HalfTy; 3438 else { 3439 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16); 3440 return ExprError(); 3441 } 3442 } else if (Literal.isFloat) 3443 Ty = Context.FloatTy; 3444 else if (Literal.isLong) 3445 Ty = Context.LongDoubleTy; 3446 else if (Literal.isFloat16) 3447 Ty = Context.Float16Ty; 3448 else if (Literal.isFloat128) 3449 Ty = Context.Float128Ty; 3450 else 3451 Ty = Context.DoubleTy; 3452 3453 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation()); 3454 3455 if (Ty == Context.DoubleTy) { 3456 if (getLangOpts().SinglePrecisionConstants) { 3457 const BuiltinType *BTy = Ty->getAs<BuiltinType>(); 3458 if (BTy->getKind() != BuiltinType::Float) { 3459 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3460 } 3461 } else if (getLangOpts().OpenCL && 3462 !getOpenCLOptions().isEnabled("cl_khr_fp64")) { 3463 // Impose single-precision float type when cl_khr_fp64 is not enabled. 3464 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64); 3465 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get(); 3466 } 3467 } 3468 } else if (!Literal.isIntegerLiteral()) { 3469 return ExprError(); 3470 } else { 3471 QualType Ty; 3472 3473 // 'long long' is a C99 or C++11 feature. 3474 if (!getLangOpts().C99 && Literal.isLongLong) { 3475 if (getLangOpts().CPlusPlus) 3476 Diag(Tok.getLocation(), 3477 getLangOpts().CPlusPlus11 ? 3478 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); 3479 else 3480 Diag(Tok.getLocation(), diag::ext_c99_longlong); 3481 } 3482 3483 // Get the value in the widest-possible width. 3484 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth(); 3485 llvm::APInt ResultVal(MaxWidth, 0); 3486 3487 if (Literal.GetIntegerValue(ResultVal)) { 3488 // If this value didn't fit into uintmax_t, error and force to ull. 3489 Diag(Tok.getLocation(), diag::err_integer_literal_too_large) 3490 << /* Unsigned */ 1; 3491 Ty = Context.UnsignedLongLongTy; 3492 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() && 3493 "long long is not intmax_t?"); 3494 } else { 3495 // If this value fits into a ULL, try to figure out what else it fits into 3496 // according to the rules of C99 6.4.4.1p5. 3497 3498 // Octal, Hexadecimal, and integers with a U suffix are allowed to 3499 // be an unsigned int. 3500 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10; 3501 3502 // Check from smallest to largest, picking the smallest type we can. 3503 unsigned Width = 0; 3504 3505 // Microsoft specific integer suffixes are explicitly sized. 3506 if (Literal.MicrosoftInteger) { 3507 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) { 3508 Width = 8; 3509 Ty = Context.CharTy; 3510 } else { 3511 Width = Literal.MicrosoftInteger; 3512 Ty = Context.getIntTypeForBitwidth(Width, 3513 /*Signed=*/!Literal.isUnsigned); 3514 } 3515 } 3516 3517 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) { 3518 // Are int/unsigned possibilities? 3519 unsigned IntSize = Context.getTargetInfo().getIntWidth(); 3520 3521 // Does it fit in a unsigned int? 3522 if (ResultVal.isIntN(IntSize)) { 3523 // Does it fit in a signed int? 3524 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0) 3525 Ty = Context.IntTy; 3526 else if (AllowUnsigned) 3527 Ty = Context.UnsignedIntTy; 3528 Width = IntSize; 3529 } 3530 } 3531 3532 // Are long/unsigned long possibilities? 3533 if (Ty.isNull() && !Literal.isLongLong) { 3534 unsigned LongSize = Context.getTargetInfo().getLongWidth(); 3535 3536 // Does it fit in a unsigned long? 3537 if (ResultVal.isIntN(LongSize)) { 3538 // Does it fit in a signed long? 3539 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0) 3540 Ty = Context.LongTy; 3541 else if (AllowUnsigned) 3542 Ty = Context.UnsignedLongTy; 3543 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2 3544 // is compatible. 3545 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) { 3546 const unsigned LongLongSize = 3547 Context.getTargetInfo().getLongLongWidth(); 3548 Diag(Tok.getLocation(), 3549 getLangOpts().CPlusPlus 3550 ? Literal.isLong 3551 ? diag::warn_old_implicitly_unsigned_long_cxx 3552 : /*C++98 UB*/ diag:: 3553 ext_old_implicitly_unsigned_long_cxx 3554 : diag::warn_old_implicitly_unsigned_long) 3555 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0 3556 : /*will be ill-formed*/ 1); 3557 Ty = Context.UnsignedLongTy; 3558 } 3559 Width = LongSize; 3560 } 3561 } 3562 3563 // Check long long if needed. 3564 if (Ty.isNull()) { 3565 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth(); 3566 3567 // Does it fit in a unsigned long long? 3568 if (ResultVal.isIntN(LongLongSize)) { 3569 // Does it fit in a signed long long? 3570 // To be compatible with MSVC, hex integer literals ending with the 3571 // LL or i64 suffix are always signed in Microsoft mode. 3572 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 || 3573 (getLangOpts().MSVCCompat && Literal.isLongLong))) 3574 Ty = Context.LongLongTy; 3575 else if (AllowUnsigned) 3576 Ty = Context.UnsignedLongLongTy; 3577 Width = LongLongSize; 3578 } 3579 } 3580 3581 // If we still couldn't decide a type, we probably have something that 3582 // does not fit in a signed long long, but has no U suffix. 3583 if (Ty.isNull()) { 3584 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed); 3585 Ty = Context.UnsignedLongLongTy; 3586 Width = Context.getTargetInfo().getLongLongWidth(); 3587 } 3588 3589 if (ResultVal.getBitWidth() != Width) 3590 ResultVal = ResultVal.trunc(Width); 3591 } 3592 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation()); 3593 } 3594 3595 // If this is an imaginary literal, create the ImaginaryLiteral wrapper. 3596 if (Literal.isImaginary) { 3597 Res = new (Context) ImaginaryLiteral(Res, 3598 Context.getComplexType(Res->getType())); 3599 3600 Diag(Tok.getLocation(), diag::ext_imaginary_constant); 3601 } 3602 return Res; 3603 } 3604 3605 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) { 3606 assert(E && "ActOnParenExpr() missing expr"); 3607 return new (Context) ParenExpr(L, R, E); 3608 } 3609 3610 static bool CheckVecStepTraitOperandType(Sema &S, QualType T, 3611 SourceLocation Loc, 3612 SourceRange ArgRange) { 3613 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in 3614 // scalar or vector data type argument..." 3615 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic 3616 // type (C99 6.2.5p18) or void. 3617 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) { 3618 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type) 3619 << T << ArgRange; 3620 return true; 3621 } 3622 3623 assert((T->isVoidType() || !T->isIncompleteType()) && 3624 "Scalar types should always be complete"); 3625 return false; 3626 } 3627 3628 static bool CheckExtensionTraitOperandType(Sema &S, QualType T, 3629 SourceLocation Loc, 3630 SourceRange ArgRange, 3631 UnaryExprOrTypeTrait TraitKind) { 3632 // Invalid types must be hard errors for SFINAE in C++. 3633 if (S.LangOpts.CPlusPlus) 3634 return true; 3635 3636 // C99 6.5.3.4p1: 3637 if (T->isFunctionType() && 3638 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf || 3639 TraitKind == UETT_PreferredAlignOf)) { 3640 // sizeof(function)/alignof(function) is allowed as an extension. 3641 S.Diag(Loc, diag::ext_sizeof_alignof_function_type) 3642 << TraitKind << ArgRange; 3643 return false; 3644 } 3645 3646 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where 3647 // this is an error (OpenCL v1.1 s6.3.k) 3648 if (T->isVoidType()) { 3649 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type 3650 : diag::ext_sizeof_alignof_void_type; 3651 S.Diag(Loc, DiagID) << TraitKind << ArgRange; 3652 return false; 3653 } 3654 3655 return true; 3656 } 3657 3658 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, 3659 SourceLocation Loc, 3660 SourceRange ArgRange, 3661 UnaryExprOrTypeTrait TraitKind) { 3662 // Reject sizeof(interface) and sizeof(interface<proto>) if the 3663 // runtime doesn't allow it. 3664 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) { 3665 S.Diag(Loc, diag::err_sizeof_nonfragile_interface) 3666 << T << (TraitKind == UETT_SizeOf) 3667 << ArgRange; 3668 return true; 3669 } 3670 3671 return false; 3672 } 3673 3674 /// Check whether E is a pointer from a decayed array type (the decayed 3675 /// pointer type is equal to T) and emit a warning if it is. 3676 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, 3677 Expr *E) { 3678 // Don't warn if the operation changed the type. 3679 if (T != E->getType()) 3680 return; 3681 3682 // Now look for array decays. 3683 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E); 3684 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay) 3685 return; 3686 3687 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange() 3688 << ICE->getType() 3689 << ICE->getSubExpr()->getType(); 3690 } 3691 3692 /// Check the constraints on expression operands to unary type expression 3693 /// and type traits. 3694 /// 3695 /// Completes any types necessary and validates the constraints on the operand 3696 /// expression. The logic mostly mirrors the type-based overload, but may modify 3697 /// the expression as it completes the type for that expression through template 3698 /// instantiation, etc. 3699 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E, 3700 UnaryExprOrTypeTrait ExprKind) { 3701 QualType ExprTy = E->getType(); 3702 assert(!ExprTy->isReferenceType()); 3703 3704 if (ExprKind == UETT_VecStep) 3705 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(), 3706 E->getSourceRange()); 3707 3708 // Whitelist some types as extensions 3709 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(), 3710 E->getSourceRange(), ExprKind)) 3711 return false; 3712 3713 // 'alignof' applied to an expression only requires the base element type of 3714 // the expression to be complete. 'sizeof' requires the expression's type to 3715 // be complete (and will attempt to complete it if it's an array of unknown 3716 // bound). 3717 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 3718 if (RequireCompleteType(E->getExprLoc(), 3719 Context.getBaseElementType(E->getType()), 3720 diag::err_sizeof_alignof_incomplete_type, ExprKind, 3721 E->getSourceRange())) 3722 return true; 3723 } else { 3724 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type, 3725 ExprKind, E->getSourceRange())) 3726 return true; 3727 } 3728 3729 // Completing the expression's type may have changed it. 3730 ExprTy = E->getType(); 3731 assert(!ExprTy->isReferenceType()); 3732 3733 if (ExprTy->isFunctionType()) { 3734 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type) 3735 << ExprKind << E->getSourceRange(); 3736 return true; 3737 } 3738 3739 // The operand for sizeof and alignof is in an unevaluated expression context, 3740 // so side effects could result in unintended consequences. 3741 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf || 3742 ExprKind == UETT_PreferredAlignOf) && 3743 !inTemplateInstantiation() && E->HasSideEffects(Context, false)) 3744 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context); 3745 3746 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(), 3747 E->getSourceRange(), ExprKind)) 3748 return true; 3749 3750 if (ExprKind == UETT_SizeOf) { 3751 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) { 3752 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) { 3753 QualType OType = PVD->getOriginalType(); 3754 QualType Type = PVD->getType(); 3755 if (Type->isPointerType() && OType->isArrayType()) { 3756 Diag(E->getExprLoc(), diag::warn_sizeof_array_param) 3757 << Type << OType; 3758 Diag(PVD->getLocation(), diag::note_declared_at); 3759 } 3760 } 3761 } 3762 3763 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array 3764 // decays into a pointer and returns an unintended result. This is most 3765 // likely a typo for "sizeof(array) op x". 3766 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) { 3767 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3768 BO->getLHS()); 3769 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(), 3770 BO->getRHS()); 3771 } 3772 } 3773 3774 return false; 3775 } 3776 3777 /// Check the constraints on operands to unary expression and type 3778 /// traits. 3779 /// 3780 /// This will complete any types necessary, and validate the various constraints 3781 /// on those operands. 3782 /// 3783 /// The UsualUnaryConversions() function is *not* called by this routine. 3784 /// C99 6.3.2.1p[2-4] all state: 3785 /// Except when it is the operand of the sizeof operator ... 3786 /// 3787 /// C++ [expr.sizeof]p4 3788 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer 3789 /// standard conversions are not applied to the operand of sizeof. 3790 /// 3791 /// This policy is followed for all of the unary trait expressions. 3792 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType, 3793 SourceLocation OpLoc, 3794 SourceRange ExprRange, 3795 UnaryExprOrTypeTrait ExprKind) { 3796 if (ExprType->isDependentType()) 3797 return false; 3798 3799 // C++ [expr.sizeof]p2: 3800 // When applied to a reference or a reference type, the result 3801 // is the size of the referenced type. 3802 // C++11 [expr.alignof]p3: 3803 // When alignof is applied to a reference type, the result 3804 // shall be the alignment of the referenced type. 3805 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>()) 3806 ExprType = Ref->getPointeeType(); 3807 3808 // C11 6.5.3.4/3, C++11 [expr.alignof]p3: 3809 // When alignof or _Alignof is applied to an array type, the result 3810 // is the alignment of the element type. 3811 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf || 3812 ExprKind == UETT_OpenMPRequiredSimdAlign) 3813 ExprType = Context.getBaseElementType(ExprType); 3814 3815 if (ExprKind == UETT_VecStep) 3816 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange); 3817 3818 // Whitelist some types as extensions 3819 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange, 3820 ExprKind)) 3821 return false; 3822 3823 if (RequireCompleteType(OpLoc, ExprType, 3824 diag::err_sizeof_alignof_incomplete_type, 3825 ExprKind, ExprRange)) 3826 return true; 3827 3828 if (ExprType->isFunctionType()) { 3829 Diag(OpLoc, diag::err_sizeof_alignof_function_type) 3830 << ExprKind << ExprRange; 3831 return true; 3832 } 3833 3834 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange, 3835 ExprKind)) 3836 return true; 3837 3838 return false; 3839 } 3840 3841 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) { 3842 E = E->IgnoreParens(); 3843 3844 // Cannot know anything else if the expression is dependent. 3845 if (E->isTypeDependent()) 3846 return false; 3847 3848 if (E->getObjectKind() == OK_BitField) { 3849 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) 3850 << 1 << E->getSourceRange(); 3851 return true; 3852 } 3853 3854 ValueDecl *D = nullptr; 3855 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3856 D = DRE->getDecl(); 3857 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3858 D = ME->getMemberDecl(); 3859 } 3860 3861 // If it's a field, require the containing struct to have a 3862 // complete definition so that we can compute the layout. 3863 // 3864 // This can happen in C++11 onwards, either by naming the member 3865 // in a way that is not transformed into a member access expression 3866 // (in an unevaluated operand, for instance), or by naming the member 3867 // in a trailing-return-type. 3868 // 3869 // For the record, since __alignof__ on expressions is a GCC 3870 // extension, GCC seems to permit this but always gives the 3871 // nonsensical answer 0. 3872 // 3873 // We don't really need the layout here --- we could instead just 3874 // directly check for all the appropriate alignment-lowing 3875 // attributes --- but that would require duplicating a lot of 3876 // logic that just isn't worth duplicating for such a marginal 3877 // use-case. 3878 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) { 3879 // Fast path this check, since we at least know the record has a 3880 // definition if we can find a member of it. 3881 if (!FD->getParent()->isCompleteDefinition()) { 3882 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type) 3883 << E->getSourceRange(); 3884 return true; 3885 } 3886 3887 // Otherwise, if it's a field, and the field doesn't have 3888 // reference type, then it must have a complete type (or be a 3889 // flexible array member, which we explicitly want to 3890 // white-list anyway), which makes the following checks trivial. 3891 if (!FD->getType()->isReferenceType()) 3892 return false; 3893 } 3894 3895 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind); 3896 } 3897 3898 bool Sema::CheckVecStepExpr(Expr *E) { 3899 E = E->IgnoreParens(); 3900 3901 // Cannot know anything else if the expression is dependent. 3902 if (E->isTypeDependent()) 3903 return false; 3904 3905 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep); 3906 } 3907 3908 static void captureVariablyModifiedType(ASTContext &Context, QualType T, 3909 CapturingScopeInfo *CSI) { 3910 assert(T->isVariablyModifiedType()); 3911 assert(CSI != nullptr); 3912 3913 // We're going to walk down into the type and look for VLA expressions. 3914 do { 3915 const Type *Ty = T.getTypePtr(); 3916 switch (Ty->getTypeClass()) { 3917 #define TYPE(Class, Base) 3918 #define ABSTRACT_TYPE(Class, Base) 3919 #define NON_CANONICAL_TYPE(Class, Base) 3920 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 3921 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 3922 #include "clang/AST/TypeNodes.def" 3923 T = QualType(); 3924 break; 3925 // These types are never variably-modified. 3926 case Type::Builtin: 3927 case Type::Complex: 3928 case Type::Vector: 3929 case Type::ExtVector: 3930 case Type::Record: 3931 case Type::Enum: 3932 case Type::Elaborated: 3933 case Type::TemplateSpecialization: 3934 case Type::ObjCObject: 3935 case Type::ObjCInterface: 3936 case Type::ObjCObjectPointer: 3937 case Type::ObjCTypeParam: 3938 case Type::Pipe: 3939 llvm_unreachable("type class is never variably-modified!"); 3940 case Type::Adjusted: 3941 T = cast<AdjustedType>(Ty)->getOriginalType(); 3942 break; 3943 case Type::Decayed: 3944 T = cast<DecayedType>(Ty)->getPointeeType(); 3945 break; 3946 case Type::Pointer: 3947 T = cast<PointerType>(Ty)->getPointeeType(); 3948 break; 3949 case Type::BlockPointer: 3950 T = cast<BlockPointerType>(Ty)->getPointeeType(); 3951 break; 3952 case Type::LValueReference: 3953 case Type::RValueReference: 3954 T = cast<ReferenceType>(Ty)->getPointeeType(); 3955 break; 3956 case Type::MemberPointer: 3957 T = cast<MemberPointerType>(Ty)->getPointeeType(); 3958 break; 3959 case Type::ConstantArray: 3960 case Type::IncompleteArray: 3961 // Losing element qualification here is fine. 3962 T = cast<ArrayType>(Ty)->getElementType(); 3963 break; 3964 case Type::VariableArray: { 3965 // Losing element qualification here is fine. 3966 const VariableArrayType *VAT = cast<VariableArrayType>(Ty); 3967 3968 // Unknown size indication requires no size computation. 3969 // Otherwise, evaluate and record it. 3970 if (auto Size = VAT->getSizeExpr()) { 3971 if (!CSI->isVLATypeCaptured(VAT)) { 3972 RecordDecl *CapRecord = nullptr; 3973 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) { 3974 CapRecord = LSI->Lambda; 3975 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 3976 CapRecord = CRSI->TheRecordDecl; 3977 } 3978 if (CapRecord) { 3979 auto ExprLoc = Size->getExprLoc(); 3980 auto SizeType = Context.getSizeType(); 3981 // Build the non-static data member. 3982 auto Field = 3983 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc, 3984 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr, 3985 /*BW*/ nullptr, /*Mutable*/ false, 3986 /*InitStyle*/ ICIS_NoInit); 3987 Field->setImplicit(true); 3988 Field->setAccess(AS_private); 3989 Field->setCapturedVLAType(VAT); 3990 CapRecord->addDecl(Field); 3991 3992 CSI->addVLATypeCapture(ExprLoc, SizeType); 3993 } 3994 } 3995 } 3996 T = VAT->getElementType(); 3997 break; 3998 } 3999 case Type::FunctionProto: 4000 case Type::FunctionNoProto: 4001 T = cast<FunctionType>(Ty)->getReturnType(); 4002 break; 4003 case Type::Paren: 4004 case Type::TypeOf: 4005 case Type::UnaryTransform: 4006 case Type::Attributed: 4007 case Type::SubstTemplateTypeParm: 4008 case Type::PackExpansion: 4009 // Keep walking after single level desugaring. 4010 T = T.getSingleStepDesugaredType(Context); 4011 break; 4012 case Type::Typedef: 4013 T = cast<TypedefType>(Ty)->desugar(); 4014 break; 4015 case Type::Decltype: 4016 T = cast<DecltypeType>(Ty)->desugar(); 4017 break; 4018 case Type::Auto: 4019 case Type::DeducedTemplateSpecialization: 4020 T = cast<DeducedType>(Ty)->getDeducedType(); 4021 break; 4022 case Type::TypeOfExpr: 4023 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType(); 4024 break; 4025 case Type::Atomic: 4026 T = cast<AtomicType>(Ty)->getValueType(); 4027 break; 4028 } 4029 } while (!T.isNull() && T->isVariablyModifiedType()); 4030 } 4031 4032 /// Build a sizeof or alignof expression given a type operand. 4033 ExprResult 4034 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 4035 SourceLocation OpLoc, 4036 UnaryExprOrTypeTrait ExprKind, 4037 SourceRange R) { 4038 if (!TInfo) 4039 return ExprError(); 4040 4041 QualType T = TInfo->getType(); 4042 4043 if (!T->isDependentType() && 4044 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind)) 4045 return ExprError(); 4046 4047 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) { 4048 if (auto *TT = T->getAs<TypedefType>()) { 4049 for (auto I = FunctionScopes.rbegin(), 4050 E = std::prev(FunctionScopes.rend()); 4051 I != E; ++I) { 4052 auto *CSI = dyn_cast<CapturingScopeInfo>(*I); 4053 if (CSI == nullptr) 4054 break; 4055 DeclContext *DC = nullptr; 4056 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI)) 4057 DC = LSI->CallOperator; 4058 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) 4059 DC = CRSI->TheCapturedDecl; 4060 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI)) 4061 DC = BSI->TheDecl; 4062 if (DC) { 4063 if (DC->containsDecl(TT->getDecl())) 4064 break; 4065 captureVariablyModifiedType(Context, T, CSI); 4066 } 4067 } 4068 } 4069 } 4070 4071 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4072 return new (Context) UnaryExprOrTypeTraitExpr( 4073 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd()); 4074 } 4075 4076 /// Build a sizeof or alignof expression given an expression 4077 /// operand. 4078 ExprResult 4079 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 4080 UnaryExprOrTypeTrait ExprKind) { 4081 ExprResult PE = CheckPlaceholderExpr(E); 4082 if (PE.isInvalid()) 4083 return ExprError(); 4084 4085 E = PE.get(); 4086 4087 // Verify that the operand is valid. 4088 bool isInvalid = false; 4089 if (E->isTypeDependent()) { 4090 // Delay type-checking for type-dependent expressions. 4091 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) { 4092 isInvalid = CheckAlignOfExpr(*this, E, ExprKind); 4093 } else if (ExprKind == UETT_VecStep) { 4094 isInvalid = CheckVecStepExpr(E); 4095 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) { 4096 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr); 4097 isInvalid = true; 4098 } else if (E->refersToBitField()) { // C99 6.5.3.4p1. 4099 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0; 4100 isInvalid = true; 4101 } else { 4102 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf); 4103 } 4104 4105 if (isInvalid) 4106 return ExprError(); 4107 4108 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) { 4109 PE = TransformToPotentiallyEvaluated(E); 4110 if (PE.isInvalid()) return ExprError(); 4111 E = PE.get(); 4112 } 4113 4114 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t. 4115 return new (Context) UnaryExprOrTypeTraitExpr( 4116 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd()); 4117 } 4118 4119 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c 4120 /// expr and the same for @c alignof and @c __alignof 4121 /// Note that the ArgRange is invalid if isType is false. 4122 ExprResult 4123 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 4124 UnaryExprOrTypeTrait ExprKind, bool IsType, 4125 void *TyOrEx, SourceRange ArgRange) { 4126 // If error parsing type, ignore. 4127 if (!TyOrEx) return ExprError(); 4128 4129 if (IsType) { 4130 TypeSourceInfo *TInfo; 4131 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo); 4132 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange); 4133 } 4134 4135 Expr *ArgEx = (Expr *)TyOrEx; 4136 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind); 4137 return Result; 4138 } 4139 4140 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, 4141 bool IsReal) { 4142 if (V.get()->isTypeDependent()) 4143 return S.Context.DependentTy; 4144 4145 // _Real and _Imag are only l-values for normal l-values. 4146 if (V.get()->getObjectKind() != OK_Ordinary) { 4147 V = S.DefaultLvalueConversion(V.get()); 4148 if (V.isInvalid()) 4149 return QualType(); 4150 } 4151 4152 // These operators return the element type of a complex type. 4153 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>()) 4154 return CT->getElementType(); 4155 4156 // Otherwise they pass through real integer and floating point types here. 4157 if (V.get()->getType()->isArithmeticType()) 4158 return V.get()->getType(); 4159 4160 // Test for placeholders. 4161 ExprResult PR = S.CheckPlaceholderExpr(V.get()); 4162 if (PR.isInvalid()) return QualType(); 4163 if (PR.get() != V.get()) { 4164 V = PR; 4165 return CheckRealImagOperand(S, V, Loc, IsReal); 4166 } 4167 4168 // Reject anything else. 4169 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType() 4170 << (IsReal ? "__real" : "__imag"); 4171 return QualType(); 4172 } 4173 4174 4175 4176 ExprResult 4177 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 4178 tok::TokenKind Kind, Expr *Input) { 4179 UnaryOperatorKind Opc; 4180 switch (Kind) { 4181 default: llvm_unreachable("Unknown unary op!"); 4182 case tok::plusplus: Opc = UO_PostInc; break; 4183 case tok::minusminus: Opc = UO_PostDec; break; 4184 } 4185 4186 // Since this might is a postfix expression, get rid of ParenListExprs. 4187 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input); 4188 if (Result.isInvalid()) return ExprError(); 4189 Input = Result.get(); 4190 4191 return BuildUnaryOp(S, OpLoc, Opc, Input); 4192 } 4193 4194 /// Diagnose if arithmetic on the given ObjC pointer is illegal. 4195 /// 4196 /// \return true on error 4197 static bool checkArithmeticOnObjCPointer(Sema &S, 4198 SourceLocation opLoc, 4199 Expr *op) { 4200 assert(op->getType()->isObjCObjectPointerType()); 4201 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() && 4202 !S.LangOpts.ObjCSubscriptingLegacyRuntime) 4203 return false; 4204 4205 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface) 4206 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType() 4207 << op->getSourceRange(); 4208 return true; 4209 } 4210 4211 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) { 4212 auto *BaseNoParens = Base->IgnoreParens(); 4213 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens)) 4214 return MSProp->getPropertyDecl()->getType()->isArrayType(); 4215 return isa<MSPropertySubscriptExpr>(BaseNoParens); 4216 } 4217 4218 ExprResult 4219 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc, 4220 Expr *idx, SourceLocation rbLoc) { 4221 if (base && !base->getType().isNull() && 4222 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection)) 4223 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(), 4224 /*Length=*/nullptr, rbLoc); 4225 4226 // Since this might be a postfix expression, get rid of ParenListExprs. 4227 if (isa<ParenListExpr>(base)) { 4228 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base); 4229 if (result.isInvalid()) return ExprError(); 4230 base = result.get(); 4231 } 4232 4233 // Handle any non-overload placeholder types in the base and index 4234 // expressions. We can't handle overloads here because the other 4235 // operand might be an overloadable type, in which case the overload 4236 // resolution for the operator overload should get the first crack 4237 // at the overload. 4238 bool IsMSPropertySubscript = false; 4239 if (base->getType()->isNonOverloadPlaceholderType()) { 4240 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base); 4241 if (!IsMSPropertySubscript) { 4242 ExprResult result = CheckPlaceholderExpr(base); 4243 if (result.isInvalid()) 4244 return ExprError(); 4245 base = result.get(); 4246 } 4247 } 4248 if (idx->getType()->isNonOverloadPlaceholderType()) { 4249 ExprResult result = CheckPlaceholderExpr(idx); 4250 if (result.isInvalid()) return ExprError(); 4251 idx = result.get(); 4252 } 4253 4254 // Build an unanalyzed expression if either operand is type-dependent. 4255 if (getLangOpts().CPlusPlus && 4256 (base->isTypeDependent() || idx->isTypeDependent())) { 4257 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy, 4258 VK_LValue, OK_Ordinary, rbLoc); 4259 } 4260 4261 // MSDN, property (C++) 4262 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx 4263 // This attribute can also be used in the declaration of an empty array in a 4264 // class or structure definition. For example: 4265 // __declspec(property(get=GetX, put=PutX)) int x[]; 4266 // The above statement indicates that x[] can be used with one or more array 4267 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), 4268 // and p->x[a][b] = i will be turned into p->PutX(a, b, i); 4269 if (IsMSPropertySubscript) { 4270 // Build MS property subscript expression if base is MS property reference 4271 // or MS property subscript. 4272 return new (Context) MSPropertySubscriptExpr( 4273 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc); 4274 } 4275 4276 // Use C++ overloaded-operator rules if either operand has record 4277 // type. The spec says to do this if either type is *overloadable*, 4278 // but enum types can't declare subscript operators or conversion 4279 // operators, so there's nothing interesting for overload resolution 4280 // to do if there aren't any record types involved. 4281 // 4282 // ObjC pointers have their own subscripting logic that is not tied 4283 // to overload resolution and so should not take this path. 4284 if (getLangOpts().CPlusPlus && 4285 (base->getType()->isRecordType() || 4286 (!base->getType()->isObjCObjectPointerType() && 4287 idx->getType()->isRecordType()))) { 4288 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx); 4289 } 4290 4291 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc); 4292 } 4293 4294 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, 4295 Expr *LowerBound, 4296 SourceLocation ColonLoc, Expr *Length, 4297 SourceLocation RBLoc) { 4298 if (Base->getType()->isPlaceholderType() && 4299 !Base->getType()->isSpecificPlaceholderType( 4300 BuiltinType::OMPArraySection)) { 4301 ExprResult Result = CheckPlaceholderExpr(Base); 4302 if (Result.isInvalid()) 4303 return ExprError(); 4304 Base = Result.get(); 4305 } 4306 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) { 4307 ExprResult Result = CheckPlaceholderExpr(LowerBound); 4308 if (Result.isInvalid()) 4309 return ExprError(); 4310 Result = DefaultLvalueConversion(Result.get()); 4311 if (Result.isInvalid()) 4312 return ExprError(); 4313 LowerBound = Result.get(); 4314 } 4315 if (Length && Length->getType()->isNonOverloadPlaceholderType()) { 4316 ExprResult Result = CheckPlaceholderExpr(Length); 4317 if (Result.isInvalid()) 4318 return ExprError(); 4319 Result = DefaultLvalueConversion(Result.get()); 4320 if (Result.isInvalid()) 4321 return ExprError(); 4322 Length = Result.get(); 4323 } 4324 4325 // Build an unanalyzed expression if either operand is type-dependent. 4326 if (Base->isTypeDependent() || 4327 (LowerBound && 4328 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) || 4329 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) { 4330 return new (Context) 4331 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy, 4332 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4333 } 4334 4335 // Perform default conversions. 4336 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base); 4337 QualType ResultTy; 4338 if (OriginalTy->isAnyPointerType()) { 4339 ResultTy = OriginalTy->getPointeeType(); 4340 } else if (OriginalTy->isArrayType()) { 4341 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType(); 4342 } else { 4343 return ExprError( 4344 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value) 4345 << Base->getSourceRange()); 4346 } 4347 // C99 6.5.2.1p1 4348 if (LowerBound) { 4349 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(), 4350 LowerBound); 4351 if (Res.isInvalid()) 4352 return ExprError(Diag(LowerBound->getExprLoc(), 4353 diag::err_omp_typecheck_section_not_integer) 4354 << 0 << LowerBound->getSourceRange()); 4355 LowerBound = Res.get(); 4356 4357 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4358 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4359 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char) 4360 << 0 << LowerBound->getSourceRange(); 4361 } 4362 if (Length) { 4363 auto Res = 4364 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length); 4365 if (Res.isInvalid()) 4366 return ExprError(Diag(Length->getExprLoc(), 4367 diag::err_omp_typecheck_section_not_integer) 4368 << 1 << Length->getSourceRange()); 4369 Length = Res.get(); 4370 4371 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4372 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4373 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char) 4374 << 1 << Length->getSourceRange(); 4375 } 4376 4377 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4378 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4379 // type. Note that functions are not objects, and that (in C99 parlance) 4380 // incomplete types are not object types. 4381 if (ResultTy->isFunctionType()) { 4382 Diag(Base->getExprLoc(), diag::err_omp_section_function_type) 4383 << ResultTy << Base->getSourceRange(); 4384 return ExprError(); 4385 } 4386 4387 if (RequireCompleteType(Base->getExprLoc(), ResultTy, 4388 diag::err_omp_section_incomplete_type, Base)) 4389 return ExprError(); 4390 4391 if (LowerBound && !OriginalTy->isAnyPointerType()) { 4392 Expr::EvalResult Result; 4393 if (LowerBound->EvaluateAsInt(Result, Context)) { 4394 // OpenMP 4.5, [2.4 Array Sections] 4395 // The array section must be a subset of the original array. 4396 llvm::APSInt LowerBoundValue = Result.Val.getInt(); 4397 if (LowerBoundValue.isNegative()) { 4398 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array) 4399 << LowerBound->getSourceRange(); 4400 return ExprError(); 4401 } 4402 } 4403 } 4404 4405 if (Length) { 4406 Expr::EvalResult Result; 4407 if (Length->EvaluateAsInt(Result, Context)) { 4408 // OpenMP 4.5, [2.4 Array Sections] 4409 // The length must evaluate to non-negative integers. 4410 llvm::APSInt LengthValue = Result.Val.getInt(); 4411 if (LengthValue.isNegative()) { 4412 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative) 4413 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true) 4414 << Length->getSourceRange(); 4415 return ExprError(); 4416 } 4417 } 4418 } else if (ColonLoc.isValid() && 4419 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() && 4420 !OriginalTy->isVariableArrayType()))) { 4421 // OpenMP 4.5, [2.4 Array Sections] 4422 // When the size of the array dimension is not known, the length must be 4423 // specified explicitly. 4424 Diag(ColonLoc, diag::err_omp_section_length_undefined) 4425 << (!OriginalTy.isNull() && OriginalTy->isArrayType()); 4426 return ExprError(); 4427 } 4428 4429 if (!Base->getType()->isSpecificPlaceholderType( 4430 BuiltinType::OMPArraySection)) { 4431 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base); 4432 if (Result.isInvalid()) 4433 return ExprError(); 4434 Base = Result.get(); 4435 } 4436 return new (Context) 4437 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy, 4438 VK_LValue, OK_Ordinary, ColonLoc, RBLoc); 4439 } 4440 4441 ExprResult 4442 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 4443 Expr *Idx, SourceLocation RLoc) { 4444 Expr *LHSExp = Base; 4445 Expr *RHSExp = Idx; 4446 4447 ExprValueKind VK = VK_LValue; 4448 ExprObjectKind OK = OK_Ordinary; 4449 4450 // Per C++ core issue 1213, the result is an xvalue if either operand is 4451 // a non-lvalue array, and an lvalue otherwise. 4452 if (getLangOpts().CPlusPlus11) { 4453 for (auto *Op : {LHSExp, RHSExp}) { 4454 Op = Op->IgnoreImplicit(); 4455 if (Op->getType()->isArrayType() && !Op->isLValue()) 4456 VK = VK_XValue; 4457 } 4458 } 4459 4460 // Perform default conversions. 4461 if (!LHSExp->getType()->getAs<VectorType>()) { 4462 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp); 4463 if (Result.isInvalid()) 4464 return ExprError(); 4465 LHSExp = Result.get(); 4466 } 4467 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp); 4468 if (Result.isInvalid()) 4469 return ExprError(); 4470 RHSExp = Result.get(); 4471 4472 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType(); 4473 4474 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent 4475 // to the expression *((e1)+(e2)). This means the array "Base" may actually be 4476 // in the subscript position. As a result, we need to derive the array base 4477 // and index from the expression types. 4478 Expr *BaseExpr, *IndexExpr; 4479 QualType ResultType; 4480 if (LHSTy->isDependentType() || RHSTy->isDependentType()) { 4481 BaseExpr = LHSExp; 4482 IndexExpr = RHSExp; 4483 ResultType = Context.DependentTy; 4484 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) { 4485 BaseExpr = LHSExp; 4486 IndexExpr = RHSExp; 4487 ResultType = PTy->getPointeeType(); 4488 } else if (const ObjCObjectPointerType *PTy = 4489 LHSTy->getAs<ObjCObjectPointerType>()) { 4490 BaseExpr = LHSExp; 4491 IndexExpr = RHSExp; 4492 4493 // Use custom logic if this should be the pseudo-object subscript 4494 // expression. 4495 if (!LangOpts.isSubscriptPointerArithmetic()) 4496 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr, 4497 nullptr); 4498 4499 ResultType = PTy->getPointeeType(); 4500 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) { 4501 // Handle the uncommon case of "123[Ptr]". 4502 BaseExpr = RHSExp; 4503 IndexExpr = LHSExp; 4504 ResultType = PTy->getPointeeType(); 4505 } else if (const ObjCObjectPointerType *PTy = 4506 RHSTy->getAs<ObjCObjectPointerType>()) { 4507 // Handle the uncommon case of "123[Ptr]". 4508 BaseExpr = RHSExp; 4509 IndexExpr = LHSExp; 4510 ResultType = PTy->getPointeeType(); 4511 if (!LangOpts.isSubscriptPointerArithmetic()) { 4512 Diag(LLoc, diag::err_subscript_nonfragile_interface) 4513 << ResultType << BaseExpr->getSourceRange(); 4514 return ExprError(); 4515 } 4516 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) { 4517 BaseExpr = LHSExp; // vectors: V[123] 4518 IndexExpr = RHSExp; 4519 // We apply C++ DR1213 to vector subscripting too. 4520 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) { 4521 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp); 4522 if (Materialized.isInvalid()) 4523 return ExprError(); 4524 LHSExp = Materialized.get(); 4525 } 4526 VK = LHSExp->getValueKind(); 4527 if (VK != VK_RValue) 4528 OK = OK_VectorComponent; 4529 4530 ResultType = VTy->getElementType(); 4531 QualType BaseType = BaseExpr->getType(); 4532 Qualifiers BaseQuals = BaseType.getQualifiers(); 4533 Qualifiers MemberQuals = ResultType.getQualifiers(); 4534 Qualifiers Combined = BaseQuals + MemberQuals; 4535 if (Combined != MemberQuals) 4536 ResultType = Context.getQualifiedType(ResultType, Combined); 4537 } else if (LHSTy->isArrayType()) { 4538 // If we see an array that wasn't promoted by 4539 // DefaultFunctionArrayLvalueConversion, it must be an array that 4540 // wasn't promoted because of the C90 rule that doesn't 4541 // allow promoting non-lvalue arrays. Warn, then 4542 // force the promotion here. 4543 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4544 << LHSExp->getSourceRange(); 4545 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy), 4546 CK_ArrayToPointerDecay).get(); 4547 LHSTy = LHSExp->getType(); 4548 4549 BaseExpr = LHSExp; 4550 IndexExpr = RHSExp; 4551 ResultType = LHSTy->getAs<PointerType>()->getPointeeType(); 4552 } else if (RHSTy->isArrayType()) { 4553 // Same as previous, except for 123[f().a] case 4554 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue) 4555 << RHSExp->getSourceRange(); 4556 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy), 4557 CK_ArrayToPointerDecay).get(); 4558 RHSTy = RHSExp->getType(); 4559 4560 BaseExpr = RHSExp; 4561 IndexExpr = LHSExp; 4562 ResultType = RHSTy->getAs<PointerType>()->getPointeeType(); 4563 } else { 4564 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value) 4565 << LHSExp->getSourceRange() << RHSExp->getSourceRange()); 4566 } 4567 // C99 6.5.2.1p1 4568 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent()) 4569 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer) 4570 << IndexExpr->getSourceRange()); 4571 4572 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) || 4573 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) 4574 && !IndexExpr->isTypeDependent()) 4575 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange(); 4576 4577 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly, 4578 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object 4579 // type. Note that Functions are not objects, and that (in C99 parlance) 4580 // incomplete types are not object types. 4581 if (ResultType->isFunctionType()) { 4582 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type) 4583 << ResultType << BaseExpr->getSourceRange(); 4584 return ExprError(); 4585 } 4586 4587 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) { 4588 // GNU extension: subscripting on pointer to void 4589 Diag(LLoc, diag::ext_gnu_subscript_void_type) 4590 << BaseExpr->getSourceRange(); 4591 4592 // C forbids expressions of unqualified void type from being l-values. 4593 // See IsCForbiddenLValueType. 4594 if (!ResultType.hasQualifiers()) VK = VK_RValue; 4595 } else if (!ResultType->isDependentType() && 4596 RequireCompleteType(LLoc, ResultType, 4597 diag::err_subscript_incomplete_type, BaseExpr)) 4598 return ExprError(); 4599 4600 assert(VK == VK_RValue || LangOpts.CPlusPlus || 4601 !ResultType.isCForbiddenLValueType()); 4602 4603 return new (Context) 4604 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc); 4605 } 4606 4607 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, 4608 ParmVarDecl *Param) { 4609 if (Param->hasUnparsedDefaultArg()) { 4610 Diag(CallLoc, 4611 diag::err_use_of_default_argument_to_function_declared_later) << 4612 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName(); 4613 Diag(UnparsedDefaultArgLocs[Param], 4614 diag::note_default_argument_declared_here); 4615 return true; 4616 } 4617 4618 if (Param->hasUninstantiatedDefaultArg()) { 4619 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4620 4621 EnterExpressionEvaluationContext EvalContext( 4622 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4623 4624 // Instantiate the expression. 4625 // 4626 // FIXME: Pass in a correct Pattern argument, otherwise 4627 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4628 // 4629 // template<typename T> 4630 // struct A { 4631 // static int FooImpl(); 4632 // 4633 // template<typename Tp> 4634 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4635 // // template argument list [[T], [Tp]], should be [[Tp]]. 4636 // friend A<Tp> Foo(int a); 4637 // }; 4638 // 4639 // template<typename T> 4640 // A<T> Foo(int a = A<T>::FooImpl()); 4641 MultiLevelTemplateArgumentList MutiLevelArgList 4642 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4643 4644 InstantiatingTemplate Inst(*this, CallLoc, Param, 4645 MutiLevelArgList.getInnermost()); 4646 if (Inst.isInvalid()) 4647 return true; 4648 if (Inst.isAlreadyInstantiating()) { 4649 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4650 Param->setInvalidDecl(); 4651 return true; 4652 } 4653 4654 ExprResult Result; 4655 { 4656 // C++ [dcl.fct.default]p5: 4657 // The names in the [default argument] expression are bound, and 4658 // the semantic constraints are checked, at the point where the 4659 // default argument expression appears. 4660 ContextRAII SavedContext(*this, FD); 4661 LocalInstantiationScope Local(*this); 4662 Result = SubstInitializer(UninstExpr, MutiLevelArgList, 4663 /*DirectInit*/false); 4664 } 4665 if (Result.isInvalid()) 4666 return true; 4667 4668 // Check the expression as an initializer for the parameter. 4669 InitializedEntity Entity 4670 = InitializedEntity::InitializeParameter(Context, Param); 4671 InitializationKind Kind = InitializationKind::CreateCopy( 4672 Param->getLocation(), 4673 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4674 Expr *ResultE = Result.getAs<Expr>(); 4675 4676 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4677 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4678 if (Result.isInvalid()) 4679 return true; 4680 4681 Result = ActOnFinishFullExpr(Result.getAs<Expr>(), 4682 Param->getOuterLocStart()); 4683 if (Result.isInvalid()) 4684 return true; 4685 4686 // Remember the instantiated default argument. 4687 Param->setDefaultArg(Result.getAs<Expr>()); 4688 if (ASTMutationListener *L = getASTMutationListener()) { 4689 L->DefaultArgumentInstantiated(Param); 4690 } 4691 } 4692 4693 // If the default argument expression is not set yet, we are building it now. 4694 if (!Param->hasInit()) { 4695 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4696 Param->setInvalidDecl(); 4697 return true; 4698 } 4699 4700 // If the default expression creates temporaries, we need to 4701 // push them to the current stack of expression temporaries so they'll 4702 // be properly destroyed. 4703 // FIXME: We should really be rebuilding the default argument with new 4704 // bound temporaries; see the comment in PR5810. 4705 // We don't need to do that with block decls, though, because 4706 // blocks in default argument expression can never capture anything. 4707 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) { 4708 // Set the "needs cleanups" bit regardless of whether there are 4709 // any explicit objects. 4710 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects()); 4711 4712 // Append all the objects to the cleanup list. Right now, this 4713 // should always be a no-op, because blocks in default argument 4714 // expressions should never be able to capture anything. 4715 assert(!Init->getNumObjects() && 4716 "default argument expression has capturing blocks?"); 4717 } 4718 4719 // We already type-checked the argument, so we know it works. 4720 // Just mark all of the declarations in this potentially-evaluated expression 4721 // as being "referenced". 4722 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(), 4723 /*SkipLocalVariables=*/true); 4724 return false; 4725 } 4726 4727 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc, 4728 FunctionDecl *FD, ParmVarDecl *Param) { 4729 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param)) 4730 return ExprError(); 4731 return CXXDefaultArgExpr::Create(Context, CallLoc, Param); 4732 } 4733 4734 Sema::VariadicCallType 4735 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, 4736 Expr *Fn) { 4737 if (Proto && Proto->isVariadic()) { 4738 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl)) 4739 return VariadicConstructor; 4740 else if (Fn && Fn->getType()->isBlockPointerType()) 4741 return VariadicBlock; 4742 else if (FDecl) { 4743 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 4744 if (Method->isInstance()) 4745 return VariadicMethod; 4746 } else if (Fn && Fn->getType() == Context.BoundMemberTy) 4747 return VariadicMethod; 4748 return VariadicFunction; 4749 } 4750 return VariadicDoesNotApply; 4751 } 4752 4753 namespace { 4754 class FunctionCallCCC : public FunctionCallFilterCCC { 4755 public: 4756 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName, 4757 unsigned NumArgs, MemberExpr *ME) 4758 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME), 4759 FunctionName(FuncName) {} 4760 4761 bool ValidateCandidate(const TypoCorrection &candidate) override { 4762 if (!candidate.getCorrectionSpecifier() || 4763 candidate.getCorrectionAsIdentifierInfo() != FunctionName) { 4764 return false; 4765 } 4766 4767 return FunctionCallFilterCCC::ValidateCandidate(candidate); 4768 } 4769 4770 private: 4771 const IdentifierInfo *const FunctionName; 4772 }; 4773 } 4774 4775 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, 4776 FunctionDecl *FDecl, 4777 ArrayRef<Expr *> Args) { 4778 MemberExpr *ME = dyn_cast<MemberExpr>(Fn); 4779 DeclarationName FuncName = FDecl->getDeclName(); 4780 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc(); 4781 4782 if (TypoCorrection Corrected = S.CorrectTypo( 4783 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName, 4784 S.getScopeForContext(S.CurContext), nullptr, 4785 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(), 4786 Args.size(), ME), 4787 Sema::CTK_ErrorRecovery)) { 4788 if (NamedDecl *ND = Corrected.getFoundDecl()) { 4789 if (Corrected.isOverloaded()) { 4790 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal); 4791 OverloadCandidateSet::iterator Best; 4792 for (NamedDecl *CD : Corrected) { 4793 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) 4794 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args, 4795 OCS); 4796 } 4797 switch (OCS.BestViableFunction(S, NameLoc, Best)) { 4798 case OR_Success: 4799 ND = Best->FoundDecl; 4800 Corrected.setCorrectionDecl(ND); 4801 break; 4802 default: 4803 break; 4804 } 4805 } 4806 ND = ND->getUnderlyingDecl(); 4807 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) 4808 return Corrected; 4809 } 4810 } 4811 return TypoCorrection(); 4812 } 4813 4814 /// ConvertArgumentsForCall - Converts the arguments specified in 4815 /// Args/NumArgs to the parameter types of the function FDecl with 4816 /// function prototype Proto. Call is the call expression itself, and 4817 /// Fn is the function expression. For a C++ member function, this 4818 /// routine does not attempt to convert the object argument. Returns 4819 /// true if the call is ill-formed. 4820 bool 4821 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 4822 FunctionDecl *FDecl, 4823 const FunctionProtoType *Proto, 4824 ArrayRef<Expr *> Args, 4825 SourceLocation RParenLoc, 4826 bool IsExecConfig) { 4827 // Bail out early if calling a builtin with custom typechecking. 4828 if (FDecl) 4829 if (unsigned ID = FDecl->getBuiltinID()) 4830 if (Context.BuiltinInfo.hasCustomTypechecking(ID)) 4831 return false; 4832 4833 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by 4834 // assignment, to the types of the corresponding parameter, ... 4835 unsigned NumParams = Proto->getNumParams(); 4836 bool Invalid = false; 4837 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams; 4838 unsigned FnKind = Fn->getType()->isBlockPointerType() 4839 ? 1 /* block */ 4840 : (IsExecConfig ? 3 /* kernel function (exec config) */ 4841 : 0 /* function */); 4842 4843 // If too few arguments are available (and we don't have default 4844 // arguments for the remaining parameters), don't make the call. 4845 if (Args.size() < NumParams) { 4846 if (Args.size() < MinArgs) { 4847 TypoCorrection TC; 4848 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4849 unsigned diag_id = 4850 MinArgs == NumParams && !Proto->isVariadic() 4851 ? diag::err_typecheck_call_too_few_args_suggest 4852 : diag::err_typecheck_call_too_few_args_at_least_suggest; 4853 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs 4854 << static_cast<unsigned>(Args.size()) 4855 << TC.getCorrectionRange()); 4856 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName()) 4857 Diag(RParenLoc, 4858 MinArgs == NumParams && !Proto->isVariadic() 4859 ? diag::err_typecheck_call_too_few_args_one 4860 : diag::err_typecheck_call_too_few_args_at_least_one) 4861 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange(); 4862 else 4863 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic() 4864 ? diag::err_typecheck_call_too_few_args 4865 : diag::err_typecheck_call_too_few_args_at_least) 4866 << FnKind << MinArgs << static_cast<unsigned>(Args.size()) 4867 << Fn->getSourceRange(); 4868 4869 // Emit the location of the prototype. 4870 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4871 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 4872 4873 return true; 4874 } 4875 // We reserve space for the default arguments when we create 4876 // the call expression, before calling ConvertArgumentsForCall. 4877 assert((Call->getNumArgs() == NumParams) && 4878 "We should have reserved space for the default arguments before!"); 4879 } 4880 4881 // If too many are passed and not variadic, error on the extras and drop 4882 // them. 4883 if (Args.size() > NumParams) { 4884 if (!Proto->isVariadic()) { 4885 TypoCorrection TC; 4886 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) { 4887 unsigned diag_id = 4888 MinArgs == NumParams && !Proto->isVariadic() 4889 ? diag::err_typecheck_call_too_many_args_suggest 4890 : diag::err_typecheck_call_too_many_args_at_most_suggest; 4891 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams 4892 << static_cast<unsigned>(Args.size()) 4893 << TC.getCorrectionRange()); 4894 } else if (NumParams == 1 && FDecl && 4895 FDecl->getParamDecl(0)->getDeclName()) 4896 Diag(Args[NumParams]->getBeginLoc(), 4897 MinArgs == NumParams 4898 ? diag::err_typecheck_call_too_many_args_one 4899 : diag::err_typecheck_call_too_many_args_at_most_one) 4900 << FnKind << FDecl->getParamDecl(0) 4901 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange() 4902 << SourceRange(Args[NumParams]->getBeginLoc(), 4903 Args.back()->getEndLoc()); 4904 else 4905 Diag(Args[NumParams]->getBeginLoc(), 4906 MinArgs == NumParams 4907 ? diag::err_typecheck_call_too_many_args 4908 : diag::err_typecheck_call_too_many_args_at_most) 4909 << FnKind << NumParams << static_cast<unsigned>(Args.size()) 4910 << Fn->getSourceRange() 4911 << SourceRange(Args[NumParams]->getBeginLoc(), 4912 Args.back()->getEndLoc()); 4913 4914 // Emit the location of the prototype. 4915 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig) 4916 Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl; 4917 4918 // This deletes the extra arguments. 4919 Call->shrinkNumArgs(NumParams); 4920 return true; 4921 } 4922 } 4923 SmallVector<Expr *, 8> AllArgs; 4924 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn); 4925 4926 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args, 4927 AllArgs, CallType); 4928 if (Invalid) 4929 return true; 4930 unsigned TotalNumArgs = AllArgs.size(); 4931 for (unsigned i = 0; i < TotalNumArgs; ++i) 4932 Call->setArg(i, AllArgs[i]); 4933 4934 return false; 4935 } 4936 4937 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, 4938 const FunctionProtoType *Proto, 4939 unsigned FirstParam, ArrayRef<Expr *> Args, 4940 SmallVectorImpl<Expr *> &AllArgs, 4941 VariadicCallType CallType, bool AllowExplicit, 4942 bool IsListInitialization) { 4943 unsigned NumParams = Proto->getNumParams(); 4944 bool Invalid = false; 4945 size_t ArgIx = 0; 4946 // Continue to check argument types (even if we have too few/many args). 4947 for (unsigned i = FirstParam; i < NumParams; i++) { 4948 QualType ProtoArgType = Proto->getParamType(i); 4949 4950 Expr *Arg; 4951 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr; 4952 if (ArgIx < Args.size()) { 4953 Arg = Args[ArgIx++]; 4954 4955 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType, 4956 diag::err_call_incomplete_argument, Arg)) 4957 return true; 4958 4959 // Strip the unbridged-cast placeholder expression off, if applicable. 4960 bool CFAudited = false; 4961 if (Arg->getType() == Context.ARCUnbridgedCastTy && 4962 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4963 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4964 Arg = stripARCUnbridgedCast(Arg); 4965 else if (getLangOpts().ObjCAutoRefCount && 4966 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() && 4967 (!Param || !Param->hasAttr<CFConsumedAttr>())) 4968 CFAudited = true; 4969 4970 if (Proto->getExtParameterInfo(i).isNoEscape()) 4971 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context))) 4972 BE->getBlockDecl()->setDoesNotEscape(); 4973 4974 InitializedEntity Entity = 4975 Param ? InitializedEntity::InitializeParameter(Context, Param, 4976 ProtoArgType) 4977 : InitializedEntity::InitializeParameter( 4978 Context, ProtoArgType, Proto->isParamConsumed(i)); 4979 4980 // Remember that parameter belongs to a CF audited API. 4981 if (CFAudited) 4982 Entity.setParameterCFAudited(); 4983 4984 ExprResult ArgE = PerformCopyInitialization( 4985 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit); 4986 if (ArgE.isInvalid()) 4987 return true; 4988 4989 Arg = ArgE.getAs<Expr>(); 4990 } else { 4991 assert(Param && "can't use default arguments without a known callee"); 4992 4993 ExprResult ArgExpr = 4994 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param); 4995 if (ArgExpr.isInvalid()) 4996 return true; 4997 4998 Arg = ArgExpr.getAs<Expr>(); 4999 } 5000 5001 // Check for array bounds violations for each argument to the call. This 5002 // check only triggers warnings when the argument isn't a more complex Expr 5003 // with its own checking, such as a BinaryOperator. 5004 CheckArrayAccess(Arg); 5005 5006 // Check for violations of C99 static array rules (C99 6.7.5.3p7). 5007 CheckStaticArrayArgument(CallLoc, Param, Arg); 5008 5009 AllArgs.push_back(Arg); 5010 } 5011 5012 // If this is a variadic call, handle args passed through "...". 5013 if (CallType != VariadicDoesNotApply) { 5014 // Assume that extern "C" functions with variadic arguments that 5015 // return __unknown_anytype aren't *really* variadic. 5016 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl && 5017 FDecl->isExternC()) { 5018 for (Expr *A : Args.slice(ArgIx)) { 5019 QualType paramType; // ignored 5020 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType); 5021 Invalid |= arg.isInvalid(); 5022 AllArgs.push_back(arg.get()); 5023 } 5024 5025 // Otherwise do argument promotion, (C99 6.5.2.2p7). 5026 } else { 5027 for (Expr *A : Args.slice(ArgIx)) { 5028 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl); 5029 Invalid |= Arg.isInvalid(); 5030 AllArgs.push_back(Arg.get()); 5031 } 5032 } 5033 5034 // Check for array bounds violations. 5035 for (Expr *A : Args.slice(ArgIx)) 5036 CheckArrayAccess(A); 5037 } 5038 return Invalid; 5039 } 5040 5041 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) { 5042 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc(); 5043 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>()) 5044 TL = DTL.getOriginalLoc(); 5045 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>()) 5046 S.Diag(PVD->getLocation(), diag::note_callee_static_array) 5047 << ATL.getLocalSourceRange(); 5048 } 5049 5050 /// CheckStaticArrayArgument - If the given argument corresponds to a static 5051 /// array parameter, check that it is non-null, and that if it is formed by 5052 /// array-to-pointer decay, the underlying array is sufficiently large. 5053 /// 5054 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the 5055 /// array type derivation, then for each call to the function, the value of the 5056 /// corresponding actual argument shall provide access to the first element of 5057 /// an array with at least as many elements as specified by the size expression. 5058 void 5059 Sema::CheckStaticArrayArgument(SourceLocation CallLoc, 5060 ParmVarDecl *Param, 5061 const Expr *ArgExpr) { 5062 // Static array parameters are not supported in C++. 5063 if (!Param || getLangOpts().CPlusPlus) 5064 return; 5065 5066 QualType OrigTy = Param->getOriginalType(); 5067 5068 const ArrayType *AT = Context.getAsArrayType(OrigTy); 5069 if (!AT || AT->getSizeModifier() != ArrayType::Static) 5070 return; 5071 5072 if (ArgExpr->isNullPointerConstant(Context, 5073 Expr::NPC_NeverValueDependent)) { 5074 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange(); 5075 DiagnoseCalleeStaticArrayParam(*this, Param); 5076 return; 5077 } 5078 5079 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT); 5080 if (!CAT) 5081 return; 5082 5083 const ConstantArrayType *ArgCAT = 5084 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType()); 5085 if (!ArgCAT) 5086 return; 5087 5088 if (ArgCAT->getSize().ult(CAT->getSize())) { 5089 Diag(CallLoc, diag::warn_static_array_too_small) 5090 << ArgExpr->getSourceRange() 5091 << (unsigned) ArgCAT->getSize().getZExtValue() 5092 << (unsigned) CAT->getSize().getZExtValue(); 5093 DiagnoseCalleeStaticArrayParam(*this, Param); 5094 } 5095 } 5096 5097 /// Given a function expression of unknown-any type, try to rebuild it 5098 /// to have a function type. 5099 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn); 5100 5101 /// Is the given type a placeholder that we need to lower out 5102 /// immediately during argument processing? 5103 static bool isPlaceholderToRemoveAsArg(QualType type) { 5104 // Placeholders are never sugared. 5105 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type); 5106 if (!placeholder) return false; 5107 5108 switch (placeholder->getKind()) { 5109 // Ignore all the non-placeholder types. 5110 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 5111 case BuiltinType::Id: 5112 #include "clang/Basic/OpenCLImageTypes.def" 5113 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 5114 case BuiltinType::Id: 5115 #include "clang/Basic/OpenCLExtensionTypes.def" 5116 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) 5117 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: 5118 #include "clang/AST/BuiltinTypes.def" 5119 return false; 5120 5121 // We cannot lower out overload sets; they might validly be resolved 5122 // by the call machinery. 5123 case BuiltinType::Overload: 5124 return false; 5125 5126 // Unbridged casts in ARC can be handled in some call positions and 5127 // should be left in place. 5128 case BuiltinType::ARCUnbridgedCast: 5129 return false; 5130 5131 // Pseudo-objects should be converted as soon as possible. 5132 case BuiltinType::PseudoObject: 5133 return true; 5134 5135 // The debugger mode could theoretically but currently does not try 5136 // to resolve unknown-typed arguments based on known parameter types. 5137 case BuiltinType::UnknownAny: 5138 return true; 5139 5140 // These are always invalid as call arguments and should be reported. 5141 case BuiltinType::BoundMember: 5142 case BuiltinType::BuiltinFn: 5143 case BuiltinType::OMPArraySection: 5144 return true; 5145 5146 } 5147 llvm_unreachable("bad builtin type kind"); 5148 } 5149 5150 /// Check an argument list for placeholders that we won't try to 5151 /// handle later. 5152 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) { 5153 // Apply this processing to all the arguments at once instead of 5154 // dying at the first failure. 5155 bool hasInvalid = false; 5156 for (size_t i = 0, e = args.size(); i != e; i++) { 5157 if (isPlaceholderToRemoveAsArg(args[i]->getType())) { 5158 ExprResult result = S.CheckPlaceholderExpr(args[i]); 5159 if (result.isInvalid()) hasInvalid = true; 5160 else args[i] = result.get(); 5161 } else if (hasInvalid) { 5162 (void)S.CorrectDelayedTyposInExpr(args[i]); 5163 } 5164 } 5165 return hasInvalid; 5166 } 5167 5168 /// If a builtin function has a pointer argument with no explicit address 5169 /// space, then it should be able to accept a pointer to any address 5170 /// space as input. In order to do this, we need to replace the 5171 /// standard builtin declaration with one that uses the same address space 5172 /// as the call. 5173 /// 5174 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e. 5175 /// it does not contain any pointer arguments without 5176 /// an address space qualifer. Otherwise the rewritten 5177 /// FunctionDecl is returned. 5178 /// TODO: Handle pointer return types. 5179 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, 5180 const FunctionDecl *FDecl, 5181 MultiExprArg ArgExprs) { 5182 5183 QualType DeclType = FDecl->getType(); 5184 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType); 5185 5186 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || 5187 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams()) 5188 return nullptr; 5189 5190 bool NeedsNewDecl = false; 5191 unsigned i = 0; 5192 SmallVector<QualType, 8> OverloadParams; 5193 5194 for (QualType ParamType : FT->param_types()) { 5195 5196 // Convert array arguments to pointer to simplify type lookup. 5197 ExprResult ArgRes = 5198 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]); 5199 if (ArgRes.isInvalid()) 5200 return nullptr; 5201 Expr *Arg = ArgRes.get(); 5202 QualType ArgType = Arg->getType(); 5203 if (!ParamType->isPointerType() || 5204 ParamType.getQualifiers().hasAddressSpace() || 5205 !ArgType->isPointerType() || 5206 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) { 5207 OverloadParams.push_back(ParamType); 5208 continue; 5209 } 5210 5211 QualType PointeeType = ParamType->getPointeeType(); 5212 if (PointeeType.getQualifiers().hasAddressSpace()) 5213 continue; 5214 5215 NeedsNewDecl = true; 5216 LangAS AS = ArgType->getPointeeType().getAddressSpace(); 5217 5218 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS); 5219 OverloadParams.push_back(Context.getPointerType(PointeeType)); 5220 } 5221 5222 if (!NeedsNewDecl) 5223 return nullptr; 5224 5225 FunctionProtoType::ExtProtoInfo EPI; 5226 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(), 5227 OverloadParams, EPI); 5228 DeclContext *Parent = Context.getTranslationUnitDecl(); 5229 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent, 5230 FDecl->getLocation(), 5231 FDecl->getLocation(), 5232 FDecl->getIdentifier(), 5233 OverloadTy, 5234 /*TInfo=*/nullptr, 5235 SC_Extern, false, 5236 /*hasPrototype=*/true); 5237 SmallVector<ParmVarDecl*, 16> Params; 5238 FT = cast<FunctionProtoType>(OverloadTy); 5239 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 5240 QualType ParamType = FT->getParamType(i); 5241 ParmVarDecl *Parm = 5242 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(), 5243 SourceLocation(), nullptr, ParamType, 5244 /*TInfo=*/nullptr, SC_None, nullptr); 5245 Parm->setScopeInfo(0, i); 5246 Params.push_back(Parm); 5247 } 5248 OverloadDecl->setParams(Params); 5249 return OverloadDecl; 5250 } 5251 5252 static void checkDirectCallValidity(Sema &S, const Expr *Fn, 5253 FunctionDecl *Callee, 5254 MultiExprArg ArgExprs) { 5255 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and 5256 // similar attributes) really don't like it when functions are called with an 5257 // invalid number of args. 5258 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(), 5259 /*PartialOverloading=*/false) && 5260 !Callee->isVariadic()) 5261 return; 5262 if (Callee->getMinRequiredArguments() > ArgExprs.size()) 5263 return; 5264 5265 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) { 5266 S.Diag(Fn->getBeginLoc(), 5267 isa<CXXMethodDecl>(Callee) 5268 ? diag::err_ovl_no_viable_member_function_in_call 5269 : diag::err_ovl_no_viable_function_in_call) 5270 << Callee << Callee->getSourceRange(); 5271 S.Diag(Callee->getLocation(), 5272 diag::note_ovl_candidate_disabled_by_function_cond_attr) 5273 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 5274 return; 5275 } 5276 } 5277 5278 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound( 5279 const UnresolvedMemberExpr *const UME, Sema &S) { 5280 5281 const auto GetFunctionLevelDCIfCXXClass = 5282 [](Sema &S) -> const CXXRecordDecl * { 5283 const DeclContext *const DC = S.getFunctionLevelDeclContext(); 5284 if (!DC || !DC->getParent()) 5285 return nullptr; 5286 5287 // If the call to some member function was made from within a member 5288 // function body 'M' return return 'M's parent. 5289 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 5290 return MD->getParent()->getCanonicalDecl(); 5291 // else the call was made from within a default member initializer of a 5292 // class, so return the class. 5293 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 5294 return RD->getCanonicalDecl(); 5295 return nullptr; 5296 }; 5297 // If our DeclContext is neither a member function nor a class (in the 5298 // case of a lambda in a default member initializer), we can't have an 5299 // enclosing 'this'. 5300 5301 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S); 5302 if (!CurParentClass) 5303 return false; 5304 5305 // The naming class for implicit member functions call is the class in which 5306 // name lookup starts. 5307 const CXXRecordDecl *const NamingClass = 5308 UME->getNamingClass()->getCanonicalDecl(); 5309 assert(NamingClass && "Must have naming class even for implicit access"); 5310 5311 // If the unresolved member functions were found in a 'naming class' that is 5312 // related (either the same or derived from) to the class that contains the 5313 // member function that itself contained the implicit member access. 5314 5315 return CurParentClass == NamingClass || 5316 CurParentClass->isDerivedFrom(NamingClass); 5317 } 5318 5319 static void 5320 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5321 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) { 5322 5323 if (!UME) 5324 return; 5325 5326 LambdaScopeInfo *const CurLSI = S.getCurLambda(); 5327 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't 5328 // already been captured, or if this is an implicit member function call (if 5329 // it isn't, an attempt to capture 'this' should already have been made). 5330 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None || 5331 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured()) 5332 return; 5333 5334 // Check if the naming class in which the unresolved members were found is 5335 // related (same as or is a base of) to the enclosing class. 5336 5337 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S)) 5338 return; 5339 5340 5341 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent(); 5342 // If the enclosing function is not dependent, then this lambda is 5343 // capture ready, so if we can capture this, do so. 5344 if (!EnclosingFunctionCtx->isDependentContext()) { 5345 // If the current lambda and all enclosing lambdas can capture 'this' - 5346 // then go ahead and capture 'this' (since our unresolved overload set 5347 // contains at least one non-static member function). 5348 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false)) 5349 S.CheckCXXThisCapture(CallLoc); 5350 } else if (S.CurContext->isDependentContext()) { 5351 // ... since this is an implicit member reference, that might potentially 5352 // involve a 'this' capture, mark 'this' for potential capture in 5353 // enclosing lambdas. 5354 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 5355 CurLSI->addPotentialThisCapture(CallLoc); 5356 } 5357 } 5358 5359 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 5360 /// This provides the location of the left/right parens and a list of comma 5361 /// locations. 5362 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc, 5363 MultiExprArg ArgExprs, SourceLocation RParenLoc, 5364 Expr *ExecConfig, bool IsExecConfig) { 5365 // Since this might be a postfix expression, get rid of ParenListExprs. 5366 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn); 5367 if (Result.isInvalid()) return ExprError(); 5368 Fn = Result.get(); 5369 5370 if (checkArgsForPlaceholders(*this, ArgExprs)) 5371 return ExprError(); 5372 5373 if (getLangOpts().CPlusPlus) { 5374 // If this is a pseudo-destructor expression, build the call immediately. 5375 if (isa<CXXPseudoDestructorExpr>(Fn)) { 5376 if (!ArgExprs.empty()) { 5377 // Pseudo-destructor calls should not have any arguments. 5378 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args) 5379 << FixItHint::CreateRemoval( 5380 SourceRange(ArgExprs.front()->getBeginLoc(), 5381 ArgExprs.back()->getEndLoc())); 5382 } 5383 5384 return new (Context) 5385 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc); 5386 } 5387 if (Fn->getType() == Context.PseudoObjectTy) { 5388 ExprResult result = CheckPlaceholderExpr(Fn); 5389 if (result.isInvalid()) return ExprError(); 5390 Fn = result.get(); 5391 } 5392 5393 // Determine whether this is a dependent call inside a C++ template, 5394 // in which case we won't do any semantic analysis now. 5395 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) { 5396 if (ExecConfig) { 5397 return new (Context) CUDAKernelCallExpr( 5398 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs, 5399 Context.DependentTy, VK_RValue, RParenLoc); 5400 } else { 5401 5402 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs( 5403 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()), 5404 Fn->getBeginLoc()); 5405 5406 return new (Context) CallExpr( 5407 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5408 } 5409 } 5410 5411 // Determine whether this is a call to an object (C++ [over.call.object]). 5412 if (Fn->getType()->isRecordType()) 5413 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs, 5414 RParenLoc); 5415 5416 if (Fn->getType() == Context.UnknownAnyTy) { 5417 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5418 if (result.isInvalid()) return ExprError(); 5419 Fn = result.get(); 5420 } 5421 5422 if (Fn->getType() == Context.BoundMemberTy) { 5423 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5424 RParenLoc); 5425 } 5426 } 5427 5428 // Check for overloaded calls. This can happen even in C due to extensions. 5429 if (Fn->getType() == Context.OverloadTy) { 5430 OverloadExpr::FindResult find = OverloadExpr::find(Fn); 5431 5432 // We aren't supposed to apply this logic if there's an '&' involved. 5433 if (!find.HasFormOfMemberPointer) { 5434 if (Expr::hasAnyTypeDependentArguments(ArgExprs)) 5435 return new (Context) CallExpr( 5436 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc); 5437 OverloadExpr *ovl = find.Expression; 5438 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl)) 5439 return BuildOverloadedCallExpr( 5440 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig, 5441 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand); 5442 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs, 5443 RParenLoc); 5444 } 5445 } 5446 5447 // If we're directly calling a function, get the appropriate declaration. 5448 if (Fn->getType() == Context.UnknownAnyTy) { 5449 ExprResult result = rebuildUnknownAnyFunction(*this, Fn); 5450 if (result.isInvalid()) return ExprError(); 5451 Fn = result.get(); 5452 } 5453 5454 Expr *NakedFn = Fn->IgnoreParens(); 5455 5456 bool CallingNDeclIndirectly = false; 5457 NamedDecl *NDecl = nullptr; 5458 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) { 5459 if (UnOp->getOpcode() == UO_AddrOf) { 5460 CallingNDeclIndirectly = true; 5461 NakedFn = UnOp->getSubExpr()->IgnoreParens(); 5462 } 5463 } 5464 5465 if (isa<DeclRefExpr>(NakedFn)) { 5466 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl(); 5467 5468 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl); 5469 if (FDecl && FDecl->getBuiltinID()) { 5470 // Rewrite the function decl for this builtin by replacing parameters 5471 // with no explicit address space with the address space of the arguments 5472 // in ArgExprs. 5473 if ((FDecl = 5474 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) { 5475 NDecl = FDecl; 5476 Fn = DeclRefExpr::Create( 5477 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false, 5478 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl); 5479 } 5480 } 5481 } else if (isa<MemberExpr>(NakedFn)) 5482 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl(); 5483 5484 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) { 5485 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable( 5486 FD, /*Complain=*/true, Fn->getBeginLoc())) 5487 return ExprError(); 5488 5489 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn)) 5490 return ExprError(); 5491 5492 checkDirectCallValidity(*this, Fn, FD, ArgExprs); 5493 } 5494 5495 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc, 5496 ExecConfig, IsExecConfig); 5497 } 5498 5499 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments. 5500 /// 5501 /// __builtin_astype( value, dst type ) 5502 /// 5503 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 5504 SourceLocation BuiltinLoc, 5505 SourceLocation RParenLoc) { 5506 ExprValueKind VK = VK_RValue; 5507 ExprObjectKind OK = OK_Ordinary; 5508 QualType DstTy = GetTypeFromParser(ParsedDestTy); 5509 QualType SrcTy = E->getType(); 5510 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy)) 5511 return ExprError(Diag(BuiltinLoc, 5512 diag::err_invalid_astype_of_different_size) 5513 << DstTy 5514 << SrcTy 5515 << E->getSourceRange()); 5516 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5517 } 5518 5519 /// ActOnConvertVectorExpr - create a new convert-vector expression from the 5520 /// provided arguments. 5521 /// 5522 /// __builtin_convertvector( value, dst type ) 5523 /// 5524 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, 5525 SourceLocation BuiltinLoc, 5526 SourceLocation RParenLoc) { 5527 TypeSourceInfo *TInfo; 5528 GetTypeFromParser(ParsedDestTy, &TInfo); 5529 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc); 5530 } 5531 5532 /// BuildResolvedCallExpr - Build a call to a resolved expression, 5533 /// i.e. an expression not of \p OverloadTy. The expression should 5534 /// unary-convert to an expression of function-pointer or 5535 /// block-pointer type. 5536 /// 5537 /// \param NDecl the declaration being called, if available 5538 ExprResult 5539 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 5540 SourceLocation LParenLoc, 5541 ArrayRef<Expr *> Args, 5542 SourceLocation RParenLoc, 5543 Expr *Config, bool IsExecConfig) { 5544 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl); 5545 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0); 5546 5547 // Functions with 'interrupt' attribute cannot be called directly. 5548 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) { 5549 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called); 5550 return ExprError(); 5551 } 5552 5553 // Interrupt handlers don't save off the VFP regs automatically on ARM, 5554 // so there's some risk when calling out to non-interrupt handler functions 5555 // that the callee might not preserve them. This is easy to diagnose here, 5556 // but can be very challenging to debug. 5557 if (auto *Caller = getCurFunctionDecl()) 5558 if (Caller->hasAttr<ARMInterruptAttr>()) { 5559 bool VFP = Context.getTargetInfo().hasFeature("vfp"); 5560 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) 5561 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention); 5562 } 5563 5564 // Promote the function operand. 5565 // We special-case function promotion here because we only allow promoting 5566 // builtin functions to function pointers in the callee of a call. 5567 ExprResult Result; 5568 QualType ResultTy; 5569 if (BuiltinID && 5570 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) { 5571 // Extract the return type from the (builtin) function pointer type. 5572 // FIXME Several builtins still have setType in 5573 // Sema::CheckBuiltinFunctionCall. One should review their definitions in 5574 // Builtins.def to ensure they are correct before removing setType calls. 5575 QualType FnPtrTy = Context.getPointerType(FDecl->getType()); 5576 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get(); 5577 ResultTy = FDecl->getCallResultType(); 5578 } else { 5579 Result = CallExprUnaryConversions(Fn); 5580 ResultTy = Context.BoolTy; 5581 } 5582 if (Result.isInvalid()) 5583 return ExprError(); 5584 Fn = Result.get(); 5585 5586 // Check for a valid function type, but only if it is not a builtin which 5587 // requires custom type checking. These will be handled by 5588 // CheckBuiltinFunctionCall below just after creation of the call expression. 5589 const FunctionType *FuncT = nullptr; 5590 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { 5591 retry: 5592 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) { 5593 // C99 6.5.2.2p1 - "The expression that denotes the called function shall 5594 // have type pointer to function". 5595 FuncT = PT->getPointeeType()->getAs<FunctionType>(); 5596 if (!FuncT) 5597 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5598 << Fn->getType() << Fn->getSourceRange()); 5599 } else if (const BlockPointerType *BPT = 5600 Fn->getType()->getAs<BlockPointerType>()) { 5601 FuncT = BPT->getPointeeType()->castAs<FunctionType>(); 5602 } else { 5603 // Handle calls to expressions of unknown-any type. 5604 if (Fn->getType() == Context.UnknownAnyTy) { 5605 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn); 5606 if (rewrite.isInvalid()) return ExprError(); 5607 Fn = rewrite.get(); 5608 goto retry; 5609 } 5610 5611 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function) 5612 << Fn->getType() << Fn->getSourceRange()); 5613 } 5614 } 5615 5616 // Get the number of parameters in the function prototype, if any. 5617 // We will allocate space for max(Args.size(), NumParams) arguments 5618 // in the call expression. 5619 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT); 5620 unsigned NumParams = Proto ? Proto->getNumParams() : 0; 5621 5622 CallExpr *TheCall; 5623 if (Config) 5624 TheCall = new (Context) 5625 CUDAKernelCallExpr(Context, Fn, cast<CallExpr>(Config), Args, ResultTy, 5626 VK_RValue, RParenLoc, NumParams); 5627 else 5628 TheCall = new (Context) 5629 CallExpr(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc, NumParams); 5630 5631 if (!getLangOpts().CPlusPlus) { 5632 // C cannot always handle TypoExpr nodes in builtin calls and direct 5633 // function calls as their argument checking don't necessarily handle 5634 // dependent types properly, so make sure any TypoExprs have been 5635 // dealt with. 5636 ExprResult Result = CorrectDelayedTyposInExpr(TheCall); 5637 if (!Result.isUsable()) return ExprError(); 5638 TheCall = dyn_cast<CallExpr>(Result.get()); 5639 if (!TheCall) return Result; 5640 // TheCall at this point has max(Args.size(), NumParams) arguments, 5641 // with extra arguments nulled. We don't want to introduce nulled 5642 // arguments in Args and so we only take the first Args.size() arguments. 5643 Args = llvm::makeArrayRef(TheCall->getArgs(), Args.size()); 5644 } 5645 5646 // Bail out early if calling a builtin with custom type checking. 5647 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) 5648 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5649 5650 if (getLangOpts().CUDA) { 5651 if (Config) { 5652 // CUDA: Kernel calls must be to global functions 5653 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>()) 5654 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function) 5655 << FDecl << Fn->getSourceRange()); 5656 5657 // CUDA: Kernel function must have 'void' return type 5658 if (!FuncT->getReturnType()->isVoidType()) 5659 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return) 5660 << Fn->getType() << Fn->getSourceRange()); 5661 } else { 5662 // CUDA: Calls to global functions must be configured 5663 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>()) 5664 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config) 5665 << FDecl << Fn->getSourceRange()); 5666 } 5667 } 5668 5669 // Check for a valid return type 5670 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall, 5671 FDecl)) 5672 return ExprError(); 5673 5674 // We know the result type of the call, set it. 5675 TheCall->setType(FuncT->getCallResultType(Context)); 5676 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType())); 5677 5678 if (Proto) { 5679 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc, 5680 IsExecConfig)) 5681 return ExprError(); 5682 } else { 5683 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"); 5684 5685 if (FDecl) { 5686 // Check if we have too few/too many template arguments, based 5687 // on our knowledge of the function definition. 5688 const FunctionDecl *Def = nullptr; 5689 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) { 5690 Proto = Def->getType()->getAs<FunctionProtoType>(); 5691 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size())) 5692 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments) 5693 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange(); 5694 } 5695 5696 // If the function we're calling isn't a function prototype, but we have 5697 // a function prototype from a prior declaratiom, use that prototype. 5698 if (!FDecl->hasPrototype()) 5699 Proto = FDecl->getType()->getAs<FunctionProtoType>(); 5700 } 5701 5702 // Promote the arguments (C99 6.5.2.2p6). 5703 for (unsigned i = 0, e = Args.size(); i != e; i++) { 5704 Expr *Arg = Args[i]; 5705 5706 if (Proto && i < Proto->getNumParams()) { 5707 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5708 Context, Proto->getParamType(i), Proto->isParamConsumed(i)); 5709 ExprResult ArgE = 5710 PerformCopyInitialization(Entity, SourceLocation(), Arg); 5711 if (ArgE.isInvalid()) 5712 return true; 5713 5714 Arg = ArgE.getAs<Expr>(); 5715 5716 } else { 5717 ExprResult ArgE = DefaultArgumentPromotion(Arg); 5718 5719 if (ArgE.isInvalid()) 5720 return true; 5721 5722 Arg = ArgE.getAs<Expr>(); 5723 } 5724 5725 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(), 5726 diag::err_call_incomplete_argument, Arg)) 5727 return ExprError(); 5728 5729 TheCall->setArg(i, Arg); 5730 } 5731 } 5732 5733 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl)) 5734 if (!Method->isStatic()) 5735 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object) 5736 << Fn->getSourceRange()); 5737 5738 // Check for sentinels 5739 if (NDecl) 5740 DiagnoseSentinelCalls(NDecl, LParenLoc, Args); 5741 5742 // Do special checking on direct calls to functions. 5743 if (FDecl) { 5744 if (CheckFunctionCall(FDecl, TheCall, Proto)) 5745 return ExprError(); 5746 5747 if (BuiltinID) 5748 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall); 5749 } else if (NDecl) { 5750 if (CheckPointerCall(NDecl, TheCall, Proto)) 5751 return ExprError(); 5752 } else { 5753 if (CheckOtherCall(TheCall, Proto)) 5754 return ExprError(); 5755 } 5756 5757 return MaybeBindToTemporary(TheCall); 5758 } 5759 5760 ExprResult 5761 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, 5762 SourceLocation RParenLoc, Expr *InitExpr) { 5763 assert(Ty && "ActOnCompoundLiteral(): missing type"); 5764 assert(InitExpr && "ActOnCompoundLiteral(): missing expression"); 5765 5766 TypeSourceInfo *TInfo; 5767 QualType literalType = GetTypeFromParser(Ty, &TInfo); 5768 if (!TInfo) 5769 TInfo = Context.getTrivialTypeSourceInfo(literalType); 5770 5771 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr); 5772 } 5773 5774 ExprResult 5775 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, 5776 SourceLocation RParenLoc, Expr *LiteralExpr) { 5777 QualType literalType = TInfo->getType(); 5778 5779 if (literalType->isArrayType()) { 5780 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType), 5781 diag::err_illegal_decl_array_incomplete_type, 5782 SourceRange(LParenLoc, 5783 LiteralExpr->getSourceRange().getEnd()))) 5784 return ExprError(); 5785 if (literalType->isVariableArrayType()) 5786 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init) 5787 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())); 5788 } else if (!literalType->isDependentType() && 5789 RequireCompleteType(LParenLoc, literalType, 5790 diag::err_typecheck_decl_incomplete_type, 5791 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()))) 5792 return ExprError(); 5793 5794 InitializedEntity Entity 5795 = InitializedEntity::InitializeCompoundLiteralInit(TInfo); 5796 InitializationKind Kind 5797 = InitializationKind::CreateCStyleCast(LParenLoc, 5798 SourceRange(LParenLoc, RParenLoc), 5799 /*InitList=*/true); 5800 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr); 5801 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr, 5802 &literalType); 5803 if (Result.isInvalid()) 5804 return ExprError(); 5805 LiteralExpr = Result.get(); 5806 5807 bool isFileScope = !CurContext->isFunctionOrMethod(); 5808 5809 // In C, compound literals are l-values for some reason. 5810 // For GCC compatibility, in C++, file-scope array compound literals with 5811 // constant initializers are also l-values, and compound literals are 5812 // otherwise prvalues. 5813 // 5814 // (GCC also treats C++ list-initialized file-scope array prvalues with 5815 // constant initializers as l-values, but that's non-conforming, so we don't 5816 // follow it there.) 5817 // 5818 // FIXME: It would be better to handle the lvalue cases as materializing and 5819 // lifetime-extending a temporary object, but our materialized temporaries 5820 // representation only supports lifetime extension from a variable, not "out 5821 // of thin air". 5822 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer 5823 // is bound to the result of applying array-to-pointer decay to the compound 5824 // literal. 5825 // FIXME: GCC supports compound literals of reference type, which should 5826 // obviously have a value kind derived from the kind of reference involved. 5827 ExprValueKind VK = 5828 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType())) 5829 ? VK_RValue 5830 : VK_LValue; 5831 5832 if (isFileScope) 5833 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr)) 5834 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) { 5835 Expr *Init = ILE->getInit(i); 5836 ILE->setInit(i, ConstantExpr::Create(Context, Init)); 5837 } 5838 5839 Expr *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, 5840 VK, LiteralExpr, isFileScope); 5841 if (isFileScope) { 5842 if (!LiteralExpr->isTypeDependent() && 5843 !LiteralExpr->isValueDependent() && 5844 !literalType->isDependentType()) // C99 6.5.2.5p3 5845 if (CheckForConstantInitializer(LiteralExpr, literalType)) 5846 return ExprError(); 5847 } else if (literalType.getAddressSpace() != LangAS::opencl_private && 5848 literalType.getAddressSpace() != LangAS::Default) { 5849 // Embedded-C extensions to C99 6.5.2.5: 5850 // "If the compound literal occurs inside the body of a function, the 5851 // type name shall not be qualified by an address-space qualifier." 5852 Diag(LParenLoc, diag::err_compound_literal_with_address_space) 5853 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()); 5854 return ExprError(); 5855 } 5856 5857 return MaybeBindToTemporary(E); 5858 } 5859 5860 ExprResult 5861 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, 5862 SourceLocation RBraceLoc) { 5863 // Immediately handle non-overload placeholders. Overloads can be 5864 // resolved contextually, but everything else here can't. 5865 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) { 5866 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) { 5867 ExprResult result = CheckPlaceholderExpr(InitArgList[I]); 5868 5869 // Ignore failures; dropping the entire initializer list because 5870 // of one failure would be terrible for indexing/etc. 5871 if (result.isInvalid()) continue; 5872 5873 InitArgList[I] = result.get(); 5874 } 5875 } 5876 5877 // Semantic analysis for initializers is done by ActOnDeclarator() and 5878 // CheckInitializer() - it requires knowledge of the object being initialized. 5879 5880 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList, 5881 RBraceLoc); 5882 E->setType(Context.VoidTy); // FIXME: just a place holder for now. 5883 return E; 5884 } 5885 5886 /// Do an explicit extend of the given block pointer if we're in ARC. 5887 void Sema::maybeExtendBlockObject(ExprResult &E) { 5888 assert(E.get()->getType()->isBlockPointerType()); 5889 assert(E.get()->isRValue()); 5890 5891 // Only do this in an r-value context. 5892 if (!getLangOpts().ObjCAutoRefCount) return; 5893 5894 E = ImplicitCastExpr::Create(Context, E.get()->getType(), 5895 CK_ARCExtendBlockObject, E.get(), 5896 /*base path*/ nullptr, VK_RValue); 5897 Cleanup.setExprNeedsCleanups(true); 5898 } 5899 5900 /// Prepare a conversion of the given expression to an ObjC object 5901 /// pointer type. 5902 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) { 5903 QualType type = E.get()->getType(); 5904 if (type->isObjCObjectPointerType()) { 5905 return CK_BitCast; 5906 } else if (type->isBlockPointerType()) { 5907 maybeExtendBlockObject(E); 5908 return CK_BlockPointerToObjCPointerCast; 5909 } else { 5910 assert(type->isPointerType()); 5911 return CK_CPointerToObjCPointerCast; 5912 } 5913 } 5914 5915 /// Prepares for a scalar cast, performing all the necessary stages 5916 /// except the final cast and returning the kind required. 5917 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) { 5918 // Both Src and Dest are scalar types, i.e. arithmetic or pointer. 5919 // Also, callers should have filtered out the invalid cases with 5920 // pointers. Everything else should be possible. 5921 5922 QualType SrcTy = Src.get()->getType(); 5923 if (Context.hasSameUnqualifiedType(SrcTy, DestTy)) 5924 return CK_NoOp; 5925 5926 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) { 5927 case Type::STK_MemberPointer: 5928 llvm_unreachable("member pointer type in C"); 5929 5930 case Type::STK_CPointer: 5931 case Type::STK_BlockPointer: 5932 case Type::STK_ObjCObjectPointer: 5933 switch (DestTy->getScalarTypeKind()) { 5934 case Type::STK_CPointer: { 5935 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace(); 5936 LangAS DestAS = DestTy->getPointeeType().getAddressSpace(); 5937 if (SrcAS != DestAS) 5938 return CK_AddressSpaceConversion; 5939 if (Context.hasCvrSimilarType(SrcTy, DestTy)) 5940 return CK_NoOp; 5941 return CK_BitCast; 5942 } 5943 case Type::STK_BlockPointer: 5944 return (SrcKind == Type::STK_BlockPointer 5945 ? CK_BitCast : CK_AnyPointerToBlockPointerCast); 5946 case Type::STK_ObjCObjectPointer: 5947 if (SrcKind == Type::STK_ObjCObjectPointer) 5948 return CK_BitCast; 5949 if (SrcKind == Type::STK_CPointer) 5950 return CK_CPointerToObjCPointerCast; 5951 maybeExtendBlockObject(Src); 5952 return CK_BlockPointerToObjCPointerCast; 5953 case Type::STK_Bool: 5954 return CK_PointerToBoolean; 5955 case Type::STK_Integral: 5956 return CK_PointerToIntegral; 5957 case Type::STK_Floating: 5958 case Type::STK_FloatingComplex: 5959 case Type::STK_IntegralComplex: 5960 case Type::STK_MemberPointer: 5961 case Type::STK_FixedPoint: 5962 llvm_unreachable("illegal cast from pointer"); 5963 } 5964 llvm_unreachable("Should have returned before this"); 5965 5966 case Type::STK_FixedPoint: 5967 switch (DestTy->getScalarTypeKind()) { 5968 case Type::STK_FixedPoint: 5969 return CK_FixedPointCast; 5970 case Type::STK_Bool: 5971 return CK_FixedPointToBoolean; 5972 case Type::STK_Integral: 5973 case Type::STK_Floating: 5974 case Type::STK_IntegralComplex: 5975 case Type::STK_FloatingComplex: 5976 Diag(Src.get()->getExprLoc(), 5977 diag::err_unimplemented_conversion_with_fixed_point_type) 5978 << DestTy; 5979 return CK_IntegralCast; 5980 case Type::STK_CPointer: 5981 case Type::STK_ObjCObjectPointer: 5982 case Type::STK_BlockPointer: 5983 case Type::STK_MemberPointer: 5984 llvm_unreachable("illegal cast to pointer type"); 5985 } 5986 llvm_unreachable("Should have returned before this"); 5987 5988 case Type::STK_Bool: // casting from bool is like casting from an integer 5989 case Type::STK_Integral: 5990 switch (DestTy->getScalarTypeKind()) { 5991 case Type::STK_CPointer: 5992 case Type::STK_ObjCObjectPointer: 5993 case Type::STK_BlockPointer: 5994 if (Src.get()->isNullPointerConstant(Context, 5995 Expr::NPC_ValueDependentIsNull)) 5996 return CK_NullToPointer; 5997 return CK_IntegralToPointer; 5998 case Type::STK_Bool: 5999 return CK_IntegralToBoolean; 6000 case Type::STK_Integral: 6001 return CK_IntegralCast; 6002 case Type::STK_Floating: 6003 return CK_IntegralToFloating; 6004 case Type::STK_IntegralComplex: 6005 Src = ImpCastExprToType(Src.get(), 6006 DestTy->castAs<ComplexType>()->getElementType(), 6007 CK_IntegralCast); 6008 return CK_IntegralRealToComplex; 6009 case Type::STK_FloatingComplex: 6010 Src = ImpCastExprToType(Src.get(), 6011 DestTy->castAs<ComplexType>()->getElementType(), 6012 CK_IntegralToFloating); 6013 return CK_FloatingRealToComplex; 6014 case Type::STK_MemberPointer: 6015 llvm_unreachable("member pointer type in C"); 6016 case Type::STK_FixedPoint: 6017 Diag(Src.get()->getExprLoc(), 6018 diag::err_unimplemented_conversion_with_fixed_point_type) 6019 << SrcTy; 6020 return CK_IntegralCast; 6021 } 6022 llvm_unreachable("Should have returned before this"); 6023 6024 case Type::STK_Floating: 6025 switch (DestTy->getScalarTypeKind()) { 6026 case Type::STK_Floating: 6027 return CK_FloatingCast; 6028 case Type::STK_Bool: 6029 return CK_FloatingToBoolean; 6030 case Type::STK_Integral: 6031 return CK_FloatingToIntegral; 6032 case Type::STK_FloatingComplex: 6033 Src = ImpCastExprToType(Src.get(), 6034 DestTy->castAs<ComplexType>()->getElementType(), 6035 CK_FloatingCast); 6036 return CK_FloatingRealToComplex; 6037 case Type::STK_IntegralComplex: 6038 Src = ImpCastExprToType(Src.get(), 6039 DestTy->castAs<ComplexType>()->getElementType(), 6040 CK_FloatingToIntegral); 6041 return CK_IntegralRealToComplex; 6042 case Type::STK_CPointer: 6043 case Type::STK_ObjCObjectPointer: 6044 case Type::STK_BlockPointer: 6045 llvm_unreachable("valid float->pointer cast?"); 6046 case Type::STK_MemberPointer: 6047 llvm_unreachable("member pointer type in C"); 6048 case Type::STK_FixedPoint: 6049 Diag(Src.get()->getExprLoc(), 6050 diag::err_unimplemented_conversion_with_fixed_point_type) 6051 << SrcTy; 6052 return CK_IntegralCast; 6053 } 6054 llvm_unreachable("Should have returned before this"); 6055 6056 case Type::STK_FloatingComplex: 6057 switch (DestTy->getScalarTypeKind()) { 6058 case Type::STK_FloatingComplex: 6059 return CK_FloatingComplexCast; 6060 case Type::STK_IntegralComplex: 6061 return CK_FloatingComplexToIntegralComplex; 6062 case Type::STK_Floating: { 6063 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6064 if (Context.hasSameType(ET, DestTy)) 6065 return CK_FloatingComplexToReal; 6066 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal); 6067 return CK_FloatingCast; 6068 } 6069 case Type::STK_Bool: 6070 return CK_FloatingComplexToBoolean; 6071 case Type::STK_Integral: 6072 Src = ImpCastExprToType(Src.get(), 6073 SrcTy->castAs<ComplexType>()->getElementType(), 6074 CK_FloatingComplexToReal); 6075 return CK_FloatingToIntegral; 6076 case Type::STK_CPointer: 6077 case Type::STK_ObjCObjectPointer: 6078 case Type::STK_BlockPointer: 6079 llvm_unreachable("valid complex float->pointer cast?"); 6080 case Type::STK_MemberPointer: 6081 llvm_unreachable("member pointer type in C"); 6082 case Type::STK_FixedPoint: 6083 Diag(Src.get()->getExprLoc(), 6084 diag::err_unimplemented_conversion_with_fixed_point_type) 6085 << SrcTy; 6086 return CK_IntegralCast; 6087 } 6088 llvm_unreachable("Should have returned before this"); 6089 6090 case Type::STK_IntegralComplex: 6091 switch (DestTy->getScalarTypeKind()) { 6092 case Type::STK_FloatingComplex: 6093 return CK_IntegralComplexToFloatingComplex; 6094 case Type::STK_IntegralComplex: 6095 return CK_IntegralComplexCast; 6096 case Type::STK_Integral: { 6097 QualType ET = SrcTy->castAs<ComplexType>()->getElementType(); 6098 if (Context.hasSameType(ET, DestTy)) 6099 return CK_IntegralComplexToReal; 6100 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal); 6101 return CK_IntegralCast; 6102 } 6103 case Type::STK_Bool: 6104 return CK_IntegralComplexToBoolean; 6105 case Type::STK_Floating: 6106 Src = ImpCastExprToType(Src.get(), 6107 SrcTy->castAs<ComplexType>()->getElementType(), 6108 CK_IntegralComplexToReal); 6109 return CK_IntegralToFloating; 6110 case Type::STK_CPointer: 6111 case Type::STK_ObjCObjectPointer: 6112 case Type::STK_BlockPointer: 6113 llvm_unreachable("valid complex int->pointer cast?"); 6114 case Type::STK_MemberPointer: 6115 llvm_unreachable("member pointer type in C"); 6116 case Type::STK_FixedPoint: 6117 Diag(Src.get()->getExprLoc(), 6118 diag::err_unimplemented_conversion_with_fixed_point_type) 6119 << SrcTy; 6120 return CK_IntegralCast; 6121 } 6122 llvm_unreachable("Should have returned before this"); 6123 } 6124 6125 llvm_unreachable("Unhandled scalar cast"); 6126 } 6127 6128 static bool breakDownVectorType(QualType type, uint64_t &len, 6129 QualType &eltType) { 6130 // Vectors are simple. 6131 if (const VectorType *vecType = type->getAs<VectorType>()) { 6132 len = vecType->getNumElements(); 6133 eltType = vecType->getElementType(); 6134 assert(eltType->isScalarType()); 6135 return true; 6136 } 6137 6138 // We allow lax conversion to and from non-vector types, but only if 6139 // they're real types (i.e. non-complex, non-pointer scalar types). 6140 if (!type->isRealType()) return false; 6141 6142 len = 1; 6143 eltType = type; 6144 return true; 6145 } 6146 6147 /// Are the two types lax-compatible vector types? That is, given 6148 /// that one of them is a vector, do they have equal storage sizes, 6149 /// where the storage size is the number of elements times the element 6150 /// size? 6151 /// 6152 /// This will also return false if either of the types is neither a 6153 /// vector nor a real type. 6154 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) { 6155 assert(destTy->isVectorType() || srcTy->isVectorType()); 6156 6157 // Disallow lax conversions between scalars and ExtVectors (these 6158 // conversions are allowed for other vector types because common headers 6159 // depend on them). Most scalar OP ExtVector cases are handled by the 6160 // splat path anyway, which does what we want (convert, not bitcast). 6161 // What this rules out for ExtVectors is crazy things like char4*float. 6162 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false; 6163 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false; 6164 6165 uint64_t srcLen, destLen; 6166 QualType srcEltTy, destEltTy; 6167 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false; 6168 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false; 6169 6170 // ASTContext::getTypeSize will return the size rounded up to a 6171 // power of 2, so instead of using that, we need to use the raw 6172 // element size multiplied by the element count. 6173 uint64_t srcEltSize = Context.getTypeSize(srcEltTy); 6174 uint64_t destEltSize = Context.getTypeSize(destEltTy); 6175 6176 return (srcLen * srcEltSize == destLen * destEltSize); 6177 } 6178 6179 /// Is this a legal conversion between two types, one of which is 6180 /// known to be a vector type? 6181 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) { 6182 assert(destTy->isVectorType() || srcTy->isVectorType()); 6183 6184 if (!Context.getLangOpts().LaxVectorConversions) 6185 return false; 6186 return areLaxCompatibleVectorTypes(srcTy, destTy); 6187 } 6188 6189 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6190 CastKind &Kind) { 6191 assert(VectorTy->isVectorType() && "Not a vector type!"); 6192 6193 if (Ty->isVectorType() || Ty->isIntegralType(Context)) { 6194 if (!areLaxCompatibleVectorTypes(Ty, VectorTy)) 6195 return Diag(R.getBegin(), 6196 Ty->isVectorType() ? 6197 diag::err_invalid_conversion_between_vectors : 6198 diag::err_invalid_conversion_between_vector_and_integer) 6199 << VectorTy << Ty << R; 6200 } else 6201 return Diag(R.getBegin(), 6202 diag::err_invalid_conversion_between_vector_and_scalar) 6203 << VectorTy << Ty << R; 6204 6205 Kind = CK_BitCast; 6206 return false; 6207 } 6208 6209 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) { 6210 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType(); 6211 6212 if (DestElemTy == SplattedExpr->getType()) 6213 return SplattedExpr; 6214 6215 assert(DestElemTy->isFloatingType() || 6216 DestElemTy->isIntegralOrEnumerationType()); 6217 6218 CastKind CK; 6219 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) { 6220 // OpenCL requires that we convert `true` boolean expressions to -1, but 6221 // only when splatting vectors. 6222 if (DestElemTy->isFloatingType()) { 6223 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast 6224 // in two steps: boolean to signed integral, then to floating. 6225 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy, 6226 CK_BooleanToSignedIntegral); 6227 SplattedExpr = CastExprRes.get(); 6228 CK = CK_IntegralToFloating; 6229 } else { 6230 CK = CK_BooleanToSignedIntegral; 6231 } 6232 } else { 6233 ExprResult CastExprRes = SplattedExpr; 6234 CK = PrepareScalarCast(CastExprRes, DestElemTy); 6235 if (CastExprRes.isInvalid()) 6236 return ExprError(); 6237 SplattedExpr = CastExprRes.get(); 6238 } 6239 return ImpCastExprToType(SplattedExpr, DestElemTy, CK); 6240 } 6241 6242 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, 6243 Expr *CastExpr, CastKind &Kind) { 6244 assert(DestTy->isExtVectorType() && "Not an extended vector type!"); 6245 6246 QualType SrcTy = CastExpr->getType(); 6247 6248 // If SrcTy is a VectorType, the total size must match to explicitly cast to 6249 // an ExtVectorType. 6250 // In OpenCL, casts between vectors of different types are not allowed. 6251 // (See OpenCL 6.2). 6252 if (SrcTy->isVectorType()) { 6253 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) || 6254 (getLangOpts().OpenCL && 6255 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) { 6256 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors) 6257 << DestTy << SrcTy << R; 6258 return ExprError(); 6259 } 6260 Kind = CK_BitCast; 6261 return CastExpr; 6262 } 6263 6264 // All non-pointer scalars can be cast to ExtVector type. The appropriate 6265 // conversion will take place first from scalar to elt type, and then 6266 // splat from elt type to vector. 6267 if (SrcTy->isPointerType()) 6268 return Diag(R.getBegin(), 6269 diag::err_invalid_conversion_between_vector_and_scalar) 6270 << DestTy << SrcTy << R; 6271 6272 Kind = CK_VectorSplat; 6273 return prepareVectorSplat(DestTy, CastExpr); 6274 } 6275 6276 ExprResult 6277 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 6278 Declarator &D, ParsedType &Ty, 6279 SourceLocation RParenLoc, Expr *CastExpr) { 6280 assert(!D.isInvalidType() && (CastExpr != nullptr) && 6281 "ActOnCastExpr(): missing type or expr"); 6282 6283 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType()); 6284 if (D.isInvalidType()) 6285 return ExprError(); 6286 6287 if (getLangOpts().CPlusPlus) { 6288 // Check that there are no default arguments (C++ only). 6289 CheckExtraCXXDefaultArguments(D); 6290 } else { 6291 // Make sure any TypoExprs have been dealt with. 6292 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr); 6293 if (!Res.isUsable()) 6294 return ExprError(); 6295 CastExpr = Res.get(); 6296 } 6297 6298 checkUnusedDeclAttributes(D); 6299 6300 QualType castType = castTInfo->getType(); 6301 Ty = CreateParsedType(castType, castTInfo); 6302 6303 bool isVectorLiteral = false; 6304 6305 // Check for an altivec or OpenCL literal, 6306 // i.e. all the elements are integer constants. 6307 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr); 6308 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr); 6309 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL) 6310 && castType->isVectorType() && (PE || PLE)) { 6311 if (PLE && PLE->getNumExprs() == 0) { 6312 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer); 6313 return ExprError(); 6314 } 6315 if (PE || PLE->getNumExprs() == 1) { 6316 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0)); 6317 if (!E->getType()->isVectorType()) 6318 isVectorLiteral = true; 6319 } 6320 else 6321 isVectorLiteral = true; 6322 } 6323 6324 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')' 6325 // then handle it as such. 6326 if (isVectorLiteral) 6327 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo); 6328 6329 // If the Expr being casted is a ParenListExpr, handle it specially. 6330 // This is not an AltiVec-style cast, so turn the ParenListExpr into a 6331 // sequence of BinOp comma operators. 6332 if (isa<ParenListExpr>(CastExpr)) { 6333 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr); 6334 if (Result.isInvalid()) return ExprError(); 6335 CastExpr = Result.get(); 6336 } 6337 6338 if (getLangOpts().CPlusPlus && !castType->isVoidType() && 6339 !getSourceManager().isInSystemMacro(LParenLoc)) 6340 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange(); 6341 6342 CheckTollFreeBridgeCast(castType, CastExpr); 6343 6344 CheckObjCBridgeRelatedCast(castType, CastExpr); 6345 6346 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr); 6347 6348 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr); 6349 } 6350 6351 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc, 6352 SourceLocation RParenLoc, Expr *E, 6353 TypeSourceInfo *TInfo) { 6354 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && 6355 "Expected paren or paren list expression"); 6356 6357 Expr **exprs; 6358 unsigned numExprs; 6359 Expr *subExpr; 6360 SourceLocation LiteralLParenLoc, LiteralRParenLoc; 6361 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) { 6362 LiteralLParenLoc = PE->getLParenLoc(); 6363 LiteralRParenLoc = PE->getRParenLoc(); 6364 exprs = PE->getExprs(); 6365 numExprs = PE->getNumExprs(); 6366 } else { // isa<ParenExpr> by assertion at function entrance 6367 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen(); 6368 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen(); 6369 subExpr = cast<ParenExpr>(E)->getSubExpr(); 6370 exprs = &subExpr; 6371 numExprs = 1; 6372 } 6373 6374 QualType Ty = TInfo->getType(); 6375 assert(Ty->isVectorType() && "Expected vector type"); 6376 6377 SmallVector<Expr *, 8> initExprs; 6378 const VectorType *VTy = Ty->getAs<VectorType>(); 6379 unsigned numElems = Ty->getAs<VectorType>()->getNumElements(); 6380 6381 // '(...)' form of vector initialization in AltiVec: the number of 6382 // initializers must be one or must match the size of the vector. 6383 // If a single value is specified in the initializer then it will be 6384 // replicated to all the components of the vector 6385 if (VTy->getVectorKind() == VectorType::AltiVecVector) { 6386 // The number of initializers must be one or must match the size of the 6387 // vector. If a single value is specified in the initializer then it will 6388 // be replicated to all the components of the vector 6389 if (numExprs == 1) { 6390 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6391 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6392 if (Literal.isInvalid()) 6393 return ExprError(); 6394 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6395 PrepareScalarCast(Literal, ElemTy)); 6396 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6397 } 6398 else if (numExprs < numElems) { 6399 Diag(E->getExprLoc(), 6400 diag::err_incorrect_number_of_vector_initializers); 6401 return ExprError(); 6402 } 6403 else 6404 initExprs.append(exprs, exprs + numExprs); 6405 } 6406 else { 6407 // For OpenCL, when the number of initializers is a single value, 6408 // it will be replicated to all components of the vector. 6409 if (getLangOpts().OpenCL && 6410 VTy->getVectorKind() == VectorType::GenericVector && 6411 numExprs == 1) { 6412 QualType ElemTy = Ty->getAs<VectorType>()->getElementType(); 6413 ExprResult Literal = DefaultLvalueConversion(exprs[0]); 6414 if (Literal.isInvalid()) 6415 return ExprError(); 6416 Literal = ImpCastExprToType(Literal.get(), ElemTy, 6417 PrepareScalarCast(Literal, ElemTy)); 6418 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get()); 6419 } 6420 6421 initExprs.append(exprs, exprs + numExprs); 6422 } 6423 // FIXME: This means that pretty-printing the final AST will produce curly 6424 // braces instead of the original commas. 6425 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc, 6426 initExprs, LiteralRParenLoc); 6427 initE->setType(Ty); 6428 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE); 6429 } 6430 6431 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn 6432 /// the ParenListExpr into a sequence of comma binary operators. 6433 ExprResult 6434 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) { 6435 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr); 6436 if (!E) 6437 return OrigExpr; 6438 6439 ExprResult Result(E->getExpr(0)); 6440 6441 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i) 6442 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(), 6443 E->getExpr(i)); 6444 6445 if (Result.isInvalid()) return ExprError(); 6446 6447 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get()); 6448 } 6449 6450 ExprResult Sema::ActOnParenListExpr(SourceLocation L, 6451 SourceLocation R, 6452 MultiExprArg Val) { 6453 return ParenListExpr::Create(Context, L, Val, R); 6454 } 6455 6456 /// Emit a specialized diagnostic when one expression is a null pointer 6457 /// constant and the other is not a pointer. Returns true if a diagnostic is 6458 /// emitted. 6459 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6460 SourceLocation QuestionLoc) { 6461 Expr *NullExpr = LHSExpr; 6462 Expr *NonPointerExpr = RHSExpr; 6463 Expr::NullPointerConstantKind NullKind = 6464 NullExpr->isNullPointerConstant(Context, 6465 Expr::NPC_ValueDependentIsNotNull); 6466 6467 if (NullKind == Expr::NPCK_NotNull) { 6468 NullExpr = RHSExpr; 6469 NonPointerExpr = LHSExpr; 6470 NullKind = 6471 NullExpr->isNullPointerConstant(Context, 6472 Expr::NPC_ValueDependentIsNotNull); 6473 } 6474 6475 if (NullKind == Expr::NPCK_NotNull) 6476 return false; 6477 6478 if (NullKind == Expr::NPCK_ZeroExpression) 6479 return false; 6480 6481 if (NullKind == Expr::NPCK_ZeroLiteral) { 6482 // In this case, check to make sure that we got here from a "NULL" 6483 // string in the source code. 6484 NullExpr = NullExpr->IgnoreParenImpCasts(); 6485 SourceLocation loc = NullExpr->getExprLoc(); 6486 if (!findMacroSpelling(loc, "NULL")) 6487 return false; 6488 } 6489 6490 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr); 6491 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null) 6492 << NonPointerExpr->getType() << DiagType 6493 << NonPointerExpr->getSourceRange(); 6494 return true; 6495 } 6496 6497 /// Return false if the condition expression is valid, true otherwise. 6498 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) { 6499 QualType CondTy = Cond->getType(); 6500 6501 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type. 6502 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) { 6503 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6504 << CondTy << Cond->getSourceRange(); 6505 return true; 6506 } 6507 6508 // C99 6.5.15p2 6509 if (CondTy->isScalarType()) return false; 6510 6511 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar) 6512 << CondTy << Cond->getSourceRange(); 6513 return true; 6514 } 6515 6516 /// Handle when one or both operands are void type. 6517 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS, 6518 ExprResult &RHS) { 6519 Expr *LHSExpr = LHS.get(); 6520 Expr *RHSExpr = RHS.get(); 6521 6522 if (!LHSExpr->getType()->isVoidType()) 6523 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6524 << RHSExpr->getSourceRange(); 6525 if (!RHSExpr->getType()->isVoidType()) 6526 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void) 6527 << LHSExpr->getSourceRange(); 6528 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid); 6529 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid); 6530 return S.Context.VoidTy; 6531 } 6532 6533 /// Return false if the NullExpr can be promoted to PointerTy, 6534 /// true otherwise. 6535 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, 6536 QualType PointerTy) { 6537 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) || 6538 !NullExpr.get()->isNullPointerConstant(S.Context, 6539 Expr::NPC_ValueDependentIsNull)) 6540 return true; 6541 6542 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer); 6543 return false; 6544 } 6545 6546 /// Checks compatibility between two pointers and return the resulting 6547 /// type. 6548 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, 6549 ExprResult &RHS, 6550 SourceLocation Loc) { 6551 QualType LHSTy = LHS.get()->getType(); 6552 QualType RHSTy = RHS.get()->getType(); 6553 6554 if (S.Context.hasSameType(LHSTy, RHSTy)) { 6555 // Two identical pointers types are always compatible. 6556 return LHSTy; 6557 } 6558 6559 QualType lhptee, rhptee; 6560 6561 // Get the pointee types. 6562 bool IsBlockPointer = false; 6563 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) { 6564 lhptee = LHSBTy->getPointeeType(); 6565 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType(); 6566 IsBlockPointer = true; 6567 } else { 6568 lhptee = LHSTy->castAs<PointerType>()->getPointeeType(); 6569 rhptee = RHSTy->castAs<PointerType>()->getPointeeType(); 6570 } 6571 6572 // C99 6.5.15p6: If both operands are pointers to compatible types or to 6573 // differently qualified versions of compatible types, the result type is 6574 // a pointer to an appropriately qualified version of the composite 6575 // type. 6576 6577 // Only CVR-qualifiers exist in the standard, and the differently-qualified 6578 // clause doesn't make sense for our extensions. E.g. address space 2 should 6579 // be incompatible with address space 3: they may live on different devices or 6580 // anything. 6581 Qualifiers lhQual = lhptee.getQualifiers(); 6582 Qualifiers rhQual = rhptee.getQualifiers(); 6583 6584 LangAS ResultAddrSpace = LangAS::Default; 6585 LangAS LAddrSpace = lhQual.getAddressSpace(); 6586 LangAS RAddrSpace = rhQual.getAddressSpace(); 6587 6588 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address 6589 // spaces is disallowed. 6590 if (lhQual.isAddressSpaceSupersetOf(rhQual)) 6591 ResultAddrSpace = LAddrSpace; 6592 else if (rhQual.isAddressSpaceSupersetOf(lhQual)) 6593 ResultAddrSpace = RAddrSpace; 6594 else { 6595 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 6596 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange() 6597 << RHS.get()->getSourceRange(); 6598 return QualType(); 6599 } 6600 6601 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers(); 6602 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast; 6603 lhQual.removeCVRQualifiers(); 6604 rhQual.removeCVRQualifiers(); 6605 6606 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers 6607 // (C99 6.7.3) for address spaces. We assume that the check should behave in 6608 // the same manner as it's defined for CVR qualifiers, so for OpenCL two 6609 // qual types are compatible iff 6610 // * corresponded types are compatible 6611 // * CVR qualifiers are equal 6612 // * address spaces are equal 6613 // Thus for conditional operator we merge CVR and address space unqualified 6614 // pointees and if there is a composite type we return a pointer to it with 6615 // merged qualifiers. 6616 LHSCastKind = 6617 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6618 RHSCastKind = 6619 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion; 6620 lhQual.removeAddressSpace(); 6621 rhQual.removeAddressSpace(); 6622 6623 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual); 6624 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual); 6625 6626 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee); 6627 6628 if (CompositeTy.isNull()) { 6629 // In this situation, we assume void* type. No especially good 6630 // reason, but this is what gcc does, and we do have to pick 6631 // to get a consistent AST. 6632 QualType incompatTy; 6633 incompatTy = S.Context.getPointerType( 6634 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace)); 6635 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind); 6636 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind); 6637 6638 // FIXME: For OpenCL the warning emission and cast to void* leaves a room 6639 // for casts between types with incompatible address space qualifiers. 6640 // For the following code the compiler produces casts between global and 6641 // local address spaces of the corresponded innermost pointees: 6642 // local int *global *a; 6643 // global int *global *b; 6644 // a = (0 ? a : b); // see C99 6.5.16.1.p1. 6645 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers) 6646 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6647 << RHS.get()->getSourceRange(); 6648 6649 return incompatTy; 6650 } 6651 6652 // The pointer types are compatible. 6653 // In case of OpenCL ResultTy should have the address space qualifier 6654 // which is a superset of address spaces of both the 2nd and the 3rd 6655 // operands of the conditional operator. 6656 QualType ResultTy = [&, ResultAddrSpace]() { 6657 if (S.getLangOpts().OpenCL) { 6658 Qualifiers CompositeQuals = CompositeTy.getQualifiers(); 6659 CompositeQuals.setAddressSpace(ResultAddrSpace); 6660 return S.Context 6661 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals) 6662 .withCVRQualifiers(MergedCVRQual); 6663 } 6664 return CompositeTy.withCVRQualifiers(MergedCVRQual); 6665 }(); 6666 if (IsBlockPointer) 6667 ResultTy = S.Context.getBlockPointerType(ResultTy); 6668 else 6669 ResultTy = S.Context.getPointerType(ResultTy); 6670 6671 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind); 6672 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind); 6673 return ResultTy; 6674 } 6675 6676 /// Return the resulting type when the operands are both block pointers. 6677 static QualType checkConditionalBlockPointerCompatibility(Sema &S, 6678 ExprResult &LHS, 6679 ExprResult &RHS, 6680 SourceLocation Loc) { 6681 QualType LHSTy = LHS.get()->getType(); 6682 QualType RHSTy = RHS.get()->getType(); 6683 6684 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) { 6685 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) { 6686 QualType destType = S.Context.getPointerType(S.Context.VoidTy); 6687 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6688 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6689 return destType; 6690 } 6691 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands) 6692 << LHSTy << RHSTy << LHS.get()->getSourceRange() 6693 << RHS.get()->getSourceRange(); 6694 return QualType(); 6695 } 6696 6697 // We have 2 block pointer types. 6698 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6699 } 6700 6701 /// Return the resulting type when the operands are both pointers. 6702 static QualType 6703 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, 6704 ExprResult &RHS, 6705 SourceLocation Loc) { 6706 // get the pointer types 6707 QualType LHSTy = LHS.get()->getType(); 6708 QualType RHSTy = RHS.get()->getType(); 6709 6710 // get the "pointed to" types 6711 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 6712 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 6713 6714 // ignore qualifiers on void (C99 6.5.15p3, clause 6) 6715 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) { 6716 // Figure out necessary qualifiers (C99 6.5.15p6) 6717 QualType destPointee 6718 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 6719 QualType destType = S.Context.getPointerType(destPointee); 6720 // Add qualifiers if necessary. 6721 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp); 6722 // Promote to void*. 6723 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast); 6724 return destType; 6725 } 6726 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) { 6727 QualType destPointee 6728 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 6729 QualType destType = S.Context.getPointerType(destPointee); 6730 // Add qualifiers if necessary. 6731 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp); 6732 // Promote to void*. 6733 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast); 6734 return destType; 6735 } 6736 6737 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc); 6738 } 6739 6740 /// Return false if the first expression is not an integer and the second 6741 /// expression is not a pointer, true otherwise. 6742 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, 6743 Expr* PointerExpr, SourceLocation Loc, 6744 bool IsIntFirstExpr) { 6745 if (!PointerExpr->getType()->isPointerType() || 6746 !Int.get()->getType()->isIntegerType()) 6747 return false; 6748 6749 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr; 6750 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get(); 6751 6752 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch) 6753 << Expr1->getType() << Expr2->getType() 6754 << Expr1->getSourceRange() << Expr2->getSourceRange(); 6755 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(), 6756 CK_IntegralToPointer); 6757 return true; 6758 } 6759 6760 /// Simple conversion between integer and floating point types. 6761 /// 6762 /// Used when handling the OpenCL conditional operator where the 6763 /// condition is a vector while the other operands are scalar. 6764 /// 6765 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar 6766 /// types are either integer or floating type. Between the two 6767 /// operands, the type with the higher rank is defined as the "result 6768 /// type". The other operand needs to be promoted to the same type. No 6769 /// other type promotion is allowed. We cannot use 6770 /// UsualArithmeticConversions() for this purpose, since it always 6771 /// promotes promotable types. 6772 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, 6773 ExprResult &RHS, 6774 SourceLocation QuestionLoc) { 6775 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get()); 6776 if (LHS.isInvalid()) 6777 return QualType(); 6778 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 6779 if (RHS.isInvalid()) 6780 return QualType(); 6781 6782 // For conversion purposes, we ignore any qualifiers. 6783 // For example, "const float" and "float" are equivalent. 6784 QualType LHSType = 6785 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType(); 6786 QualType RHSType = 6787 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType(); 6788 6789 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) { 6790 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6791 << LHSType << LHS.get()->getSourceRange(); 6792 return QualType(); 6793 } 6794 6795 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) { 6796 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float) 6797 << RHSType << RHS.get()->getSourceRange(); 6798 return QualType(); 6799 } 6800 6801 // If both types are identical, no conversion is needed. 6802 if (LHSType == RHSType) 6803 return LHSType; 6804 6805 // Now handle "real" floating types (i.e. float, double, long double). 6806 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) 6807 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType, 6808 /*IsCompAssign = */ false); 6809 6810 // Finally, we have two differing integer types. 6811 return handleIntegerConversion<doIntegralCast, doIntegralCast> 6812 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false); 6813 } 6814 6815 /// Convert scalar operands to a vector that matches the 6816 /// condition in length. 6817 /// 6818 /// Used when handling the OpenCL conditional operator where the 6819 /// condition is a vector while the other operands are scalar. 6820 /// 6821 /// We first compute the "result type" for the scalar operands 6822 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted 6823 /// into a vector of that type where the length matches the condition 6824 /// vector type. s6.11.6 requires that the element types of the result 6825 /// and the condition must have the same number of bits. 6826 static QualType 6827 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, 6828 QualType CondTy, SourceLocation QuestionLoc) { 6829 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc); 6830 if (ResTy.isNull()) return QualType(); 6831 6832 const VectorType *CV = CondTy->getAs<VectorType>(); 6833 assert(CV); 6834 6835 // Determine the vector result type 6836 unsigned NumElements = CV->getNumElements(); 6837 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements); 6838 6839 // Ensure that all types have the same number of bits 6840 if (S.Context.getTypeSize(CV->getElementType()) 6841 != S.Context.getTypeSize(ResTy)) { 6842 // Since VectorTy is created internally, it does not pretty print 6843 // with an OpenCL name. Instead, we just print a description. 6844 std::string EleTyName = ResTy.getUnqualifiedType().getAsString(); 6845 SmallString<64> Str; 6846 llvm::raw_svector_ostream OS(Str); 6847 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)"; 6848 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6849 << CondTy << OS.str(); 6850 return QualType(); 6851 } 6852 6853 // Convert operands to the vector result type 6854 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat); 6855 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat); 6856 6857 return VectorTy; 6858 } 6859 6860 /// Return false if this is a valid OpenCL condition vector 6861 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, 6862 SourceLocation QuestionLoc) { 6863 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of 6864 // integral type. 6865 const VectorType *CondTy = Cond->getType()->getAs<VectorType>(); 6866 assert(CondTy); 6867 QualType EleTy = CondTy->getElementType(); 6868 if (EleTy->isIntegerType()) return false; 6869 6870 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat) 6871 << Cond->getType() << Cond->getSourceRange(); 6872 return true; 6873 } 6874 6875 /// Return false if the vector condition type and the vector 6876 /// result type are compatible. 6877 /// 6878 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same 6879 /// number of elements, and their element types have the same number 6880 /// of bits. 6881 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, 6882 SourceLocation QuestionLoc) { 6883 const VectorType *CV = CondTy->getAs<VectorType>(); 6884 const VectorType *RV = VecResTy->getAs<VectorType>(); 6885 assert(CV && RV); 6886 6887 if (CV->getNumElements() != RV->getNumElements()) { 6888 S.Diag(QuestionLoc, diag::err_conditional_vector_size) 6889 << CondTy << VecResTy; 6890 return true; 6891 } 6892 6893 QualType CVE = CV->getElementType(); 6894 QualType RVE = RV->getElementType(); 6895 6896 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) { 6897 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size) 6898 << CondTy << VecResTy; 6899 return true; 6900 } 6901 6902 return false; 6903 } 6904 6905 /// Return the resulting type for the conditional operator in 6906 /// OpenCL (aka "ternary selection operator", OpenCL v1.1 6907 /// s6.3.i) when the condition is a vector type. 6908 static QualType 6909 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, 6910 ExprResult &LHS, ExprResult &RHS, 6911 SourceLocation QuestionLoc) { 6912 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get()); 6913 if (Cond.isInvalid()) 6914 return QualType(); 6915 QualType CondTy = Cond.get()->getType(); 6916 6917 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc)) 6918 return QualType(); 6919 6920 // If either operand is a vector then find the vector type of the 6921 // result as specified in OpenCL v1.1 s6.3.i. 6922 if (LHS.get()->getType()->isVectorType() || 6923 RHS.get()->getType()->isVectorType()) { 6924 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc, 6925 /*isCompAssign*/false, 6926 /*AllowBothBool*/true, 6927 /*AllowBoolConversions*/false); 6928 if (VecResTy.isNull()) return QualType(); 6929 // The result type must match the condition type as specified in 6930 // OpenCL v1.1 s6.11.6. 6931 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc)) 6932 return QualType(); 6933 return VecResTy; 6934 } 6935 6936 // Both operands are scalar. 6937 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc); 6938 } 6939 6940 /// Return true if the Expr is block type 6941 static bool checkBlockType(Sema &S, const Expr *E) { 6942 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 6943 QualType Ty = CE->getCallee()->getType(); 6944 if (Ty->isBlockPointerType()) { 6945 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block); 6946 return true; 6947 } 6948 } 6949 return false; 6950 } 6951 6952 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension. 6953 /// In that case, LHS = cond. 6954 /// C99 6.5.15 6955 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 6956 ExprResult &RHS, ExprValueKind &VK, 6957 ExprObjectKind &OK, 6958 SourceLocation QuestionLoc) { 6959 6960 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get()); 6961 if (!LHSResult.isUsable()) return QualType(); 6962 LHS = LHSResult; 6963 6964 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get()); 6965 if (!RHSResult.isUsable()) return QualType(); 6966 RHS = RHSResult; 6967 6968 // C++ is sufficiently different to merit its own checker. 6969 if (getLangOpts().CPlusPlus) 6970 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc); 6971 6972 VK = VK_RValue; 6973 OK = OK_Ordinary; 6974 6975 // The OpenCL operator with a vector condition is sufficiently 6976 // different to merit its own checker. 6977 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) 6978 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc); 6979 6980 // First, check the condition. 6981 Cond = UsualUnaryConversions(Cond.get()); 6982 if (Cond.isInvalid()) 6983 return QualType(); 6984 if (checkCondition(*this, Cond.get(), QuestionLoc)) 6985 return QualType(); 6986 6987 // Now check the two expressions. 6988 if (LHS.get()->getType()->isVectorType() || 6989 RHS.get()->getType()->isVectorType()) 6990 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 6991 /*AllowBothBool*/true, 6992 /*AllowBoolConversions*/false); 6993 6994 QualType ResTy = UsualArithmeticConversions(LHS, RHS); 6995 if (LHS.isInvalid() || RHS.isInvalid()) 6996 return QualType(); 6997 6998 QualType LHSTy = LHS.get()->getType(); 6999 QualType RHSTy = RHS.get()->getType(); 7000 7001 // Diagnose attempts to convert between __float128 and long double where 7002 // such conversions currently can't be handled. 7003 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) { 7004 Diag(QuestionLoc, 7005 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy 7006 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7007 return QualType(); 7008 } 7009 7010 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary 7011 // selection operator (?:). 7012 if (getLangOpts().OpenCL && 7013 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) { 7014 return QualType(); 7015 } 7016 7017 // If both operands have arithmetic type, do the usual arithmetic conversions 7018 // to find a common type: C99 6.5.15p3,5. 7019 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) { 7020 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 7021 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 7022 7023 return ResTy; 7024 } 7025 7026 // If both operands are the same structure or union type, the result is that 7027 // type. 7028 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3 7029 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>()) 7030 if (LHSRT->getDecl() == RHSRT->getDecl()) 7031 // "If both the operands have structure or union type, the result has 7032 // that type." This implies that CV qualifiers are dropped. 7033 return LHSTy.getUnqualifiedType(); 7034 // FIXME: Type of conditional expression must be complete in C mode. 7035 } 7036 7037 // C99 6.5.15p5: "If both operands have void type, the result has void type." 7038 // The following || allows only one side to be void (a GCC-ism). 7039 if (LHSTy->isVoidType() || RHSTy->isVoidType()) { 7040 return checkConditionalVoidType(*this, LHS, RHS); 7041 } 7042 7043 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has 7044 // the type of the other operand." 7045 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy; 7046 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy; 7047 7048 // All objective-c pointer type analysis is done here. 7049 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS, 7050 QuestionLoc); 7051 if (LHS.isInvalid() || RHS.isInvalid()) 7052 return QualType(); 7053 if (!compositeType.isNull()) 7054 return compositeType; 7055 7056 7057 // Handle block pointer types. 7058 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) 7059 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS, 7060 QuestionLoc); 7061 7062 // Check constraints for C object pointers types (C99 6.5.15p3,6). 7063 if (LHSTy->isPointerType() && RHSTy->isPointerType()) 7064 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS, 7065 QuestionLoc); 7066 7067 // GCC compatibility: soften pointer/integer mismatch. Note that 7068 // null pointers have been filtered out by this point. 7069 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc, 7070 /*isIntFirstExpr=*/true)) 7071 return RHSTy; 7072 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc, 7073 /*isIntFirstExpr=*/false)) 7074 return LHSTy; 7075 7076 // Emit a better diagnostic if one of the expressions is a null pointer 7077 // constant and the other is not a pointer type. In this case, the user most 7078 // likely forgot to take the address of the other expression. 7079 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 7080 return QualType(); 7081 7082 // Otherwise, the operands are not compatible. 7083 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 7084 << LHSTy << RHSTy << LHS.get()->getSourceRange() 7085 << RHS.get()->getSourceRange(); 7086 return QualType(); 7087 } 7088 7089 /// FindCompositeObjCPointerType - Helper method to find composite type of 7090 /// two objective-c pointer types of the two input expressions. 7091 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 7092 SourceLocation QuestionLoc) { 7093 QualType LHSTy = LHS.get()->getType(); 7094 QualType RHSTy = RHS.get()->getType(); 7095 7096 // Handle things like Class and struct objc_class*. Here we case the result 7097 // to the pseudo-builtin, because that will be implicitly cast back to the 7098 // redefinition type if an attempt is made to access its fields. 7099 if (LHSTy->isObjCClassType() && 7100 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) { 7101 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7102 return LHSTy; 7103 } 7104 if (RHSTy->isObjCClassType() && 7105 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) { 7106 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7107 return RHSTy; 7108 } 7109 // And the same for struct objc_object* / id 7110 if (LHSTy->isObjCIdType() && 7111 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) { 7112 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast); 7113 return LHSTy; 7114 } 7115 if (RHSTy->isObjCIdType() && 7116 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) { 7117 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast); 7118 return RHSTy; 7119 } 7120 // And the same for struct objc_selector* / SEL 7121 if (Context.isObjCSelType(LHSTy) && 7122 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) { 7123 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast); 7124 return LHSTy; 7125 } 7126 if (Context.isObjCSelType(RHSTy) && 7127 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) { 7128 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast); 7129 return RHSTy; 7130 } 7131 // Check constraints for Objective-C object pointers types. 7132 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) { 7133 7134 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) { 7135 // Two identical object pointer types are always compatible. 7136 return LHSTy; 7137 } 7138 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>(); 7139 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>(); 7140 QualType compositeType = LHSTy; 7141 7142 // If both operands are interfaces and either operand can be 7143 // assigned to the other, use that type as the composite 7144 // type. This allows 7145 // xxx ? (A*) a : (B*) b 7146 // where B is a subclass of A. 7147 // 7148 // Additionally, as for assignment, if either type is 'id' 7149 // allow silent coercion. Finally, if the types are 7150 // incompatible then make sure to use 'id' as the composite 7151 // type so the result is acceptable for sending messages to. 7152 7153 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'. 7154 // It could return the composite type. 7155 if (!(compositeType = 7156 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) { 7157 // Nothing more to do. 7158 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) { 7159 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy; 7160 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) { 7161 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy; 7162 } else if ((LHSTy->isObjCQualifiedIdType() || 7163 RHSTy->isObjCQualifiedIdType()) && 7164 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) { 7165 // Need to handle "id<xx>" explicitly. 7166 // GCC allows qualified id and any Objective-C type to devolve to 7167 // id. Currently localizing to here until clear this should be 7168 // part of ObjCQualifiedIdTypesAreCompatible. 7169 compositeType = Context.getObjCIdType(); 7170 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) { 7171 compositeType = Context.getObjCIdType(); 7172 } else { 7173 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands) 7174 << LHSTy << RHSTy 7175 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7176 QualType incompatTy = Context.getObjCIdType(); 7177 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast); 7178 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast); 7179 return incompatTy; 7180 } 7181 // The object pointer types are compatible. 7182 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast); 7183 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast); 7184 return compositeType; 7185 } 7186 // Check Objective-C object pointer types and 'void *' 7187 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) { 7188 if (getLangOpts().ObjCAutoRefCount) { 7189 // ARC forbids the implicit conversion of object pointers to 'void *', 7190 // so these types are not compatible. 7191 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7192 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7193 LHS = RHS = true; 7194 return QualType(); 7195 } 7196 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType(); 7197 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7198 QualType destPointee 7199 = Context.getQualifiedType(lhptee, rhptee.getQualifiers()); 7200 QualType destType = Context.getPointerType(destPointee); 7201 // Add qualifiers if necessary. 7202 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp); 7203 // Promote to void*. 7204 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast); 7205 return destType; 7206 } 7207 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) { 7208 if (getLangOpts().ObjCAutoRefCount) { 7209 // ARC forbids the implicit conversion of object pointers to 'void *', 7210 // so these types are not compatible. 7211 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy 7212 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 7213 LHS = RHS = true; 7214 return QualType(); 7215 } 7216 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType(); 7217 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType(); 7218 QualType destPointee 7219 = Context.getQualifiedType(rhptee, lhptee.getQualifiers()); 7220 QualType destType = Context.getPointerType(destPointee); 7221 // Add qualifiers if necessary. 7222 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp); 7223 // Promote to void*. 7224 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast); 7225 return destType; 7226 } 7227 return QualType(); 7228 } 7229 7230 /// SuggestParentheses - Emit a note with a fixit hint that wraps 7231 /// ParenRange in parentheses. 7232 static void SuggestParentheses(Sema &Self, SourceLocation Loc, 7233 const PartialDiagnostic &Note, 7234 SourceRange ParenRange) { 7235 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd()); 7236 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() && 7237 EndLoc.isValid()) { 7238 Self.Diag(Loc, Note) 7239 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") 7240 << FixItHint::CreateInsertion(EndLoc, ")"); 7241 } else { 7242 // We can't display the parentheses, so just show the bare note. 7243 Self.Diag(Loc, Note) << ParenRange; 7244 } 7245 } 7246 7247 static bool IsArithmeticOp(BinaryOperatorKind Opc) { 7248 return BinaryOperator::isAdditiveOp(Opc) || 7249 BinaryOperator::isMultiplicativeOp(Opc) || 7250 BinaryOperator::isShiftOp(Opc); 7251 } 7252 7253 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary 7254 /// expression, either using a built-in or overloaded operator, 7255 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side 7256 /// expression. 7257 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode, 7258 Expr **RHSExprs) { 7259 // Don't strip parenthesis: we should not warn if E is in parenthesis. 7260 E = E->IgnoreImpCasts(); 7261 E = E->IgnoreConversionOperator(); 7262 E = E->IgnoreImpCasts(); 7263 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) { 7264 E = MTE->GetTemporaryExpr(); 7265 E = E->IgnoreImpCasts(); 7266 } 7267 7268 // Built-in binary operator. 7269 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) { 7270 if (IsArithmeticOp(OP->getOpcode())) { 7271 *Opcode = OP->getOpcode(); 7272 *RHSExprs = OP->getRHS(); 7273 return true; 7274 } 7275 } 7276 7277 // Overloaded operator. 7278 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) { 7279 if (Call->getNumArgs() != 2) 7280 return false; 7281 7282 // Make sure this is really a binary operator that is safe to pass into 7283 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op. 7284 OverloadedOperatorKind OO = Call->getOperator(); 7285 if (OO < OO_Plus || OO > OO_Arrow || 7286 OO == OO_PlusPlus || OO == OO_MinusMinus) 7287 return false; 7288 7289 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO); 7290 if (IsArithmeticOp(OpKind)) { 7291 *Opcode = OpKind; 7292 *RHSExprs = Call->getArg(1); 7293 return true; 7294 } 7295 } 7296 7297 return false; 7298 } 7299 7300 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type 7301 /// or is a logical expression such as (x==y) which has int type, but is 7302 /// commonly interpreted as boolean. 7303 static bool ExprLooksBoolean(Expr *E) { 7304 E = E->IgnoreParenImpCasts(); 7305 7306 if (E->getType()->isBooleanType()) 7307 return true; 7308 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) 7309 return OP->isComparisonOp() || OP->isLogicalOp(); 7310 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E)) 7311 return OP->getOpcode() == UO_LNot; 7312 if (E->getType()->isPointerType()) 7313 return true; 7314 // FIXME: What about overloaded operator calls returning "unspecified boolean 7315 // type"s (commonly pointer-to-members)? 7316 7317 return false; 7318 } 7319 7320 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator 7321 /// and binary operator are mixed in a way that suggests the programmer assumed 7322 /// the conditional operator has higher precedence, for example: 7323 /// "int x = a + someBinaryCondition ? 1 : 2". 7324 static void DiagnoseConditionalPrecedence(Sema &Self, 7325 SourceLocation OpLoc, 7326 Expr *Condition, 7327 Expr *LHSExpr, 7328 Expr *RHSExpr) { 7329 BinaryOperatorKind CondOpcode; 7330 Expr *CondRHS; 7331 7332 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS)) 7333 return; 7334 if (!ExprLooksBoolean(CondRHS)) 7335 return; 7336 7337 // The condition is an arithmetic binary expression, with a right- 7338 // hand side that looks boolean, so warn. 7339 7340 Self.Diag(OpLoc, diag::warn_precedence_conditional) 7341 << Condition->getSourceRange() 7342 << BinaryOperator::getOpcodeStr(CondOpcode); 7343 7344 SuggestParentheses( 7345 Self, OpLoc, 7346 Self.PDiag(diag::note_precedence_silence) 7347 << BinaryOperator::getOpcodeStr(CondOpcode), 7348 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc())); 7349 7350 SuggestParentheses(Self, OpLoc, 7351 Self.PDiag(diag::note_precedence_conditional_first), 7352 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc())); 7353 } 7354 7355 /// Compute the nullability of a conditional expression. 7356 static QualType computeConditionalNullability(QualType ResTy, bool IsBin, 7357 QualType LHSTy, QualType RHSTy, 7358 ASTContext &Ctx) { 7359 if (!ResTy->isAnyPointerType()) 7360 return ResTy; 7361 7362 auto GetNullability = [&Ctx](QualType Ty) { 7363 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx); 7364 if (Kind) 7365 return *Kind; 7366 return NullabilityKind::Unspecified; 7367 }; 7368 7369 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy); 7370 NullabilityKind MergedKind; 7371 7372 // Compute nullability of a binary conditional expression. 7373 if (IsBin) { 7374 if (LHSKind == NullabilityKind::NonNull) 7375 MergedKind = NullabilityKind::NonNull; 7376 else 7377 MergedKind = RHSKind; 7378 // Compute nullability of a normal conditional expression. 7379 } else { 7380 if (LHSKind == NullabilityKind::Nullable || 7381 RHSKind == NullabilityKind::Nullable) 7382 MergedKind = NullabilityKind::Nullable; 7383 else if (LHSKind == NullabilityKind::NonNull) 7384 MergedKind = RHSKind; 7385 else if (RHSKind == NullabilityKind::NonNull) 7386 MergedKind = LHSKind; 7387 else 7388 MergedKind = NullabilityKind::Unspecified; 7389 } 7390 7391 // Return if ResTy already has the correct nullability. 7392 if (GetNullability(ResTy) == MergedKind) 7393 return ResTy; 7394 7395 // Strip all nullability from ResTy. 7396 while (ResTy->getNullability(Ctx)) 7397 ResTy = ResTy.getSingleStepDesugaredType(Ctx); 7398 7399 // Create a new AttributedType with the new nullability kind. 7400 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind); 7401 return Ctx.getAttributedType(NewAttr, ResTy, ResTy); 7402 } 7403 7404 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 7405 /// in the case of a the GNU conditional expr extension. 7406 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc, 7407 SourceLocation ColonLoc, 7408 Expr *CondExpr, Expr *LHSExpr, 7409 Expr *RHSExpr) { 7410 if (!getLangOpts().CPlusPlus) { 7411 // C cannot handle TypoExpr nodes in the condition because it 7412 // doesn't handle dependent types properly, so make sure any TypoExprs have 7413 // been dealt with before checking the operands. 7414 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr); 7415 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr); 7416 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr); 7417 7418 if (!CondResult.isUsable()) 7419 return ExprError(); 7420 7421 if (LHSExpr) { 7422 if (!LHSResult.isUsable()) 7423 return ExprError(); 7424 } 7425 7426 if (!RHSResult.isUsable()) 7427 return ExprError(); 7428 7429 CondExpr = CondResult.get(); 7430 LHSExpr = LHSResult.get(); 7431 RHSExpr = RHSResult.get(); 7432 } 7433 7434 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS 7435 // was the condition. 7436 OpaqueValueExpr *opaqueValue = nullptr; 7437 Expr *commonExpr = nullptr; 7438 if (!LHSExpr) { 7439 commonExpr = CondExpr; 7440 // Lower out placeholder types first. This is important so that we don't 7441 // try to capture a placeholder. This happens in few cases in C++; such 7442 // as Objective-C++'s dictionary subscripting syntax. 7443 if (commonExpr->hasPlaceholderType()) { 7444 ExprResult result = CheckPlaceholderExpr(commonExpr); 7445 if (!result.isUsable()) return ExprError(); 7446 commonExpr = result.get(); 7447 } 7448 // We usually want to apply unary conversions *before* saving, except 7449 // in the special case of a C++ l-value conditional. 7450 if (!(getLangOpts().CPlusPlus 7451 && !commonExpr->isTypeDependent() 7452 && commonExpr->getValueKind() == RHSExpr->getValueKind() 7453 && commonExpr->isGLValue() 7454 && commonExpr->isOrdinaryOrBitFieldObject() 7455 && RHSExpr->isOrdinaryOrBitFieldObject() 7456 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) { 7457 ExprResult commonRes = UsualUnaryConversions(commonExpr); 7458 if (commonRes.isInvalid()) 7459 return ExprError(); 7460 commonExpr = commonRes.get(); 7461 } 7462 7463 // If the common expression is a class or array prvalue, materialize it 7464 // so that we can safely refer to it multiple times. 7465 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() || 7466 commonExpr->getType()->isArrayType())) { 7467 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr); 7468 if (MatExpr.isInvalid()) 7469 return ExprError(); 7470 commonExpr = MatExpr.get(); 7471 } 7472 7473 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(), 7474 commonExpr->getType(), 7475 commonExpr->getValueKind(), 7476 commonExpr->getObjectKind(), 7477 commonExpr); 7478 LHSExpr = CondExpr = opaqueValue; 7479 } 7480 7481 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType(); 7482 ExprValueKind VK = VK_RValue; 7483 ExprObjectKind OK = OK_Ordinary; 7484 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr; 7485 QualType result = CheckConditionalOperands(Cond, LHS, RHS, 7486 VK, OK, QuestionLoc); 7487 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() || 7488 RHS.isInvalid()) 7489 return ExprError(); 7490 7491 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(), 7492 RHS.get()); 7493 7494 CheckBoolLikeConversion(Cond.get(), QuestionLoc); 7495 7496 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy, 7497 Context); 7498 7499 if (!commonExpr) 7500 return new (Context) 7501 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc, 7502 RHS.get(), result, VK, OK); 7503 7504 return new (Context) BinaryConditionalOperator( 7505 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc, 7506 ColonLoc, result, VK, OK); 7507 } 7508 7509 // checkPointerTypesForAssignment - This is a very tricky routine (despite 7510 // being closely modeled after the C99 spec:-). The odd characteristic of this 7511 // routine is it effectively iqnores the qualifiers on the top level pointee. 7512 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3]. 7513 // FIXME: add a couple examples in this comment. 7514 static Sema::AssignConvertType 7515 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) { 7516 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7517 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7518 7519 // get the "pointed to" type (ignoring qualifiers at the top level) 7520 const Type *lhptee, *rhptee; 7521 Qualifiers lhq, rhq; 7522 std::tie(lhptee, lhq) = 7523 cast<PointerType>(LHSType)->getPointeeType().split().asPair(); 7524 std::tie(rhptee, rhq) = 7525 cast<PointerType>(RHSType)->getPointeeType().split().asPair(); 7526 7527 Sema::AssignConvertType ConvTy = Sema::Compatible; 7528 7529 // C99 6.5.16.1p1: This following citation is common to constraints 7530 // 3 & 4 (below). ...and the type *pointed to* by the left has all the 7531 // qualifiers of the type *pointed to* by the right; 7532 7533 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay. 7534 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() && 7535 lhq.compatiblyIncludesObjCLifetime(rhq)) { 7536 // Ignore lifetime for further calculation. 7537 lhq.removeObjCLifetime(); 7538 rhq.removeObjCLifetime(); 7539 } 7540 7541 if (!lhq.compatiblyIncludes(rhq)) { 7542 // Treat address-space mismatches as fatal. TODO: address subspaces 7543 if (!lhq.isAddressSpaceSupersetOf(rhq)) 7544 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7545 7546 // It's okay to add or remove GC or lifetime qualifiers when converting to 7547 // and from void*. 7548 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime() 7549 .compatiblyIncludes( 7550 rhq.withoutObjCGCAttr().withoutObjCLifetime()) 7551 && (lhptee->isVoidType() || rhptee->isVoidType())) 7552 ; // keep old 7553 7554 // Treat lifetime mismatches as fatal. 7555 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) 7556 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers; 7557 7558 // For GCC/MS compatibility, other qualifier mismatches are treated 7559 // as still compatible in C. 7560 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7561 } 7562 7563 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or 7564 // incomplete type and the other is a pointer to a qualified or unqualified 7565 // version of void... 7566 if (lhptee->isVoidType()) { 7567 if (rhptee->isIncompleteOrObjectType()) 7568 return ConvTy; 7569 7570 // As an extension, we allow cast to/from void* to function pointer. 7571 assert(rhptee->isFunctionType()); 7572 return Sema::FunctionVoidPointer; 7573 } 7574 7575 if (rhptee->isVoidType()) { 7576 if (lhptee->isIncompleteOrObjectType()) 7577 return ConvTy; 7578 7579 // As an extension, we allow cast to/from void* to function pointer. 7580 assert(lhptee->isFunctionType()); 7581 return Sema::FunctionVoidPointer; 7582 } 7583 7584 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or 7585 // unqualified versions of compatible types, ... 7586 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0); 7587 if (!S.Context.typesAreCompatible(ltrans, rtrans)) { 7588 // Check if the pointee types are compatible ignoring the sign. 7589 // We explicitly check for char so that we catch "char" vs 7590 // "unsigned char" on systems where "char" is unsigned. 7591 if (lhptee->isCharType()) 7592 ltrans = S.Context.UnsignedCharTy; 7593 else if (lhptee->hasSignedIntegerRepresentation()) 7594 ltrans = S.Context.getCorrespondingUnsignedType(ltrans); 7595 7596 if (rhptee->isCharType()) 7597 rtrans = S.Context.UnsignedCharTy; 7598 else if (rhptee->hasSignedIntegerRepresentation()) 7599 rtrans = S.Context.getCorrespondingUnsignedType(rtrans); 7600 7601 if (ltrans == rtrans) { 7602 // Types are compatible ignoring the sign. Qualifier incompatibility 7603 // takes priority over sign incompatibility because the sign 7604 // warning can be disabled. 7605 if (ConvTy != Sema::Compatible) 7606 return ConvTy; 7607 7608 return Sema::IncompatiblePointerSign; 7609 } 7610 7611 // If we are a multi-level pointer, it's possible that our issue is simply 7612 // one of qualification - e.g. char ** -> const char ** is not allowed. If 7613 // the eventual target type is the same and the pointers have the same 7614 // level of indirection, this must be the issue. 7615 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) { 7616 do { 7617 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr(); 7618 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr(); 7619 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)); 7620 7621 if (lhptee == rhptee) 7622 return Sema::IncompatibleNestedPointerQualifiers; 7623 } 7624 7625 // General pointer incompatibility takes priority over qualifiers. 7626 return Sema::IncompatiblePointer; 7627 } 7628 if (!S.getLangOpts().CPlusPlus && 7629 S.IsFunctionConversion(ltrans, rtrans, ltrans)) 7630 return Sema::IncompatiblePointer; 7631 return ConvTy; 7632 } 7633 7634 /// checkBlockPointerTypesForAssignment - This routine determines whether two 7635 /// block pointer types are compatible or whether a block and normal pointer 7636 /// are compatible. It is more restrict than comparing two function pointer 7637 // types. 7638 static Sema::AssignConvertType 7639 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, 7640 QualType RHSType) { 7641 assert(LHSType.isCanonical() && "LHS not canonicalized!"); 7642 assert(RHSType.isCanonical() && "RHS not canonicalized!"); 7643 7644 QualType lhptee, rhptee; 7645 7646 // get the "pointed to" type (ignoring qualifiers at the top level) 7647 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType(); 7648 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType(); 7649 7650 // In C++, the types have to match exactly. 7651 if (S.getLangOpts().CPlusPlus) 7652 return Sema::IncompatibleBlockPointer; 7653 7654 Sema::AssignConvertType ConvTy = Sema::Compatible; 7655 7656 // For blocks we enforce that qualifiers are identical. 7657 Qualifiers LQuals = lhptee.getLocalQualifiers(); 7658 Qualifiers RQuals = rhptee.getLocalQualifiers(); 7659 if (S.getLangOpts().OpenCL) { 7660 LQuals.removeAddressSpace(); 7661 RQuals.removeAddressSpace(); 7662 } 7663 if (LQuals != RQuals) 7664 ConvTy = Sema::CompatiblePointerDiscardsQualifiers; 7665 7666 // FIXME: OpenCL doesn't define the exact compile time semantics for a block 7667 // assignment. 7668 // The current behavior is similar to C++ lambdas. A block might be 7669 // assigned to a variable iff its return type and parameters are compatible 7670 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of 7671 // an assignment. Presumably it should behave in way that a function pointer 7672 // assignment does in C, so for each parameter and return type: 7673 // * CVR and address space of LHS should be a superset of CVR and address 7674 // space of RHS. 7675 // * unqualified types should be compatible. 7676 if (S.getLangOpts().OpenCL) { 7677 if (!S.Context.typesAreBlockPointerCompatible( 7678 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals), 7679 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals))) 7680 return Sema::IncompatibleBlockPointer; 7681 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType)) 7682 return Sema::IncompatibleBlockPointer; 7683 7684 return ConvTy; 7685 } 7686 7687 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types 7688 /// for assignment compatibility. 7689 static Sema::AssignConvertType 7690 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, 7691 QualType RHSType) { 7692 assert(LHSType.isCanonical() && "LHS was not canonicalized!"); 7693 assert(RHSType.isCanonical() && "RHS was not canonicalized!"); 7694 7695 if (LHSType->isObjCBuiltinType()) { 7696 // Class is not compatible with ObjC object pointers. 7697 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() && 7698 !RHSType->isObjCQualifiedClassType()) 7699 return Sema::IncompatiblePointer; 7700 return Sema::Compatible; 7701 } 7702 if (RHSType->isObjCBuiltinType()) { 7703 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() && 7704 !LHSType->isObjCQualifiedClassType()) 7705 return Sema::IncompatiblePointer; 7706 return Sema::Compatible; 7707 } 7708 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7709 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType(); 7710 7711 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) && 7712 // make an exception for id<P> 7713 !LHSType->isObjCQualifiedIdType()) 7714 return Sema::CompatiblePointerDiscardsQualifiers; 7715 7716 if (S.Context.typesAreCompatible(LHSType, RHSType)) 7717 return Sema::Compatible; 7718 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType()) 7719 return Sema::IncompatibleObjCQualifiedId; 7720 return Sema::IncompatiblePointer; 7721 } 7722 7723 Sema::AssignConvertType 7724 Sema::CheckAssignmentConstraints(SourceLocation Loc, 7725 QualType LHSType, QualType RHSType) { 7726 // Fake up an opaque expression. We don't actually care about what 7727 // cast operations are required, so if CheckAssignmentConstraints 7728 // adds casts to this they'll be wasted, but fortunately that doesn't 7729 // usually happen on valid code. 7730 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue); 7731 ExprResult RHSPtr = &RHSExpr; 7732 CastKind K; 7733 7734 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false); 7735 } 7736 7737 /// This helper function returns true if QT is a vector type that has element 7738 /// type ElementType. 7739 static bool isVector(QualType QT, QualType ElementType) { 7740 if (const VectorType *VT = QT->getAs<VectorType>()) 7741 return VT->getElementType() == ElementType; 7742 return false; 7743 } 7744 7745 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently 7746 /// has code to accommodate several GCC extensions when type checking 7747 /// pointers. Here are some objectionable examples that GCC considers warnings: 7748 /// 7749 /// int a, *pint; 7750 /// short *pshort; 7751 /// struct foo *pfoo; 7752 /// 7753 /// pint = pshort; // warning: assignment from incompatible pointer type 7754 /// a = pint; // warning: assignment makes integer from pointer without a cast 7755 /// pint = a; // warning: assignment makes pointer from integer without a cast 7756 /// pint = pfoo; // warning: assignment from incompatible pointer type 7757 /// 7758 /// As a result, the code for dealing with pointers is more complex than the 7759 /// C99 spec dictates. 7760 /// 7761 /// Sets 'Kind' for any result kind except Incompatible. 7762 Sema::AssignConvertType 7763 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, 7764 CastKind &Kind, bool ConvertRHS) { 7765 QualType RHSType = RHS.get()->getType(); 7766 QualType OrigLHSType = LHSType; 7767 7768 // Get canonical types. We're not formatting these types, just comparing 7769 // them. 7770 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType(); 7771 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType(); 7772 7773 // Common case: no conversion required. 7774 if (LHSType == RHSType) { 7775 Kind = CK_NoOp; 7776 return Compatible; 7777 } 7778 7779 // If we have an atomic type, try a non-atomic assignment, then just add an 7780 // atomic qualification step. 7781 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) { 7782 Sema::AssignConvertType result = 7783 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind); 7784 if (result != Compatible) 7785 return result; 7786 if (Kind != CK_NoOp && ConvertRHS) 7787 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind); 7788 Kind = CK_NonAtomicToAtomic; 7789 return Compatible; 7790 } 7791 7792 // If the left-hand side is a reference type, then we are in a 7793 // (rare!) case where we've allowed the use of references in C, 7794 // e.g., as a parameter type in a built-in function. In this case, 7795 // just make sure that the type referenced is compatible with the 7796 // right-hand side type. The caller is responsible for adjusting 7797 // LHSType so that the resulting expression does not have reference 7798 // type. 7799 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) { 7800 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) { 7801 Kind = CK_LValueBitCast; 7802 return Compatible; 7803 } 7804 return Incompatible; 7805 } 7806 7807 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type 7808 // to the same ExtVector type. 7809 if (LHSType->isExtVectorType()) { 7810 if (RHSType->isExtVectorType()) 7811 return Incompatible; 7812 if (RHSType->isArithmeticType()) { 7813 // CK_VectorSplat does T -> vector T, so first cast to the element type. 7814 if (ConvertRHS) 7815 RHS = prepareVectorSplat(LHSType, RHS.get()); 7816 Kind = CK_VectorSplat; 7817 return Compatible; 7818 } 7819 } 7820 7821 // Conversions to or from vector type. 7822 if (LHSType->isVectorType() || RHSType->isVectorType()) { 7823 if (LHSType->isVectorType() && RHSType->isVectorType()) { 7824 // Allow assignments of an AltiVec vector type to an equivalent GCC 7825 // vector type and vice versa 7826 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) { 7827 Kind = CK_BitCast; 7828 return Compatible; 7829 } 7830 7831 // If we are allowing lax vector conversions, and LHS and RHS are both 7832 // vectors, the total size only needs to be the same. This is a bitcast; 7833 // no bits are changed but the result type is different. 7834 if (isLaxVectorConversion(RHSType, LHSType)) { 7835 Kind = CK_BitCast; 7836 return IncompatibleVectors; 7837 } 7838 } 7839 7840 // When the RHS comes from another lax conversion (e.g. binops between 7841 // scalars and vectors) the result is canonicalized as a vector. When the 7842 // LHS is also a vector, the lax is allowed by the condition above. Handle 7843 // the case where LHS is a scalar. 7844 if (LHSType->isScalarType()) { 7845 const VectorType *VecType = RHSType->getAs<VectorType>(); 7846 if (VecType && VecType->getNumElements() == 1 && 7847 isLaxVectorConversion(RHSType, LHSType)) { 7848 ExprResult *VecExpr = &RHS; 7849 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast); 7850 Kind = CK_BitCast; 7851 return Compatible; 7852 } 7853 } 7854 7855 return Incompatible; 7856 } 7857 7858 // Diagnose attempts to convert between __float128 and long double where 7859 // such conversions currently can't be handled. 7860 if (unsupportedTypeConversion(*this, LHSType, RHSType)) 7861 return Incompatible; 7862 7863 // Disallow assigning a _Complex to a real type in C++ mode since it simply 7864 // discards the imaginary part. 7865 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() && 7866 !LHSType->getAs<ComplexType>()) 7867 return Incompatible; 7868 7869 // Arithmetic conversions. 7870 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() && 7871 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) { 7872 if (ConvertRHS) 7873 Kind = PrepareScalarCast(RHS, LHSType); 7874 return Compatible; 7875 } 7876 7877 // Conversions to normal pointers. 7878 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) { 7879 // U* -> T* 7880 if (isa<PointerType>(RHSType)) { 7881 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7882 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace(); 7883 if (AddrSpaceL != AddrSpaceR) 7884 Kind = CK_AddressSpaceConversion; 7885 else if (Context.hasCvrSimilarType(RHSType, LHSType)) 7886 Kind = CK_NoOp; 7887 else 7888 Kind = CK_BitCast; 7889 return checkPointerTypesForAssignment(*this, LHSType, RHSType); 7890 } 7891 7892 // int -> T* 7893 if (RHSType->isIntegerType()) { 7894 Kind = CK_IntegralToPointer; // FIXME: null? 7895 return IntToPointer; 7896 } 7897 7898 // C pointers are not compatible with ObjC object pointers, 7899 // with two exceptions: 7900 if (isa<ObjCObjectPointerType>(RHSType)) { 7901 // - conversions to void* 7902 if (LHSPointer->getPointeeType()->isVoidType()) { 7903 Kind = CK_BitCast; 7904 return Compatible; 7905 } 7906 7907 // - conversions from 'Class' to the redefinition type 7908 if (RHSType->isObjCClassType() && 7909 Context.hasSameType(LHSType, 7910 Context.getObjCClassRedefinitionType())) { 7911 Kind = CK_BitCast; 7912 return Compatible; 7913 } 7914 7915 Kind = CK_BitCast; 7916 return IncompatiblePointer; 7917 } 7918 7919 // U^ -> void* 7920 if (RHSType->getAs<BlockPointerType>()) { 7921 if (LHSPointer->getPointeeType()->isVoidType()) { 7922 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace(); 7923 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7924 ->getPointeeType() 7925 .getAddressSpace(); 7926 Kind = 7927 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7928 return Compatible; 7929 } 7930 } 7931 7932 return Incompatible; 7933 } 7934 7935 // Conversions to block pointers. 7936 if (isa<BlockPointerType>(LHSType)) { 7937 // U^ -> T^ 7938 if (RHSType->isBlockPointerType()) { 7939 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>() 7940 ->getPointeeType() 7941 .getAddressSpace(); 7942 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>() 7943 ->getPointeeType() 7944 .getAddressSpace(); 7945 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 7946 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType); 7947 } 7948 7949 // int or null -> T^ 7950 if (RHSType->isIntegerType()) { 7951 Kind = CK_IntegralToPointer; // FIXME: null 7952 return IntToBlockPointer; 7953 } 7954 7955 // id -> T^ 7956 if (getLangOpts().ObjC && RHSType->isObjCIdType()) { 7957 Kind = CK_AnyPointerToBlockPointerCast; 7958 return Compatible; 7959 } 7960 7961 // void* -> T^ 7962 if (const PointerType *RHSPT = RHSType->getAs<PointerType>()) 7963 if (RHSPT->getPointeeType()->isVoidType()) { 7964 Kind = CK_AnyPointerToBlockPointerCast; 7965 return Compatible; 7966 } 7967 7968 return Incompatible; 7969 } 7970 7971 // Conversions to Objective-C pointers. 7972 if (isa<ObjCObjectPointerType>(LHSType)) { 7973 // A* -> B* 7974 if (RHSType->isObjCObjectPointerType()) { 7975 Kind = CK_BitCast; 7976 Sema::AssignConvertType result = 7977 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType); 7978 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 7979 result == Compatible && 7980 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType)) 7981 result = IncompatibleObjCWeakRef; 7982 return result; 7983 } 7984 7985 // int or null -> A* 7986 if (RHSType->isIntegerType()) { 7987 Kind = CK_IntegralToPointer; // FIXME: null 7988 return IntToPointer; 7989 } 7990 7991 // In general, C pointers are not compatible with ObjC object pointers, 7992 // with two exceptions: 7993 if (isa<PointerType>(RHSType)) { 7994 Kind = CK_CPointerToObjCPointerCast; 7995 7996 // - conversions from 'void*' 7997 if (RHSType->isVoidPointerType()) { 7998 return Compatible; 7999 } 8000 8001 // - conversions to 'Class' from its redefinition type 8002 if (LHSType->isObjCClassType() && 8003 Context.hasSameType(RHSType, 8004 Context.getObjCClassRedefinitionType())) { 8005 return Compatible; 8006 } 8007 8008 return IncompatiblePointer; 8009 } 8010 8011 // Only under strict condition T^ is compatible with an Objective-C pointer. 8012 if (RHSType->isBlockPointerType() && 8013 LHSType->isBlockCompatibleObjCPointerType(Context)) { 8014 if (ConvertRHS) 8015 maybeExtendBlockObject(RHS); 8016 Kind = CK_BlockPointerToObjCPointerCast; 8017 return Compatible; 8018 } 8019 8020 return Incompatible; 8021 } 8022 8023 // Conversions from pointers that are not covered by the above. 8024 if (isa<PointerType>(RHSType)) { 8025 // T* -> _Bool 8026 if (LHSType == Context.BoolTy) { 8027 Kind = CK_PointerToBoolean; 8028 return Compatible; 8029 } 8030 8031 // T* -> int 8032 if (LHSType->isIntegerType()) { 8033 Kind = CK_PointerToIntegral; 8034 return PointerToInt; 8035 } 8036 8037 return Incompatible; 8038 } 8039 8040 // Conversions from Objective-C pointers that are not covered by the above. 8041 if (isa<ObjCObjectPointerType>(RHSType)) { 8042 // T* -> _Bool 8043 if (LHSType == Context.BoolTy) { 8044 Kind = CK_PointerToBoolean; 8045 return Compatible; 8046 } 8047 8048 // T* -> int 8049 if (LHSType->isIntegerType()) { 8050 Kind = CK_PointerToIntegral; 8051 return PointerToInt; 8052 } 8053 8054 return Incompatible; 8055 } 8056 8057 // struct A -> struct B 8058 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) { 8059 if (Context.typesAreCompatible(LHSType, RHSType)) { 8060 Kind = CK_NoOp; 8061 return Compatible; 8062 } 8063 } 8064 8065 if (LHSType->isSamplerT() && RHSType->isIntegerType()) { 8066 Kind = CK_IntToOCLSampler; 8067 return Compatible; 8068 } 8069 8070 return Incompatible; 8071 } 8072 8073 /// Constructs a transparent union from an expression that is 8074 /// used to initialize the transparent union. 8075 static void ConstructTransparentUnion(Sema &S, ASTContext &C, 8076 ExprResult &EResult, QualType UnionType, 8077 FieldDecl *Field) { 8078 // Build an initializer list that designates the appropriate member 8079 // of the transparent union. 8080 Expr *E = EResult.get(); 8081 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(), 8082 E, SourceLocation()); 8083 Initializer->setType(UnionType); 8084 Initializer->setInitializedFieldInUnion(Field); 8085 8086 // Build a compound literal constructing a value of the transparent 8087 // union type from this initializer list. 8088 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType); 8089 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType, 8090 VK_RValue, Initializer, false); 8091 } 8092 8093 Sema::AssignConvertType 8094 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, 8095 ExprResult &RHS) { 8096 QualType RHSType = RHS.get()->getType(); 8097 8098 // If the ArgType is a Union type, we want to handle a potential 8099 // transparent_union GCC extension. 8100 const RecordType *UT = ArgType->getAsUnionType(); 8101 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 8102 return Incompatible; 8103 8104 // The field to initialize within the transparent union. 8105 RecordDecl *UD = UT->getDecl(); 8106 FieldDecl *InitField = nullptr; 8107 // It's compatible if the expression matches any of the fields. 8108 for (auto *it : UD->fields()) { 8109 if (it->getType()->isPointerType()) { 8110 // If the transparent union contains a pointer type, we allow: 8111 // 1) void pointer 8112 // 2) null pointer constant 8113 if (RHSType->isPointerType()) 8114 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) { 8115 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast); 8116 InitField = it; 8117 break; 8118 } 8119 8120 if (RHS.get()->isNullPointerConstant(Context, 8121 Expr::NPC_ValueDependentIsNull)) { 8122 RHS = ImpCastExprToType(RHS.get(), it->getType(), 8123 CK_NullToPointer); 8124 InitField = it; 8125 break; 8126 } 8127 } 8128 8129 CastKind Kind; 8130 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) 8131 == Compatible) { 8132 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind); 8133 InitField = it; 8134 break; 8135 } 8136 } 8137 8138 if (!InitField) 8139 return Incompatible; 8140 8141 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField); 8142 return Compatible; 8143 } 8144 8145 Sema::AssignConvertType 8146 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS, 8147 bool Diagnose, 8148 bool DiagnoseCFAudited, 8149 bool ConvertRHS) { 8150 // We need to be able to tell the caller whether we diagnosed a problem, if 8151 // they ask us to issue diagnostics. 8152 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"); 8153 8154 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly, 8155 // we can't avoid *all* modifications at the moment, so we need some somewhere 8156 // to put the updated value. 8157 ExprResult LocalRHS = CallerRHS; 8158 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS; 8159 8160 if (getLangOpts().CPlusPlus) { 8161 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) { 8162 // C++ 5.17p3: If the left operand is not of class type, the 8163 // expression is implicitly converted (C++ 4) to the 8164 // cv-unqualified type of the left operand. 8165 QualType RHSType = RHS.get()->getType(); 8166 if (Diagnose) { 8167 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8168 AA_Assigning); 8169 } else { 8170 ImplicitConversionSequence ICS = 8171 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8172 /*SuppressUserConversions=*/false, 8173 /*AllowExplicit=*/false, 8174 /*InOverloadResolution=*/false, 8175 /*CStyle=*/false, 8176 /*AllowObjCWritebackConversion=*/false); 8177 if (ICS.isFailure()) 8178 return Incompatible; 8179 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(), 8180 ICS, AA_Assigning); 8181 } 8182 if (RHS.isInvalid()) 8183 return Incompatible; 8184 Sema::AssignConvertType result = Compatible; 8185 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8186 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType)) 8187 result = IncompatibleObjCWeakRef; 8188 return result; 8189 } 8190 8191 // FIXME: Currently, we fall through and treat C++ classes like C 8192 // structures. 8193 // FIXME: We also fall through for atomics; not sure what should 8194 // happen there, though. 8195 } else if (RHS.get()->getType() == Context.OverloadTy) { 8196 // As a set of extensions to C, we support overloading on functions. These 8197 // functions need to be resolved here. 8198 DeclAccessPair DAP; 8199 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction( 8200 RHS.get(), LHSType, /*Complain=*/false, DAP)) 8201 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD); 8202 else 8203 return Incompatible; 8204 } 8205 8206 // C99 6.5.16.1p1: the left operand is a pointer and the right is 8207 // a null pointer constant. 8208 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() || 8209 LHSType->isBlockPointerType()) && 8210 RHS.get()->isNullPointerConstant(Context, 8211 Expr::NPC_ValueDependentIsNull)) { 8212 if (Diagnose || ConvertRHS) { 8213 CastKind Kind; 8214 CXXCastPath Path; 8215 CheckPointerConversion(RHS.get(), LHSType, Kind, Path, 8216 /*IgnoreBaseAccess=*/false, Diagnose); 8217 if (ConvertRHS) 8218 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path); 8219 } 8220 return Compatible; 8221 } 8222 8223 // OpenCL queue_t type assignment. 8224 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant( 8225 Context, Expr::NPC_ValueDependentIsNull)) { 8226 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 8227 return Compatible; 8228 } 8229 8230 // This check seems unnatural, however it is necessary to ensure the proper 8231 // conversion of functions/arrays. If the conversion were done for all 8232 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary 8233 // expressions that suppress this implicit conversion (&, sizeof). 8234 // 8235 // Suppress this for references: C++ 8.5.3p5. 8236 if (!LHSType->isReferenceType()) { 8237 // FIXME: We potentially allocate here even if ConvertRHS is false. 8238 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose); 8239 if (RHS.isInvalid()) 8240 return Incompatible; 8241 } 8242 CastKind Kind; 8243 Sema::AssignConvertType result = 8244 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS); 8245 8246 // C99 6.5.16.1p2: The value of the right operand is converted to the 8247 // type of the assignment expression. 8248 // CheckAssignmentConstraints allows the left-hand side to be a reference, 8249 // so that we can use references in built-in functions even in C. 8250 // The getNonReferenceType() call makes sure that the resulting expression 8251 // does not have reference type. 8252 if (result != Incompatible && RHS.get()->getType() != LHSType) { 8253 QualType Ty = LHSType.getNonLValueExprType(Context); 8254 Expr *E = RHS.get(); 8255 8256 // Check for various Objective-C errors. If we are not reporting 8257 // diagnostics and just checking for errors, e.g., during overload 8258 // resolution, return Incompatible to indicate the failure. 8259 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 8260 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion, 8261 Diagnose, DiagnoseCFAudited) != ACR_okay) { 8262 if (!Diagnose) 8263 return Incompatible; 8264 } 8265 if (getLangOpts().ObjC && 8266 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType, 8267 E->getType(), E, Diagnose) || 8268 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) { 8269 if (!Diagnose) 8270 return Incompatible; 8271 // Replace the expression with a corrected version and continue so we 8272 // can find further errors. 8273 RHS = E; 8274 return Compatible; 8275 } 8276 8277 if (ConvertRHS) 8278 RHS = ImpCastExprToType(E, Ty, Kind); 8279 } 8280 return result; 8281 } 8282 8283 namespace { 8284 /// The original operand to an operator, prior to the application of the usual 8285 /// arithmetic conversions and converting the arguments of a builtin operator 8286 /// candidate. 8287 struct OriginalOperand { 8288 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) { 8289 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op)) 8290 Op = MTE->GetTemporaryExpr(); 8291 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op)) 8292 Op = BTE->getSubExpr(); 8293 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) { 8294 Orig = ICE->getSubExprAsWritten(); 8295 Conversion = ICE->getConversionFunction(); 8296 } 8297 } 8298 8299 QualType getType() const { return Orig->getType(); } 8300 8301 Expr *Orig; 8302 NamedDecl *Conversion; 8303 }; 8304 } 8305 8306 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS, 8307 ExprResult &RHS) { 8308 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get()); 8309 8310 Diag(Loc, diag::err_typecheck_invalid_operands) 8311 << OrigLHS.getType() << OrigRHS.getType() 8312 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8313 8314 // If a user-defined conversion was applied to either of the operands prior 8315 // to applying the built-in operator rules, tell the user about it. 8316 if (OrigLHS.Conversion) { 8317 Diag(OrigLHS.Conversion->getLocation(), 8318 diag::note_typecheck_invalid_operands_converted) 8319 << 0 << LHS.get()->getType(); 8320 } 8321 if (OrigRHS.Conversion) { 8322 Diag(OrigRHS.Conversion->getLocation(), 8323 diag::note_typecheck_invalid_operands_converted) 8324 << 1 << RHS.get()->getType(); 8325 } 8326 8327 return QualType(); 8328 } 8329 8330 // Diagnose cases where a scalar was implicitly converted to a vector and 8331 // diagnose the underlying types. Otherwise, diagnose the error 8332 // as invalid vector logical operands for non-C++ cases. 8333 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, 8334 ExprResult &RHS) { 8335 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType(); 8336 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType(); 8337 8338 bool LHSNatVec = LHSType->isVectorType(); 8339 bool RHSNatVec = RHSType->isVectorType(); 8340 8341 if (!(LHSNatVec && RHSNatVec)) { 8342 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get(); 8343 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get(); 8344 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8345 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType() 8346 << Vector->getSourceRange(); 8347 return QualType(); 8348 } 8349 8350 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict) 8351 << 1 << LHSType << RHSType << LHS.get()->getSourceRange() 8352 << RHS.get()->getSourceRange(); 8353 8354 return QualType(); 8355 } 8356 8357 /// Try to convert a value of non-vector type to a vector type by converting 8358 /// the type to the element type of the vector and then performing a splat. 8359 /// If the language is OpenCL, we only use conversions that promote scalar 8360 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except 8361 /// for float->int. 8362 /// 8363 /// OpenCL V2.0 6.2.6.p2: 8364 /// An error shall occur if any scalar operand type has greater rank 8365 /// than the type of the vector element. 8366 /// 8367 /// \param scalar - if non-null, actually perform the conversions 8368 /// \return true if the operation fails (but without diagnosing the failure) 8369 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, 8370 QualType scalarTy, 8371 QualType vectorEltTy, 8372 QualType vectorTy, 8373 unsigned &DiagID) { 8374 // The conversion to apply to the scalar before splatting it, 8375 // if necessary. 8376 CastKind scalarCast = CK_NoOp; 8377 8378 if (vectorEltTy->isIntegralType(S.Context)) { 8379 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() || 8380 (scalarTy->isIntegerType() && 8381 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) { 8382 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8383 return true; 8384 } 8385 if (!scalarTy->isIntegralType(S.Context)) 8386 return true; 8387 scalarCast = CK_IntegralCast; 8388 } else if (vectorEltTy->isRealFloatingType()) { 8389 if (scalarTy->isRealFloatingType()) { 8390 if (S.getLangOpts().OpenCL && 8391 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) { 8392 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type; 8393 return true; 8394 } 8395 scalarCast = CK_FloatingCast; 8396 } 8397 else if (scalarTy->isIntegralType(S.Context)) 8398 scalarCast = CK_IntegralToFloating; 8399 else 8400 return true; 8401 } else { 8402 return true; 8403 } 8404 8405 // Adjust scalar if desired. 8406 if (scalar) { 8407 if (scalarCast != CK_NoOp) 8408 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast); 8409 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat); 8410 } 8411 return false; 8412 } 8413 8414 /// Convert vector E to a vector with the same number of elements but different 8415 /// element type. 8416 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) { 8417 const auto *VecTy = E->getType()->getAs<VectorType>(); 8418 assert(VecTy && "Expression E must be a vector"); 8419 QualType NewVecTy = S.Context.getVectorType(ElementType, 8420 VecTy->getNumElements(), 8421 VecTy->getVectorKind()); 8422 8423 // Look through the implicit cast. Return the subexpression if its type is 8424 // NewVecTy. 8425 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 8426 if (ICE->getSubExpr()->getType() == NewVecTy) 8427 return ICE->getSubExpr(); 8428 8429 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast; 8430 return S.ImpCastExprToType(E, NewVecTy, Cast); 8431 } 8432 8433 /// Test if a (constant) integer Int can be casted to another integer type 8434 /// IntTy without losing precision. 8435 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, 8436 QualType OtherIntTy) { 8437 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8438 8439 // Reject cases where the value of the Int is unknown as that would 8440 // possibly cause truncation, but accept cases where the scalar can be 8441 // demoted without loss of precision. 8442 Expr::EvalResult EVResult; 8443 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8444 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy); 8445 bool IntSigned = IntTy->hasSignedIntegerRepresentation(); 8446 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation(); 8447 8448 if (CstInt) { 8449 // If the scalar is constant and is of a higher order and has more active 8450 // bits that the vector element type, reject it. 8451 llvm::APSInt Result = EVResult.Val.getInt(); 8452 unsigned NumBits = IntSigned 8453 ? (Result.isNegative() ? Result.getMinSignedBits() 8454 : Result.getActiveBits()) 8455 : Result.getActiveBits(); 8456 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits) 8457 return true; 8458 8459 // If the signedness of the scalar type and the vector element type 8460 // differs and the number of bits is greater than that of the vector 8461 // element reject it. 8462 return (IntSigned != OtherIntSigned && 8463 NumBits > S.Context.getIntWidth(OtherIntTy)); 8464 } 8465 8466 // Reject cases where the value of the scalar is not constant and it's 8467 // order is greater than that of the vector element type. 8468 return (Order < 0); 8469 } 8470 8471 /// Test if a (constant) integer Int can be casted to floating point type 8472 /// FloatTy without losing precision. 8473 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, 8474 QualType FloatTy) { 8475 QualType IntTy = Int->get()->getType().getUnqualifiedType(); 8476 8477 // Determine if the integer constant can be expressed as a floating point 8478 // number of the appropriate type. 8479 Expr::EvalResult EVResult; 8480 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context); 8481 8482 uint64_t Bits = 0; 8483 if (CstInt) { 8484 // Reject constants that would be truncated if they were converted to 8485 // the floating point type. Test by simple to/from conversion. 8486 // FIXME: Ideally the conversion to an APFloat and from an APFloat 8487 // could be avoided if there was a convertFromAPInt method 8488 // which could signal back if implicit truncation occurred. 8489 llvm::APSInt Result = EVResult.Val.getInt(); 8490 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy)); 8491 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(), 8492 llvm::APFloat::rmTowardZero); 8493 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy), 8494 !IntTy->hasSignedIntegerRepresentation()); 8495 bool Ignored = false; 8496 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven, 8497 &Ignored); 8498 if (Result != ConvertBack) 8499 return true; 8500 } else { 8501 // Reject types that cannot be fully encoded into the mantissa of 8502 // the float. 8503 Bits = S.Context.getTypeSize(IntTy); 8504 unsigned FloatPrec = llvm::APFloat::semanticsPrecision( 8505 S.Context.getFloatTypeSemantics(FloatTy)); 8506 if (Bits > FloatPrec) 8507 return true; 8508 } 8509 8510 return false; 8511 } 8512 8513 /// Attempt to convert and splat Scalar into a vector whose types matches 8514 /// Vector following GCC conversion rules. The rule is that implicit 8515 /// conversion can occur when Scalar can be casted to match Vector's element 8516 /// type without causing truncation of Scalar. 8517 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, 8518 ExprResult *Vector) { 8519 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType(); 8520 QualType VectorTy = Vector->get()->getType().getUnqualifiedType(); 8521 const VectorType *VT = VectorTy->getAs<VectorType>(); 8522 8523 assert(!isa<ExtVectorType>(VT) && 8524 "ExtVectorTypes should not be handled here!"); 8525 8526 QualType VectorEltTy = VT->getElementType(); 8527 8528 // Reject cases where the vector element type or the scalar element type are 8529 // not integral or floating point types. 8530 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType()) 8531 return true; 8532 8533 // The conversion to apply to the scalar before splatting it, 8534 // if necessary. 8535 CastKind ScalarCast = CK_NoOp; 8536 8537 // Accept cases where the vector elements are integers and the scalar is 8538 // an integer. 8539 // FIXME: Notionally if the scalar was a floating point value with a precise 8540 // integral representation, we could cast it to an appropriate integer 8541 // type and then perform the rest of the checks here. GCC will perform 8542 // this conversion in some cases as determined by the input language. 8543 // We should accept it on a language independent basis. 8544 if (VectorEltTy->isIntegralType(S.Context) && 8545 ScalarTy->isIntegralType(S.Context) && 8546 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) { 8547 8548 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy)) 8549 return true; 8550 8551 ScalarCast = CK_IntegralCast; 8552 } else if (VectorEltTy->isRealFloatingType()) { 8553 if (ScalarTy->isRealFloatingType()) { 8554 8555 // Reject cases where the scalar type is not a constant and has a higher 8556 // Order than the vector element type. 8557 llvm::APFloat Result(0.0); 8558 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context); 8559 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy); 8560 if (!CstScalar && Order < 0) 8561 return true; 8562 8563 // If the scalar cannot be safely casted to the vector element type, 8564 // reject it. 8565 if (CstScalar) { 8566 bool Truncated = false; 8567 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy), 8568 llvm::APFloat::rmNearestTiesToEven, &Truncated); 8569 if (Truncated) 8570 return true; 8571 } 8572 8573 ScalarCast = CK_FloatingCast; 8574 } else if (ScalarTy->isIntegralType(S.Context)) { 8575 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy)) 8576 return true; 8577 8578 ScalarCast = CK_IntegralToFloating; 8579 } else 8580 return true; 8581 } 8582 8583 // Adjust scalar if desired. 8584 if (Scalar) { 8585 if (ScalarCast != CK_NoOp) 8586 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast); 8587 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat); 8588 } 8589 return false; 8590 } 8591 8592 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 8593 SourceLocation Loc, bool IsCompAssign, 8594 bool AllowBothBool, 8595 bool AllowBoolConversions) { 8596 if (!IsCompAssign) { 8597 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 8598 if (LHS.isInvalid()) 8599 return QualType(); 8600 } 8601 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 8602 if (RHS.isInvalid()) 8603 return QualType(); 8604 8605 // For conversion purposes, we ignore any qualifiers. 8606 // For example, "const float" and "float" are equivalent. 8607 QualType LHSType = LHS.get()->getType().getUnqualifiedType(); 8608 QualType RHSType = RHS.get()->getType().getUnqualifiedType(); 8609 8610 const VectorType *LHSVecType = LHSType->getAs<VectorType>(); 8611 const VectorType *RHSVecType = RHSType->getAs<VectorType>(); 8612 assert(LHSVecType || RHSVecType); 8613 8614 // AltiVec-style "vector bool op vector bool" combinations are allowed 8615 // for some operators but not others. 8616 if (!AllowBothBool && 8617 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8618 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool) 8619 return InvalidOperands(Loc, LHS, RHS); 8620 8621 // If the vector types are identical, return. 8622 if (Context.hasSameType(LHSType, RHSType)) 8623 return LHSType; 8624 8625 // If we have compatible AltiVec and GCC vector types, use the AltiVec type. 8626 if (LHSVecType && RHSVecType && 8627 Context.areCompatibleVectorTypes(LHSType, RHSType)) { 8628 if (isa<ExtVectorType>(LHSVecType)) { 8629 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8630 return LHSType; 8631 } 8632 8633 if (!IsCompAssign) 8634 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8635 return RHSType; 8636 } 8637 8638 // AllowBoolConversions says that bool and non-bool AltiVec vectors 8639 // can be mixed, with the result being the non-bool type. The non-bool 8640 // operand must have integer element type. 8641 if (AllowBoolConversions && LHSVecType && RHSVecType && 8642 LHSVecType->getNumElements() == RHSVecType->getNumElements() && 8643 (Context.getTypeSize(LHSVecType->getElementType()) == 8644 Context.getTypeSize(RHSVecType->getElementType()))) { 8645 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector && 8646 LHSVecType->getElementType()->isIntegerType() && 8647 RHSVecType->getVectorKind() == VectorType::AltiVecBool) { 8648 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 8649 return LHSType; 8650 } 8651 if (!IsCompAssign && 8652 LHSVecType->getVectorKind() == VectorType::AltiVecBool && 8653 RHSVecType->getVectorKind() == VectorType::AltiVecVector && 8654 RHSVecType->getElementType()->isIntegerType()) { 8655 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 8656 return RHSType; 8657 } 8658 } 8659 8660 // If there's a vector type and a scalar, try to convert the scalar to 8661 // the vector element type and splat. 8662 unsigned DiagID = diag::err_typecheck_vector_not_convertable; 8663 if (!RHSVecType) { 8664 if (isa<ExtVectorType>(LHSVecType)) { 8665 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType, 8666 LHSVecType->getElementType(), LHSType, 8667 DiagID)) 8668 return LHSType; 8669 } else { 8670 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS)) 8671 return LHSType; 8672 } 8673 } 8674 if (!LHSVecType) { 8675 if (isa<ExtVectorType>(RHSVecType)) { 8676 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS), 8677 LHSType, RHSVecType->getElementType(), 8678 RHSType, DiagID)) 8679 return RHSType; 8680 } else { 8681 if (LHS.get()->getValueKind() == VK_LValue || 8682 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS)) 8683 return RHSType; 8684 } 8685 } 8686 8687 // FIXME: The code below also handles conversion between vectors and 8688 // non-scalars, we should break this down into fine grained specific checks 8689 // and emit proper diagnostics. 8690 QualType VecType = LHSVecType ? LHSType : RHSType; 8691 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType; 8692 QualType OtherType = LHSVecType ? RHSType : LHSType; 8693 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS; 8694 if (isLaxVectorConversion(OtherType, VecType)) { 8695 // If we're allowing lax vector conversions, only the total (data) size 8696 // needs to be the same. For non compound assignment, if one of the types is 8697 // scalar, the result is always the vector type. 8698 if (!IsCompAssign) { 8699 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast); 8700 return VecType; 8701 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding 8702 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs' 8703 // type. Note that this is already done by non-compound assignments in 8704 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for 8705 // <1 x T> -> T. The result is also a vector type. 8706 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() || 8707 (OtherType->isScalarType() && VT->getNumElements() == 1)) { 8708 ExprResult *RHSExpr = &RHS; 8709 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast); 8710 return VecType; 8711 } 8712 } 8713 8714 // Okay, the expression is invalid. 8715 8716 // If there's a non-vector, non-real operand, diagnose that. 8717 if ((!RHSVecType && !RHSType->isRealType()) || 8718 (!LHSVecType && !LHSType->isRealType())) { 8719 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar) 8720 << LHSType << RHSType 8721 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8722 return QualType(); 8723 } 8724 8725 // OpenCL V1.1 6.2.6.p1: 8726 // If the operands are of more than one vector type, then an error shall 8727 // occur. Implicit conversions between vector types are not permitted, per 8728 // section 6.2.1. 8729 if (getLangOpts().OpenCL && 8730 RHSVecType && isa<ExtVectorType>(RHSVecType) && 8731 LHSVecType && isa<ExtVectorType>(LHSVecType)) { 8732 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType 8733 << RHSType; 8734 return QualType(); 8735 } 8736 8737 8738 // If there is a vector type that is not a ExtVector and a scalar, we reach 8739 // this point if scalar could not be converted to the vector's element type 8740 // without truncation. 8741 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) || 8742 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) { 8743 QualType Scalar = LHSVecType ? RHSType : LHSType; 8744 QualType Vector = LHSVecType ? LHSType : RHSType; 8745 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0; 8746 Diag(Loc, 8747 diag::err_typecheck_vector_not_convertable_implict_truncation) 8748 << ScalarOrVector << Scalar << Vector; 8749 8750 return QualType(); 8751 } 8752 8753 // Otherwise, use the generic diagnostic. 8754 Diag(Loc, DiagID) 8755 << LHSType << RHSType 8756 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8757 return QualType(); 8758 } 8759 8760 // checkArithmeticNull - Detect when a NULL constant is used improperly in an 8761 // expression. These are mainly cases where the null pointer is used as an 8762 // integer instead of a pointer. 8763 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, 8764 SourceLocation Loc, bool IsCompare) { 8765 // The canonical way to check for a GNU null is with isNullPointerConstant, 8766 // but we use a bit of a hack here for speed; this is a relatively 8767 // hot path, and isNullPointerConstant is slow. 8768 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts()); 8769 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts()); 8770 8771 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType(); 8772 8773 // Avoid analyzing cases where the result will either be invalid (and 8774 // diagnosed as such) or entirely valid and not something to warn about. 8775 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() || 8776 NonNullType->isMemberPointerType() || NonNullType->isFunctionType()) 8777 return; 8778 8779 // Comparison operations would not make sense with a null pointer no matter 8780 // what the other expression is. 8781 if (!IsCompare) { 8782 S.Diag(Loc, diag::warn_null_in_arithmetic_operation) 8783 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange()) 8784 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange()); 8785 return; 8786 } 8787 8788 // The rest of the operations only make sense with a null pointer 8789 // if the other expression is a pointer. 8790 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() || 8791 NonNullType->canDecayToPointerType()) 8792 return; 8793 8794 S.Diag(Loc, diag::warn_null_in_comparison_operation) 8795 << LHSNull /* LHS is NULL */ << NonNullType 8796 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 8797 } 8798 8799 static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS, 8800 SourceLocation Loc) { 8801 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS); 8802 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS); 8803 if (!LUE || !RUE) 8804 return; 8805 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() || 8806 RUE->getKind() != UETT_SizeOf) 8807 return; 8808 8809 QualType LHSTy = LUE->getArgumentExpr()->IgnoreParens()->getType(); 8810 QualType RHSTy; 8811 8812 if (RUE->isArgumentType()) 8813 RHSTy = RUE->getArgumentType(); 8814 else 8815 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType(); 8816 8817 if (!LHSTy->isPointerType() || RHSTy->isPointerType()) 8818 return; 8819 if (LHSTy->getPointeeType() != RHSTy) 8820 return; 8821 8822 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange(); 8823 } 8824 8825 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS, 8826 ExprResult &RHS, 8827 SourceLocation Loc, bool IsDiv) { 8828 // Check for division/remainder by zero. 8829 Expr::EvalResult RHSValue; 8830 if (!RHS.get()->isValueDependent() && 8831 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && 8832 RHSValue.Val.getInt() == 0) 8833 S.DiagRuntimeBehavior(Loc, RHS.get(), 8834 S.PDiag(diag::warn_remainder_division_by_zero) 8835 << IsDiv << RHS.get()->getSourceRange()); 8836 } 8837 8838 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, 8839 SourceLocation Loc, 8840 bool IsCompAssign, bool IsDiv) { 8841 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8842 8843 if (LHS.get()->getType()->isVectorType() || 8844 RHS.get()->getType()->isVectorType()) 8845 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8846 /*AllowBothBool*/getLangOpts().AltiVec, 8847 /*AllowBoolConversions*/false); 8848 8849 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8850 if (LHS.isInvalid() || RHS.isInvalid()) 8851 return QualType(); 8852 8853 8854 if (compType.isNull() || !compType->isArithmeticType()) 8855 return InvalidOperands(Loc, LHS, RHS); 8856 if (IsDiv) { 8857 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv); 8858 DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc); 8859 } 8860 return compType; 8861 } 8862 8863 QualType Sema::CheckRemainderOperands( 8864 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) { 8865 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 8866 8867 if (LHS.get()->getType()->isVectorType() || 8868 RHS.get()->getType()->isVectorType()) { 8869 if (LHS.get()->getType()->hasIntegerRepresentation() && 8870 RHS.get()->getType()->hasIntegerRepresentation()) 8871 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 8872 /*AllowBothBool*/getLangOpts().AltiVec, 8873 /*AllowBoolConversions*/false); 8874 return InvalidOperands(Loc, LHS, RHS); 8875 } 8876 8877 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign); 8878 if (LHS.isInvalid() || RHS.isInvalid()) 8879 return QualType(); 8880 8881 if (compType.isNull() || !compType->isIntegerType()) 8882 return InvalidOperands(Loc, LHS, RHS); 8883 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */); 8884 return compType; 8885 } 8886 8887 /// Diagnose invalid arithmetic on two void pointers. 8888 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, 8889 Expr *LHSExpr, Expr *RHSExpr) { 8890 S.Diag(Loc, S.getLangOpts().CPlusPlus 8891 ? diag::err_typecheck_pointer_arith_void_type 8892 : diag::ext_gnu_void_ptr) 8893 << 1 /* two pointers */ << LHSExpr->getSourceRange() 8894 << RHSExpr->getSourceRange(); 8895 } 8896 8897 /// Diagnose invalid arithmetic on a void pointer. 8898 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, 8899 Expr *Pointer) { 8900 S.Diag(Loc, S.getLangOpts().CPlusPlus 8901 ? diag::err_typecheck_pointer_arith_void_type 8902 : diag::ext_gnu_void_ptr) 8903 << 0 /* one pointer */ << Pointer->getSourceRange(); 8904 } 8905 8906 /// Diagnose invalid arithmetic on a null pointer. 8907 /// 8908 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n' 8909 /// idiom, which we recognize as a GNU extension. 8910 /// 8911 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, 8912 Expr *Pointer, bool IsGNUIdiom) { 8913 if (IsGNUIdiom) 8914 S.Diag(Loc, diag::warn_gnu_null_ptr_arith) 8915 << Pointer->getSourceRange(); 8916 else 8917 S.Diag(Loc, diag::warn_pointer_arith_null_ptr) 8918 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange(); 8919 } 8920 8921 /// Diagnose invalid arithmetic on two function pointers. 8922 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, 8923 Expr *LHS, Expr *RHS) { 8924 assert(LHS->getType()->isAnyPointerType()); 8925 assert(RHS->getType()->isAnyPointerType()); 8926 S.Diag(Loc, S.getLangOpts().CPlusPlus 8927 ? diag::err_typecheck_pointer_arith_function_type 8928 : diag::ext_gnu_ptr_func_arith) 8929 << 1 /* two pointers */ << LHS->getType()->getPointeeType() 8930 // We only show the second type if it differs from the first. 8931 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(), 8932 RHS->getType()) 8933 << RHS->getType()->getPointeeType() 8934 << LHS->getSourceRange() << RHS->getSourceRange(); 8935 } 8936 8937 /// Diagnose invalid arithmetic on a function pointer. 8938 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, 8939 Expr *Pointer) { 8940 assert(Pointer->getType()->isAnyPointerType()); 8941 S.Diag(Loc, S.getLangOpts().CPlusPlus 8942 ? diag::err_typecheck_pointer_arith_function_type 8943 : diag::ext_gnu_ptr_func_arith) 8944 << 0 /* one pointer */ << Pointer->getType()->getPointeeType() 8945 << 0 /* one pointer, so only one type */ 8946 << Pointer->getSourceRange(); 8947 } 8948 8949 /// Emit error if Operand is incomplete pointer type 8950 /// 8951 /// \returns True if pointer has incomplete type 8952 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, 8953 Expr *Operand) { 8954 QualType ResType = Operand->getType(); 8955 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8956 ResType = ResAtomicType->getValueType(); 8957 8958 assert(ResType->isAnyPointerType() && !ResType->isDependentType()); 8959 QualType PointeeTy = ResType->getPointeeType(); 8960 return S.RequireCompleteType(Loc, PointeeTy, 8961 diag::err_typecheck_arithmetic_incomplete_type, 8962 PointeeTy, Operand->getSourceRange()); 8963 } 8964 8965 /// Check the validity of an arithmetic pointer operand. 8966 /// 8967 /// If the operand has pointer type, this code will check for pointer types 8968 /// which are invalid in arithmetic operations. These will be diagnosed 8969 /// appropriately, including whether or not the use is supported as an 8970 /// extension. 8971 /// 8972 /// \returns True when the operand is valid to use (even if as an extension). 8973 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, 8974 Expr *Operand) { 8975 QualType ResType = Operand->getType(); 8976 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 8977 ResType = ResAtomicType->getValueType(); 8978 8979 if (!ResType->isAnyPointerType()) return true; 8980 8981 QualType PointeeTy = ResType->getPointeeType(); 8982 if (PointeeTy->isVoidType()) { 8983 diagnoseArithmeticOnVoidPointer(S, Loc, Operand); 8984 return !S.getLangOpts().CPlusPlus; 8985 } 8986 if (PointeeTy->isFunctionType()) { 8987 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand); 8988 return !S.getLangOpts().CPlusPlus; 8989 } 8990 8991 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false; 8992 8993 return true; 8994 } 8995 8996 /// Check the validity of a binary arithmetic operation w.r.t. pointer 8997 /// operands. 8998 /// 8999 /// This routine will diagnose any invalid arithmetic on pointer operands much 9000 /// like \see checkArithmeticOpPointerOperand. However, it has special logic 9001 /// for emitting a single diagnostic even for operations where both LHS and RHS 9002 /// are (potentially problematic) pointers. 9003 /// 9004 /// \returns True when the operand is valid to use (even if as an extension). 9005 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, 9006 Expr *LHSExpr, Expr *RHSExpr) { 9007 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType(); 9008 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType(); 9009 if (!isLHSPointer && !isRHSPointer) return true; 9010 9011 QualType LHSPointeeTy, RHSPointeeTy; 9012 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType(); 9013 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType(); 9014 9015 // if both are pointers check if operation is valid wrt address spaces 9016 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) { 9017 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>(); 9018 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>(); 9019 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) { 9020 S.Diag(Loc, 9021 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 9022 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/ 9023 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange(); 9024 return false; 9025 } 9026 } 9027 9028 // Check for arithmetic on pointers to incomplete types. 9029 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType(); 9030 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType(); 9031 if (isLHSVoidPtr || isRHSVoidPtr) { 9032 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr); 9033 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr); 9034 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr); 9035 9036 return !S.getLangOpts().CPlusPlus; 9037 } 9038 9039 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType(); 9040 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType(); 9041 if (isLHSFuncPtr || isRHSFuncPtr) { 9042 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr); 9043 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, 9044 RHSExpr); 9045 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr); 9046 9047 return !S.getLangOpts().CPlusPlus; 9048 } 9049 9050 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) 9051 return false; 9052 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) 9053 return false; 9054 9055 return true; 9056 } 9057 9058 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string 9059 /// literal. 9060 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, 9061 Expr *LHSExpr, Expr *RHSExpr) { 9062 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts()); 9063 Expr* IndexExpr = RHSExpr; 9064 if (!StrExpr) { 9065 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts()); 9066 IndexExpr = LHSExpr; 9067 } 9068 9069 bool IsStringPlusInt = StrExpr && 9070 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType(); 9071 if (!IsStringPlusInt || IndexExpr->isValueDependent()) 9072 return; 9073 9074 Expr::EvalResult Result; 9075 if (IndexExpr->EvaluateAsInt(Result, Self.getASTContext())) { 9076 llvm::APSInt index = Result.Val.getInt(); 9077 unsigned StrLenWithNull = StrExpr->getLength() + 1; 9078 if (index.isNonNegative() && 9079 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull), 9080 index.isUnsigned())) 9081 return; 9082 } 9083 9084 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9085 Self.Diag(OpLoc, diag::warn_string_plus_int) 9086 << DiagRange << IndexExpr->IgnoreImpCasts()->getType(); 9087 9088 // Only print a fixit for "str" + int, not for int + "str". 9089 if (IndexExpr == RHSExpr) { 9090 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9091 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9092 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9093 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9094 << FixItHint::CreateInsertion(EndLoc, "]"); 9095 } else 9096 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9097 } 9098 9099 /// Emit a warning when adding a char literal to a string. 9100 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, 9101 Expr *LHSExpr, Expr *RHSExpr) { 9102 const Expr *StringRefExpr = LHSExpr; 9103 const CharacterLiteral *CharExpr = 9104 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts()); 9105 9106 if (!CharExpr) { 9107 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts()); 9108 StringRefExpr = RHSExpr; 9109 } 9110 9111 if (!CharExpr || !StringRefExpr) 9112 return; 9113 9114 const QualType StringType = StringRefExpr->getType(); 9115 9116 // Return if not a PointerType. 9117 if (!StringType->isAnyPointerType()) 9118 return; 9119 9120 // Return if not a CharacterType. 9121 if (!StringType->getPointeeType()->isAnyCharacterType()) 9122 return; 9123 9124 ASTContext &Ctx = Self.getASTContext(); 9125 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 9126 9127 const QualType CharType = CharExpr->getType(); 9128 if (!CharType->isAnyCharacterType() && 9129 CharType->isIntegerType() && 9130 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) { 9131 Self.Diag(OpLoc, diag::warn_string_plus_char) 9132 << DiagRange << Ctx.CharTy; 9133 } else { 9134 Self.Diag(OpLoc, diag::warn_string_plus_char) 9135 << DiagRange << CharExpr->getType(); 9136 } 9137 9138 // Only print a fixit for str + char, not for char + str. 9139 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) { 9140 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc()); 9141 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence) 9142 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&") 9143 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[") 9144 << FixItHint::CreateInsertion(EndLoc, "]"); 9145 } else { 9146 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence); 9147 } 9148 } 9149 9150 /// Emit error when two pointers are incompatible. 9151 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, 9152 Expr *LHSExpr, Expr *RHSExpr) { 9153 assert(LHSExpr->getType()->isAnyPointerType()); 9154 assert(RHSExpr->getType()->isAnyPointerType()); 9155 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible) 9156 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange() 9157 << RHSExpr->getSourceRange(); 9158 } 9159 9160 // C99 6.5.6 9161 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, 9162 SourceLocation Loc, BinaryOperatorKind Opc, 9163 QualType* CompLHSTy) { 9164 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9165 9166 if (LHS.get()->getType()->isVectorType() || 9167 RHS.get()->getType()->isVectorType()) { 9168 QualType compType = CheckVectorOperands( 9169 LHS, RHS, Loc, CompLHSTy, 9170 /*AllowBothBool*/getLangOpts().AltiVec, 9171 /*AllowBoolConversions*/getLangOpts().ZVector); 9172 if (CompLHSTy) *CompLHSTy = compType; 9173 return compType; 9174 } 9175 9176 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9177 if (LHS.isInvalid() || RHS.isInvalid()) 9178 return QualType(); 9179 9180 // Diagnose "string literal" '+' int and string '+' "char literal". 9181 if (Opc == BO_Add) { 9182 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get()); 9183 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get()); 9184 } 9185 9186 // handle the common case first (both operands are arithmetic). 9187 if (!compType.isNull() && compType->isArithmeticType()) { 9188 if (CompLHSTy) *CompLHSTy = compType; 9189 return compType; 9190 } 9191 9192 // Type-checking. Ultimately the pointer's going to be in PExp; 9193 // note that we bias towards the LHS being the pointer. 9194 Expr *PExp = LHS.get(), *IExp = RHS.get(); 9195 9196 bool isObjCPointer; 9197 if (PExp->getType()->isPointerType()) { 9198 isObjCPointer = false; 9199 } else if (PExp->getType()->isObjCObjectPointerType()) { 9200 isObjCPointer = true; 9201 } else { 9202 std::swap(PExp, IExp); 9203 if (PExp->getType()->isPointerType()) { 9204 isObjCPointer = false; 9205 } else if (PExp->getType()->isObjCObjectPointerType()) { 9206 isObjCPointer = true; 9207 } else { 9208 return InvalidOperands(Loc, LHS, RHS); 9209 } 9210 } 9211 assert(PExp->getType()->isAnyPointerType()); 9212 9213 if (!IExp->getType()->isIntegerType()) 9214 return InvalidOperands(Loc, LHS, RHS); 9215 9216 // Adding to a null pointer results in undefined behavior. 9217 if (PExp->IgnoreParenCasts()->isNullPointerConstant( 9218 Context, Expr::NPC_ValueDependentIsNotNull)) { 9219 // In C++ adding zero to a null pointer is defined. 9220 Expr::EvalResult KnownVal; 9221 if (!getLangOpts().CPlusPlus || 9222 (!IExp->isValueDependent() && 9223 (!IExp->EvaluateAsInt(KnownVal, Context) || 9224 KnownVal.Val.getInt() != 0))) { 9225 // Check the conditions to see if this is the 'p = nullptr + n' idiom. 9226 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension( 9227 Context, BO_Add, PExp, IExp); 9228 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom); 9229 } 9230 } 9231 9232 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp)) 9233 return QualType(); 9234 9235 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp)) 9236 return QualType(); 9237 9238 // Check array bounds for pointer arithemtic 9239 CheckArrayAccess(PExp, IExp); 9240 9241 if (CompLHSTy) { 9242 QualType LHSTy = Context.isPromotableBitField(LHS.get()); 9243 if (LHSTy.isNull()) { 9244 LHSTy = LHS.get()->getType(); 9245 if (LHSTy->isPromotableIntegerType()) 9246 LHSTy = Context.getPromotedIntegerType(LHSTy); 9247 } 9248 *CompLHSTy = LHSTy; 9249 } 9250 9251 return PExp->getType(); 9252 } 9253 9254 // C99 6.5.6 9255 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, 9256 SourceLocation Loc, 9257 QualType* CompLHSTy) { 9258 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9259 9260 if (LHS.get()->getType()->isVectorType() || 9261 RHS.get()->getType()->isVectorType()) { 9262 QualType compType = CheckVectorOperands( 9263 LHS, RHS, Loc, CompLHSTy, 9264 /*AllowBothBool*/getLangOpts().AltiVec, 9265 /*AllowBoolConversions*/getLangOpts().ZVector); 9266 if (CompLHSTy) *CompLHSTy = compType; 9267 return compType; 9268 } 9269 9270 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy); 9271 if (LHS.isInvalid() || RHS.isInvalid()) 9272 return QualType(); 9273 9274 // Enforce type constraints: C99 6.5.6p3. 9275 9276 // Handle the common case first (both operands are arithmetic). 9277 if (!compType.isNull() && compType->isArithmeticType()) { 9278 if (CompLHSTy) *CompLHSTy = compType; 9279 return compType; 9280 } 9281 9282 // Either ptr - int or ptr - ptr. 9283 if (LHS.get()->getType()->isAnyPointerType()) { 9284 QualType lpointee = LHS.get()->getType()->getPointeeType(); 9285 9286 // Diagnose bad cases where we step over interface counts. 9287 if (LHS.get()->getType()->isObjCObjectPointerType() && 9288 checkArithmeticOnObjCPointer(*this, Loc, LHS.get())) 9289 return QualType(); 9290 9291 // The result type of a pointer-int computation is the pointer type. 9292 if (RHS.get()->getType()->isIntegerType()) { 9293 // Subtracting from a null pointer should produce a warning. 9294 // The last argument to the diagnose call says this doesn't match the 9295 // GNU int-to-pointer idiom. 9296 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context, 9297 Expr::NPC_ValueDependentIsNotNull)) { 9298 // In C++ adding zero to a null pointer is defined. 9299 Expr::EvalResult KnownVal; 9300 if (!getLangOpts().CPlusPlus || 9301 (!RHS.get()->isValueDependent() && 9302 (!RHS.get()->EvaluateAsInt(KnownVal, Context) || 9303 KnownVal.Val.getInt() != 0))) { 9304 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false); 9305 } 9306 } 9307 9308 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get())) 9309 return QualType(); 9310 9311 // Check array bounds for pointer arithemtic 9312 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr, 9313 /*AllowOnePastEnd*/true, /*IndexNegated*/true); 9314 9315 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9316 return LHS.get()->getType(); 9317 } 9318 9319 // Handle pointer-pointer subtractions. 9320 if (const PointerType *RHSPTy 9321 = RHS.get()->getType()->getAs<PointerType>()) { 9322 QualType rpointee = RHSPTy->getPointeeType(); 9323 9324 if (getLangOpts().CPlusPlus) { 9325 // Pointee types must be the same: C++ [expr.add] 9326 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) { 9327 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9328 } 9329 } else { 9330 // Pointee types must be compatible C99 6.5.6p3 9331 if (!Context.typesAreCompatible( 9332 Context.getCanonicalType(lpointee).getUnqualifiedType(), 9333 Context.getCanonicalType(rpointee).getUnqualifiedType())) { 9334 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get()); 9335 return QualType(); 9336 } 9337 } 9338 9339 if (!checkArithmeticBinOpPointerOperands(*this, Loc, 9340 LHS.get(), RHS.get())) 9341 return QualType(); 9342 9343 // FIXME: Add warnings for nullptr - ptr. 9344 9345 // The pointee type may have zero size. As an extension, a structure or 9346 // union may have zero size or an array may have zero length. In this 9347 // case subtraction does not make sense. 9348 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { 9349 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); 9350 if (ElementSize.isZero()) { 9351 Diag(Loc,diag::warn_sub_ptr_zero_size_types) 9352 << rpointee.getUnqualifiedType() 9353 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9354 } 9355 } 9356 9357 if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); 9358 return Context.getPointerDiffType(); 9359 } 9360 } 9361 9362 return InvalidOperands(Loc, LHS, RHS); 9363 } 9364 9365 static bool isScopedEnumerationType(QualType T) { 9366 if (const EnumType *ET = T->getAs<EnumType>()) 9367 return ET->getDecl()->isScoped(); 9368 return false; 9369 } 9370 9371 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS, 9372 SourceLocation Loc, BinaryOperatorKind Opc, 9373 QualType LHSType) { 9374 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined), 9375 // so skip remaining warnings as we don't want to modify values within Sema. 9376 if (S.getLangOpts().OpenCL) 9377 return; 9378 9379 // Check right/shifter operand 9380 Expr::EvalResult RHSResult; 9381 if (RHS.get()->isValueDependent() || 9382 !RHS.get()->EvaluateAsInt(RHSResult, S.Context)) 9383 return; 9384 llvm::APSInt Right = RHSResult.Val.getInt(); 9385 9386 if (Right.isNegative()) { 9387 S.DiagRuntimeBehavior(Loc, RHS.get(), 9388 S.PDiag(diag::warn_shift_negative) 9389 << RHS.get()->getSourceRange()); 9390 return; 9391 } 9392 llvm::APInt LeftBits(Right.getBitWidth(), 9393 S.Context.getTypeSize(LHS.get()->getType())); 9394 if (Right.uge(LeftBits)) { 9395 S.DiagRuntimeBehavior(Loc, RHS.get(), 9396 S.PDiag(diag::warn_shift_gt_typewidth) 9397 << RHS.get()->getSourceRange()); 9398 return; 9399 } 9400 if (Opc != BO_Shl) 9401 return; 9402 9403 // When left shifting an ICE which is signed, we can check for overflow which 9404 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned 9405 // integers have defined behavior modulo one more than the maximum value 9406 // representable in the result type, so never warn for those. 9407 Expr::EvalResult LHSResult; 9408 if (LHS.get()->isValueDependent() || 9409 LHSType->hasUnsignedIntegerRepresentation() || 9410 !LHS.get()->EvaluateAsInt(LHSResult, S.Context)) 9411 return; 9412 llvm::APSInt Left = LHSResult.Val.getInt(); 9413 9414 // If LHS does not have a signed type and non-negative value 9415 // then, the behavior is undefined. Warn about it. 9416 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) { 9417 S.DiagRuntimeBehavior(Loc, LHS.get(), 9418 S.PDiag(diag::warn_shift_lhs_negative) 9419 << LHS.get()->getSourceRange()); 9420 return; 9421 } 9422 9423 llvm::APInt ResultBits = 9424 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits(); 9425 if (LeftBits.uge(ResultBits)) 9426 return; 9427 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue()); 9428 Result = Result.shl(Right); 9429 9430 // Print the bit representation of the signed integer as an unsigned 9431 // hexadecimal number. 9432 SmallString<40> HexResult; 9433 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true); 9434 9435 // If we are only missing a sign bit, this is less likely to result in actual 9436 // bugs -- if the result is cast back to an unsigned type, it will have the 9437 // expected value. Thus we place this behind a different warning that can be 9438 // turned off separately if needed. 9439 if (LeftBits == ResultBits - 1) { 9440 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit) 9441 << HexResult << LHSType 9442 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9443 return; 9444 } 9445 9446 S.Diag(Loc, diag::warn_shift_result_gt_typewidth) 9447 << HexResult.str() << Result.getMinSignedBits() << LHSType 9448 << Left.getBitWidth() << LHS.get()->getSourceRange() 9449 << RHS.get()->getSourceRange(); 9450 } 9451 9452 /// Return the resulting type when a vector is shifted 9453 /// by a scalar or vector shift amount. 9454 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, 9455 SourceLocation Loc, bool IsCompAssign) { 9456 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector. 9457 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) && 9458 !LHS.get()->getType()->isVectorType()) { 9459 S.Diag(Loc, diag::err_shift_rhs_only_vector) 9460 << RHS.get()->getType() << LHS.get()->getType() 9461 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9462 return QualType(); 9463 } 9464 9465 if (!IsCompAssign) { 9466 LHS = S.UsualUnaryConversions(LHS.get()); 9467 if (LHS.isInvalid()) return QualType(); 9468 } 9469 9470 RHS = S.UsualUnaryConversions(RHS.get()); 9471 if (RHS.isInvalid()) return QualType(); 9472 9473 QualType LHSType = LHS.get()->getType(); 9474 // Note that LHS might be a scalar because the routine calls not only in 9475 // OpenCL case. 9476 const VectorType *LHSVecTy = LHSType->getAs<VectorType>(); 9477 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType; 9478 9479 // Note that RHS might not be a vector. 9480 QualType RHSType = RHS.get()->getType(); 9481 const VectorType *RHSVecTy = RHSType->getAs<VectorType>(); 9482 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType; 9483 9484 // The operands need to be integers. 9485 if (!LHSEleType->isIntegerType()) { 9486 S.Diag(Loc, diag::err_typecheck_expect_int) 9487 << LHS.get()->getType() << LHS.get()->getSourceRange(); 9488 return QualType(); 9489 } 9490 9491 if (!RHSEleType->isIntegerType()) { 9492 S.Diag(Loc, diag::err_typecheck_expect_int) 9493 << RHS.get()->getType() << RHS.get()->getSourceRange(); 9494 return QualType(); 9495 } 9496 9497 if (!LHSVecTy) { 9498 assert(RHSVecTy); 9499 if (IsCompAssign) 9500 return RHSType; 9501 if (LHSEleType != RHSEleType) { 9502 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast); 9503 LHSEleType = RHSEleType; 9504 } 9505 QualType VecTy = 9506 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements()); 9507 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat); 9508 LHSType = VecTy; 9509 } else if (RHSVecTy) { 9510 // OpenCL v1.1 s6.3.j says that for vector types, the operators 9511 // are applied component-wise. So if RHS is a vector, then ensure 9512 // that the number of elements is the same as LHS... 9513 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) { 9514 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal) 9515 << LHS.get()->getType() << RHS.get()->getType() 9516 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9517 return QualType(); 9518 } 9519 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) { 9520 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>(); 9521 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>(); 9522 if (LHSBT != RHSBT && 9523 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) { 9524 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal) 9525 << LHS.get()->getType() << RHS.get()->getType() 9526 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9527 } 9528 } 9529 } else { 9530 // ...else expand RHS to match the number of elements in LHS. 9531 QualType VecTy = 9532 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements()); 9533 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat); 9534 } 9535 9536 return LHSType; 9537 } 9538 9539 // C99 6.5.7 9540 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, 9541 SourceLocation Loc, BinaryOperatorKind Opc, 9542 bool IsCompAssign) { 9543 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 9544 9545 // Vector shifts promote their scalar inputs to vector type. 9546 if (LHS.get()->getType()->isVectorType() || 9547 RHS.get()->getType()->isVectorType()) { 9548 if (LangOpts.ZVector) { 9549 // The shift operators for the z vector extensions work basically 9550 // like general shifts, except that neither the LHS nor the RHS is 9551 // allowed to be a "vector bool". 9552 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>()) 9553 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool) 9554 return InvalidOperands(Loc, LHS, RHS); 9555 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>()) 9556 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool) 9557 return InvalidOperands(Loc, LHS, RHS); 9558 } 9559 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign); 9560 } 9561 9562 // Shifts don't perform usual arithmetic conversions, they just do integer 9563 // promotions on each operand. C99 6.5.7p3 9564 9565 // For the LHS, do usual unary conversions, but then reset them away 9566 // if this is a compound assignment. 9567 ExprResult OldLHS = LHS; 9568 LHS = UsualUnaryConversions(LHS.get()); 9569 if (LHS.isInvalid()) 9570 return QualType(); 9571 QualType LHSType = LHS.get()->getType(); 9572 if (IsCompAssign) LHS = OldLHS; 9573 9574 // The RHS is simpler. 9575 RHS = UsualUnaryConversions(RHS.get()); 9576 if (RHS.isInvalid()) 9577 return QualType(); 9578 QualType RHSType = RHS.get()->getType(); 9579 9580 // C99 6.5.7p2: Each of the operands shall have integer type. 9581 if (!LHSType->hasIntegerRepresentation() || 9582 !RHSType->hasIntegerRepresentation()) 9583 return InvalidOperands(Loc, LHS, RHS); 9584 9585 // C++0x: Don't allow scoped enums. FIXME: Use something better than 9586 // hasIntegerRepresentation() above instead of this. 9587 if (isScopedEnumerationType(LHSType) || 9588 isScopedEnumerationType(RHSType)) { 9589 return InvalidOperands(Loc, LHS, RHS); 9590 } 9591 // Sanity-check shift operands 9592 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType); 9593 9594 // "The type of the result is that of the promoted left operand." 9595 return LHSType; 9596 } 9597 9598 /// If two different enums are compared, raise a warning. 9599 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS, 9600 Expr *RHS) { 9601 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType(); 9602 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType(); 9603 9604 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>(); 9605 if (!LHSEnumType) 9606 return; 9607 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>(); 9608 if (!RHSEnumType) 9609 return; 9610 9611 // Ignore anonymous enums. 9612 if (!LHSEnumType->getDecl()->getIdentifier() && 9613 !LHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9614 return; 9615 if (!RHSEnumType->getDecl()->getIdentifier() && 9616 !RHSEnumType->getDecl()->getTypedefNameForAnonDecl()) 9617 return; 9618 9619 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) 9620 return; 9621 9622 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types) 9623 << LHSStrippedType << RHSStrippedType 9624 << LHS->getSourceRange() << RHS->getSourceRange(); 9625 } 9626 9627 /// Diagnose bad pointer comparisons. 9628 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, 9629 ExprResult &LHS, ExprResult &RHS, 9630 bool IsError) { 9631 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers 9632 : diag::ext_typecheck_comparison_of_distinct_pointers) 9633 << LHS.get()->getType() << RHS.get()->getType() 9634 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9635 } 9636 9637 /// Returns false if the pointers are converted to a composite type, 9638 /// true otherwise. 9639 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, 9640 ExprResult &LHS, ExprResult &RHS) { 9641 // C++ [expr.rel]p2: 9642 // [...] Pointer conversions (4.10) and qualification 9643 // conversions (4.4) are performed on pointer operands (or on 9644 // a pointer operand and a null pointer constant) to bring 9645 // them to their composite pointer type. [...] 9646 // 9647 // C++ [expr.eq]p1 uses the same notion for (in)equality 9648 // comparisons of pointers. 9649 9650 QualType LHSType = LHS.get()->getType(); 9651 QualType RHSType = RHS.get()->getType(); 9652 assert(LHSType->isPointerType() || RHSType->isPointerType() || 9653 LHSType->isMemberPointerType() || RHSType->isMemberPointerType()); 9654 9655 QualType T = S.FindCompositePointerType(Loc, LHS, RHS); 9656 if (T.isNull()) { 9657 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) && 9658 (RHSType->isPointerType() || RHSType->isMemberPointerType())) 9659 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true); 9660 else 9661 S.InvalidOperands(Loc, LHS, RHS); 9662 return true; 9663 } 9664 9665 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast); 9666 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast); 9667 return false; 9668 } 9669 9670 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, 9671 ExprResult &LHS, 9672 ExprResult &RHS, 9673 bool IsError) { 9674 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void 9675 : diag::ext_typecheck_comparison_of_fptr_to_void) 9676 << LHS.get()->getType() << RHS.get()->getType() 9677 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 9678 } 9679 9680 static bool isObjCObjectLiteral(ExprResult &E) { 9681 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) { 9682 case Stmt::ObjCArrayLiteralClass: 9683 case Stmt::ObjCDictionaryLiteralClass: 9684 case Stmt::ObjCStringLiteralClass: 9685 case Stmt::ObjCBoxedExprClass: 9686 return true; 9687 default: 9688 // Note that ObjCBoolLiteral is NOT an object literal! 9689 return false; 9690 } 9691 } 9692 9693 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) { 9694 const ObjCObjectPointerType *Type = 9695 LHS->getType()->getAs<ObjCObjectPointerType>(); 9696 9697 // If this is not actually an Objective-C object, bail out. 9698 if (!Type) 9699 return false; 9700 9701 // Get the LHS object's interface type. 9702 QualType InterfaceType = Type->getPointeeType(); 9703 9704 // If the RHS isn't an Objective-C object, bail out. 9705 if (!RHS->getType()->isObjCObjectPointerType()) 9706 return false; 9707 9708 // Try to find the -isEqual: method. 9709 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector(); 9710 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel, 9711 InterfaceType, 9712 /*instance=*/true); 9713 if (!Method) { 9714 if (Type->isObjCIdType()) { 9715 // For 'id', just check the global pool. 9716 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(), 9717 /*receiverId=*/true); 9718 } else { 9719 // Check protocols. 9720 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type, 9721 /*instance=*/true); 9722 } 9723 } 9724 9725 if (!Method) 9726 return false; 9727 9728 QualType T = Method->parameters()[0]->getType(); 9729 if (!T->isObjCObjectPointerType()) 9730 return false; 9731 9732 QualType R = Method->getReturnType(); 9733 if (!R->isScalarType()) 9734 return false; 9735 9736 return true; 9737 } 9738 9739 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) { 9740 FromE = FromE->IgnoreParenImpCasts(); 9741 switch (FromE->getStmtClass()) { 9742 default: 9743 break; 9744 case Stmt::ObjCStringLiteralClass: 9745 // "string literal" 9746 return LK_String; 9747 case Stmt::ObjCArrayLiteralClass: 9748 // "array literal" 9749 return LK_Array; 9750 case Stmt::ObjCDictionaryLiteralClass: 9751 // "dictionary literal" 9752 return LK_Dictionary; 9753 case Stmt::BlockExprClass: 9754 return LK_Block; 9755 case Stmt::ObjCBoxedExprClass: { 9756 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens(); 9757 switch (Inner->getStmtClass()) { 9758 case Stmt::IntegerLiteralClass: 9759 case Stmt::FloatingLiteralClass: 9760 case Stmt::CharacterLiteralClass: 9761 case Stmt::ObjCBoolLiteralExprClass: 9762 case Stmt::CXXBoolLiteralExprClass: 9763 // "numeric literal" 9764 return LK_Numeric; 9765 case Stmt::ImplicitCastExprClass: { 9766 CastKind CK = cast<CastExpr>(Inner)->getCastKind(); 9767 // Boolean literals can be represented by implicit casts. 9768 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) 9769 return LK_Numeric; 9770 break; 9771 } 9772 default: 9773 break; 9774 } 9775 return LK_Boxed; 9776 } 9777 } 9778 return LK_None; 9779 } 9780 9781 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, 9782 ExprResult &LHS, ExprResult &RHS, 9783 BinaryOperator::Opcode Opc){ 9784 Expr *Literal; 9785 Expr *Other; 9786 if (isObjCObjectLiteral(LHS)) { 9787 Literal = LHS.get(); 9788 Other = RHS.get(); 9789 } else { 9790 Literal = RHS.get(); 9791 Other = LHS.get(); 9792 } 9793 9794 // Don't warn on comparisons against nil. 9795 Other = Other->IgnoreParenCasts(); 9796 if (Other->isNullPointerConstant(S.getASTContext(), 9797 Expr::NPC_ValueDependentIsNotNull)) 9798 return; 9799 9800 // This should be kept in sync with warn_objc_literal_comparison. 9801 // LK_String should always be after the other literals, since it has its own 9802 // warning flag. 9803 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal); 9804 assert(LiteralKind != Sema::LK_Block); 9805 if (LiteralKind == Sema::LK_None) { 9806 llvm_unreachable("Unknown Objective-C object literal kind"); 9807 } 9808 9809 if (LiteralKind == Sema::LK_String) 9810 S.Diag(Loc, diag::warn_objc_string_literal_comparison) 9811 << Literal->getSourceRange(); 9812 else 9813 S.Diag(Loc, diag::warn_objc_literal_comparison) 9814 << LiteralKind << Literal->getSourceRange(); 9815 9816 if (BinaryOperator::isEqualityOp(Opc) && 9817 hasIsEqualMethod(S, LHS.get(), RHS.get())) { 9818 SourceLocation Start = LHS.get()->getBeginLoc(); 9819 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc()); 9820 CharSourceRange OpRange = 9821 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 9822 9823 S.Diag(Loc, diag::note_objc_literal_comparison_isequal) 9824 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![") 9825 << FixItHint::CreateReplacement(OpRange, " isEqual:") 9826 << FixItHint::CreateInsertion(End, "]"); 9827 } 9828 } 9829 9830 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended. 9831 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, 9832 ExprResult &RHS, SourceLocation Loc, 9833 BinaryOperatorKind Opc) { 9834 // Check that left hand side is !something. 9835 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts()); 9836 if (!UO || UO->getOpcode() != UO_LNot) return; 9837 9838 // Only check if the right hand side is non-bool arithmetic type. 9839 if (RHS.get()->isKnownToHaveBooleanValue()) return; 9840 9841 // Make sure that the something in !something is not bool. 9842 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts(); 9843 if (SubExpr->isKnownToHaveBooleanValue()) return; 9844 9845 // Emit warning. 9846 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor; 9847 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check) 9848 << Loc << IsBitwiseOp; 9849 9850 // First note suggest !(x < y) 9851 SourceLocation FirstOpen = SubExpr->getBeginLoc(); 9852 SourceLocation FirstClose = RHS.get()->getEndLoc(); 9853 FirstClose = S.getLocForEndOfToken(FirstClose); 9854 if (FirstClose.isInvalid()) 9855 FirstOpen = SourceLocation(); 9856 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix) 9857 << IsBitwiseOp 9858 << FixItHint::CreateInsertion(FirstOpen, "(") 9859 << FixItHint::CreateInsertion(FirstClose, ")"); 9860 9861 // Second note suggests (!x) < y 9862 SourceLocation SecondOpen = LHS.get()->getBeginLoc(); 9863 SourceLocation SecondClose = LHS.get()->getEndLoc(); 9864 SecondClose = S.getLocForEndOfToken(SecondClose); 9865 if (SecondClose.isInvalid()) 9866 SecondOpen = SourceLocation(); 9867 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens) 9868 << FixItHint::CreateInsertion(SecondOpen, "(") 9869 << FixItHint::CreateInsertion(SecondClose, ")"); 9870 } 9871 9872 // Get the decl for a simple expression: a reference to a variable, 9873 // an implicit C++ field reference, or an implicit ObjC ivar reference. 9874 static ValueDecl *getCompareDecl(Expr *E) { 9875 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) 9876 return DR->getDecl(); 9877 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) { 9878 if (Ivar->isFreeIvar()) 9879 return Ivar->getDecl(); 9880 } 9881 if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) { 9882 if (Mem->isImplicitAccess()) 9883 return Mem->getMemberDecl(); 9884 } 9885 return nullptr; 9886 } 9887 9888 /// Diagnose some forms of syntactically-obvious tautological comparison. 9889 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, 9890 Expr *LHS, Expr *RHS, 9891 BinaryOperatorKind Opc) { 9892 Expr *LHSStripped = LHS->IgnoreParenImpCasts(); 9893 Expr *RHSStripped = RHS->IgnoreParenImpCasts(); 9894 9895 QualType LHSType = LHS->getType(); 9896 QualType RHSType = RHS->getType(); 9897 if (LHSType->hasFloatingRepresentation() || 9898 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) || 9899 LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() || 9900 S.inTemplateInstantiation()) 9901 return; 9902 9903 // Comparisons between two array types are ill-formed for operator<=>, so 9904 // we shouldn't emit any additional warnings about it. 9905 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType()) 9906 return; 9907 9908 // For non-floating point types, check for self-comparisons of the form 9909 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 9910 // often indicate logic errors in the program. 9911 // 9912 // NOTE: Don't warn about comparison expressions resulting from macro 9913 // expansion. Also don't warn about comparisons which are only self 9914 // comparisons within a template instantiation. The warnings should catch 9915 // obvious cases in the definition of the template anyways. The idea is to 9916 // warn when the typed comparison operator will always evaluate to the same 9917 // result. 9918 ValueDecl *DL = getCompareDecl(LHSStripped); 9919 ValueDecl *DR = getCompareDecl(RHSStripped); 9920 if (DL && DR && declaresSameEntity(DL, DR)) { 9921 StringRef Result; 9922 switch (Opc) { 9923 case BO_EQ: case BO_LE: case BO_GE: 9924 Result = "true"; 9925 break; 9926 case BO_NE: case BO_LT: case BO_GT: 9927 Result = "false"; 9928 break; 9929 case BO_Cmp: 9930 Result = "'std::strong_ordering::equal'"; 9931 break; 9932 default: 9933 break; 9934 } 9935 S.DiagRuntimeBehavior(Loc, nullptr, 9936 S.PDiag(diag::warn_comparison_always) 9937 << 0 /*self-comparison*/ << !Result.empty() 9938 << Result); 9939 } else if (DL && DR && 9940 DL->getType()->isArrayType() && DR->getType()->isArrayType() && 9941 !DL->isWeak() && !DR->isWeak()) { 9942 // What is it always going to evaluate to? 9943 StringRef Result; 9944 switch(Opc) { 9945 case BO_EQ: // e.g. array1 == array2 9946 Result = "false"; 9947 break; 9948 case BO_NE: // e.g. array1 != array2 9949 Result = "true"; 9950 break; 9951 default: // e.g. array1 <= array2 9952 // The best we can say is 'a constant' 9953 break; 9954 } 9955 S.DiagRuntimeBehavior(Loc, nullptr, 9956 S.PDiag(diag::warn_comparison_always) 9957 << 1 /*array comparison*/ 9958 << !Result.empty() << Result); 9959 } 9960 9961 if (isa<CastExpr>(LHSStripped)) 9962 LHSStripped = LHSStripped->IgnoreParenCasts(); 9963 if (isa<CastExpr>(RHSStripped)) 9964 RHSStripped = RHSStripped->IgnoreParenCasts(); 9965 9966 // Warn about comparisons against a string constant (unless the other 9967 // operand is null); the user probably wants strcmp. 9968 Expr *LiteralString = nullptr; 9969 Expr *LiteralStringStripped = nullptr; 9970 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) && 9971 !RHSStripped->isNullPointerConstant(S.Context, 9972 Expr::NPC_ValueDependentIsNull)) { 9973 LiteralString = LHS; 9974 LiteralStringStripped = LHSStripped; 9975 } else if ((isa<StringLiteral>(RHSStripped) || 9976 isa<ObjCEncodeExpr>(RHSStripped)) && 9977 !LHSStripped->isNullPointerConstant(S.Context, 9978 Expr::NPC_ValueDependentIsNull)) { 9979 LiteralString = RHS; 9980 LiteralStringStripped = RHSStripped; 9981 } 9982 9983 if (LiteralString) { 9984 S.DiagRuntimeBehavior(Loc, nullptr, 9985 S.PDiag(diag::warn_stringcompare) 9986 << isa<ObjCEncodeExpr>(LiteralStringStripped) 9987 << LiteralString->getSourceRange()); 9988 } 9989 } 9990 9991 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) { 9992 switch (CK) { 9993 default: { 9994 #ifndef NDEBUG 9995 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK) 9996 << "\n"; 9997 #endif 9998 llvm_unreachable("unhandled cast kind"); 9999 } 10000 case CK_UserDefinedConversion: 10001 return ICK_Identity; 10002 case CK_LValueToRValue: 10003 return ICK_Lvalue_To_Rvalue; 10004 case CK_ArrayToPointerDecay: 10005 return ICK_Array_To_Pointer; 10006 case CK_FunctionToPointerDecay: 10007 return ICK_Function_To_Pointer; 10008 case CK_IntegralCast: 10009 return ICK_Integral_Conversion; 10010 case CK_FloatingCast: 10011 return ICK_Floating_Conversion; 10012 case CK_IntegralToFloating: 10013 case CK_FloatingToIntegral: 10014 return ICK_Floating_Integral; 10015 case CK_IntegralComplexCast: 10016 case CK_FloatingComplexCast: 10017 case CK_FloatingComplexToIntegralComplex: 10018 case CK_IntegralComplexToFloatingComplex: 10019 return ICK_Complex_Conversion; 10020 case CK_FloatingComplexToReal: 10021 case CK_FloatingRealToComplex: 10022 case CK_IntegralComplexToReal: 10023 case CK_IntegralRealToComplex: 10024 return ICK_Complex_Real; 10025 } 10026 } 10027 10028 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, 10029 QualType FromType, 10030 SourceLocation Loc) { 10031 // Check for a narrowing implicit conversion. 10032 StandardConversionSequence SCS; 10033 SCS.setAsIdentityConversion(); 10034 SCS.setToType(0, FromType); 10035 SCS.setToType(1, ToType); 10036 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 10037 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind()); 10038 10039 APValue PreNarrowingValue; 10040 QualType PreNarrowingType; 10041 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue, 10042 PreNarrowingType, 10043 /*IgnoreFloatToIntegralConversion*/ true)) { 10044 case NK_Dependent_Narrowing: 10045 // Implicit conversion to a narrower type, but the expression is 10046 // value-dependent so we can't tell whether it's actually narrowing. 10047 case NK_Not_Narrowing: 10048 return false; 10049 10050 case NK_Constant_Narrowing: 10051 // Implicit conversion to a narrower type, and the value is not a constant 10052 // expression. 10053 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10054 << /*Constant*/ 1 10055 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType; 10056 return true; 10057 10058 case NK_Variable_Narrowing: 10059 // Implicit conversion to a narrower type, and the value is not a constant 10060 // expression. 10061 case NK_Type_Narrowing: 10062 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing) 10063 << /*Constant*/ 0 << FromType << ToType; 10064 // TODO: It's not a constant expression, but what if the user intended it 10065 // to be? Can we produce notes to help them figure out why it isn't? 10066 return true; 10067 } 10068 llvm_unreachable("unhandled case in switch"); 10069 } 10070 10071 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, 10072 ExprResult &LHS, 10073 ExprResult &RHS, 10074 SourceLocation Loc) { 10075 using CCT = ComparisonCategoryType; 10076 10077 QualType LHSType = LHS.get()->getType(); 10078 QualType RHSType = RHS.get()->getType(); 10079 // Dig out the original argument type and expression before implicit casts 10080 // were applied. These are the types/expressions we need to check the 10081 // [expr.spaceship] requirements against. 10082 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts(); 10083 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts(); 10084 QualType LHSStrippedType = LHSStripped.get()->getType(); 10085 QualType RHSStrippedType = RHSStripped.get()->getType(); 10086 10087 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the 10088 // other is not, the program is ill-formed. 10089 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) { 10090 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10091 return QualType(); 10092 } 10093 10094 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() + 10095 RHSStrippedType->isEnumeralType(); 10096 if (NumEnumArgs == 1) { 10097 bool LHSIsEnum = LHSStrippedType->isEnumeralType(); 10098 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType; 10099 if (OtherTy->hasFloatingRepresentation()) { 10100 S.InvalidOperands(Loc, LHSStripped, RHSStripped); 10101 return QualType(); 10102 } 10103 } 10104 if (NumEnumArgs == 2) { 10105 // C++2a [expr.spaceship]p5: If both operands have the same enumeration 10106 // type E, the operator yields the result of converting the operands 10107 // to the underlying type of E and applying <=> to the converted operands. 10108 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) { 10109 S.InvalidOperands(Loc, LHS, RHS); 10110 return QualType(); 10111 } 10112 QualType IntType = 10113 LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType(); 10114 assert(IntType->isArithmeticType()); 10115 10116 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we 10117 // promote the boolean type, and all other promotable integer types, to 10118 // avoid this. 10119 if (IntType->isPromotableIntegerType()) 10120 IntType = S.Context.getPromotedIntegerType(IntType); 10121 10122 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast); 10123 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast); 10124 LHSType = RHSType = IntType; 10125 } 10126 10127 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the 10128 // usual arithmetic conversions are applied to the operands. 10129 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10130 if (LHS.isInvalid() || RHS.isInvalid()) 10131 return QualType(); 10132 if (Type.isNull()) 10133 return S.InvalidOperands(Loc, LHS, RHS); 10134 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10135 10136 bool HasNarrowing = checkThreeWayNarrowingConversion( 10137 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc()); 10138 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType, 10139 RHS.get()->getBeginLoc()); 10140 if (HasNarrowing) 10141 return QualType(); 10142 10143 assert(!Type.isNull() && "composite type for <=> has not been set"); 10144 10145 auto TypeKind = [&]() { 10146 if (const ComplexType *CT = Type->getAs<ComplexType>()) { 10147 if (CT->getElementType()->hasFloatingRepresentation()) 10148 return CCT::WeakEquality; 10149 return CCT::StrongEquality; 10150 } 10151 if (Type->isIntegralOrEnumerationType()) 10152 return CCT::StrongOrdering; 10153 if (Type->hasFloatingRepresentation()) 10154 return CCT::PartialOrdering; 10155 llvm_unreachable("other types are unimplemented"); 10156 }(); 10157 10158 return S.CheckComparisonCategoryType(TypeKind, Loc); 10159 } 10160 10161 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, 10162 ExprResult &RHS, 10163 SourceLocation Loc, 10164 BinaryOperatorKind Opc) { 10165 if (Opc == BO_Cmp) 10166 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc); 10167 10168 // C99 6.5.8p3 / C99 6.5.9p4 10169 QualType Type = S.UsualArithmeticConversions(LHS, RHS); 10170 if (LHS.isInvalid() || RHS.isInvalid()) 10171 return QualType(); 10172 if (Type.isNull()) 10173 return S.InvalidOperands(Loc, LHS, RHS); 10174 assert(Type->isArithmeticType() || Type->isEnumeralType()); 10175 10176 checkEnumComparison(S, Loc, LHS.get(), RHS.get()); 10177 10178 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc)) 10179 return S.InvalidOperands(Loc, LHS, RHS); 10180 10181 // Check for comparisons of floating point operands using != and ==. 10182 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc)) 10183 S.CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10184 10185 // The result of comparisons is 'bool' in C++, 'int' in C. 10186 return S.Context.getLogicalOperationType(); 10187 } 10188 10189 // C99 6.5.8, C++ [expr.rel] 10190 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, 10191 SourceLocation Loc, 10192 BinaryOperatorKind Opc) { 10193 bool IsRelational = BinaryOperator::isRelationalOp(Opc); 10194 bool IsThreeWay = Opc == BO_Cmp; 10195 auto IsAnyPointerType = [](ExprResult E) { 10196 QualType Ty = E.get()->getType(); 10197 return Ty->isPointerType() || Ty->isMemberPointerType(); 10198 }; 10199 10200 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer 10201 // type, array-to-pointer, ..., conversions are performed on both operands to 10202 // bring them to their composite type. 10203 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before 10204 // any type-related checks. 10205 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) { 10206 LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 10207 if (LHS.isInvalid()) 10208 return QualType(); 10209 RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 10210 if (RHS.isInvalid()) 10211 return QualType(); 10212 } else { 10213 LHS = DefaultLvalueConversion(LHS.get()); 10214 if (LHS.isInvalid()) 10215 return QualType(); 10216 RHS = DefaultLvalueConversion(RHS.get()); 10217 if (RHS.isInvalid()) 10218 return QualType(); 10219 } 10220 10221 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true); 10222 10223 // Handle vector comparisons separately. 10224 if (LHS.get()->getType()->isVectorType() || 10225 RHS.get()->getType()->isVectorType()) 10226 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc); 10227 10228 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10229 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10230 10231 QualType LHSType = LHS.get()->getType(); 10232 QualType RHSType = RHS.get()->getType(); 10233 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) && 10234 (RHSType->isArithmeticType() || RHSType->isEnumeralType())) 10235 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc); 10236 10237 const Expr::NullPointerConstantKind LHSNullKind = 10238 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10239 const Expr::NullPointerConstantKind RHSNullKind = 10240 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); 10241 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull; 10242 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull; 10243 10244 auto computeResultTy = [&]() { 10245 if (Opc != BO_Cmp) 10246 return Context.getLogicalOperationType(); 10247 assert(getLangOpts().CPlusPlus); 10248 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())); 10249 10250 QualType CompositeTy = LHS.get()->getType(); 10251 assert(!CompositeTy->isReferenceType()); 10252 10253 auto buildResultTy = [&](ComparisonCategoryType Kind) { 10254 return CheckComparisonCategoryType(Kind, Loc); 10255 }; 10256 10257 // C++2a [expr.spaceship]p7: If the composite pointer type is a function 10258 // pointer type, a pointer-to-member type, or std::nullptr_t, the 10259 // result is of type std::strong_equality 10260 if (CompositeTy->isFunctionPointerType() || 10261 CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType()) 10262 // FIXME: consider making the function pointer case produce 10263 // strong_ordering not strong_equality, per P0946R0-Jax18 discussion 10264 // and direction polls 10265 return buildResultTy(ComparisonCategoryType::StrongEquality); 10266 10267 // C++2a [expr.spaceship]p8: If the composite pointer type is an object 10268 // pointer type, p <=> q is of type std::strong_ordering. 10269 if (CompositeTy->isPointerType()) { 10270 // P0946R0: Comparisons between a null pointer constant and an object 10271 // pointer result in std::strong_equality 10272 if (LHSIsNull != RHSIsNull) 10273 return buildResultTy(ComparisonCategoryType::StrongEquality); 10274 return buildResultTy(ComparisonCategoryType::StrongOrdering); 10275 } 10276 // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed. 10277 // TODO: Extend support for operator<=> to ObjC types. 10278 return InvalidOperands(Loc, LHS, RHS); 10279 }; 10280 10281 10282 if (!IsRelational && LHSIsNull != RHSIsNull) { 10283 bool IsEquality = Opc == BO_EQ; 10284 if (RHSIsNull) 10285 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality, 10286 RHS.get()->getSourceRange()); 10287 else 10288 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality, 10289 LHS.get()->getSourceRange()); 10290 } 10291 10292 if ((LHSType->isIntegerType() && !LHSIsNull) || 10293 (RHSType->isIntegerType() && !RHSIsNull)) { 10294 // Skip normal pointer conversion checks in this case; we have better 10295 // diagnostics for this below. 10296 } else if (getLangOpts().CPlusPlus) { 10297 // Equality comparison of a function pointer to a void pointer is invalid, 10298 // but we allow it as an extension. 10299 // FIXME: If we really want to allow this, should it be part of composite 10300 // pointer type computation so it works in conditionals too? 10301 if (!IsRelational && 10302 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) || 10303 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) { 10304 // This is a gcc extension compatibility comparison. 10305 // In a SFINAE context, we treat this as a hard error to maintain 10306 // conformance with the C++ standard. 10307 diagnoseFunctionPointerToVoidComparison( 10308 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext()); 10309 10310 if (isSFINAEContext()) 10311 return QualType(); 10312 10313 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10314 return computeResultTy(); 10315 } 10316 10317 // C++ [expr.eq]p2: 10318 // If at least one operand is a pointer [...] bring them to their 10319 // composite pointer type. 10320 // C++ [expr.spaceship]p6 10321 // If at least one of the operands is of pointer type, [...] bring them 10322 // to their composite pointer type. 10323 // C++ [expr.rel]p2: 10324 // If both operands are pointers, [...] bring them to their composite 10325 // pointer type. 10326 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >= 10327 (IsRelational ? 2 : 1) && 10328 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() || 10329 RHSType->isObjCObjectPointerType()))) { 10330 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10331 return QualType(); 10332 return computeResultTy(); 10333 } 10334 } else if (LHSType->isPointerType() && 10335 RHSType->isPointerType()) { // C99 6.5.8p2 10336 // All of the following pointer-related warnings are GCC extensions, except 10337 // when handling null pointer constants. 10338 QualType LCanPointeeTy = 10339 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10340 QualType RCanPointeeTy = 10341 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType(); 10342 10343 // C99 6.5.9p2 and C99 6.5.8p2 10344 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(), 10345 RCanPointeeTy.getUnqualifiedType())) { 10346 // Valid unless a relational comparison of function pointers 10347 if (IsRelational && LCanPointeeTy->isFunctionType()) { 10348 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers) 10349 << LHSType << RHSType << LHS.get()->getSourceRange() 10350 << RHS.get()->getSourceRange(); 10351 } 10352 } else if (!IsRelational && 10353 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) { 10354 // Valid unless comparison between non-null pointer and function pointer 10355 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType()) 10356 && !LHSIsNull && !RHSIsNull) 10357 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, 10358 /*isError*/false); 10359 } else { 10360 // Invalid 10361 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false); 10362 } 10363 if (LCanPointeeTy != RCanPointeeTy) { 10364 // Treat NULL constant as a special case in OpenCL. 10365 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) { 10366 const PointerType *LHSPtr = LHSType->getAs<PointerType>(); 10367 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) { 10368 Diag(Loc, 10369 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers) 10370 << LHSType << RHSType << 0 /* comparison */ 10371 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 10372 } 10373 } 10374 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace(); 10375 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace(); 10376 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion 10377 : CK_BitCast; 10378 if (LHSIsNull && !RHSIsNull) 10379 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind); 10380 else 10381 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind); 10382 } 10383 return computeResultTy(); 10384 } 10385 10386 if (getLangOpts().CPlusPlus) { 10387 // C++ [expr.eq]p4: 10388 // Two operands of type std::nullptr_t or one operand of type 10389 // std::nullptr_t and the other a null pointer constant compare equal. 10390 if (!IsRelational && LHSIsNull && RHSIsNull) { 10391 if (LHSType->isNullPtrType()) { 10392 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10393 return computeResultTy(); 10394 } 10395 if (RHSType->isNullPtrType()) { 10396 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10397 return computeResultTy(); 10398 } 10399 } 10400 10401 // Comparison of Objective-C pointers and block pointers against nullptr_t. 10402 // These aren't covered by the composite pointer type rules. 10403 if (!IsRelational && RHSType->isNullPtrType() && 10404 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) { 10405 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10406 return computeResultTy(); 10407 } 10408 if (!IsRelational && LHSType->isNullPtrType() && 10409 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) { 10410 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10411 return computeResultTy(); 10412 } 10413 10414 if (IsRelational && 10415 ((LHSType->isNullPtrType() && RHSType->isPointerType()) || 10416 (RHSType->isNullPtrType() && LHSType->isPointerType()))) { 10417 // HACK: Relational comparison of nullptr_t against a pointer type is 10418 // invalid per DR583, but we allow it within std::less<> and friends, 10419 // since otherwise common uses of it break. 10420 // FIXME: Consider removing this hack once LWG fixes std::less<> and 10421 // friends to have std::nullptr_t overload candidates. 10422 DeclContext *DC = CurContext; 10423 if (isa<FunctionDecl>(DC)) 10424 DC = DC->getParent(); 10425 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) { 10426 if (CTSD->isInStdNamespace() && 10427 llvm::StringSwitch<bool>(CTSD->getName()) 10428 .Cases("less", "less_equal", "greater", "greater_equal", true) 10429 .Default(false)) { 10430 if (RHSType->isNullPtrType()) 10431 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10432 else 10433 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10434 return computeResultTy(); 10435 } 10436 } 10437 } 10438 10439 // C++ [expr.eq]p2: 10440 // If at least one operand is a pointer to member, [...] bring them to 10441 // their composite pointer type. 10442 if (!IsRelational && 10443 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) { 10444 if (convertPointersToCompositeType(*this, Loc, LHS, RHS)) 10445 return QualType(); 10446 else 10447 return computeResultTy(); 10448 } 10449 } 10450 10451 // Handle block pointer types. 10452 if (!IsRelational && LHSType->isBlockPointerType() && 10453 RHSType->isBlockPointerType()) { 10454 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType(); 10455 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType(); 10456 10457 if (!LHSIsNull && !RHSIsNull && 10458 !Context.typesAreCompatible(lpointee, rpointee)) { 10459 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10460 << LHSType << RHSType << LHS.get()->getSourceRange() 10461 << RHS.get()->getSourceRange(); 10462 } 10463 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10464 return computeResultTy(); 10465 } 10466 10467 // Allow block pointers to be compared with null pointer constants. 10468 if (!IsRelational 10469 && ((LHSType->isBlockPointerType() && RHSType->isPointerType()) 10470 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) { 10471 if (!LHSIsNull && !RHSIsNull) { 10472 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>() 10473 ->getPointeeType()->isVoidType()) 10474 || (LHSType->isPointerType() && LHSType->castAs<PointerType>() 10475 ->getPointeeType()->isVoidType()))) 10476 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks) 10477 << LHSType << RHSType << LHS.get()->getSourceRange() 10478 << RHS.get()->getSourceRange(); 10479 } 10480 if (LHSIsNull && !RHSIsNull) 10481 LHS = ImpCastExprToType(LHS.get(), RHSType, 10482 RHSType->isPointerType() ? CK_BitCast 10483 : CK_AnyPointerToBlockPointerCast); 10484 else 10485 RHS = ImpCastExprToType(RHS.get(), LHSType, 10486 LHSType->isPointerType() ? CK_BitCast 10487 : CK_AnyPointerToBlockPointerCast); 10488 return computeResultTy(); 10489 } 10490 10491 if (LHSType->isObjCObjectPointerType() || 10492 RHSType->isObjCObjectPointerType()) { 10493 const PointerType *LPT = LHSType->getAs<PointerType>(); 10494 const PointerType *RPT = RHSType->getAs<PointerType>(); 10495 if (LPT || RPT) { 10496 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false; 10497 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false; 10498 10499 if (!LPtrToVoid && !RPtrToVoid && 10500 !Context.typesAreCompatible(LHSType, RHSType)) { 10501 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10502 /*isError*/false); 10503 } 10504 if (LHSIsNull && !RHSIsNull) { 10505 Expr *E = LHS.get(); 10506 if (getLangOpts().ObjCAutoRefCount) 10507 CheckObjCConversion(SourceRange(), RHSType, E, 10508 CCK_ImplicitConversion); 10509 LHS = ImpCastExprToType(E, RHSType, 10510 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10511 } 10512 else { 10513 Expr *E = RHS.get(); 10514 if (getLangOpts().ObjCAutoRefCount) 10515 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, 10516 /*Diagnose=*/true, 10517 /*DiagnoseCFAudited=*/false, Opc); 10518 RHS = ImpCastExprToType(E, LHSType, 10519 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast); 10520 } 10521 return computeResultTy(); 10522 } 10523 if (LHSType->isObjCObjectPointerType() && 10524 RHSType->isObjCObjectPointerType()) { 10525 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType)) 10526 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, 10527 /*isError*/false); 10528 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) 10529 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc); 10530 10531 if (LHSIsNull && !RHSIsNull) 10532 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast); 10533 else 10534 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast); 10535 return computeResultTy(); 10536 } 10537 10538 if (!IsRelational && LHSType->isBlockPointerType() && 10539 RHSType->isBlockCompatibleObjCPointerType(Context)) { 10540 LHS = ImpCastExprToType(LHS.get(), RHSType, 10541 CK_BlockPointerToObjCPointerCast); 10542 return computeResultTy(); 10543 } else if (!IsRelational && 10544 LHSType->isBlockCompatibleObjCPointerType(Context) && 10545 RHSType->isBlockPointerType()) { 10546 RHS = ImpCastExprToType(RHS.get(), LHSType, 10547 CK_BlockPointerToObjCPointerCast); 10548 return computeResultTy(); 10549 } 10550 } 10551 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) || 10552 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) { 10553 unsigned DiagID = 0; 10554 bool isError = false; 10555 if (LangOpts.DebuggerSupport) { 10556 // Under a debugger, allow the comparison of pointers to integers, 10557 // since users tend to want to compare addresses. 10558 } else if ((LHSIsNull && LHSType->isIntegerType()) || 10559 (RHSIsNull && RHSType->isIntegerType())) { 10560 if (IsRelational) { 10561 isError = getLangOpts().CPlusPlus; 10562 DiagID = 10563 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero 10564 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero; 10565 } 10566 } else if (getLangOpts().CPlusPlus) { 10567 DiagID = diag::err_typecheck_comparison_of_pointer_integer; 10568 isError = true; 10569 } else if (IsRelational) 10570 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer; 10571 else 10572 DiagID = diag::ext_typecheck_comparison_of_pointer_integer; 10573 10574 if (DiagID) { 10575 Diag(Loc, DiagID) 10576 << LHSType << RHSType << LHS.get()->getSourceRange() 10577 << RHS.get()->getSourceRange(); 10578 if (isError) 10579 return QualType(); 10580 } 10581 10582 if (LHSType->isIntegerType()) 10583 LHS = ImpCastExprToType(LHS.get(), RHSType, 10584 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10585 else 10586 RHS = ImpCastExprToType(RHS.get(), LHSType, 10587 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer); 10588 return computeResultTy(); 10589 } 10590 10591 // Handle block pointers. 10592 if (!IsRelational && RHSIsNull 10593 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) { 10594 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10595 return computeResultTy(); 10596 } 10597 if (!IsRelational && LHSIsNull 10598 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) { 10599 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10600 return computeResultTy(); 10601 } 10602 10603 if (getLangOpts().OpenCLVersion >= 200) { 10604 if (LHSType->isClkEventT() && RHSType->isClkEventT()) { 10605 return computeResultTy(); 10606 } 10607 10608 if (LHSType->isQueueT() && RHSType->isQueueT()) { 10609 return computeResultTy(); 10610 } 10611 10612 if (LHSIsNull && RHSType->isQueueT()) { 10613 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer); 10614 return computeResultTy(); 10615 } 10616 10617 if (LHSType->isQueueT() && RHSIsNull) { 10618 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer); 10619 return computeResultTy(); 10620 } 10621 } 10622 10623 return InvalidOperands(Loc, LHS, RHS); 10624 } 10625 10626 // Return a signed ext_vector_type that is of identical size and number of 10627 // elements. For floating point vectors, return an integer type of identical 10628 // size and number of elements. In the non ext_vector_type case, search from 10629 // the largest type to the smallest type to avoid cases where long long == long, 10630 // where long gets picked over long long. 10631 QualType Sema::GetSignedVectorType(QualType V) { 10632 const VectorType *VTy = V->getAs<VectorType>(); 10633 unsigned TypeSize = Context.getTypeSize(VTy->getElementType()); 10634 10635 if (isa<ExtVectorType>(VTy)) { 10636 if (TypeSize == Context.getTypeSize(Context.CharTy)) 10637 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements()); 10638 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10639 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements()); 10640 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10641 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements()); 10642 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10643 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements()); 10644 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) && 10645 "Unhandled vector element size in vector compare"); 10646 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements()); 10647 } 10648 10649 if (TypeSize == Context.getTypeSize(Context.LongLongTy)) 10650 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(), 10651 VectorType::GenericVector); 10652 else if (TypeSize == Context.getTypeSize(Context.LongTy)) 10653 return Context.getVectorType(Context.LongTy, VTy->getNumElements(), 10654 VectorType::GenericVector); 10655 else if (TypeSize == Context.getTypeSize(Context.IntTy)) 10656 return Context.getVectorType(Context.IntTy, VTy->getNumElements(), 10657 VectorType::GenericVector); 10658 else if (TypeSize == Context.getTypeSize(Context.ShortTy)) 10659 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(), 10660 VectorType::GenericVector); 10661 assert(TypeSize == Context.getTypeSize(Context.CharTy) && 10662 "Unhandled vector element size in vector compare"); 10663 return Context.getVectorType(Context.CharTy, VTy->getNumElements(), 10664 VectorType::GenericVector); 10665 } 10666 10667 /// CheckVectorCompareOperands - vector comparisons are a clang extension that 10668 /// operates on extended vector types. Instead of producing an IntTy result, 10669 /// like a scalar comparison, a vector comparison produces a vector of integer 10670 /// types. 10671 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 10672 SourceLocation Loc, 10673 BinaryOperatorKind Opc) { 10674 // Check to make sure we're operating on vectors of the same type and width, 10675 // Allowing one side to be a scalar of element type. 10676 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false, 10677 /*AllowBothBool*/true, 10678 /*AllowBoolConversions*/getLangOpts().ZVector); 10679 if (vType.isNull()) 10680 return vType; 10681 10682 QualType LHSType = LHS.get()->getType(); 10683 10684 // If AltiVec, the comparison results in a numeric type, i.e. 10685 // bool for C++, int for C 10686 if (getLangOpts().AltiVec && 10687 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector) 10688 return Context.getLogicalOperationType(); 10689 10690 // For non-floating point types, check for self-comparisons of the form 10691 // x == x, x != x, x < x, etc. These always evaluate to a constant, and 10692 // often indicate logic errors in the program. 10693 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc); 10694 10695 // Check for comparisons of floating point operands using != and ==. 10696 if (BinaryOperator::isEqualityOp(Opc) && 10697 LHSType->hasFloatingRepresentation()) { 10698 assert(RHS.get()->getType()->hasFloatingRepresentation()); 10699 CheckFloatComparison(Loc, LHS.get(), RHS.get()); 10700 } 10701 10702 // Return a signed type for the vector. 10703 return GetSignedVectorType(vType); 10704 } 10705 10706 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10707 SourceLocation Loc) { 10708 // Ensure that either both operands are of the same vector type, or 10709 // one operand is of a vector type and the other is of its element type. 10710 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false, 10711 /*AllowBothBool*/true, 10712 /*AllowBoolConversions*/false); 10713 if (vType.isNull()) 10714 return InvalidOperands(Loc, LHS, RHS); 10715 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 && 10716 vType->hasFloatingRepresentation()) 10717 return InvalidOperands(Loc, LHS, RHS); 10718 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the 10719 // usage of the logical operators && and || with vectors in C. This 10720 // check could be notionally dropped. 10721 if (!getLangOpts().CPlusPlus && 10722 !(isa<ExtVectorType>(vType->getAs<VectorType>()))) 10723 return InvalidLogicalVectorOperands(Loc, LHS, RHS); 10724 10725 return GetSignedVectorType(LHS.get()->getType()); 10726 } 10727 10728 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, 10729 SourceLocation Loc, 10730 BinaryOperatorKind Opc) { 10731 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false); 10732 10733 bool IsCompAssign = 10734 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign; 10735 10736 if (LHS.get()->getType()->isVectorType() || 10737 RHS.get()->getType()->isVectorType()) { 10738 if (LHS.get()->getType()->hasIntegerRepresentation() && 10739 RHS.get()->getType()->hasIntegerRepresentation()) 10740 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign, 10741 /*AllowBothBool*/true, 10742 /*AllowBoolConversions*/getLangOpts().ZVector); 10743 return InvalidOperands(Loc, LHS, RHS); 10744 } 10745 10746 if (Opc == BO_And) 10747 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc); 10748 10749 ExprResult LHSResult = LHS, RHSResult = RHS; 10750 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult, 10751 IsCompAssign); 10752 if (LHSResult.isInvalid() || RHSResult.isInvalid()) 10753 return QualType(); 10754 LHS = LHSResult.get(); 10755 RHS = RHSResult.get(); 10756 10757 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType()) 10758 return compType; 10759 return InvalidOperands(Loc, LHS, RHS); 10760 } 10761 10762 // C99 6.5.[13,14] 10763 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, 10764 SourceLocation Loc, 10765 BinaryOperatorKind Opc) { 10766 // Check vector operands differently. 10767 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType()) 10768 return CheckVectorLogicalOperands(LHS, RHS, Loc); 10769 10770 // Diagnose cases where the user write a logical and/or but probably meant a 10771 // bitwise one. We do this when the LHS is a non-bool integer and the RHS 10772 // is a constant. 10773 if (LHS.get()->getType()->isIntegerType() && 10774 !LHS.get()->getType()->isBooleanType() && 10775 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() && 10776 // Don't warn in macros or template instantiations. 10777 !Loc.isMacroID() && !inTemplateInstantiation()) { 10778 // If the RHS can be constant folded, and if it constant folds to something 10779 // that isn't 0 or 1 (which indicate a potential logical operation that 10780 // happened to fold to true/false) then warn. 10781 // Parens on the RHS are ignored. 10782 Expr::EvalResult EVResult; 10783 if (RHS.get()->EvaluateAsInt(EVResult, Context)) { 10784 llvm::APSInt Result = EVResult.Val.getInt(); 10785 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() && 10786 !RHS.get()->getExprLoc().isMacroID()) || 10787 (Result != 0 && Result != 1)) { 10788 Diag(Loc, diag::warn_logical_instead_of_bitwise) 10789 << RHS.get()->getSourceRange() 10790 << (Opc == BO_LAnd ? "&&" : "||"); 10791 // Suggest replacing the logical operator with the bitwise version 10792 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator) 10793 << (Opc == BO_LAnd ? "&" : "|") 10794 << FixItHint::CreateReplacement(SourceRange( 10795 Loc, getLocForEndOfToken(Loc)), 10796 Opc == BO_LAnd ? "&" : "|"); 10797 if (Opc == BO_LAnd) 10798 // Suggest replacing "Foo() && kNonZero" with "Foo()" 10799 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant) 10800 << FixItHint::CreateRemoval( 10801 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()), 10802 RHS.get()->getEndLoc())); 10803 } 10804 } 10805 } 10806 10807 if (!Context.getLangOpts().CPlusPlus) { 10808 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do 10809 // not operate on the built-in scalar and vector float types. 10810 if (Context.getLangOpts().OpenCL && 10811 Context.getLangOpts().OpenCLVersion < 120) { 10812 if (LHS.get()->getType()->isFloatingType() || 10813 RHS.get()->getType()->isFloatingType()) 10814 return InvalidOperands(Loc, LHS, RHS); 10815 } 10816 10817 LHS = UsualUnaryConversions(LHS.get()); 10818 if (LHS.isInvalid()) 10819 return QualType(); 10820 10821 RHS = UsualUnaryConversions(RHS.get()); 10822 if (RHS.isInvalid()) 10823 return QualType(); 10824 10825 if (!LHS.get()->getType()->isScalarType() || 10826 !RHS.get()->getType()->isScalarType()) 10827 return InvalidOperands(Loc, LHS, RHS); 10828 10829 return Context.IntTy; 10830 } 10831 10832 // The following is safe because we only use this method for 10833 // non-overloadable operands. 10834 10835 // C++ [expr.log.and]p1 10836 // C++ [expr.log.or]p1 10837 // The operands are both contextually converted to type bool. 10838 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get()); 10839 if (LHSRes.isInvalid()) 10840 return InvalidOperands(Loc, LHS, RHS); 10841 LHS = LHSRes; 10842 10843 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get()); 10844 if (RHSRes.isInvalid()) 10845 return InvalidOperands(Loc, LHS, RHS); 10846 RHS = RHSRes; 10847 10848 // C++ [expr.log.and]p2 10849 // C++ [expr.log.or]p2 10850 // The result is a bool. 10851 return Context.BoolTy; 10852 } 10853 10854 static bool IsReadonlyMessage(Expr *E, Sema &S) { 10855 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 10856 if (!ME) return false; 10857 if (!isa<FieldDecl>(ME->getMemberDecl())) return false; 10858 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>( 10859 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts()); 10860 if (!Base) return false; 10861 return Base->getMethodDecl() != nullptr; 10862 } 10863 10864 /// Is the given expression (which must be 'const') a reference to a 10865 /// variable which was originally non-const, but which has become 10866 /// 'const' due to being captured within a block? 10867 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda }; 10868 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) { 10869 assert(E->isLValue() && E->getType().isConstQualified()); 10870 E = E->IgnoreParens(); 10871 10872 // Must be a reference to a declaration from an enclosing scope. 10873 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 10874 if (!DRE) return NCCK_None; 10875 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None; 10876 10877 // The declaration must be a variable which is not declared 'const'. 10878 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl()); 10879 if (!var) return NCCK_None; 10880 if (var->getType().isConstQualified()) return NCCK_None; 10881 assert(var->hasLocalStorage() && "capture added 'const' to non-local?"); 10882 10883 // Decide whether the first capture was for a block or a lambda. 10884 DeclContext *DC = S.CurContext, *Prev = nullptr; 10885 // Decide whether the first capture was for a block or a lambda. 10886 while (DC) { 10887 // For init-capture, it is possible that the variable belongs to the 10888 // template pattern of the current context. 10889 if (auto *FD = dyn_cast<FunctionDecl>(DC)) 10890 if (var->isInitCapture() && 10891 FD->getTemplateInstantiationPattern() == var->getDeclContext()) 10892 break; 10893 if (DC == var->getDeclContext()) 10894 break; 10895 Prev = DC; 10896 DC = DC->getParent(); 10897 } 10898 // Unless we have an init-capture, we've gone one step too far. 10899 if (!var->isInitCapture()) 10900 DC = Prev; 10901 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda); 10902 } 10903 10904 static bool IsTypeModifiable(QualType Ty, bool IsDereference) { 10905 Ty = Ty.getNonReferenceType(); 10906 if (IsDereference && Ty->isPointerType()) 10907 Ty = Ty->getPointeeType(); 10908 return !Ty.isConstQualified(); 10909 } 10910 10911 // Update err_typecheck_assign_const and note_typecheck_assign_const 10912 // when this enum is changed. 10913 enum { 10914 ConstFunction, 10915 ConstVariable, 10916 ConstMember, 10917 ConstMethod, 10918 NestedConstMember, 10919 ConstUnknown, // Keep as last element 10920 }; 10921 10922 /// Emit the "read-only variable not assignable" error and print notes to give 10923 /// more information about why the variable is not assignable, such as pointing 10924 /// to the declaration of a const variable, showing that a method is const, or 10925 /// that the function is returning a const reference. 10926 static void DiagnoseConstAssignment(Sema &S, const Expr *E, 10927 SourceLocation Loc) { 10928 SourceRange ExprRange = E->getSourceRange(); 10929 10930 // Only emit one error on the first const found. All other consts will emit 10931 // a note to the error. 10932 bool DiagnosticEmitted = false; 10933 10934 // Track if the current expression is the result of a dereference, and if the 10935 // next checked expression is the result of a dereference. 10936 bool IsDereference = false; 10937 bool NextIsDereference = false; 10938 10939 // Loop to process MemberExpr chains. 10940 while (true) { 10941 IsDereference = NextIsDereference; 10942 10943 E = E->IgnoreImplicit()->IgnoreParenImpCasts(); 10944 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 10945 NextIsDereference = ME->isArrow(); 10946 const ValueDecl *VD = ME->getMemberDecl(); 10947 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) { 10948 // Mutable fields can be modified even if the class is const. 10949 if (Field->isMutable()) { 10950 assert(DiagnosticEmitted && "Expected diagnostic not emitted."); 10951 break; 10952 } 10953 10954 if (!IsTypeModifiable(Field->getType(), IsDereference)) { 10955 if (!DiagnosticEmitted) { 10956 S.Diag(Loc, diag::err_typecheck_assign_const) 10957 << ExprRange << ConstMember << false /*static*/ << Field 10958 << Field->getType(); 10959 DiagnosticEmitted = true; 10960 } 10961 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10962 << ConstMember << false /*static*/ << Field << Field->getType() 10963 << Field->getSourceRange(); 10964 } 10965 E = ME->getBase(); 10966 continue; 10967 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) { 10968 if (VDecl->getType().isConstQualified()) { 10969 if (!DiagnosticEmitted) { 10970 S.Diag(Loc, diag::err_typecheck_assign_const) 10971 << ExprRange << ConstMember << true /*static*/ << VDecl 10972 << VDecl->getType(); 10973 DiagnosticEmitted = true; 10974 } 10975 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 10976 << ConstMember << true /*static*/ << VDecl << VDecl->getType() 10977 << VDecl->getSourceRange(); 10978 } 10979 // Static fields do not inherit constness from parents. 10980 break; 10981 } 10982 break; // End MemberExpr 10983 } else if (const ArraySubscriptExpr *ASE = 10984 dyn_cast<ArraySubscriptExpr>(E)) { 10985 E = ASE->getBase()->IgnoreParenImpCasts(); 10986 continue; 10987 } else if (const ExtVectorElementExpr *EVE = 10988 dyn_cast<ExtVectorElementExpr>(E)) { 10989 E = EVE->getBase()->IgnoreParenImpCasts(); 10990 continue; 10991 } 10992 break; 10993 } 10994 10995 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10996 // Function calls 10997 const FunctionDecl *FD = CE->getDirectCallee(); 10998 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) { 10999 if (!DiagnosticEmitted) { 11000 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11001 << ConstFunction << FD; 11002 DiagnosticEmitted = true; 11003 } 11004 S.Diag(FD->getReturnTypeSourceRange().getBegin(), 11005 diag::note_typecheck_assign_const) 11006 << ConstFunction << FD << FD->getReturnType() 11007 << FD->getReturnTypeSourceRange(); 11008 } 11009 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 11010 // Point to variable declaration. 11011 if (const ValueDecl *VD = DRE->getDecl()) { 11012 if (!IsTypeModifiable(VD->getType(), IsDereference)) { 11013 if (!DiagnosticEmitted) { 11014 S.Diag(Loc, diag::err_typecheck_assign_const) 11015 << ExprRange << ConstVariable << VD << VD->getType(); 11016 DiagnosticEmitted = true; 11017 } 11018 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const) 11019 << ConstVariable << VD << VD->getType() << VD->getSourceRange(); 11020 } 11021 } 11022 } else if (isa<CXXThisExpr>(E)) { 11023 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) { 11024 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 11025 if (MD->isConst()) { 11026 if (!DiagnosticEmitted) { 11027 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange 11028 << ConstMethod << MD; 11029 DiagnosticEmitted = true; 11030 } 11031 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const) 11032 << ConstMethod << MD << MD->getSourceRange(); 11033 } 11034 } 11035 } 11036 } 11037 11038 if (DiagnosticEmitted) 11039 return; 11040 11041 // Can't determine a more specific message, so display the generic error. 11042 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown; 11043 } 11044 11045 enum OriginalExprKind { 11046 OEK_Variable, 11047 OEK_Member, 11048 OEK_LValue 11049 }; 11050 11051 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, 11052 const RecordType *Ty, 11053 SourceLocation Loc, SourceRange Range, 11054 OriginalExprKind OEK, 11055 bool &DiagnosticEmitted, 11056 bool IsNested = false) { 11057 // We walk the record hierarchy breadth-first to ensure that we print 11058 // diagnostics in field nesting order. 11059 // First, check every field for constness. 11060 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 11061 if (Field->getType().isConstQualified()) { 11062 if (!DiagnosticEmitted) { 11063 S.Diag(Loc, diag::err_typecheck_assign_const) 11064 << Range << NestedConstMember << OEK << VD 11065 << IsNested << Field; 11066 DiagnosticEmitted = true; 11067 } 11068 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const) 11069 << NestedConstMember << IsNested << Field 11070 << Field->getType() << Field->getSourceRange(); 11071 } 11072 } 11073 // Then, recurse. 11074 for (const FieldDecl *Field : Ty->getDecl()->fields()) { 11075 QualType FTy = Field->getType(); 11076 if (const RecordType *FieldRecTy = FTy->getAs<RecordType>()) 11077 DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range, 11078 OEK, DiagnosticEmitted, true); 11079 } 11080 } 11081 11082 /// Emit an error for the case where a record we are trying to assign to has a 11083 /// const-qualified field somewhere in its hierarchy. 11084 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E, 11085 SourceLocation Loc) { 11086 QualType Ty = E->getType(); 11087 assert(Ty->isRecordType() && "lvalue was not record?"); 11088 SourceRange Range = E->getSourceRange(); 11089 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>(); 11090 bool DiagEmitted = false; 11091 11092 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) 11093 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc, 11094 Range, OEK_Member, DiagEmitted); 11095 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11096 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc, 11097 Range, OEK_Variable, DiagEmitted); 11098 else 11099 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc, 11100 Range, OEK_LValue, DiagEmitted); 11101 if (!DiagEmitted) 11102 DiagnoseConstAssignment(S, E, Loc); 11103 } 11104 11105 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not, 11106 /// emit an error and return true. If so, return false. 11107 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) { 11108 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject)); 11109 11110 S.CheckShadowingDeclModification(E, Loc); 11111 11112 SourceLocation OrigLoc = Loc; 11113 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context, 11114 &Loc); 11115 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S)) 11116 IsLV = Expr::MLV_InvalidMessageExpression; 11117 if (IsLV == Expr::MLV_Valid) 11118 return false; 11119 11120 unsigned DiagID = 0; 11121 bool NeedType = false; 11122 switch (IsLV) { // C99 6.5.16p2 11123 case Expr::MLV_ConstQualified: 11124 // Use a specialized diagnostic when we're assigning to an object 11125 // from an enclosing function or block. 11126 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) { 11127 if (NCCK == NCCK_Block) 11128 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue; 11129 else 11130 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue; 11131 break; 11132 } 11133 11134 // In ARC, use some specialized diagnostics for occasions where we 11135 // infer 'const'. These are always pseudo-strong variables. 11136 if (S.getLangOpts().ObjCAutoRefCount) { 11137 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()); 11138 if (declRef && isa<VarDecl>(declRef->getDecl())) { 11139 VarDecl *var = cast<VarDecl>(declRef->getDecl()); 11140 11141 // Use the normal diagnostic if it's pseudo-__strong but the 11142 // user actually wrote 'const'. 11143 if (var->isARCPseudoStrong() && 11144 (!var->getTypeSourceInfo() || 11145 !var->getTypeSourceInfo()->getType().isConstQualified())) { 11146 // There are two pseudo-strong cases: 11147 // - self 11148 ObjCMethodDecl *method = S.getCurMethodDecl(); 11149 if (method && var == method->getSelfDecl()) 11150 DiagID = method->isClassMethod() 11151 ? diag::err_typecheck_arc_assign_self_class_method 11152 : diag::err_typecheck_arc_assign_self; 11153 11154 // - fast enumeration variables 11155 else 11156 DiagID = diag::err_typecheck_arr_assign_enumeration; 11157 11158 SourceRange Assign; 11159 if (Loc != OrigLoc) 11160 Assign = SourceRange(OrigLoc, OrigLoc); 11161 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11162 // We need to preserve the AST regardless, so migration tool 11163 // can do its job. 11164 return false; 11165 } 11166 } 11167 } 11168 11169 // If none of the special cases above are triggered, then this is a 11170 // simple const assignment. 11171 if (DiagID == 0) { 11172 DiagnoseConstAssignment(S, E, Loc); 11173 return true; 11174 } 11175 11176 break; 11177 case Expr::MLV_ConstAddrSpace: 11178 DiagnoseConstAssignment(S, E, Loc); 11179 return true; 11180 case Expr::MLV_ConstQualifiedField: 11181 DiagnoseRecursiveConstFields(S, E, Loc); 11182 return true; 11183 case Expr::MLV_ArrayType: 11184 case Expr::MLV_ArrayTemporary: 11185 DiagID = diag::err_typecheck_array_not_modifiable_lvalue; 11186 NeedType = true; 11187 break; 11188 case Expr::MLV_NotObjectType: 11189 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue; 11190 NeedType = true; 11191 break; 11192 case Expr::MLV_LValueCast: 11193 DiagID = diag::err_typecheck_lvalue_casts_not_supported; 11194 break; 11195 case Expr::MLV_Valid: 11196 llvm_unreachable("did not take early return for MLV_Valid"); 11197 case Expr::MLV_InvalidExpression: 11198 case Expr::MLV_MemberFunction: 11199 case Expr::MLV_ClassTemporary: 11200 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue; 11201 break; 11202 case Expr::MLV_IncompleteType: 11203 case Expr::MLV_IncompleteVoidType: 11204 return S.RequireCompleteType(Loc, E->getType(), 11205 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E); 11206 case Expr::MLV_DuplicateVectorComponents: 11207 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue; 11208 break; 11209 case Expr::MLV_NoSetterProperty: 11210 llvm_unreachable("readonly properties should be processed differently"); 11211 case Expr::MLV_InvalidMessageExpression: 11212 DiagID = diag::err_readonly_message_assignment; 11213 break; 11214 case Expr::MLV_SubObjCPropertySetting: 11215 DiagID = diag::err_no_subobject_property_setting; 11216 break; 11217 } 11218 11219 SourceRange Assign; 11220 if (Loc != OrigLoc) 11221 Assign = SourceRange(OrigLoc, OrigLoc); 11222 if (NeedType) 11223 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign; 11224 else 11225 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign; 11226 return true; 11227 } 11228 11229 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, 11230 SourceLocation Loc, 11231 Sema &Sema) { 11232 if (Sema.inTemplateInstantiation()) 11233 return; 11234 if (Sema.isUnevaluatedContext()) 11235 return; 11236 if (Loc.isInvalid() || Loc.isMacroID()) 11237 return; 11238 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID()) 11239 return; 11240 11241 // C / C++ fields 11242 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr); 11243 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr); 11244 if (ML && MR) { 11245 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))) 11246 return; 11247 const ValueDecl *LHSDecl = 11248 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl()); 11249 const ValueDecl *RHSDecl = 11250 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl()); 11251 if (LHSDecl != RHSDecl) 11252 return; 11253 if (LHSDecl->getType().isVolatileQualified()) 11254 return; 11255 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 11256 if (RefTy->getPointeeType().isVolatileQualified()) 11257 return; 11258 11259 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0; 11260 } 11261 11262 // Objective-C instance variables 11263 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr); 11264 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr); 11265 if (OL && OR && OL->getDecl() == OR->getDecl()) { 11266 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts()); 11267 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts()); 11268 if (RL && RR && RL->getDecl() == RR->getDecl()) 11269 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1; 11270 } 11271 } 11272 11273 // C99 6.5.16.1 11274 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, 11275 SourceLocation Loc, 11276 QualType CompoundType) { 11277 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)); 11278 11279 // Verify that LHS is a modifiable lvalue, and emit error if not. 11280 if (CheckForModifiableLvalue(LHSExpr, Loc, *this)) 11281 return QualType(); 11282 11283 QualType LHSType = LHSExpr->getType(); 11284 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() : 11285 CompoundType; 11286 // OpenCL v1.2 s6.1.1.1 p2: 11287 // The half data type can only be used to declare a pointer to a buffer that 11288 // contains half values 11289 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") && 11290 LHSType->isHalfType()) { 11291 Diag(Loc, diag::err_opencl_half_load_store) << 1 11292 << LHSType.getUnqualifiedType(); 11293 return QualType(); 11294 } 11295 11296 AssignConvertType ConvTy; 11297 if (CompoundType.isNull()) { 11298 Expr *RHSCheck = RHS.get(); 11299 11300 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this); 11301 11302 QualType LHSTy(LHSType); 11303 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 11304 if (RHS.isInvalid()) 11305 return QualType(); 11306 // Special case of NSObject attributes on c-style pointer types. 11307 if (ConvTy == IncompatiblePointer && 11308 ((Context.isObjCNSObjectType(LHSType) && 11309 RHSType->isObjCObjectPointerType()) || 11310 (Context.isObjCNSObjectType(RHSType) && 11311 LHSType->isObjCObjectPointerType()))) 11312 ConvTy = Compatible; 11313 11314 if (ConvTy == Compatible && 11315 LHSType->isObjCObjectType()) 11316 Diag(Loc, diag::err_objc_object_assignment) 11317 << LHSType; 11318 11319 // If the RHS is a unary plus or minus, check to see if they = and + are 11320 // right next to each other. If so, the user may have typo'd "x =+ 4" 11321 // instead of "x += 4". 11322 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck)) 11323 RHSCheck = ICE->getSubExpr(); 11324 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) { 11325 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) && 11326 Loc.isFileID() && UO->getOperatorLoc().isFileID() && 11327 // Only if the two operators are exactly adjacent. 11328 Loc.getLocWithOffset(1) == UO->getOperatorLoc() && 11329 // And there is a space or other character before the subexpr of the 11330 // unary +/-. We don't want to warn on "x=-1". 11331 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() && 11332 UO->getSubExpr()->getBeginLoc().isFileID()) { 11333 Diag(Loc, diag::warn_not_compound_assign) 11334 << (UO->getOpcode() == UO_Plus ? "+" : "-") 11335 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()); 11336 } 11337 } 11338 11339 if (ConvTy == Compatible) { 11340 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) { 11341 // Warn about retain cycles where a block captures the LHS, but 11342 // not if the LHS is a simple variable into which the block is 11343 // being stored...unless that variable can be captured by reference! 11344 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts(); 11345 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS); 11346 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>()) 11347 checkRetainCycles(LHSExpr, RHS.get()); 11348 } 11349 11350 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong || 11351 LHSType.isNonWeakInMRRWithObjCWeak(Context)) { 11352 // It is safe to assign a weak reference into a strong variable. 11353 // Although this code can still have problems: 11354 // id x = self.weakProp; 11355 // id y = self.weakProp; 11356 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11357 // paths through the function. This should be revisited if 11358 // -Wrepeated-use-of-weak is made flow-sensitive. 11359 // For ObjCWeak only, we do not warn if the assign is to a non-weak 11360 // variable, which will be valid for the current autorelease scope. 11361 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11362 RHS.get()->getBeginLoc())) 11363 getCurFunction()->markSafeWeakUse(RHS.get()); 11364 11365 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) { 11366 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get()); 11367 } 11368 } 11369 } else { 11370 // Compound assignment "x += y" 11371 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType); 11372 } 11373 11374 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, 11375 RHS.get(), AA_Assigning)) 11376 return QualType(); 11377 11378 CheckForNullPointerDereference(*this, LHSExpr); 11379 11380 // C99 6.5.16p3: The type of an assignment expression is the type of the 11381 // left operand unless the left operand has qualified type, in which case 11382 // it is the unqualified version of the type of the left operand. 11383 // C99 6.5.16.1p2: In simple assignment, the value of the right operand 11384 // is converted to the type of the assignment expression (above). 11385 // C++ 5.17p1: the type of the assignment expression is that of its left 11386 // operand. 11387 return (getLangOpts().CPlusPlus 11388 ? LHSType : LHSType.getUnqualifiedType()); 11389 } 11390 11391 // Only ignore explicit casts to void. 11392 static bool IgnoreCommaOperand(const Expr *E) { 11393 E = E->IgnoreParens(); 11394 11395 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 11396 if (CE->getCastKind() == CK_ToVoid) { 11397 return true; 11398 } 11399 11400 // static_cast<void> on a dependent type will not show up as CK_ToVoid. 11401 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() && 11402 CE->getSubExpr()->getType()->isDependentType()) { 11403 return true; 11404 } 11405 } 11406 11407 return false; 11408 } 11409 11410 // Look for instances where it is likely the comma operator is confused with 11411 // another operator. There is a whitelist of acceptable expressions for the 11412 // left hand side of the comma operator, otherwise emit a warning. 11413 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) { 11414 // No warnings in macros 11415 if (Loc.isMacroID()) 11416 return; 11417 11418 // Don't warn in template instantiations. 11419 if (inTemplateInstantiation()) 11420 return; 11421 11422 // Scope isn't fine-grained enough to whitelist the specific cases, so 11423 // instead, skip more than needed, then call back into here with the 11424 // CommaVisitor in SemaStmt.cpp. 11425 // The whitelisted locations are the initialization and increment portions 11426 // of a for loop. The additional checks are on the condition of 11427 // if statements, do/while loops, and for loops. 11428 // Differences in scope flags for C89 mode requires the extra logic. 11429 const unsigned ForIncrementFlags = 11430 getLangOpts().C99 || getLangOpts().CPlusPlus 11431 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope 11432 : Scope::ContinueScope | Scope::BreakScope; 11433 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope; 11434 const unsigned ScopeFlags = getCurScope()->getFlags(); 11435 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags || 11436 (ScopeFlags & ForInitFlags) == ForInitFlags) 11437 return; 11438 11439 // If there are multiple comma operators used together, get the RHS of the 11440 // of the comma operator as the LHS. 11441 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) { 11442 if (BO->getOpcode() != BO_Comma) 11443 break; 11444 LHS = BO->getRHS(); 11445 } 11446 11447 // Only allow some expressions on LHS to not warn. 11448 if (IgnoreCommaOperand(LHS)) 11449 return; 11450 11451 Diag(Loc, diag::warn_comma_operator); 11452 Diag(LHS->getBeginLoc(), diag::note_cast_to_void) 11453 << LHS->getSourceRange() 11454 << FixItHint::CreateInsertion(LHS->getBeginLoc(), 11455 LangOpts.CPlusPlus ? "static_cast<void>(" 11456 : "(void)(") 11457 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()), 11458 ")"); 11459 } 11460 11461 // C99 6.5.17 11462 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, 11463 SourceLocation Loc) { 11464 LHS = S.CheckPlaceholderExpr(LHS.get()); 11465 RHS = S.CheckPlaceholderExpr(RHS.get()); 11466 if (LHS.isInvalid() || RHS.isInvalid()) 11467 return QualType(); 11468 11469 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its 11470 // operands, but not unary promotions. 11471 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1). 11472 11473 // So we treat the LHS as a ignored value, and in C++ we allow the 11474 // containing site to determine what should be done with the RHS. 11475 LHS = S.IgnoredValueConversions(LHS.get()); 11476 if (LHS.isInvalid()) 11477 return QualType(); 11478 11479 S.DiagnoseUnusedExprResult(LHS.get()); 11480 11481 if (!S.getLangOpts().CPlusPlus) { 11482 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get()); 11483 if (RHS.isInvalid()) 11484 return QualType(); 11485 if (!RHS.get()->getType()->isVoidType()) 11486 S.RequireCompleteType(Loc, RHS.get()->getType(), 11487 diag::err_incomplete_type); 11488 } 11489 11490 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc)) 11491 S.DiagnoseCommaOperator(LHS.get(), Loc); 11492 11493 return RHS.get()->getType(); 11494 } 11495 11496 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine 11497 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions. 11498 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, 11499 ExprValueKind &VK, 11500 ExprObjectKind &OK, 11501 SourceLocation OpLoc, 11502 bool IsInc, bool IsPrefix) { 11503 if (Op->isTypeDependent()) 11504 return S.Context.DependentTy; 11505 11506 QualType ResType = Op->getType(); 11507 // Atomic types can be used for increment / decrement where the non-atomic 11508 // versions can, so ignore the _Atomic() specifier for the purpose of 11509 // checking. 11510 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>()) 11511 ResType = ResAtomicType->getValueType(); 11512 11513 assert(!ResType.isNull() && "no type for increment/decrement expression"); 11514 11515 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) { 11516 // Decrement of bool is not allowed. 11517 if (!IsInc) { 11518 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange(); 11519 return QualType(); 11520 } 11521 // Increment of bool sets it to true, but is deprecated. 11522 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool 11523 : diag::warn_increment_bool) 11524 << Op->getSourceRange(); 11525 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) { 11526 // Error on enum increments and decrements in C++ mode 11527 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType; 11528 return QualType(); 11529 } else if (ResType->isRealType()) { 11530 // OK! 11531 } else if (ResType->isPointerType()) { 11532 // C99 6.5.2.4p2, 6.5.6p2 11533 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op)) 11534 return QualType(); 11535 } else if (ResType->isObjCObjectPointerType()) { 11536 // On modern runtimes, ObjC pointer arithmetic is forbidden. 11537 // Otherwise, we just need a complete type. 11538 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) || 11539 checkArithmeticOnObjCPointer(S, OpLoc, Op)) 11540 return QualType(); 11541 } else if (ResType->isAnyComplexType()) { 11542 // C99 does not support ++/-- on complex types, we allow as an extension. 11543 S.Diag(OpLoc, diag::ext_integer_increment_complex) 11544 << ResType << Op->getSourceRange(); 11545 } else if (ResType->isPlaceholderType()) { 11546 ExprResult PR = S.CheckPlaceholderExpr(Op); 11547 if (PR.isInvalid()) return QualType(); 11548 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc, 11549 IsInc, IsPrefix); 11550 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) { 11551 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 ) 11552 } else if (S.getLangOpts().ZVector && ResType->isVectorType() && 11553 (ResType->getAs<VectorType>()->getVectorKind() != 11554 VectorType::AltiVecBool)) { 11555 // The z vector extensions allow ++ and -- for non-bool vectors. 11556 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() && 11557 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) { 11558 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types. 11559 } else { 11560 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement) 11561 << ResType << int(IsInc) << Op->getSourceRange(); 11562 return QualType(); 11563 } 11564 // At this point, we know we have a real, complex or pointer type. 11565 // Now make sure the operand is a modifiable lvalue. 11566 if (CheckForModifiableLvalue(Op, OpLoc, S)) 11567 return QualType(); 11568 // In C++, a prefix increment is the same type as the operand. Otherwise 11569 // (in C or with postfix), the increment is the unqualified type of the 11570 // operand. 11571 if (IsPrefix && S.getLangOpts().CPlusPlus) { 11572 VK = VK_LValue; 11573 OK = Op->getObjectKind(); 11574 return ResType; 11575 } else { 11576 VK = VK_RValue; 11577 return ResType.getUnqualifiedType(); 11578 } 11579 } 11580 11581 11582 /// getPrimaryDecl - Helper function for CheckAddressOfOperand(). 11583 /// This routine allows us to typecheck complex/recursive expressions 11584 /// where the declaration is needed for type checking. We only need to 11585 /// handle cases when the expression references a function designator 11586 /// or is an lvalue. Here are some examples: 11587 /// - &(x) => x 11588 /// - &*****f => f for f a function designator. 11589 /// - &s.xx => s 11590 /// - &s.zz[1].yy -> s, if zz is an array 11591 /// - *(x + 1) -> x, if x is an array 11592 /// - &"123"[2] -> 0 11593 /// - & __real__ x -> x 11594 static ValueDecl *getPrimaryDecl(Expr *E) { 11595 switch (E->getStmtClass()) { 11596 case Stmt::DeclRefExprClass: 11597 return cast<DeclRefExpr>(E)->getDecl(); 11598 case Stmt::MemberExprClass: 11599 // If this is an arrow operator, the address is an offset from 11600 // the base's value, so the object the base refers to is 11601 // irrelevant. 11602 if (cast<MemberExpr>(E)->isArrow()) 11603 return nullptr; 11604 // Otherwise, the expression refers to a part of the base 11605 return getPrimaryDecl(cast<MemberExpr>(E)->getBase()); 11606 case Stmt::ArraySubscriptExprClass: { 11607 // FIXME: This code shouldn't be necessary! We should catch the implicit 11608 // promotion of register arrays earlier. 11609 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase(); 11610 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) { 11611 if (ICE->getSubExpr()->getType()->isArrayType()) 11612 return getPrimaryDecl(ICE->getSubExpr()); 11613 } 11614 return nullptr; 11615 } 11616 case Stmt::UnaryOperatorClass: { 11617 UnaryOperator *UO = cast<UnaryOperator>(E); 11618 11619 switch(UO->getOpcode()) { 11620 case UO_Real: 11621 case UO_Imag: 11622 case UO_Extension: 11623 return getPrimaryDecl(UO->getSubExpr()); 11624 default: 11625 return nullptr; 11626 } 11627 } 11628 case Stmt::ParenExprClass: 11629 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr()); 11630 case Stmt::ImplicitCastExprClass: 11631 // If the result of an implicit cast is an l-value, we care about 11632 // the sub-expression; otherwise, the result here doesn't matter. 11633 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr()); 11634 default: 11635 return nullptr; 11636 } 11637 } 11638 11639 namespace { 11640 enum { 11641 AO_Bit_Field = 0, 11642 AO_Vector_Element = 1, 11643 AO_Property_Expansion = 2, 11644 AO_Register_Variable = 3, 11645 AO_No_Error = 4 11646 }; 11647 } 11648 /// Diagnose invalid operand for address of operations. 11649 /// 11650 /// \param Type The type of operand which cannot have its address taken. 11651 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, 11652 Expr *E, unsigned Type) { 11653 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange(); 11654 } 11655 11656 /// CheckAddressOfOperand - The operand of & must be either a function 11657 /// designator or an lvalue designating an object. If it is an lvalue, the 11658 /// object cannot be declared with storage class register or be a bit field. 11659 /// Note: The usual conversions are *not* applied to the operand of the & 11660 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue. 11661 /// In C++, the operand might be an overloaded function name, in which case 11662 /// we allow the '&' but retain the overloaded-function type. 11663 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) { 11664 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){ 11665 if (PTy->getKind() == BuiltinType::Overload) { 11666 Expr *E = OrigOp.get()->IgnoreParens(); 11667 if (!isa<OverloadExpr>(E)) { 11668 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf); 11669 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function) 11670 << OrigOp.get()->getSourceRange(); 11671 return QualType(); 11672 } 11673 11674 OverloadExpr *Ovl = cast<OverloadExpr>(E); 11675 if (isa<UnresolvedMemberExpr>(Ovl)) 11676 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) { 11677 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11678 << OrigOp.get()->getSourceRange(); 11679 return QualType(); 11680 } 11681 11682 return Context.OverloadTy; 11683 } 11684 11685 if (PTy->getKind() == BuiltinType::UnknownAny) 11686 return Context.UnknownAnyTy; 11687 11688 if (PTy->getKind() == BuiltinType::BoundMember) { 11689 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11690 << OrigOp.get()->getSourceRange(); 11691 return QualType(); 11692 } 11693 11694 OrigOp = CheckPlaceholderExpr(OrigOp.get()); 11695 if (OrigOp.isInvalid()) return QualType(); 11696 } 11697 11698 if (OrigOp.get()->isTypeDependent()) 11699 return Context.DependentTy; 11700 11701 assert(!OrigOp.get()->getType()->isPlaceholderType()); 11702 11703 // Make sure to ignore parentheses in subsequent checks 11704 Expr *op = OrigOp.get()->IgnoreParens(); 11705 11706 // In OpenCL captures for blocks called as lambda functions 11707 // are located in the private address space. Blocks used in 11708 // enqueue_kernel can be located in a different address space 11709 // depending on a vendor implementation. Thus preventing 11710 // taking an address of the capture to avoid invalid AS casts. 11711 if (LangOpts.OpenCL) { 11712 auto* VarRef = dyn_cast<DeclRefExpr>(op); 11713 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) { 11714 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture); 11715 return QualType(); 11716 } 11717 } 11718 11719 if (getLangOpts().C99) { 11720 // Implement C99-only parts of addressof rules. 11721 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) { 11722 if (uOp->getOpcode() == UO_Deref) 11723 // Per C99 6.5.3.2, the address of a deref always returns a valid result 11724 // (assuming the deref expression is valid). 11725 return uOp->getSubExpr()->getType(); 11726 } 11727 // Technically, there should be a check for array subscript 11728 // expressions here, but the result of one is always an lvalue anyway. 11729 } 11730 ValueDecl *dcl = getPrimaryDecl(op); 11731 11732 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl)) 11733 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11734 op->getBeginLoc())) 11735 return QualType(); 11736 11737 Expr::LValueClassification lval = op->ClassifyLValue(Context); 11738 unsigned AddressOfError = AO_No_Error; 11739 11740 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 11741 bool sfinae = (bool)isSFINAEContext(); 11742 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary 11743 : diag::ext_typecheck_addrof_temporary) 11744 << op->getType() << op->getSourceRange(); 11745 if (sfinae) 11746 return QualType(); 11747 // Materialize the temporary as an lvalue so that we can take its address. 11748 OrigOp = op = 11749 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true); 11750 } else if (isa<ObjCSelectorExpr>(op)) { 11751 return Context.getPointerType(op->getType()); 11752 } else if (lval == Expr::LV_MemberFunction) { 11753 // If it's an instance method, make a member pointer. 11754 // The expression must have exactly the form &A::foo. 11755 11756 // If the underlying expression isn't a decl ref, give up. 11757 if (!isa<DeclRefExpr>(op)) { 11758 Diag(OpLoc, diag::err_invalid_form_pointer_member_function) 11759 << OrigOp.get()->getSourceRange(); 11760 return QualType(); 11761 } 11762 DeclRefExpr *DRE = cast<DeclRefExpr>(op); 11763 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl()); 11764 11765 // The id-expression was parenthesized. 11766 if (OrigOp.get() != DRE) { 11767 Diag(OpLoc, diag::err_parens_pointer_member_function) 11768 << OrigOp.get()->getSourceRange(); 11769 11770 // The method was named without a qualifier. 11771 } else if (!DRE->getQualifier()) { 11772 if (MD->getParent()->getName().empty()) 11773 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11774 << op->getSourceRange(); 11775 else { 11776 SmallString<32> Str; 11777 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str); 11778 Diag(OpLoc, diag::err_unqualified_pointer_member_function) 11779 << op->getSourceRange() 11780 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual); 11781 } 11782 } 11783 11784 // Taking the address of a dtor is illegal per C++ [class.dtor]p2. 11785 if (isa<CXXDestructorDecl>(MD)) 11786 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange(); 11787 11788 QualType MPTy = Context.getMemberPointerType( 11789 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr()); 11790 // Under the MS ABI, lock down the inheritance model now. 11791 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11792 (void)isCompleteType(OpLoc, MPTy); 11793 return MPTy; 11794 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) { 11795 // C99 6.5.3.2p1 11796 // The operand must be either an l-value or a function designator 11797 if (!op->getType()->isFunctionType()) { 11798 // Use a special diagnostic for loads from property references. 11799 if (isa<PseudoObjectExpr>(op)) { 11800 AddressOfError = AO_Property_Expansion; 11801 } else { 11802 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof) 11803 << op->getType() << op->getSourceRange(); 11804 return QualType(); 11805 } 11806 } 11807 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1 11808 // The operand cannot be a bit-field 11809 AddressOfError = AO_Bit_Field; 11810 } else if (op->getObjectKind() == OK_VectorComponent) { 11811 // The operand cannot be an element of a vector 11812 AddressOfError = AO_Vector_Element; 11813 } else if (dcl) { // C99 6.5.3.2p1 11814 // We have an lvalue with a decl. Make sure the decl is not declared 11815 // with the register storage-class specifier. 11816 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) { 11817 // in C++ it is not error to take address of a register 11818 // variable (c++03 7.1.1P3) 11819 if (vd->getStorageClass() == SC_Register && 11820 !getLangOpts().CPlusPlus) { 11821 AddressOfError = AO_Register_Variable; 11822 } 11823 } else if (isa<MSPropertyDecl>(dcl)) { 11824 AddressOfError = AO_Property_Expansion; 11825 } else if (isa<FunctionTemplateDecl>(dcl)) { 11826 return Context.OverloadTy; 11827 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) { 11828 // Okay: we can take the address of a field. 11829 // Could be a pointer to member, though, if there is an explicit 11830 // scope qualifier for the class. 11831 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) { 11832 DeclContext *Ctx = dcl->getDeclContext(); 11833 if (Ctx && Ctx->isRecord()) { 11834 if (dcl->getType()->isReferenceType()) { 11835 Diag(OpLoc, 11836 diag::err_cannot_form_pointer_to_member_of_reference_type) 11837 << dcl->getDeclName() << dcl->getType(); 11838 return QualType(); 11839 } 11840 11841 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion()) 11842 Ctx = Ctx->getParent(); 11843 11844 QualType MPTy = Context.getMemberPointerType( 11845 op->getType(), 11846 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr()); 11847 // Under the MS ABI, lock down the inheritance model now. 11848 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11849 (void)isCompleteType(OpLoc, MPTy); 11850 return MPTy; 11851 } 11852 } 11853 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) && 11854 !isa<BindingDecl>(dcl)) 11855 llvm_unreachable("Unknown/unexpected decl type"); 11856 } 11857 11858 if (AddressOfError != AO_No_Error) { 11859 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError); 11860 return QualType(); 11861 } 11862 11863 if (lval == Expr::LV_IncompleteVoidType) { 11864 // Taking the address of a void variable is technically illegal, but we 11865 // allow it in cases which are otherwise valid. 11866 // Example: "extern void x; void* y = &x;". 11867 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange(); 11868 } 11869 11870 // If the operand has type "type", the result has type "pointer to type". 11871 if (op->getType()->isObjCObjectType()) 11872 return Context.getObjCObjectPointerType(op->getType()); 11873 11874 CheckAddressOfPackedMember(op); 11875 11876 return Context.getPointerType(op->getType()); 11877 } 11878 11879 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) { 11880 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp); 11881 if (!DRE) 11882 return; 11883 const Decl *D = DRE->getDecl(); 11884 if (!D) 11885 return; 11886 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D); 11887 if (!Param) 11888 return; 11889 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext())) 11890 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>()) 11891 return; 11892 if (FunctionScopeInfo *FD = S.getCurFunction()) 11893 if (!FD->ModifiedNonNullParams.count(Param)) 11894 FD->ModifiedNonNullParams.insert(Param); 11895 } 11896 11897 /// CheckIndirectionOperand - Type check unary indirection (prefix '*'). 11898 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, 11899 SourceLocation OpLoc) { 11900 if (Op->isTypeDependent()) 11901 return S.Context.DependentTy; 11902 11903 ExprResult ConvResult = S.UsualUnaryConversions(Op); 11904 if (ConvResult.isInvalid()) 11905 return QualType(); 11906 Op = ConvResult.get(); 11907 QualType OpTy = Op->getType(); 11908 QualType Result; 11909 11910 if (isa<CXXReinterpretCastExpr>(Op)) { 11911 QualType OpOrigType = Op->IgnoreParenCasts()->getType(); 11912 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true, 11913 Op->getSourceRange()); 11914 } 11915 11916 if (const PointerType *PT = OpTy->getAs<PointerType>()) 11917 { 11918 Result = PT->getPointeeType(); 11919 } 11920 else if (const ObjCObjectPointerType *OPT = 11921 OpTy->getAs<ObjCObjectPointerType>()) 11922 Result = OPT->getPointeeType(); 11923 else { 11924 ExprResult PR = S.CheckPlaceholderExpr(Op); 11925 if (PR.isInvalid()) return QualType(); 11926 if (PR.get() != Op) 11927 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc); 11928 } 11929 11930 if (Result.isNull()) { 11931 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer) 11932 << OpTy << Op->getSourceRange(); 11933 return QualType(); 11934 } 11935 11936 // Note that per both C89 and C99, indirection is always legal, even if Result 11937 // is an incomplete type or void. It would be possible to warn about 11938 // dereferencing a void pointer, but it's completely well-defined, and such a 11939 // warning is unlikely to catch any mistakes. In C++, indirection is not valid 11940 // for pointers to 'void' but is fine for any other pointer type: 11941 // 11942 // C++ [expr.unary.op]p1: 11943 // [...] the expression to which [the unary * operator] is applied shall 11944 // be a pointer to an object type, or a pointer to a function type 11945 if (S.getLangOpts().CPlusPlus && Result->isVoidType()) 11946 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer) 11947 << OpTy << Op->getSourceRange(); 11948 11949 // Dereferences are usually l-values... 11950 VK = VK_LValue; 11951 11952 // ...except that certain expressions are never l-values in C. 11953 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType()) 11954 VK = VK_RValue; 11955 11956 return Result; 11957 } 11958 11959 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) { 11960 BinaryOperatorKind Opc; 11961 switch (Kind) { 11962 default: llvm_unreachable("Unknown binop!"); 11963 case tok::periodstar: Opc = BO_PtrMemD; break; 11964 case tok::arrowstar: Opc = BO_PtrMemI; break; 11965 case tok::star: Opc = BO_Mul; break; 11966 case tok::slash: Opc = BO_Div; break; 11967 case tok::percent: Opc = BO_Rem; break; 11968 case tok::plus: Opc = BO_Add; break; 11969 case tok::minus: Opc = BO_Sub; break; 11970 case tok::lessless: Opc = BO_Shl; break; 11971 case tok::greatergreater: Opc = BO_Shr; break; 11972 case tok::lessequal: Opc = BO_LE; break; 11973 case tok::less: Opc = BO_LT; break; 11974 case tok::greaterequal: Opc = BO_GE; break; 11975 case tok::greater: Opc = BO_GT; break; 11976 case tok::exclaimequal: Opc = BO_NE; break; 11977 case tok::equalequal: Opc = BO_EQ; break; 11978 case tok::spaceship: Opc = BO_Cmp; break; 11979 case tok::amp: Opc = BO_And; break; 11980 case tok::caret: Opc = BO_Xor; break; 11981 case tok::pipe: Opc = BO_Or; break; 11982 case tok::ampamp: Opc = BO_LAnd; break; 11983 case tok::pipepipe: Opc = BO_LOr; break; 11984 case tok::equal: Opc = BO_Assign; break; 11985 case tok::starequal: Opc = BO_MulAssign; break; 11986 case tok::slashequal: Opc = BO_DivAssign; break; 11987 case tok::percentequal: Opc = BO_RemAssign; break; 11988 case tok::plusequal: Opc = BO_AddAssign; break; 11989 case tok::minusequal: Opc = BO_SubAssign; break; 11990 case tok::lesslessequal: Opc = BO_ShlAssign; break; 11991 case tok::greatergreaterequal: Opc = BO_ShrAssign; break; 11992 case tok::ampequal: Opc = BO_AndAssign; break; 11993 case tok::caretequal: Opc = BO_XorAssign; break; 11994 case tok::pipeequal: Opc = BO_OrAssign; break; 11995 case tok::comma: Opc = BO_Comma; break; 11996 } 11997 return Opc; 11998 } 11999 12000 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode( 12001 tok::TokenKind Kind) { 12002 UnaryOperatorKind Opc; 12003 switch (Kind) { 12004 default: llvm_unreachable("Unknown unary op!"); 12005 case tok::plusplus: Opc = UO_PreInc; break; 12006 case tok::minusminus: Opc = UO_PreDec; break; 12007 case tok::amp: Opc = UO_AddrOf; break; 12008 case tok::star: Opc = UO_Deref; break; 12009 case tok::plus: Opc = UO_Plus; break; 12010 case tok::minus: Opc = UO_Minus; break; 12011 case tok::tilde: Opc = UO_Not; break; 12012 case tok::exclaim: Opc = UO_LNot; break; 12013 case tok::kw___real: Opc = UO_Real; break; 12014 case tok::kw___imag: Opc = UO_Imag; break; 12015 case tok::kw___extension__: Opc = UO_Extension; break; 12016 } 12017 return Opc; 12018 } 12019 12020 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself. 12021 /// This warning suppressed in the event of macro expansions. 12022 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, 12023 SourceLocation OpLoc, bool IsBuiltin) { 12024 if (S.inTemplateInstantiation()) 12025 return; 12026 if (S.isUnevaluatedContext()) 12027 return; 12028 if (OpLoc.isInvalid() || OpLoc.isMacroID()) 12029 return; 12030 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 12031 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 12032 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 12033 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 12034 if (!LHSDeclRef || !RHSDeclRef || 12035 LHSDeclRef->getLocation().isMacroID() || 12036 RHSDeclRef->getLocation().isMacroID()) 12037 return; 12038 const ValueDecl *LHSDecl = 12039 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl()); 12040 const ValueDecl *RHSDecl = 12041 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl()); 12042 if (LHSDecl != RHSDecl) 12043 return; 12044 if (LHSDecl->getType().isVolatileQualified()) 12045 return; 12046 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>()) 12047 if (RefTy->getPointeeType().isVolatileQualified()) 12048 return; 12049 12050 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin 12051 : diag::warn_self_assignment_overloaded) 12052 << LHSDeclRef->getType() << LHSExpr->getSourceRange() 12053 << RHSExpr->getSourceRange(); 12054 } 12055 12056 /// Check if a bitwise-& is performed on an Objective-C pointer. This 12057 /// is usually indicative of introspection within the Objective-C pointer. 12058 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, 12059 SourceLocation OpLoc) { 12060 if (!S.getLangOpts().ObjC) 12061 return; 12062 12063 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr; 12064 const Expr *LHS = L.get(); 12065 const Expr *RHS = R.get(); 12066 12067 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12068 ObjCPointerExpr = LHS; 12069 OtherExpr = RHS; 12070 } 12071 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) { 12072 ObjCPointerExpr = RHS; 12073 OtherExpr = LHS; 12074 } 12075 12076 // This warning is deliberately made very specific to reduce false 12077 // positives with logic that uses '&' for hashing. This logic mainly 12078 // looks for code trying to introspect into tagged pointers, which 12079 // code should generally never do. 12080 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) { 12081 unsigned Diag = diag::warn_objc_pointer_masking; 12082 // Determine if we are introspecting the result of performSelectorXXX. 12083 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts(); 12084 // Special case messages to -performSelector and friends, which 12085 // can return non-pointer values boxed in a pointer value. 12086 // Some clients may wish to silence warnings in this subcase. 12087 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) { 12088 Selector S = ME->getSelector(); 12089 StringRef SelArg0 = S.getNameForSlot(0); 12090 if (SelArg0.startswith("performSelector")) 12091 Diag = diag::warn_objc_pointer_masking_performSelector; 12092 } 12093 12094 S.Diag(OpLoc, Diag) 12095 << ObjCPointerExpr->getSourceRange(); 12096 } 12097 } 12098 12099 static NamedDecl *getDeclFromExpr(Expr *E) { 12100 if (!E) 12101 return nullptr; 12102 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 12103 return DRE->getDecl(); 12104 if (auto *ME = dyn_cast<MemberExpr>(E)) 12105 return ME->getMemberDecl(); 12106 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) 12107 return IRE->getDecl(); 12108 return nullptr; 12109 } 12110 12111 // This helper function promotes a binary operator's operands (which are of a 12112 // half vector type) to a vector of floats and then truncates the result to 12113 // a vector of either half or short. 12114 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, 12115 BinaryOperatorKind Opc, QualType ResultTy, 12116 ExprValueKind VK, ExprObjectKind OK, 12117 bool IsCompAssign, SourceLocation OpLoc, 12118 FPOptions FPFeatures) { 12119 auto &Context = S.getASTContext(); 12120 assert((isVector(ResultTy, Context.HalfTy) || 12121 isVector(ResultTy, Context.ShortTy)) && 12122 "Result must be a vector of half or short"); 12123 assert(isVector(LHS.get()->getType(), Context.HalfTy) && 12124 isVector(RHS.get()->getType(), Context.HalfTy) && 12125 "both operands expected to be a half vector"); 12126 12127 RHS = convertVector(RHS.get(), Context.FloatTy, S); 12128 QualType BinOpResTy = RHS.get()->getType(); 12129 12130 // If Opc is a comparison, ResultType is a vector of shorts. In that case, 12131 // change BinOpResTy to a vector of ints. 12132 if (isVector(ResultTy, Context.ShortTy)) 12133 BinOpResTy = S.GetSignedVectorType(BinOpResTy); 12134 12135 if (IsCompAssign) 12136 return new (Context) CompoundAssignOperator( 12137 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy, 12138 OpLoc, FPFeatures); 12139 12140 LHS = convertVector(LHS.get(), Context.FloatTy, S); 12141 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy, 12142 VK, OK, OpLoc, FPFeatures); 12143 return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S); 12144 } 12145 12146 static std::pair<ExprResult, ExprResult> 12147 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, 12148 Expr *RHSExpr) { 12149 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12150 if (!S.getLangOpts().CPlusPlus) { 12151 // C cannot handle TypoExpr nodes on either side of a binop because it 12152 // doesn't handle dependent types properly, so make sure any TypoExprs have 12153 // been dealt with before checking the operands. 12154 LHS = S.CorrectDelayedTyposInExpr(LHS); 12155 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) { 12156 if (Opc != BO_Assign) 12157 return ExprResult(E); 12158 // Avoid correcting the RHS to the same Expr as the LHS. 12159 Decl *D = getDeclFromExpr(E); 12160 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E; 12161 }); 12162 } 12163 return std::make_pair(LHS, RHS); 12164 } 12165 12166 /// Returns true if conversion between vectors of halfs and vectors of floats 12167 /// is needed. 12168 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, 12169 QualType SrcType) { 12170 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType && 12171 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() && 12172 isVector(SrcType, Ctx.HalfTy); 12173 } 12174 12175 /// CreateBuiltinBinOp - Creates a new built-in binary operation with 12176 /// operator @p Opc at location @c TokLoc. This routine only supports 12177 /// built-in operations; ActOnBinOp handles overloaded operators. 12178 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc, 12179 BinaryOperatorKind Opc, 12180 Expr *LHSExpr, Expr *RHSExpr) { 12181 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) { 12182 // The syntax only allows initializer lists on the RHS of assignment, 12183 // so we don't need to worry about accepting invalid code for 12184 // non-assignment operators. 12185 // C++11 5.17p9: 12186 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning 12187 // of x = {} is x = T(). 12188 InitializationKind Kind = InitializationKind::CreateDirectList( 12189 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12190 InitializedEntity Entity = 12191 InitializedEntity::InitializeTemporary(LHSExpr->getType()); 12192 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr); 12193 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr); 12194 if (Init.isInvalid()) 12195 return Init; 12196 RHSExpr = Init.get(); 12197 } 12198 12199 ExprResult LHS = LHSExpr, RHS = RHSExpr; 12200 QualType ResultTy; // Result type of the binary operator. 12201 // The following two variables are used for compound assignment operators 12202 QualType CompLHSTy; // Type of LHS after promotions for computation 12203 QualType CompResultTy; // Type of computation result 12204 ExprValueKind VK = VK_RValue; 12205 ExprObjectKind OK = OK_Ordinary; 12206 bool ConvertHalfVec = false; 12207 12208 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12209 if (!LHS.isUsable() || !RHS.isUsable()) 12210 return ExprError(); 12211 12212 if (getLangOpts().OpenCL) { 12213 QualType LHSTy = LHSExpr->getType(); 12214 QualType RHSTy = RHSExpr->getType(); 12215 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by 12216 // the ATOMIC_VAR_INIT macro. 12217 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) { 12218 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc()); 12219 if (BO_Assign == Opc) 12220 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR; 12221 else 12222 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12223 return ExprError(); 12224 } 12225 12226 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12227 // only with a builtin functions and therefore should be disallowed here. 12228 if (LHSTy->isImageType() || RHSTy->isImageType() || 12229 LHSTy->isSamplerT() || RHSTy->isSamplerT() || 12230 LHSTy->isPipeType() || RHSTy->isPipeType() || 12231 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) { 12232 ResultTy = InvalidOperands(OpLoc, LHS, RHS); 12233 return ExprError(); 12234 } 12235 } 12236 12237 switch (Opc) { 12238 case BO_Assign: 12239 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType()); 12240 if (getLangOpts().CPlusPlus && 12241 LHS.get()->getObjectKind() != OK_ObjCProperty) { 12242 VK = LHS.get()->getValueKind(); 12243 OK = LHS.get()->getObjectKind(); 12244 } 12245 if (!ResultTy.isNull()) { 12246 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12247 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc); 12248 } 12249 RecordModifiableNonNullParam(*this, LHS.get()); 12250 break; 12251 case BO_PtrMemD: 12252 case BO_PtrMemI: 12253 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc, 12254 Opc == BO_PtrMemI); 12255 break; 12256 case BO_Mul: 12257 case BO_Div: 12258 ConvertHalfVec = true; 12259 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false, 12260 Opc == BO_Div); 12261 break; 12262 case BO_Rem: 12263 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc); 12264 break; 12265 case BO_Add: 12266 ConvertHalfVec = true; 12267 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc); 12268 break; 12269 case BO_Sub: 12270 ConvertHalfVec = true; 12271 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc); 12272 break; 12273 case BO_Shl: 12274 case BO_Shr: 12275 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc); 12276 break; 12277 case BO_LE: 12278 case BO_LT: 12279 case BO_GE: 12280 case BO_GT: 12281 ConvertHalfVec = true; 12282 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12283 break; 12284 case BO_EQ: 12285 case BO_NE: 12286 ConvertHalfVec = true; 12287 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12288 break; 12289 case BO_Cmp: 12290 ConvertHalfVec = true; 12291 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc); 12292 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()); 12293 break; 12294 case BO_And: 12295 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc); 12296 LLVM_FALLTHROUGH; 12297 case BO_Xor: 12298 case BO_Or: 12299 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12300 break; 12301 case BO_LAnd: 12302 case BO_LOr: 12303 ConvertHalfVec = true; 12304 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc); 12305 break; 12306 case BO_MulAssign: 12307 case BO_DivAssign: 12308 ConvertHalfVec = true; 12309 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true, 12310 Opc == BO_DivAssign); 12311 CompLHSTy = CompResultTy; 12312 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12313 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12314 break; 12315 case BO_RemAssign: 12316 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true); 12317 CompLHSTy = CompResultTy; 12318 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12319 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12320 break; 12321 case BO_AddAssign: 12322 ConvertHalfVec = true; 12323 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy); 12324 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12325 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12326 break; 12327 case BO_SubAssign: 12328 ConvertHalfVec = true; 12329 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy); 12330 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12331 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12332 break; 12333 case BO_ShlAssign: 12334 case BO_ShrAssign: 12335 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true); 12336 CompLHSTy = CompResultTy; 12337 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12338 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12339 break; 12340 case BO_AndAssign: 12341 case BO_OrAssign: // fallthrough 12342 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true); 12343 LLVM_FALLTHROUGH; 12344 case BO_XorAssign: 12345 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc); 12346 CompLHSTy = CompResultTy; 12347 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid()) 12348 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy); 12349 break; 12350 case BO_Comma: 12351 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc); 12352 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) { 12353 VK = RHS.get()->getValueKind(); 12354 OK = RHS.get()->getObjectKind(); 12355 } 12356 break; 12357 } 12358 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid()) 12359 return ExprError(); 12360 12361 // Some of the binary operations require promoting operands of half vector to 12362 // float vectors and truncating the result back to half vector. For now, we do 12363 // this only when HalfArgsAndReturn is set (that is, when the target is arm or 12364 // arm64). 12365 assert(isVector(RHS.get()->getType(), Context.HalfTy) == 12366 isVector(LHS.get()->getType(), Context.HalfTy) && 12367 "both sides are half vectors or neither sides are"); 12368 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, 12369 LHS.get()->getType()); 12370 12371 // Check for array bounds violations for both sides of the BinaryOperator 12372 CheckArrayAccess(LHS.get()); 12373 CheckArrayAccess(RHS.get()); 12374 12375 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) { 12376 NamedDecl *ObjectSetClass = LookupSingleName(TUScope, 12377 &Context.Idents.get("object_setClass"), 12378 SourceLocation(), LookupOrdinaryName); 12379 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) { 12380 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc()); 12381 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) 12382 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(), 12383 "object_setClass(") 12384 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), 12385 ",") 12386 << FixItHint::CreateInsertion(RHSLocEnd, ")"); 12387 } 12388 else 12389 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign); 12390 } 12391 else if (const ObjCIvarRefExpr *OIRE = 12392 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts())) 12393 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get()); 12394 12395 // Opc is not a compound assignment if CompResultTy is null. 12396 if (CompResultTy.isNull()) { 12397 if (ConvertHalfVec) 12398 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false, 12399 OpLoc, FPFeatures); 12400 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK, 12401 OK, OpLoc, FPFeatures); 12402 } 12403 12404 // Handle compound assignments. 12405 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() != 12406 OK_ObjCProperty) { 12407 VK = VK_LValue; 12408 OK = LHS.get()->getObjectKind(); 12409 } 12410 12411 if (ConvertHalfVec) 12412 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true, 12413 OpLoc, FPFeatures); 12414 12415 return new (Context) CompoundAssignOperator( 12416 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy, 12417 OpLoc, FPFeatures); 12418 } 12419 12420 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison 12421 /// operators are mixed in a way that suggests that the programmer forgot that 12422 /// comparison operators have higher precedence. The most typical example of 12423 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1". 12424 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, 12425 SourceLocation OpLoc, Expr *LHSExpr, 12426 Expr *RHSExpr) { 12427 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr); 12428 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr); 12429 12430 // Check that one of the sides is a comparison operator and the other isn't. 12431 bool isLeftComp = LHSBO && LHSBO->isComparisonOp(); 12432 bool isRightComp = RHSBO && RHSBO->isComparisonOp(); 12433 if (isLeftComp == isRightComp) 12434 return; 12435 12436 // Bitwise operations are sometimes used as eager logical ops. 12437 // Don't diagnose this. 12438 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp(); 12439 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp(); 12440 if (isLeftBitwise || isRightBitwise) 12441 return; 12442 12443 SourceRange DiagRange = isLeftComp 12444 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc) 12445 : SourceRange(OpLoc, RHSExpr->getEndLoc()); 12446 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr(); 12447 SourceRange ParensRange = 12448 isLeftComp 12449 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc()) 12450 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc()); 12451 12452 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel) 12453 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr; 12454 SuggestParentheses(Self, OpLoc, 12455 Self.PDiag(diag::note_precedence_silence) << OpStr, 12456 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange()); 12457 SuggestParentheses(Self, OpLoc, 12458 Self.PDiag(diag::note_precedence_bitwise_first) 12459 << BinaryOperator::getOpcodeStr(Opc), 12460 ParensRange); 12461 } 12462 12463 /// It accepts a '&&' expr that is inside a '||' one. 12464 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression 12465 /// in parentheses. 12466 static void 12467 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, 12468 BinaryOperator *Bop) { 12469 assert(Bop->getOpcode() == BO_LAnd); 12470 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or) 12471 << Bop->getSourceRange() << OpLoc; 12472 SuggestParentheses(Self, Bop->getOperatorLoc(), 12473 Self.PDiag(diag::note_precedence_silence) 12474 << Bop->getOpcodeStr(), 12475 Bop->getSourceRange()); 12476 } 12477 12478 /// Returns true if the given expression can be evaluated as a constant 12479 /// 'true'. 12480 static bool EvaluatesAsTrue(Sema &S, Expr *E) { 12481 bool Res; 12482 return !E->isValueDependent() && 12483 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res; 12484 } 12485 12486 /// Returns true if the given expression can be evaluated as a constant 12487 /// 'false'. 12488 static bool EvaluatesAsFalse(Sema &S, Expr *E) { 12489 bool Res; 12490 return !E->isValueDependent() && 12491 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res; 12492 } 12493 12494 /// Look for '&&' in the left hand of a '||' expr. 12495 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, 12496 Expr *LHSExpr, Expr *RHSExpr) { 12497 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) { 12498 if (Bop->getOpcode() == BO_LAnd) { 12499 // If it's "a && b || 0" don't warn since the precedence doesn't matter. 12500 if (EvaluatesAsFalse(S, RHSExpr)) 12501 return; 12502 // If it's "1 && a || b" don't warn since the precedence doesn't matter. 12503 if (!EvaluatesAsTrue(S, Bop->getLHS())) 12504 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12505 } else if (Bop->getOpcode() == BO_LOr) { 12506 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) { 12507 // If it's "a || b && 1 || c" we didn't warn earlier for 12508 // "a || b && 1", but warn now. 12509 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS())) 12510 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop); 12511 } 12512 } 12513 } 12514 } 12515 12516 /// Look for '&&' in the right hand of a '||' expr. 12517 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, 12518 Expr *LHSExpr, Expr *RHSExpr) { 12519 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) { 12520 if (Bop->getOpcode() == BO_LAnd) { 12521 // If it's "0 || a && b" don't warn since the precedence doesn't matter. 12522 if (EvaluatesAsFalse(S, LHSExpr)) 12523 return; 12524 // If it's "a || b && 1" don't warn since the precedence doesn't matter. 12525 if (!EvaluatesAsTrue(S, Bop->getRHS())) 12526 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop); 12527 } 12528 } 12529 } 12530 12531 /// Look for bitwise op in the left or right hand of a bitwise op with 12532 /// lower precedence and emit a diagnostic together with a fixit hint that wraps 12533 /// the '&' expression in parentheses. 12534 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, 12535 SourceLocation OpLoc, Expr *SubExpr) { 12536 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12537 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) { 12538 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op) 12539 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc) 12540 << Bop->getSourceRange() << OpLoc; 12541 SuggestParentheses(S, Bop->getOperatorLoc(), 12542 S.PDiag(diag::note_precedence_silence) 12543 << Bop->getOpcodeStr(), 12544 Bop->getSourceRange()); 12545 } 12546 } 12547 } 12548 12549 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, 12550 Expr *SubExpr, StringRef Shift) { 12551 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) { 12552 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) { 12553 StringRef Op = Bop->getOpcodeStr(); 12554 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift) 12555 << Bop->getSourceRange() << OpLoc << Shift << Op; 12556 SuggestParentheses(S, Bop->getOperatorLoc(), 12557 S.PDiag(diag::note_precedence_silence) << Op, 12558 Bop->getSourceRange()); 12559 } 12560 } 12561 } 12562 12563 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, 12564 Expr *LHSExpr, Expr *RHSExpr) { 12565 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr); 12566 if (!OCE) 12567 return; 12568 12569 FunctionDecl *FD = OCE->getDirectCallee(); 12570 if (!FD || !FD->isOverloadedOperator()) 12571 return; 12572 12573 OverloadedOperatorKind Kind = FD->getOverloadedOperator(); 12574 if (Kind != OO_LessLess && Kind != OO_GreaterGreater) 12575 return; 12576 12577 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison) 12578 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange() 12579 << (Kind == OO_LessLess); 12580 SuggestParentheses(S, OCE->getOperatorLoc(), 12581 S.PDiag(diag::note_precedence_silence) 12582 << (Kind == OO_LessLess ? "<<" : ">>"), 12583 OCE->getSourceRange()); 12584 SuggestParentheses( 12585 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first), 12586 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc())); 12587 } 12588 12589 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky 12590 /// precedence. 12591 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, 12592 SourceLocation OpLoc, Expr *LHSExpr, 12593 Expr *RHSExpr){ 12594 // Diagnose "arg1 'bitwise' arg2 'eq' arg3". 12595 if (BinaryOperator::isBitwiseOp(Opc)) 12596 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr); 12597 12598 // Diagnose "arg1 & arg2 | arg3" 12599 if ((Opc == BO_Or || Opc == BO_Xor) && 12600 !OpLoc.isMacroID()/* Don't warn in macros. */) { 12601 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr); 12602 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr); 12603 } 12604 12605 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does. 12606 // We don't warn for 'assert(a || b && "bad")' since this is safe. 12607 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) { 12608 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr); 12609 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr); 12610 } 12611 12612 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext())) 12613 || Opc == BO_Shr) { 12614 StringRef Shift = BinaryOperator::getOpcodeStr(Opc); 12615 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift); 12616 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift); 12617 } 12618 12619 // Warn on overloaded shift operators and comparisons, such as: 12620 // cout << 5 == 4; 12621 if (BinaryOperator::isComparisonOp(Opc)) 12622 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr); 12623 } 12624 12625 // Binary Operators. 'Tok' is the token for the operator. 12626 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc, 12627 tok::TokenKind Kind, 12628 Expr *LHSExpr, Expr *RHSExpr) { 12629 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind); 12630 assert(LHSExpr && "ActOnBinOp(): missing left expression"); 12631 assert(RHSExpr && "ActOnBinOp(): missing right expression"); 12632 12633 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0" 12634 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr); 12635 12636 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr); 12637 } 12638 12639 /// Build an overloaded binary operator expression in the given scope. 12640 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, 12641 BinaryOperatorKind Opc, 12642 Expr *LHS, Expr *RHS) { 12643 switch (Opc) { 12644 case BO_Assign: 12645 case BO_DivAssign: 12646 case BO_RemAssign: 12647 case BO_SubAssign: 12648 case BO_AndAssign: 12649 case BO_OrAssign: 12650 case BO_XorAssign: 12651 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false); 12652 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S); 12653 break; 12654 default: 12655 break; 12656 } 12657 12658 // Find all of the overloaded operators visible from this 12659 // point. We perform both an operator-name lookup from the local 12660 // scope and an argument-dependent lookup based on the types of 12661 // the arguments. 12662 UnresolvedSet<16> Functions; 12663 OverloadedOperatorKind OverOp 12664 = BinaryOperator::getOverloadedOperator(Opc); 12665 if (Sc && OverOp != OO_None && OverOp != OO_Equal) 12666 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(), 12667 RHS->getType(), Functions); 12668 12669 // Build the (potentially-overloaded, potentially-dependent) 12670 // binary operation. 12671 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS); 12672 } 12673 12674 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc, 12675 BinaryOperatorKind Opc, 12676 Expr *LHSExpr, Expr *RHSExpr) { 12677 ExprResult LHS, RHS; 12678 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr); 12679 if (!LHS.isUsable() || !RHS.isUsable()) 12680 return ExprError(); 12681 LHSExpr = LHS.get(); 12682 RHSExpr = RHS.get(); 12683 12684 // We want to end up calling one of checkPseudoObjectAssignment 12685 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if 12686 // both expressions are overloadable or either is type-dependent), 12687 // or CreateBuiltinBinOp (in any other case). We also want to get 12688 // any placeholder types out of the way. 12689 12690 // Handle pseudo-objects in the LHS. 12691 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) { 12692 // Assignments with a pseudo-object l-value need special analysis. 12693 if (pty->getKind() == BuiltinType::PseudoObject && 12694 BinaryOperator::isAssignmentOp(Opc)) 12695 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr); 12696 12697 // Don't resolve overloads if the other type is overloadable. 12698 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) { 12699 // We can't actually test that if we still have a placeholder, 12700 // though. Fortunately, none of the exceptions we see in that 12701 // code below are valid when the LHS is an overload set. Note 12702 // that an overload set can be dependently-typed, but it never 12703 // instantiates to having an overloadable type. 12704 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12705 if (resolvedRHS.isInvalid()) return ExprError(); 12706 RHSExpr = resolvedRHS.get(); 12707 12708 if (RHSExpr->isTypeDependent() || 12709 RHSExpr->getType()->isOverloadableType()) 12710 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12711 } 12712 12713 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function 12714 // template, diagnose the missing 'template' keyword instead of diagnosing 12715 // an invalid use of a bound member function. 12716 // 12717 // Note that "A::x < b" might be valid if 'b' has an overloadable type due 12718 // to C++1z [over.over]/1.4, but we already checked for that case above. 12719 if (Opc == BO_LT && inTemplateInstantiation() && 12720 (pty->getKind() == BuiltinType::BoundMember || 12721 pty->getKind() == BuiltinType::Overload)) { 12722 auto *OE = dyn_cast<OverloadExpr>(LHSExpr); 12723 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() && 12724 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) { 12725 return isa<FunctionTemplateDecl>(ND); 12726 })) { 12727 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc() 12728 : OE->getNameLoc(), 12729 diag::err_template_kw_missing) 12730 << OE->getName().getAsString() << ""; 12731 return ExprError(); 12732 } 12733 } 12734 12735 ExprResult LHS = CheckPlaceholderExpr(LHSExpr); 12736 if (LHS.isInvalid()) return ExprError(); 12737 LHSExpr = LHS.get(); 12738 } 12739 12740 // Handle pseudo-objects in the RHS. 12741 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) { 12742 // An overload in the RHS can potentially be resolved by the type 12743 // being assigned to. 12744 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) { 12745 if (getLangOpts().CPlusPlus && 12746 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() || 12747 LHSExpr->getType()->isOverloadableType())) 12748 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12749 12750 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12751 } 12752 12753 // Don't resolve overloads if the other type is overloadable. 12754 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload && 12755 LHSExpr->getType()->isOverloadableType()) 12756 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12757 12758 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr); 12759 if (!resolvedRHS.isUsable()) return ExprError(); 12760 RHSExpr = resolvedRHS.get(); 12761 } 12762 12763 if (getLangOpts().CPlusPlus) { 12764 // If either expression is type-dependent, always build an 12765 // overloaded op. 12766 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) 12767 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12768 12769 // Otherwise, build an overloaded op if either expression has an 12770 // overloadable type. 12771 if (LHSExpr->getType()->isOverloadableType() || 12772 RHSExpr->getType()->isOverloadableType()) 12773 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr); 12774 } 12775 12776 // Build a built-in binary operation. 12777 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr); 12778 } 12779 12780 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) { 12781 if (T.isNull() || T->isDependentType()) 12782 return false; 12783 12784 if (!T->isPromotableIntegerType()) 12785 return true; 12786 12787 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy); 12788 } 12789 12790 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc, 12791 UnaryOperatorKind Opc, 12792 Expr *InputExpr) { 12793 ExprResult Input = InputExpr; 12794 ExprValueKind VK = VK_RValue; 12795 ExprObjectKind OK = OK_Ordinary; 12796 QualType resultType; 12797 bool CanOverflow = false; 12798 12799 bool ConvertHalfVec = false; 12800 if (getLangOpts().OpenCL) { 12801 QualType Ty = InputExpr->getType(); 12802 // The only legal unary operation for atomics is '&'. 12803 if ((Opc != UO_AddrOf && Ty->isAtomicType()) || 12804 // OpenCL special types - image, sampler, pipe, and blocks are to be used 12805 // only with a builtin functions and therefore should be disallowed here. 12806 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType() 12807 || Ty->isBlockPointerType())) { 12808 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12809 << InputExpr->getType() 12810 << Input.get()->getSourceRange()); 12811 } 12812 } 12813 switch (Opc) { 12814 case UO_PreInc: 12815 case UO_PreDec: 12816 case UO_PostInc: 12817 case UO_PostDec: 12818 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, 12819 OpLoc, 12820 Opc == UO_PreInc || 12821 Opc == UO_PostInc, 12822 Opc == UO_PreInc || 12823 Opc == UO_PreDec); 12824 CanOverflow = isOverflowingIntegerType(Context, resultType); 12825 break; 12826 case UO_AddrOf: 12827 resultType = CheckAddressOfOperand(Input, OpLoc); 12828 RecordModifiableNonNullParam(*this, InputExpr); 12829 break; 12830 case UO_Deref: { 12831 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12832 if (Input.isInvalid()) return ExprError(); 12833 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc); 12834 break; 12835 } 12836 case UO_Plus: 12837 case UO_Minus: 12838 CanOverflow = Opc == UO_Minus && 12839 isOverflowingIntegerType(Context, Input.get()->getType()); 12840 Input = UsualUnaryConversions(Input.get()); 12841 if (Input.isInvalid()) return ExprError(); 12842 // Unary plus and minus require promoting an operand of half vector to a 12843 // float vector and truncating the result back to a half vector. For now, we 12844 // do this only when HalfArgsAndReturns is set (that is, when the target is 12845 // arm or arm64). 12846 ConvertHalfVec = 12847 needsConversionOfHalfVec(true, Context, Input.get()->getType()); 12848 12849 // If the operand is a half vector, promote it to a float vector. 12850 if (ConvertHalfVec) 12851 Input = convertVector(Input.get(), Context.FloatTy, *this); 12852 resultType = Input.get()->getType(); 12853 if (resultType->isDependentType()) 12854 break; 12855 if (resultType->isArithmeticType()) // C99 6.5.3.3p1 12856 break; 12857 else if (resultType->isVectorType() && 12858 // The z vector extensions don't allow + or - with bool vectors. 12859 (!Context.getLangOpts().ZVector || 12860 resultType->getAs<VectorType>()->getVectorKind() != 12861 VectorType::AltiVecBool)) 12862 break; 12863 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6 12864 Opc == UO_Plus && 12865 resultType->isPointerType()) 12866 break; 12867 12868 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12869 << resultType << Input.get()->getSourceRange()); 12870 12871 case UO_Not: // bitwise complement 12872 Input = UsualUnaryConversions(Input.get()); 12873 if (Input.isInvalid()) 12874 return ExprError(); 12875 resultType = Input.get()->getType(); 12876 12877 if (resultType->isDependentType()) 12878 break; 12879 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension. 12880 if (resultType->isComplexType() || resultType->isComplexIntegerType()) 12881 // C99 does not support '~' for complex conjugation. 12882 Diag(OpLoc, diag::ext_integer_complement_complex) 12883 << resultType << Input.get()->getSourceRange(); 12884 else if (resultType->hasIntegerRepresentation()) 12885 break; 12886 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) { 12887 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate 12888 // on vector float types. 12889 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12890 if (!T->isIntegerType()) 12891 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12892 << resultType << Input.get()->getSourceRange()); 12893 } else { 12894 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12895 << resultType << Input.get()->getSourceRange()); 12896 } 12897 break; 12898 12899 case UO_LNot: // logical negation 12900 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5). 12901 Input = DefaultFunctionArrayLvalueConversion(Input.get()); 12902 if (Input.isInvalid()) return ExprError(); 12903 resultType = Input.get()->getType(); 12904 12905 // Though we still have to promote half FP to float... 12906 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) { 12907 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get(); 12908 resultType = Context.FloatTy; 12909 } 12910 12911 if (resultType->isDependentType()) 12912 break; 12913 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) { 12914 // C99 6.5.3.3p1: ok, fallthrough; 12915 if (Context.getLangOpts().CPlusPlus) { 12916 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9: 12917 // operand contextually converted to bool. 12918 Input = ImpCastExprToType(Input.get(), Context.BoolTy, 12919 ScalarTypeToBooleanCastKind(resultType)); 12920 } else if (Context.getLangOpts().OpenCL && 12921 Context.getLangOpts().OpenCLVersion < 120) { 12922 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12923 // operate on scalar float types. 12924 if (!resultType->isIntegerType() && !resultType->isPointerType()) 12925 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12926 << resultType << Input.get()->getSourceRange()); 12927 } 12928 } else if (resultType->isExtVectorType()) { 12929 if (Context.getLangOpts().OpenCL && 12930 Context.getLangOpts().OpenCLVersion < 120) { 12931 // OpenCL v1.1 6.3.h: The logical operator not (!) does not 12932 // operate on vector float types. 12933 QualType T = resultType->getAs<ExtVectorType>()->getElementType(); 12934 if (!T->isIntegerType()) 12935 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12936 << resultType << Input.get()->getSourceRange()); 12937 } 12938 // Vector logical not returns the signed variant of the operand type. 12939 resultType = GetSignedVectorType(resultType); 12940 break; 12941 } else { 12942 // FIXME: GCC's vector extension permits the usage of '!' with a vector 12943 // type in C++. We should allow that here too. 12944 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr) 12945 << resultType << Input.get()->getSourceRange()); 12946 } 12947 12948 // LNot always has type int. C99 6.5.3.3p5. 12949 // In C++, it's bool. C++ 5.3.1p8 12950 resultType = Context.getLogicalOperationType(); 12951 break; 12952 case UO_Real: 12953 case UO_Imag: 12954 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real); 12955 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary 12956 // complex l-values to ordinary l-values and all other values to r-values. 12957 if (Input.isInvalid()) return ExprError(); 12958 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) { 12959 if (Input.get()->getValueKind() != VK_RValue && 12960 Input.get()->getObjectKind() == OK_Ordinary) 12961 VK = Input.get()->getValueKind(); 12962 } else if (!getLangOpts().CPlusPlus) { 12963 // In C, a volatile scalar is read by __imag. In C++, it is not. 12964 Input = DefaultLvalueConversion(Input.get()); 12965 } 12966 break; 12967 case UO_Extension: 12968 resultType = Input.get()->getType(); 12969 VK = Input.get()->getValueKind(); 12970 OK = Input.get()->getObjectKind(); 12971 break; 12972 case UO_Coawait: 12973 // It's unnecessary to represent the pass-through operator co_await in the 12974 // AST; just return the input expression instead. 12975 assert(!Input.get()->getType()->isDependentType() && 12976 "the co_await expression must be non-dependant before " 12977 "building operator co_await"); 12978 return Input; 12979 } 12980 if (resultType.isNull() || Input.isInvalid()) 12981 return ExprError(); 12982 12983 // Check for array bounds violations in the operand of the UnaryOperator, 12984 // except for the '*' and '&' operators that have to be handled specially 12985 // by CheckArrayAccess (as there are special cases like &array[arraysize] 12986 // that are explicitly defined as valid by the standard). 12987 if (Opc != UO_AddrOf && Opc != UO_Deref) 12988 CheckArrayAccess(Input.get()); 12989 12990 auto *UO = new (Context) 12991 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow); 12992 // Convert the result back to a half vector. 12993 if (ConvertHalfVec) 12994 return convertVector(UO, Context.HalfTy, *this); 12995 return UO; 12996 } 12997 12998 /// Determine whether the given expression is a qualified member 12999 /// access expression, of a form that could be turned into a pointer to member 13000 /// with the address-of operator. 13001 bool Sema::isQualifiedMemberAccess(Expr *E) { 13002 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13003 if (!DRE->getQualifier()) 13004 return false; 13005 13006 ValueDecl *VD = DRE->getDecl(); 13007 if (!VD->isCXXClassMember()) 13008 return false; 13009 13010 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD)) 13011 return true; 13012 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD)) 13013 return Method->isInstance(); 13014 13015 return false; 13016 } 13017 13018 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13019 if (!ULE->getQualifier()) 13020 return false; 13021 13022 for (NamedDecl *D : ULE->decls()) { 13023 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 13024 if (Method->isInstance()) 13025 return true; 13026 } else { 13027 // Overload set does not contain methods. 13028 break; 13029 } 13030 } 13031 13032 return false; 13033 } 13034 13035 return false; 13036 } 13037 13038 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc, 13039 UnaryOperatorKind Opc, Expr *Input) { 13040 // First things first: handle placeholders so that the 13041 // overloaded-operator check considers the right type. 13042 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) { 13043 // Increment and decrement of pseudo-object references. 13044 if (pty->getKind() == BuiltinType::PseudoObject && 13045 UnaryOperator::isIncrementDecrementOp(Opc)) 13046 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input); 13047 13048 // extension is always a builtin operator. 13049 if (Opc == UO_Extension) 13050 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13051 13052 // & gets special logic for several kinds of placeholder. 13053 // The builtin code knows what to do. 13054 if (Opc == UO_AddrOf && 13055 (pty->getKind() == BuiltinType::Overload || 13056 pty->getKind() == BuiltinType::UnknownAny || 13057 pty->getKind() == BuiltinType::BoundMember)) 13058 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13059 13060 // Anything else needs to be handled now. 13061 ExprResult Result = CheckPlaceholderExpr(Input); 13062 if (Result.isInvalid()) return ExprError(); 13063 Input = Result.get(); 13064 } 13065 13066 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() && 13067 UnaryOperator::getOverloadedOperator(Opc) != OO_None && 13068 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) { 13069 // Find all of the overloaded operators visible from this 13070 // point. We perform both an operator-name lookup from the local 13071 // scope and an argument-dependent lookup based on the types of 13072 // the arguments. 13073 UnresolvedSet<16> Functions; 13074 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc); 13075 if (S && OverOp != OO_None) 13076 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(), 13077 Functions); 13078 13079 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input); 13080 } 13081 13082 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 13083 } 13084 13085 // Unary Operators. 'Tok' is the token for the operator. 13086 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 13087 tok::TokenKind Op, Expr *Input) { 13088 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input); 13089 } 13090 13091 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 13092 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 13093 LabelDecl *TheDecl) { 13094 TheDecl->markUsed(Context); 13095 // Create the AST node. The address of a label always has type 'void*'. 13096 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl, 13097 Context.getPointerType(Context.VoidTy)); 13098 } 13099 13100 /// Given the last statement in a statement-expression, check whether 13101 /// the result is a producing expression (like a call to an 13102 /// ns_returns_retained function) and, if so, rebuild it to hoist the 13103 /// release out of the full-expression. Otherwise, return null. 13104 /// Cannot fail. 13105 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) { 13106 // Should always be wrapped with one of these. 13107 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement); 13108 if (!cleanups) return nullptr; 13109 13110 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr()); 13111 if (!cast || cast->getCastKind() != CK_ARCConsumeObject) 13112 return nullptr; 13113 13114 // Splice out the cast. This shouldn't modify any interesting 13115 // features of the statement. 13116 Expr *producer = cast->getSubExpr(); 13117 assert(producer->getType() == cast->getType()); 13118 assert(producer->getValueKind() == cast->getValueKind()); 13119 cleanups->setSubExpr(producer); 13120 return cleanups; 13121 } 13122 13123 void Sema::ActOnStartStmtExpr() { 13124 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13125 } 13126 13127 void Sema::ActOnStmtExprError() { 13128 // Note that function is also called by TreeTransform when leaving a 13129 // StmtExpr scope without rebuilding anything. 13130 13131 DiscardCleanupsInEvaluationContext(); 13132 PopExpressionEvaluationContext(); 13133 } 13134 13135 ExprResult 13136 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 13137 SourceLocation RPLoc) { // "({..})" 13138 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!"); 13139 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt); 13140 13141 if (hasAnyUnrecoverableErrorsInThisFunction()) 13142 DiscardCleanupsInEvaluationContext(); 13143 assert(!Cleanup.exprNeedsCleanups() && 13144 "cleanups within StmtExpr not correctly bound!"); 13145 PopExpressionEvaluationContext(); 13146 13147 // FIXME: there are a variety of strange constraints to enforce here, for 13148 // example, it is not possible to goto into a stmt expression apparently. 13149 // More semantic analysis is needed. 13150 13151 // If there are sub-stmts in the compound stmt, take the type of the last one 13152 // as the type of the stmtexpr. 13153 QualType Ty = Context.VoidTy; 13154 bool StmtExprMayBindToTemp = false; 13155 if (!Compound->body_empty()) { 13156 Stmt *LastStmt = Compound->body_back(); 13157 LabelStmt *LastLabelStmt = nullptr; 13158 // If LastStmt is a label, skip down through into the body. 13159 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) { 13160 LastLabelStmt = Label; 13161 LastStmt = Label->getSubStmt(); 13162 } 13163 13164 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) { 13165 // Do function/array conversion on the last expression, but not 13166 // lvalue-to-rvalue. However, initialize an unqualified type. 13167 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE); 13168 if (LastExpr.isInvalid()) 13169 return ExprError(); 13170 Ty = LastExpr.get()->getType().getUnqualifiedType(); 13171 13172 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) { 13173 // In ARC, if the final expression ends in a consume, splice 13174 // the consume out and bind it later. In the alternate case 13175 // (when dealing with a retainable type), the result 13176 // initialization will create a produce. In both cases the 13177 // result will be +1, and we'll need to balance that out with 13178 // a bind. 13179 if (Expr *rebuiltLastStmt 13180 = maybeRebuildARCConsumingStmt(LastExpr.get())) { 13181 LastExpr = rebuiltLastStmt; 13182 } else { 13183 LastExpr = PerformCopyInitialization( 13184 InitializedEntity::InitializeStmtExprResult(LPLoc, Ty), 13185 SourceLocation(), LastExpr); 13186 } 13187 13188 if (LastExpr.isInvalid()) 13189 return ExprError(); 13190 if (LastExpr.get() != nullptr) { 13191 if (!LastLabelStmt) 13192 Compound->setLastStmt(LastExpr.get()); 13193 else 13194 LastLabelStmt->setSubStmt(LastExpr.get()); 13195 StmtExprMayBindToTemp = true; 13196 } 13197 } 13198 } 13199 } 13200 13201 // FIXME: Check that expression type is complete/non-abstract; statement 13202 // expressions are not lvalues. 13203 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc); 13204 if (StmtExprMayBindToTemp) 13205 return MaybeBindToTemporary(ResStmtExpr); 13206 return ResStmtExpr; 13207 } 13208 13209 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 13210 TypeSourceInfo *TInfo, 13211 ArrayRef<OffsetOfComponent> Components, 13212 SourceLocation RParenLoc) { 13213 QualType ArgTy = TInfo->getType(); 13214 bool Dependent = ArgTy->isDependentType(); 13215 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange(); 13216 13217 // We must have at least one component that refers to the type, and the first 13218 // one is known to be a field designator. Verify that the ArgTy represents 13219 // a struct/union/class. 13220 if (!Dependent && !ArgTy->isRecordType()) 13221 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 13222 << ArgTy << TypeRange); 13223 13224 // Type must be complete per C99 7.17p3 because a declaring a variable 13225 // with an incomplete type would be ill-formed. 13226 if (!Dependent 13227 && RequireCompleteType(BuiltinLoc, ArgTy, 13228 diag::err_offsetof_incomplete_type, TypeRange)) 13229 return ExprError(); 13230 13231 bool DidWarnAboutNonPOD = false; 13232 QualType CurrentType = ArgTy; 13233 SmallVector<OffsetOfNode, 4> Comps; 13234 SmallVector<Expr*, 4> Exprs; 13235 for (const OffsetOfComponent &OC : Components) { 13236 if (OC.isBrackets) { 13237 // Offset of an array sub-field. TODO: Should we allow vector elements? 13238 if (!CurrentType->isDependentType()) { 13239 const ArrayType *AT = Context.getAsArrayType(CurrentType); 13240 if(!AT) 13241 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type) 13242 << CurrentType); 13243 CurrentType = AT->getElementType(); 13244 } else 13245 CurrentType = Context.DependentTy; 13246 13247 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E)); 13248 if (IdxRval.isInvalid()) 13249 return ExprError(); 13250 Expr *Idx = IdxRval.get(); 13251 13252 // The expression must be an integral expression. 13253 // FIXME: An integral constant expression? 13254 if (!Idx->isTypeDependent() && !Idx->isValueDependent() && 13255 !Idx->getType()->isIntegerType()) 13256 return ExprError( 13257 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer) 13258 << Idx->getSourceRange()); 13259 13260 // Record this array index. 13261 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd)); 13262 Exprs.push_back(Idx); 13263 continue; 13264 } 13265 13266 // Offset of a field. 13267 if (CurrentType->isDependentType()) { 13268 // We have the offset of a field, but we can't look into the dependent 13269 // type. Just record the identifier of the field. 13270 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd)); 13271 CurrentType = Context.DependentTy; 13272 continue; 13273 } 13274 13275 // We need to have a complete type to look into. 13276 if (RequireCompleteType(OC.LocStart, CurrentType, 13277 diag::err_offsetof_incomplete_type)) 13278 return ExprError(); 13279 13280 // Look for the designated field. 13281 const RecordType *RC = CurrentType->getAs<RecordType>(); 13282 if (!RC) 13283 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type) 13284 << CurrentType); 13285 RecordDecl *RD = RC->getDecl(); 13286 13287 // C++ [lib.support.types]p5: 13288 // The macro offsetof accepts a restricted set of type arguments in this 13289 // International Standard. type shall be a POD structure or a POD union 13290 // (clause 9). 13291 // C++11 [support.types]p4: 13292 // If type is not a standard-layout class (Clause 9), the results are 13293 // undefined. 13294 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13295 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD(); 13296 unsigned DiagID = 13297 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type 13298 : diag::ext_offsetof_non_pod_type; 13299 13300 if (!IsSafe && !DidWarnAboutNonPOD && 13301 DiagRuntimeBehavior(BuiltinLoc, nullptr, 13302 PDiag(DiagID) 13303 << SourceRange(Components[0].LocStart, OC.LocEnd) 13304 << CurrentType)) 13305 DidWarnAboutNonPOD = true; 13306 } 13307 13308 // Look for the field. 13309 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName); 13310 LookupQualifiedName(R, RD); 13311 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>(); 13312 IndirectFieldDecl *IndirectMemberDecl = nullptr; 13313 if (!MemberDecl) { 13314 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>())) 13315 MemberDecl = IndirectMemberDecl->getAnonField(); 13316 } 13317 13318 if (!MemberDecl) 13319 return ExprError(Diag(BuiltinLoc, diag::err_no_member) 13320 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 13321 OC.LocEnd)); 13322 13323 // C99 7.17p3: 13324 // (If the specified member is a bit-field, the behavior is undefined.) 13325 // 13326 // We diagnose this as an error. 13327 if (MemberDecl->isBitField()) { 13328 Diag(OC.LocEnd, diag::err_offsetof_bitfield) 13329 << MemberDecl->getDeclName() 13330 << SourceRange(BuiltinLoc, RParenLoc); 13331 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl); 13332 return ExprError(); 13333 } 13334 13335 RecordDecl *Parent = MemberDecl->getParent(); 13336 if (IndirectMemberDecl) 13337 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext()); 13338 13339 // If the member was found in a base class, introduce OffsetOfNodes for 13340 // the base class indirections. 13341 CXXBasePaths Paths; 13342 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent), 13343 Paths)) { 13344 if (Paths.getDetectedVirtual()) { 13345 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base) 13346 << MemberDecl->getDeclName() 13347 << SourceRange(BuiltinLoc, RParenLoc); 13348 return ExprError(); 13349 } 13350 13351 CXXBasePath &Path = Paths.front(); 13352 for (const CXXBasePathElement &B : Path) 13353 Comps.push_back(OffsetOfNode(B.Base)); 13354 } 13355 13356 if (IndirectMemberDecl) { 13357 for (auto *FI : IndirectMemberDecl->chain()) { 13358 assert(isa<FieldDecl>(FI)); 13359 Comps.push_back(OffsetOfNode(OC.LocStart, 13360 cast<FieldDecl>(FI), OC.LocEnd)); 13361 } 13362 } else 13363 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd)); 13364 13365 CurrentType = MemberDecl->getType().getNonReferenceType(); 13366 } 13367 13368 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo, 13369 Comps, Exprs, RParenLoc); 13370 } 13371 13372 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S, 13373 SourceLocation BuiltinLoc, 13374 SourceLocation TypeLoc, 13375 ParsedType ParsedArgTy, 13376 ArrayRef<OffsetOfComponent> Components, 13377 SourceLocation RParenLoc) { 13378 13379 TypeSourceInfo *ArgTInfo; 13380 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo); 13381 if (ArgTy.isNull()) 13382 return ExprError(); 13383 13384 if (!ArgTInfo) 13385 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc); 13386 13387 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc); 13388 } 13389 13390 13391 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, 13392 Expr *CondExpr, 13393 Expr *LHSExpr, Expr *RHSExpr, 13394 SourceLocation RPLoc) { 13395 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)"); 13396 13397 ExprValueKind VK = VK_RValue; 13398 ExprObjectKind OK = OK_Ordinary; 13399 QualType resType; 13400 bool ValueDependent = false; 13401 bool CondIsTrue = false; 13402 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) { 13403 resType = Context.DependentTy; 13404 ValueDependent = true; 13405 } else { 13406 // The conditional expression is required to be a constant expression. 13407 llvm::APSInt condEval(32); 13408 ExprResult CondICE 13409 = VerifyIntegerConstantExpression(CondExpr, &condEval, 13410 diag::err_typecheck_choose_expr_requires_constant, false); 13411 if (CondICE.isInvalid()) 13412 return ExprError(); 13413 CondExpr = CondICE.get(); 13414 CondIsTrue = condEval.getZExtValue(); 13415 13416 // If the condition is > zero, then the AST type is the same as the LHSExpr. 13417 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr; 13418 13419 resType = ActiveExpr->getType(); 13420 ValueDependent = ActiveExpr->isValueDependent(); 13421 VK = ActiveExpr->getValueKind(); 13422 OK = ActiveExpr->getObjectKind(); 13423 } 13424 13425 return new (Context) 13426 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc, 13427 CondIsTrue, resType->isDependentType(), ValueDependent); 13428 } 13429 13430 //===----------------------------------------------------------------------===// 13431 // Clang Extensions. 13432 //===----------------------------------------------------------------------===// 13433 13434 /// ActOnBlockStart - This callback is invoked when a block literal is started. 13435 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) { 13436 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc); 13437 13438 if (LangOpts.CPlusPlus) { 13439 Decl *ManglingContextDecl; 13440 if (MangleNumberingContext *MCtx = 13441 getCurrentMangleNumberContext(Block->getDeclContext(), 13442 ManglingContextDecl)) { 13443 unsigned ManglingNumber = MCtx->getManglingNumber(Block); 13444 Block->setBlockMangling(ManglingNumber, ManglingContextDecl); 13445 } 13446 } 13447 13448 PushBlockScope(CurScope, Block); 13449 CurContext->addDecl(Block); 13450 if (CurScope) 13451 PushDeclContext(CurScope, Block); 13452 else 13453 CurContext = Block; 13454 13455 getCurBlock()->HasImplicitReturnType = true; 13456 13457 // Enter a new evaluation context to insulate the block from any 13458 // cleanups from the enclosing full-expression. 13459 PushExpressionEvaluationContext( 13460 ExpressionEvaluationContext::PotentiallyEvaluated); 13461 } 13462 13463 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 13464 Scope *CurScope) { 13465 assert(ParamInfo.getIdentifier() == nullptr && 13466 "block-id should have no identifier!"); 13467 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext); 13468 BlockScopeInfo *CurBlock = getCurBlock(); 13469 13470 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope); 13471 QualType T = Sig->getType(); 13472 13473 // FIXME: We should allow unexpanded parameter packs here, but that would, 13474 // in turn, make the block expression contain unexpanded parameter packs. 13475 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) { 13476 // Drop the parameters. 13477 FunctionProtoType::ExtProtoInfo EPI; 13478 EPI.HasTrailingReturn = false; 13479 EPI.TypeQuals |= DeclSpec::TQ_const; 13480 T = Context.getFunctionType(Context.DependentTy, None, EPI); 13481 Sig = Context.getTrivialTypeSourceInfo(T); 13482 } 13483 13484 // GetTypeForDeclarator always produces a function type for a block 13485 // literal signature. Furthermore, it is always a FunctionProtoType 13486 // unless the function was written with a typedef. 13487 assert(T->isFunctionType() && 13488 "GetTypeForDeclarator made a non-function block signature"); 13489 13490 // Look for an explicit signature in that function type. 13491 FunctionProtoTypeLoc ExplicitSignature; 13492 13493 if ((ExplicitSignature = 13494 Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) { 13495 13496 // Check whether that explicit signature was synthesized by 13497 // GetTypeForDeclarator. If so, don't save that as part of the 13498 // written signature. 13499 if (ExplicitSignature.getLocalRangeBegin() == 13500 ExplicitSignature.getLocalRangeEnd()) { 13501 // This would be much cheaper if we stored TypeLocs instead of 13502 // TypeSourceInfos. 13503 TypeLoc Result = ExplicitSignature.getReturnLoc(); 13504 unsigned Size = Result.getFullDataSize(); 13505 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size); 13506 Sig->getTypeLoc().initializeFullCopy(Result, Size); 13507 13508 ExplicitSignature = FunctionProtoTypeLoc(); 13509 } 13510 } 13511 13512 CurBlock->TheDecl->setSignatureAsWritten(Sig); 13513 CurBlock->FunctionType = T; 13514 13515 const FunctionType *Fn = T->getAs<FunctionType>(); 13516 QualType RetTy = Fn->getReturnType(); 13517 bool isVariadic = 13518 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic()); 13519 13520 CurBlock->TheDecl->setIsVariadic(isVariadic); 13521 13522 // Context.DependentTy is used as a placeholder for a missing block 13523 // return type. TODO: what should we do with declarators like: 13524 // ^ * { ... } 13525 // If the answer is "apply template argument deduction".... 13526 if (RetTy != Context.DependentTy) { 13527 CurBlock->ReturnType = RetTy; 13528 CurBlock->TheDecl->setBlockMissingReturnType(false); 13529 CurBlock->HasImplicitReturnType = false; 13530 } 13531 13532 // Push block parameters from the declarator if we had them. 13533 SmallVector<ParmVarDecl*, 8> Params; 13534 if (ExplicitSignature) { 13535 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) { 13536 ParmVarDecl *Param = ExplicitSignature.getParam(I); 13537 if (Param->getIdentifier() == nullptr && 13538 !Param->isImplicit() && 13539 !Param->isInvalidDecl() && 13540 !getLangOpts().CPlusPlus) 13541 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 13542 Params.push_back(Param); 13543 } 13544 13545 // Fake up parameter variables if we have a typedef, like 13546 // ^ fntype { ... } 13547 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) { 13548 for (const auto &I : Fn->param_types()) { 13549 ParmVarDecl *Param = BuildParmVarDeclForTypedef( 13550 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I); 13551 Params.push_back(Param); 13552 } 13553 } 13554 13555 // Set the parameters on the block decl. 13556 if (!Params.empty()) { 13557 CurBlock->TheDecl->setParams(Params); 13558 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(), 13559 /*CheckParameterNames=*/false); 13560 } 13561 13562 // Finally we can process decl attributes. 13563 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo); 13564 13565 // Put the parameter variables in scope. 13566 for (auto AI : CurBlock->TheDecl->parameters()) { 13567 AI->setOwningFunction(CurBlock->TheDecl); 13568 13569 // If this has an identifier, add it to the scope stack. 13570 if (AI->getIdentifier()) { 13571 CheckShadow(CurBlock->TheScope, AI); 13572 13573 PushOnScopeChains(AI, CurBlock->TheScope); 13574 } 13575 } 13576 } 13577 13578 /// ActOnBlockError - If there is an error parsing a block, this callback 13579 /// is invoked to pop the information about the block from the action impl. 13580 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) { 13581 // Leave the expression-evaluation context. 13582 DiscardCleanupsInEvaluationContext(); 13583 PopExpressionEvaluationContext(); 13584 13585 // Pop off CurBlock, handle nested blocks. 13586 PopDeclContext(); 13587 PopFunctionScopeInfo(); 13588 } 13589 13590 /// ActOnBlockStmtExpr - This is called when the body of a block statement 13591 /// literal was successfully completed. ^(int x){...} 13592 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, 13593 Stmt *Body, Scope *CurScope) { 13594 // If blocks are disabled, emit an error. 13595 if (!LangOpts.Blocks) 13596 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL; 13597 13598 // Leave the expression-evaluation context. 13599 if (hasAnyUnrecoverableErrorsInThisFunction()) 13600 DiscardCleanupsInEvaluationContext(); 13601 assert(!Cleanup.exprNeedsCleanups() && 13602 "cleanups within block not correctly bound!"); 13603 PopExpressionEvaluationContext(); 13604 13605 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back()); 13606 BlockDecl *BD = BSI->TheDecl; 13607 13608 if (BSI->HasImplicitReturnType) 13609 deduceClosureReturnType(*BSI); 13610 13611 PopDeclContext(); 13612 13613 QualType RetTy = Context.VoidTy; 13614 if (!BSI->ReturnType.isNull()) 13615 RetTy = BSI->ReturnType; 13616 13617 bool NoReturn = BD->hasAttr<NoReturnAttr>(); 13618 QualType BlockTy; 13619 13620 // Set the captured variables on the block. 13621 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo! 13622 SmallVector<BlockDecl::Capture, 4> Captures; 13623 for (Capture &Cap : BSI->Captures) { 13624 if (Cap.isThisCapture()) 13625 continue; 13626 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(), 13627 Cap.isNested(), Cap.getInitExpr()); 13628 Captures.push_back(NewCap); 13629 } 13630 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0); 13631 13632 // If the user wrote a function type in some form, try to use that. 13633 if (!BSI->FunctionType.isNull()) { 13634 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>(); 13635 13636 FunctionType::ExtInfo Ext = FTy->getExtInfo(); 13637 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true); 13638 13639 // Turn protoless block types into nullary block types. 13640 if (isa<FunctionNoProtoType>(FTy)) { 13641 FunctionProtoType::ExtProtoInfo EPI; 13642 EPI.ExtInfo = Ext; 13643 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13644 13645 // Otherwise, if we don't need to change anything about the function type, 13646 // preserve its sugar structure. 13647 } else if (FTy->getReturnType() == RetTy && 13648 (!NoReturn || FTy->getNoReturnAttr())) { 13649 BlockTy = BSI->FunctionType; 13650 13651 // Otherwise, make the minimal modifications to the function type. 13652 } else { 13653 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy); 13654 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13655 EPI.TypeQuals = 0; // FIXME: silently? 13656 EPI.ExtInfo = Ext; 13657 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI); 13658 } 13659 13660 // If we don't have a function type, just build one from nothing. 13661 } else { 13662 FunctionProtoType::ExtProtoInfo EPI; 13663 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn); 13664 BlockTy = Context.getFunctionType(RetTy, None, EPI); 13665 } 13666 13667 DiagnoseUnusedParameters(BD->parameters()); 13668 BlockTy = Context.getBlockPointerType(BlockTy); 13669 13670 // If needed, diagnose invalid gotos and switches in the block. 13671 if (getCurFunction()->NeedsScopeChecking() && 13672 !PP.isCodeCompletionEnabled()) 13673 DiagnoseInvalidJumps(cast<CompoundStmt>(Body)); 13674 13675 BD->setBody(cast<CompoundStmt>(Body)); 13676 13677 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13678 DiagnoseUnguardedAvailabilityViolations(BD); 13679 13680 // Try to apply the named return value optimization. We have to check again 13681 // if we can do this, though, because blocks keep return statements around 13682 // to deduce an implicit return type. 13683 if (getLangOpts().CPlusPlus && RetTy->isRecordType() && 13684 !BD->isDependentContext()) 13685 computeNRVO(Body, BSI); 13686 13687 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy); 13688 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13689 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result); 13690 13691 // If the block isn't obviously global, i.e. it captures anything at 13692 // all, then we need to do a few things in the surrounding context: 13693 if (Result->getBlockDecl()->hasCaptures()) { 13694 // First, this expression has a new cleanup object. 13695 ExprCleanupObjects.push_back(Result->getBlockDecl()); 13696 Cleanup.setExprNeedsCleanups(true); 13697 13698 // It also gets a branch-protected scope if any of the captured 13699 // variables needs destruction. 13700 for (const auto &CI : Result->getBlockDecl()->captures()) { 13701 const VarDecl *var = CI.getVariable(); 13702 if (var->getType().isDestructedType() != QualType::DK_none) { 13703 setFunctionHasBranchProtectedScope(); 13704 break; 13705 } 13706 } 13707 } 13708 13709 if (getCurFunction()) 13710 getCurFunction()->addBlock(BD); 13711 13712 return Result; 13713 } 13714 13715 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 13716 SourceLocation RPLoc) { 13717 TypeSourceInfo *TInfo; 13718 GetTypeFromParser(Ty, &TInfo); 13719 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc); 13720 } 13721 13722 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc, 13723 Expr *E, TypeSourceInfo *TInfo, 13724 SourceLocation RPLoc) { 13725 Expr *OrigExpr = E; 13726 bool IsMS = false; 13727 13728 // CUDA device code does not support varargs. 13729 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 13730 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) { 13731 CUDAFunctionTarget T = IdentifyCUDATarget(F); 13732 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice) 13733 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device)); 13734 } 13735 } 13736 13737 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg() 13738 // as Microsoft ABI on an actual Microsoft platform, where 13739 // __builtin_ms_va_list and __builtin_va_list are the same.) 13740 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() && 13741 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) { 13742 QualType MSVaListType = Context.getBuiltinMSVaListType(); 13743 if (Context.hasSameType(MSVaListType, E->getType())) { 13744 if (CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13745 return ExprError(); 13746 IsMS = true; 13747 } 13748 } 13749 13750 // Get the va_list type 13751 QualType VaListType = Context.getBuiltinVaListType(); 13752 if (!IsMS) { 13753 if (VaListType->isArrayType()) { 13754 // Deal with implicit array decay; for example, on x86-64, 13755 // va_list is an array, but it's supposed to decay to 13756 // a pointer for va_arg. 13757 VaListType = Context.getArrayDecayedType(VaListType); 13758 // Make sure the input expression also decays appropriately. 13759 ExprResult Result = UsualUnaryConversions(E); 13760 if (Result.isInvalid()) 13761 return ExprError(); 13762 E = Result.get(); 13763 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) { 13764 // If va_list is a record type and we are compiling in C++ mode, 13765 // check the argument using reference binding. 13766 InitializedEntity Entity = InitializedEntity::InitializeParameter( 13767 Context, Context.getLValueReferenceType(VaListType), false); 13768 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E); 13769 if (Init.isInvalid()) 13770 return ExprError(); 13771 E = Init.getAs<Expr>(); 13772 } else { 13773 // Otherwise, the va_list argument must be an l-value because 13774 // it is modified by va_arg. 13775 if (!E->isTypeDependent() && 13776 CheckForModifiableLvalue(E, BuiltinLoc, *this)) 13777 return ExprError(); 13778 } 13779 } 13780 13781 if (!IsMS && !E->isTypeDependent() && 13782 !Context.hasSameType(VaListType, E->getType())) 13783 return ExprError( 13784 Diag(E->getBeginLoc(), 13785 diag::err_first_argument_to_va_arg_not_of_type_va_list) 13786 << OrigExpr->getType() << E->getSourceRange()); 13787 13788 if (!TInfo->getType()->isDependentType()) { 13789 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(), 13790 diag::err_second_parameter_to_va_arg_incomplete, 13791 TInfo->getTypeLoc())) 13792 return ExprError(); 13793 13794 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(), 13795 TInfo->getType(), 13796 diag::err_second_parameter_to_va_arg_abstract, 13797 TInfo->getTypeLoc())) 13798 return ExprError(); 13799 13800 if (!TInfo->getType().isPODType(Context)) { 13801 Diag(TInfo->getTypeLoc().getBeginLoc(), 13802 TInfo->getType()->isObjCLifetimeType() 13803 ? diag::warn_second_parameter_to_va_arg_ownership_qualified 13804 : diag::warn_second_parameter_to_va_arg_not_pod) 13805 << TInfo->getType() 13806 << TInfo->getTypeLoc().getSourceRange(); 13807 } 13808 13809 // Check for va_arg where arguments of the given type will be promoted 13810 // (i.e. this va_arg is guaranteed to have undefined behavior). 13811 QualType PromoteType; 13812 if (TInfo->getType()->isPromotableIntegerType()) { 13813 PromoteType = Context.getPromotedIntegerType(TInfo->getType()); 13814 if (Context.typesAreCompatible(PromoteType, TInfo->getType())) 13815 PromoteType = QualType(); 13816 } 13817 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float)) 13818 PromoteType = Context.DoubleTy; 13819 if (!PromoteType.isNull()) 13820 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E, 13821 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible) 13822 << TInfo->getType() 13823 << PromoteType 13824 << TInfo->getTypeLoc().getSourceRange()); 13825 } 13826 13827 QualType T = TInfo->getType().getNonLValueExprType(Context); 13828 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS); 13829 } 13830 13831 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) { 13832 // The type of __null will be int or long, depending on the size of 13833 // pointers on the target. 13834 QualType Ty; 13835 unsigned pw = Context.getTargetInfo().getPointerWidth(0); 13836 if (pw == Context.getTargetInfo().getIntWidth()) 13837 Ty = Context.IntTy; 13838 else if (pw == Context.getTargetInfo().getLongWidth()) 13839 Ty = Context.LongTy; 13840 else if (pw == Context.getTargetInfo().getLongLongWidth()) 13841 Ty = Context.LongLongTy; 13842 else { 13843 llvm_unreachable("I don't know size of pointer!"); 13844 } 13845 13846 return new (Context) GNUNullExpr(Ty, TokenLoc); 13847 } 13848 13849 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp, 13850 bool Diagnose) { 13851 if (!getLangOpts().ObjC) 13852 return false; 13853 13854 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>(); 13855 if (!PT) 13856 return false; 13857 13858 if (!PT->isObjCIdType()) { 13859 // Check if the destination is the 'NSString' interface. 13860 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl(); 13861 if (!ID || !ID->getIdentifier()->isStr("NSString")) 13862 return false; 13863 } 13864 13865 // Ignore any parens, implicit casts (should only be 13866 // array-to-pointer decays), and not-so-opaque values. The last is 13867 // important for making this trigger for property assignments. 13868 Expr *SrcExpr = Exp->IgnoreParenImpCasts(); 13869 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr)) 13870 if (OV->getSourceExpr()) 13871 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts(); 13872 13873 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr); 13874 if (!SL || !SL->isAscii()) 13875 return false; 13876 if (Diagnose) { 13877 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix) 13878 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@"); 13879 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get(); 13880 } 13881 return true; 13882 } 13883 13884 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, 13885 const Expr *SrcExpr) { 13886 if (!DstType->isFunctionPointerType() || 13887 !SrcExpr->getType()->isFunctionType()) 13888 return false; 13889 13890 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts()); 13891 if (!DRE) 13892 return false; 13893 13894 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 13895 if (!FD) 13896 return false; 13897 13898 return !S.checkAddressOfFunctionIsAvailable(FD, 13899 /*Complain=*/true, 13900 SrcExpr->getBeginLoc()); 13901 } 13902 13903 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy, 13904 SourceLocation Loc, 13905 QualType DstType, QualType SrcType, 13906 Expr *SrcExpr, AssignmentAction Action, 13907 bool *Complained) { 13908 if (Complained) 13909 *Complained = false; 13910 13911 // Decode the result (notice that AST's are still created for extensions). 13912 bool CheckInferredResultType = false; 13913 bool isInvalid = false; 13914 unsigned DiagKind = 0; 13915 FixItHint Hint; 13916 ConversionFixItGenerator ConvHints; 13917 bool MayHaveConvFixit = false; 13918 bool MayHaveFunctionDiff = false; 13919 const ObjCInterfaceDecl *IFace = nullptr; 13920 const ObjCProtocolDecl *PDecl = nullptr; 13921 13922 switch (ConvTy) { 13923 case Compatible: 13924 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr); 13925 return false; 13926 13927 case PointerToInt: 13928 DiagKind = diag::ext_typecheck_convert_pointer_int; 13929 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13930 MayHaveConvFixit = true; 13931 break; 13932 case IntToPointer: 13933 DiagKind = diag::ext_typecheck_convert_int_pointer; 13934 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13935 MayHaveConvFixit = true; 13936 break; 13937 case IncompatiblePointer: 13938 if (Action == AA_Passing_CFAudited) 13939 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer; 13940 else if (SrcType->isFunctionPointerType() && 13941 DstType->isFunctionPointerType()) 13942 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer; 13943 else 13944 DiagKind = diag::ext_typecheck_convert_incompatible_pointer; 13945 13946 CheckInferredResultType = DstType->isObjCObjectPointerType() && 13947 SrcType->isObjCObjectPointerType(); 13948 if (Hint.isNull() && !CheckInferredResultType) { 13949 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 13950 } 13951 else if (CheckInferredResultType) { 13952 SrcType = SrcType.getUnqualifiedType(); 13953 DstType = DstType.getUnqualifiedType(); 13954 } 13955 MayHaveConvFixit = true; 13956 break; 13957 case IncompatiblePointerSign: 13958 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign; 13959 break; 13960 case FunctionVoidPointer: 13961 DiagKind = diag::ext_typecheck_convert_pointer_void_func; 13962 break; 13963 case IncompatiblePointerDiscardsQualifiers: { 13964 // Perform array-to-pointer decay if necessary. 13965 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType); 13966 13967 Qualifiers lhq = SrcType->getPointeeType().getQualifiers(); 13968 Qualifiers rhq = DstType->getPointeeType().getQualifiers(); 13969 if (lhq.getAddressSpace() != rhq.getAddressSpace()) { 13970 DiagKind = diag::err_typecheck_incompatible_address_space; 13971 break; 13972 13973 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) { 13974 DiagKind = diag::err_typecheck_incompatible_ownership; 13975 break; 13976 } 13977 13978 llvm_unreachable("unknown error case for discarding qualifiers!"); 13979 // fallthrough 13980 } 13981 case CompatiblePointerDiscardsQualifiers: 13982 // If the qualifiers lost were because we were applying the 13983 // (deprecated) C++ conversion from a string literal to a char* 13984 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME: 13985 // Ideally, this check would be performed in 13986 // checkPointerTypesForAssignment. However, that would require a 13987 // bit of refactoring (so that the second argument is an 13988 // expression, rather than a type), which should be done as part 13989 // of a larger effort to fix checkPointerTypesForAssignment for 13990 // C++ semantics. 13991 if (getLangOpts().CPlusPlus && 13992 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType)) 13993 return false; 13994 DiagKind = diag::ext_typecheck_convert_discards_qualifiers; 13995 break; 13996 case IncompatibleNestedPointerQualifiers: 13997 DiagKind = diag::ext_nested_pointer_qualifier_mismatch; 13998 break; 13999 case IntToBlockPointer: 14000 DiagKind = diag::err_int_to_block_pointer; 14001 break; 14002 case IncompatibleBlockPointer: 14003 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer; 14004 break; 14005 case IncompatibleObjCQualifiedId: { 14006 if (SrcType->isObjCQualifiedIdType()) { 14007 const ObjCObjectPointerType *srcOPT = 14008 SrcType->getAs<ObjCObjectPointerType>(); 14009 for (auto *srcProto : srcOPT->quals()) { 14010 PDecl = srcProto; 14011 break; 14012 } 14013 if (const ObjCInterfaceType *IFaceT = 14014 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 14015 IFace = IFaceT->getDecl(); 14016 } 14017 else if (DstType->isObjCQualifiedIdType()) { 14018 const ObjCObjectPointerType *dstOPT = 14019 DstType->getAs<ObjCObjectPointerType>(); 14020 for (auto *dstProto : dstOPT->quals()) { 14021 PDecl = dstProto; 14022 break; 14023 } 14024 if (const ObjCInterfaceType *IFaceT = 14025 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType()) 14026 IFace = IFaceT->getDecl(); 14027 } 14028 DiagKind = diag::warn_incompatible_qualified_id; 14029 break; 14030 } 14031 case IncompatibleVectors: 14032 DiagKind = diag::warn_incompatible_vectors; 14033 break; 14034 case IncompatibleObjCWeakRef: 14035 DiagKind = diag::err_arc_weak_unavailable_assign; 14036 break; 14037 case Incompatible: 14038 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) { 14039 if (Complained) 14040 *Complained = true; 14041 return true; 14042 } 14043 14044 DiagKind = diag::err_typecheck_convert_incompatible; 14045 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this); 14046 MayHaveConvFixit = true; 14047 isInvalid = true; 14048 MayHaveFunctionDiff = true; 14049 break; 14050 } 14051 14052 QualType FirstType, SecondType; 14053 switch (Action) { 14054 case AA_Assigning: 14055 case AA_Initializing: 14056 // The destination type comes first. 14057 FirstType = DstType; 14058 SecondType = SrcType; 14059 break; 14060 14061 case AA_Returning: 14062 case AA_Passing: 14063 case AA_Passing_CFAudited: 14064 case AA_Converting: 14065 case AA_Sending: 14066 case AA_Casting: 14067 // The source type comes first. 14068 FirstType = SrcType; 14069 SecondType = DstType; 14070 break; 14071 } 14072 14073 PartialDiagnostic FDiag = PDiag(DiagKind); 14074 if (Action == AA_Passing_CFAudited) 14075 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange(); 14076 else 14077 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange(); 14078 14079 // If we can fix the conversion, suggest the FixIts. 14080 assert(ConvHints.isNull() || Hint.isNull()); 14081 if (!ConvHints.isNull()) { 14082 for (FixItHint &H : ConvHints.Hints) 14083 FDiag << H; 14084 } else { 14085 FDiag << Hint; 14086 } 14087 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); } 14088 14089 if (MayHaveFunctionDiff) 14090 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType); 14091 14092 Diag(Loc, FDiag); 14093 if (DiagKind == diag::warn_incompatible_qualified_id && 14094 PDecl && IFace && !IFace->hasDefinition()) 14095 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id) 14096 << IFace << PDecl; 14097 14098 if (SecondType == Context.OverloadTy) 14099 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression, 14100 FirstType, /*TakingAddress=*/true); 14101 14102 if (CheckInferredResultType) 14103 EmitRelatedResultTypeNote(SrcExpr); 14104 14105 if (Action == AA_Returning && ConvTy == IncompatiblePointer) 14106 EmitRelatedResultTypeNoteForReturn(DstType); 14107 14108 if (Complained) 14109 *Complained = true; 14110 return isInvalid; 14111 } 14112 14113 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14114 llvm::APSInt *Result) { 14115 class SimpleICEDiagnoser : public VerifyICEDiagnoser { 14116 public: 14117 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14118 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR; 14119 } 14120 } Diagnoser; 14121 14122 return VerifyIntegerConstantExpression(E, Result, Diagnoser); 14123 } 14124 14125 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, 14126 llvm::APSInt *Result, 14127 unsigned DiagID, 14128 bool AllowFold) { 14129 class IDDiagnoser : public VerifyICEDiagnoser { 14130 unsigned DiagID; 14131 14132 public: 14133 IDDiagnoser(unsigned DiagID) 14134 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { } 14135 14136 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override { 14137 S.Diag(Loc, DiagID) << SR; 14138 } 14139 } Diagnoser(DiagID); 14140 14141 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold); 14142 } 14143 14144 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc, 14145 SourceRange SR) { 14146 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus; 14147 } 14148 14149 ExprResult 14150 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 14151 VerifyICEDiagnoser &Diagnoser, 14152 bool AllowFold) { 14153 SourceLocation DiagLoc = E->getBeginLoc(); 14154 14155 if (getLangOpts().CPlusPlus11) { 14156 // C++11 [expr.const]p5: 14157 // If an expression of literal class type is used in a context where an 14158 // integral constant expression is required, then that class type shall 14159 // have a single non-explicit conversion function to an integral or 14160 // unscoped enumeration type 14161 ExprResult Converted; 14162 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser { 14163 public: 14164 CXX11ConvertDiagnoser(bool Silent) 14165 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, 14166 Silent, true) {} 14167 14168 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 14169 QualType T) override { 14170 return S.Diag(Loc, diag::err_ice_not_integral) << T; 14171 } 14172 14173 SemaDiagnosticBuilder diagnoseIncomplete( 14174 Sema &S, SourceLocation Loc, QualType T) override { 14175 return S.Diag(Loc, diag::err_ice_incomplete_type) << T; 14176 } 14177 14178 SemaDiagnosticBuilder diagnoseExplicitConv( 14179 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14180 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy; 14181 } 14182 14183 SemaDiagnosticBuilder noteExplicitConv( 14184 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14185 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14186 << ConvTy->isEnumeralType() << ConvTy; 14187 } 14188 14189 SemaDiagnosticBuilder diagnoseAmbiguous( 14190 Sema &S, SourceLocation Loc, QualType T) override { 14191 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T; 14192 } 14193 14194 SemaDiagnosticBuilder noteAmbiguous( 14195 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 14196 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here) 14197 << ConvTy->isEnumeralType() << ConvTy; 14198 } 14199 14200 SemaDiagnosticBuilder diagnoseConversion( 14201 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 14202 llvm_unreachable("conversion functions are permitted"); 14203 } 14204 } ConvertDiagnoser(Diagnoser.Suppress); 14205 14206 Converted = PerformContextualImplicitConversion(DiagLoc, E, 14207 ConvertDiagnoser); 14208 if (Converted.isInvalid()) 14209 return Converted; 14210 E = Converted.get(); 14211 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) 14212 return ExprError(); 14213 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) { 14214 // An ICE must be of integral or unscoped enumeration type. 14215 if (!Diagnoser.Suppress) 14216 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14217 return ExprError(); 14218 } 14219 14220 if (!isa<ConstantExpr>(E)) 14221 E = ConstantExpr::Create(Context, E); 14222 14223 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice 14224 // in the non-ICE case. 14225 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) { 14226 if (Result) 14227 *Result = E->EvaluateKnownConstIntCheckOverflow(Context); 14228 return E; 14229 } 14230 14231 Expr::EvalResult EvalResult; 14232 SmallVector<PartialDiagnosticAt, 8> Notes; 14233 EvalResult.Diag = &Notes; 14234 14235 // Try to evaluate the expression, and produce diagnostics explaining why it's 14236 // not a constant expression as a side-effect. 14237 bool Folded = E->EvaluateAsRValue(EvalResult, Context) && 14238 EvalResult.Val.isInt() && !EvalResult.HasSideEffects; 14239 14240 // In C++11, we can rely on diagnostics being produced for any expression 14241 // which is not a constant expression. If no diagnostics were produced, then 14242 // this is a constant expression. 14243 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) { 14244 if (Result) 14245 *Result = EvalResult.Val.getInt(); 14246 return E; 14247 } 14248 14249 // If our only note is the usual "invalid subexpression" note, just point 14250 // the caret at its location rather than producing an essentially 14251 // redundant note. 14252 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 14253 diag::note_invalid_subexpr_in_const_expr) { 14254 DiagLoc = Notes[0].first; 14255 Notes.clear(); 14256 } 14257 14258 if (!Folded || !AllowFold) { 14259 if (!Diagnoser.Suppress) { 14260 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange()); 14261 for (const PartialDiagnosticAt &Note : Notes) 14262 Diag(Note.first, Note.second); 14263 } 14264 14265 return ExprError(); 14266 } 14267 14268 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange()); 14269 for (const PartialDiagnosticAt &Note : Notes) 14270 Diag(Note.first, Note.second); 14271 14272 if (Result) 14273 *Result = EvalResult.Val.getInt(); 14274 return E; 14275 } 14276 14277 namespace { 14278 // Handle the case where we conclude a expression which we speculatively 14279 // considered to be unevaluated is actually evaluated. 14280 class TransformToPE : public TreeTransform<TransformToPE> { 14281 typedef TreeTransform<TransformToPE> BaseTransform; 14282 14283 public: 14284 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { } 14285 14286 // Make sure we redo semantic analysis 14287 bool AlwaysRebuild() { return true; } 14288 14289 // Make sure we handle LabelStmts correctly. 14290 // FIXME: This does the right thing, but maybe we need a more general 14291 // fix to TreeTransform? 14292 StmtResult TransformLabelStmt(LabelStmt *S) { 14293 S->getDecl()->setStmt(nullptr); 14294 return BaseTransform::TransformLabelStmt(S); 14295 } 14296 14297 // We need to special-case DeclRefExprs referring to FieldDecls which 14298 // are not part of a member pointer formation; normal TreeTransforming 14299 // doesn't catch this case because of the way we represent them in the AST. 14300 // FIXME: This is a bit ugly; is it really the best way to handle this 14301 // case? 14302 // 14303 // Error on DeclRefExprs referring to FieldDecls. 14304 ExprResult TransformDeclRefExpr(DeclRefExpr *E) { 14305 if (isa<FieldDecl>(E->getDecl()) && 14306 !SemaRef.isUnevaluatedContext()) 14307 return SemaRef.Diag(E->getLocation(), 14308 diag::err_invalid_non_static_member_use) 14309 << E->getDecl() << E->getSourceRange(); 14310 14311 return BaseTransform::TransformDeclRefExpr(E); 14312 } 14313 14314 // Exception: filter out member pointer formation 14315 ExprResult TransformUnaryOperator(UnaryOperator *E) { 14316 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType()) 14317 return E; 14318 14319 return BaseTransform::TransformUnaryOperator(E); 14320 } 14321 14322 ExprResult TransformLambdaExpr(LambdaExpr *E) { 14323 // Lambdas never need to be transformed. 14324 return E; 14325 } 14326 }; 14327 } 14328 14329 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) { 14330 assert(isUnevaluatedContext() && 14331 "Should only transform unevaluated expressions"); 14332 ExprEvalContexts.back().Context = 14333 ExprEvalContexts[ExprEvalContexts.size()-2].Context; 14334 if (isUnevaluatedContext()) 14335 return E; 14336 return TransformToPE(*this).TransformExpr(E); 14337 } 14338 14339 void 14340 Sema::PushExpressionEvaluationContext( 14341 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl, 14342 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14343 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup, 14344 LambdaContextDecl, ExprContext); 14345 Cleanup.reset(); 14346 if (!MaybeODRUseExprs.empty()) 14347 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs); 14348 } 14349 14350 void 14351 Sema::PushExpressionEvaluationContext( 14352 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, 14353 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) { 14354 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl; 14355 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext); 14356 } 14357 14358 void Sema::PopExpressionEvaluationContext() { 14359 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back(); 14360 unsigned NumTypos = Rec.NumTypos; 14361 14362 if (!Rec.Lambdas.empty()) { 14363 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind; 14364 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() || 14365 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) { 14366 unsigned D; 14367 if (Rec.isUnevaluated()) { 14368 // C++11 [expr.prim.lambda]p2: 14369 // A lambda-expression shall not appear in an unevaluated operand 14370 // (Clause 5). 14371 D = diag::err_lambda_unevaluated_operand; 14372 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) { 14373 // C++1y [expr.const]p2: 14374 // A conditional-expression e is a core constant expression unless the 14375 // evaluation of e, following the rules of the abstract machine, would 14376 // evaluate [...] a lambda-expression. 14377 D = diag::err_lambda_in_constant_expression; 14378 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) { 14379 // C++17 [expr.prim.lamda]p2: 14380 // A lambda-expression shall not appear [...] in a template-argument. 14381 D = diag::err_lambda_in_invalid_context; 14382 } else 14383 llvm_unreachable("Couldn't infer lambda error message."); 14384 14385 for (const auto *L : Rec.Lambdas) 14386 Diag(L->getBeginLoc(), D); 14387 } else { 14388 // Mark the capture expressions odr-used. This was deferred 14389 // during lambda expression creation. 14390 for (auto *Lambda : Rec.Lambdas) { 14391 for (auto *C : Lambda->capture_inits()) 14392 MarkDeclarationsReferencedInExpr(C); 14393 } 14394 } 14395 } 14396 14397 // When are coming out of an unevaluated context, clear out any 14398 // temporaries that we may have created as part of the evaluation of 14399 // the expression in that context: they aren't relevant because they 14400 // will never be constructed. 14401 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) { 14402 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects, 14403 ExprCleanupObjects.end()); 14404 Cleanup = Rec.ParentCleanup; 14405 CleanupVarDeclMarking(); 14406 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs); 14407 // Otherwise, merge the contexts together. 14408 } else { 14409 Cleanup.mergeFrom(Rec.ParentCleanup); 14410 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(), 14411 Rec.SavedMaybeODRUseExprs.end()); 14412 } 14413 14414 // Pop the current expression evaluation context off the stack. 14415 ExprEvalContexts.pop_back(); 14416 14417 if (!ExprEvalContexts.empty()) 14418 ExprEvalContexts.back().NumTypos += NumTypos; 14419 else 14420 assert(NumTypos == 0 && "There are outstanding typos after popping the " 14421 "last ExpressionEvaluationContextRecord"); 14422 } 14423 14424 void Sema::DiscardCleanupsInEvaluationContext() { 14425 ExprCleanupObjects.erase( 14426 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects, 14427 ExprCleanupObjects.end()); 14428 Cleanup.reset(); 14429 MaybeODRUseExprs.clear(); 14430 } 14431 14432 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) { 14433 if (!E->getType()->isVariablyModifiedType()) 14434 return E; 14435 return TransformToPotentiallyEvaluated(E); 14436 } 14437 14438 /// Are we within a context in which some evaluation could be performed (be it 14439 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite 14440 /// captured by C++'s idea of an "unevaluated context". 14441 static bool isEvaluatableContext(Sema &SemaRef) { 14442 switch (SemaRef.ExprEvalContexts.back().Context) { 14443 case Sema::ExpressionEvaluationContext::Unevaluated: 14444 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14445 // Expressions in this context are never evaluated. 14446 return false; 14447 14448 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14449 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14450 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14451 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14452 // Expressions in this context could be evaluated. 14453 return true; 14454 14455 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14456 // Referenced declarations will only be used if the construct in the 14457 // containing expression is used, at which point we'll be given another 14458 // turn to mark them. 14459 return false; 14460 } 14461 llvm_unreachable("Invalid context"); 14462 } 14463 14464 /// Are we within a context in which references to resolved functions or to 14465 /// variables result in odr-use? 14466 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) { 14467 // An expression in a template is not really an expression until it's been 14468 // instantiated, so it doesn't trigger odr-use. 14469 if (SkipDependentUses && SemaRef.CurContext->isDependentContext()) 14470 return false; 14471 14472 switch (SemaRef.ExprEvalContexts.back().Context) { 14473 case Sema::ExpressionEvaluationContext::Unevaluated: 14474 case Sema::ExpressionEvaluationContext::UnevaluatedList: 14475 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract: 14476 case Sema::ExpressionEvaluationContext::DiscardedStatement: 14477 return false; 14478 14479 case Sema::ExpressionEvaluationContext::ConstantEvaluated: 14480 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated: 14481 return true; 14482 14483 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 14484 return false; 14485 } 14486 llvm_unreachable("Invalid context"); 14487 } 14488 14489 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) { 14490 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func); 14491 return Func->isConstexpr() && 14492 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided())); 14493 } 14494 14495 /// Mark a function referenced, and check whether it is odr-used 14496 /// (C++ [basic.def.odr]p2, C99 6.9p3) 14497 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, 14498 bool MightBeOdrUse) { 14499 assert(Func && "No function?"); 14500 14501 Func->setReferenced(); 14502 14503 // C++11 [basic.def.odr]p3: 14504 // A function whose name appears as a potentially-evaluated expression is 14505 // odr-used if it is the unique lookup result or the selected member of a 14506 // set of overloaded functions [...]. 14507 // 14508 // We (incorrectly) mark overload resolution as an unevaluated context, so we 14509 // can just check that here. 14510 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this); 14511 14512 // Determine whether we require a function definition to exist, per 14513 // C++11 [temp.inst]p3: 14514 // Unless a function template specialization has been explicitly 14515 // instantiated or explicitly specialized, the function template 14516 // specialization is implicitly instantiated when the specialization is 14517 // referenced in a context that requires a function definition to exist. 14518 // 14519 // That is either when this is an odr-use, or when a usage of a constexpr 14520 // function occurs within an evaluatable context. 14521 bool NeedDefinition = 14522 OdrUse || (isEvaluatableContext(*this) && 14523 isImplicitlyDefinableConstexprFunction(Func)); 14524 14525 // C++14 [temp.expl.spec]p6: 14526 // If a template [...] is explicitly specialized then that specialization 14527 // shall be declared before the first use of that specialization that would 14528 // cause an implicit instantiation to take place, in every translation unit 14529 // in which such a use occurs 14530 if (NeedDefinition && 14531 (Func->getTemplateSpecializationKind() != TSK_Undeclared || 14532 Func->getMemberSpecializationInfo())) 14533 checkSpecializationVisibility(Loc, Func); 14534 14535 // C++14 [except.spec]p17: 14536 // An exception-specification is considered to be needed when: 14537 // - the function is odr-used or, if it appears in an unevaluated operand, 14538 // would be odr-used if the expression were potentially-evaluated; 14539 // 14540 // Note, we do this even if MightBeOdrUse is false. That indicates that the 14541 // function is a pure virtual function we're calling, and in that case the 14542 // function was selected by overload resolution and we need to resolve its 14543 // exception specification for a different reason. 14544 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>(); 14545 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) 14546 ResolveExceptionSpec(Loc, FPT); 14547 14548 // If we don't need to mark the function as used, and we don't need to 14549 // try to provide a definition, there's nothing more to do. 14550 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) && 14551 (!NeedDefinition || Func->getBody())) 14552 return; 14553 14554 // Note that this declaration has been used. 14555 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) { 14556 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl()); 14557 if (Constructor->isDefaulted() && !Constructor->isDeleted()) { 14558 if (Constructor->isDefaultConstructor()) { 14559 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>()) 14560 return; 14561 DefineImplicitDefaultConstructor(Loc, Constructor); 14562 } else if (Constructor->isCopyConstructor()) { 14563 DefineImplicitCopyConstructor(Loc, Constructor); 14564 } else if (Constructor->isMoveConstructor()) { 14565 DefineImplicitMoveConstructor(Loc, Constructor); 14566 } 14567 } else if (Constructor->getInheritedConstructor()) { 14568 DefineInheritingConstructor(Loc, Constructor); 14569 } 14570 } else if (CXXDestructorDecl *Destructor = 14571 dyn_cast<CXXDestructorDecl>(Func)) { 14572 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl()); 14573 if (Destructor->isDefaulted() && !Destructor->isDeleted()) { 14574 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>()) 14575 return; 14576 DefineImplicitDestructor(Loc, Destructor); 14577 } 14578 if (Destructor->isVirtual() && getLangOpts().AppleKext) 14579 MarkVTableUsed(Loc, Destructor->getParent()); 14580 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) { 14581 if (MethodDecl->isOverloadedOperator() && 14582 MethodDecl->getOverloadedOperator() == OO_Equal) { 14583 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl()); 14584 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) { 14585 if (MethodDecl->isCopyAssignmentOperator()) 14586 DefineImplicitCopyAssignment(Loc, MethodDecl); 14587 else if (MethodDecl->isMoveAssignmentOperator()) 14588 DefineImplicitMoveAssignment(Loc, MethodDecl); 14589 } 14590 } else if (isa<CXXConversionDecl>(MethodDecl) && 14591 MethodDecl->getParent()->isLambda()) { 14592 CXXConversionDecl *Conversion = 14593 cast<CXXConversionDecl>(MethodDecl->getFirstDecl()); 14594 if (Conversion->isLambdaToBlockPointerConversion()) 14595 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion); 14596 else 14597 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion); 14598 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext) 14599 MarkVTableUsed(Loc, MethodDecl->getParent()); 14600 } 14601 14602 // Recursive functions should be marked when used from another function. 14603 // FIXME: Is this really right? 14604 if (CurContext == Func) return; 14605 14606 // Implicit instantiation of function templates and member functions of 14607 // class templates. 14608 if (Func->isImplicitlyInstantiable()) { 14609 TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind(); 14610 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation(); 14611 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 14612 if (FirstInstantiation) { 14613 PointOfInstantiation = Loc; 14614 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation); 14615 } else if (TSK != TSK_ImplicitInstantiation) { 14616 // Use the point of use as the point of instantiation, instead of the 14617 // point of explicit instantiation (which we track as the actual point of 14618 // instantiation). This gives better backtraces in diagnostics. 14619 PointOfInstantiation = Loc; 14620 } 14621 14622 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation || 14623 Func->isConstexpr()) { 14624 if (isa<CXXRecordDecl>(Func->getDeclContext()) && 14625 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() && 14626 CodeSynthesisContexts.size()) 14627 PendingLocalImplicitInstantiations.push_back( 14628 std::make_pair(Func, PointOfInstantiation)); 14629 else if (Func->isConstexpr()) 14630 // Do not defer instantiations of constexpr functions, to avoid the 14631 // expression evaluator needing to call back into Sema if it sees a 14632 // call to such a function. 14633 InstantiateFunctionDefinition(PointOfInstantiation, Func); 14634 else { 14635 Func->setInstantiationIsPending(true); 14636 PendingInstantiations.push_back(std::make_pair(Func, 14637 PointOfInstantiation)); 14638 // Notify the consumer that a function was implicitly instantiated. 14639 Consumer.HandleCXXImplicitFunctionInstantiation(Func); 14640 } 14641 } 14642 } else { 14643 // Walk redefinitions, as some of them may be instantiable. 14644 for (auto i : Func->redecls()) { 14645 if (!i->isUsed(false) && i->isImplicitlyInstantiable()) 14646 MarkFunctionReferenced(Loc, i, OdrUse); 14647 } 14648 } 14649 14650 if (!OdrUse) return; 14651 14652 // Keep track of used but undefined functions. 14653 if (!Func->isDefined()) { 14654 if (mightHaveNonExternalLinkage(Func)) 14655 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14656 else if (Func->getMostRecentDecl()->isInlined() && 14657 !LangOpts.GNUInline && 14658 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>()) 14659 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14660 else if (isExternalWithNoLinkageType(Func)) 14661 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc)); 14662 } 14663 14664 Func->markUsed(Context); 14665 } 14666 14667 static void 14668 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc, 14669 ValueDecl *var, DeclContext *DC) { 14670 DeclContext *VarDC = var->getDeclContext(); 14671 14672 // If the parameter still belongs to the translation unit, then 14673 // we're actually just using one parameter in the declaration of 14674 // the next. 14675 if (isa<ParmVarDecl>(var) && 14676 isa<TranslationUnitDecl>(VarDC)) 14677 return; 14678 14679 // For C code, don't diagnose about capture if we're not actually in code 14680 // right now; it's impossible to write a non-constant expression outside of 14681 // function context, so we'll get other (more useful) diagnostics later. 14682 // 14683 // For C++, things get a bit more nasty... it would be nice to suppress this 14684 // diagnostic for certain cases like using a local variable in an array bound 14685 // for a member of a local class, but the correct predicate is not obvious. 14686 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod()) 14687 return; 14688 14689 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0; 14690 unsigned ContextKind = 3; // unknown 14691 if (isa<CXXMethodDecl>(VarDC) && 14692 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) { 14693 ContextKind = 2; 14694 } else if (isa<FunctionDecl>(VarDC)) { 14695 ContextKind = 0; 14696 } else if (isa<BlockDecl>(VarDC)) { 14697 ContextKind = 1; 14698 } 14699 14700 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context) 14701 << var << ValueKind << ContextKind << VarDC; 14702 S.Diag(var->getLocation(), diag::note_entity_declared_at) 14703 << var; 14704 14705 // FIXME: Add additional diagnostic info about class etc. which prevents 14706 // capture. 14707 } 14708 14709 14710 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var, 14711 bool &SubCapturesAreNested, 14712 QualType &CaptureType, 14713 QualType &DeclRefType) { 14714 // Check whether we've already captured it. 14715 if (CSI->CaptureMap.count(Var)) { 14716 // If we found a capture, any subcaptures are nested. 14717 SubCapturesAreNested = true; 14718 14719 // Retrieve the capture type for this variable. 14720 CaptureType = CSI->getCapture(Var).getCaptureType(); 14721 14722 // Compute the type of an expression that refers to this variable. 14723 DeclRefType = CaptureType.getNonReferenceType(); 14724 14725 // Similarly to mutable captures in lambda, all the OpenMP captures by copy 14726 // are mutable in the sense that user can change their value - they are 14727 // private instances of the captured declarations. 14728 const Capture &Cap = CSI->getCapture(Var); 14729 if (Cap.isCopyCapture() && 14730 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) && 14731 !(isa<CapturedRegionScopeInfo>(CSI) && 14732 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP)) 14733 DeclRefType.addConst(); 14734 return true; 14735 } 14736 return false; 14737 } 14738 14739 // Only block literals, captured statements, and lambda expressions can 14740 // capture; other scopes don't work. 14741 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var, 14742 SourceLocation Loc, 14743 const bool Diagnose, Sema &S) { 14744 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC)) 14745 return getLambdaAwareParentOfDeclContext(DC); 14746 else if (Var->hasLocalStorage()) { 14747 if (Diagnose) 14748 diagnoseUncapturableValueReference(S, Loc, Var, DC); 14749 } 14750 return nullptr; 14751 } 14752 14753 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 14754 // certain types of variables (unnamed, variably modified types etc.) 14755 // so check for eligibility. 14756 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var, 14757 SourceLocation Loc, 14758 const bool Diagnose, Sema &S) { 14759 14760 bool IsBlock = isa<BlockScopeInfo>(CSI); 14761 bool IsLambda = isa<LambdaScopeInfo>(CSI); 14762 14763 // Lambdas are not allowed to capture unnamed variables 14764 // (e.g. anonymous unions). 14765 // FIXME: The C++11 rule don't actually state this explicitly, but I'm 14766 // assuming that's the intent. 14767 if (IsLambda && !Var->getDeclName()) { 14768 if (Diagnose) { 14769 S.Diag(Loc, diag::err_lambda_capture_anonymous_var); 14770 S.Diag(Var->getLocation(), diag::note_declared_at); 14771 } 14772 return false; 14773 } 14774 14775 // Prohibit variably-modified types in blocks; they're difficult to deal with. 14776 if (Var->getType()->isVariablyModifiedType() && IsBlock) { 14777 if (Diagnose) { 14778 S.Diag(Loc, diag::err_ref_vm_type); 14779 S.Diag(Var->getLocation(), diag::note_previous_decl) 14780 << Var->getDeclName(); 14781 } 14782 return false; 14783 } 14784 // Prohibit structs with flexible array members too. 14785 // We cannot capture what is in the tail end of the struct. 14786 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) { 14787 if (VTTy->getDecl()->hasFlexibleArrayMember()) { 14788 if (Diagnose) { 14789 if (IsBlock) 14790 S.Diag(Loc, diag::err_ref_flexarray_type); 14791 else 14792 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) 14793 << Var->getDeclName(); 14794 S.Diag(Var->getLocation(), diag::note_previous_decl) 14795 << Var->getDeclName(); 14796 } 14797 return false; 14798 } 14799 } 14800 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14801 // Lambdas and captured statements are not allowed to capture __block 14802 // variables; they don't support the expected semantics. 14803 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) { 14804 if (Diagnose) { 14805 S.Diag(Loc, diag::err_capture_block_variable) 14806 << Var->getDeclName() << !IsLambda; 14807 S.Diag(Var->getLocation(), diag::note_previous_decl) 14808 << Var->getDeclName(); 14809 } 14810 return false; 14811 } 14812 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks 14813 if (S.getLangOpts().OpenCL && IsBlock && 14814 Var->getType()->isBlockPointerType()) { 14815 if (Diagnose) 14816 S.Diag(Loc, diag::err_opencl_block_ref_block); 14817 return false; 14818 } 14819 14820 return true; 14821 } 14822 14823 // Returns true if the capture by block was successful. 14824 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var, 14825 SourceLocation Loc, 14826 const bool BuildAndDiagnose, 14827 QualType &CaptureType, 14828 QualType &DeclRefType, 14829 const bool Nested, 14830 Sema &S) { 14831 Expr *CopyExpr = nullptr; 14832 bool ByRef = false; 14833 14834 // Blocks are not allowed to capture arrays, excepting OpenCL. 14835 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference 14836 // (decayed to pointers). 14837 if (!S.getLangOpts().OpenCL && CaptureType->isArrayType()) { 14838 if (BuildAndDiagnose) { 14839 S.Diag(Loc, diag::err_ref_array_type); 14840 S.Diag(Var->getLocation(), diag::note_previous_decl) 14841 << Var->getDeclName(); 14842 } 14843 return false; 14844 } 14845 14846 // Forbid the block-capture of autoreleasing variables. 14847 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 14848 if (BuildAndDiagnose) { 14849 S.Diag(Loc, diag::err_arc_autoreleasing_capture) 14850 << /*block*/ 0; 14851 S.Diag(Var->getLocation(), diag::note_previous_decl) 14852 << Var->getDeclName(); 14853 } 14854 return false; 14855 } 14856 14857 // Warn about implicitly autoreleasing indirect parameters captured by blocks. 14858 if (const auto *PT = CaptureType->getAs<PointerType>()) { 14859 // This function finds out whether there is an AttributedType of kind 14860 // attr::ObjCOwnership in Ty. The existence of AttributedType of kind 14861 // attr::ObjCOwnership implies __autoreleasing was explicitly specified 14862 // rather than being added implicitly by the compiler. 14863 auto IsObjCOwnershipAttributedType = [](QualType Ty) { 14864 while (const auto *AttrTy = Ty->getAs<AttributedType>()) { 14865 if (AttrTy->getAttrKind() == attr::ObjCOwnership) 14866 return true; 14867 14868 // Peel off AttributedTypes that are not of kind ObjCOwnership. 14869 Ty = AttrTy->getModifiedType(); 14870 } 14871 14872 return false; 14873 }; 14874 14875 QualType PointeeTy = PT->getPointeeType(); 14876 14877 if (PointeeTy->getAs<ObjCObjectPointerType>() && 14878 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing && 14879 !IsObjCOwnershipAttributedType(PointeeTy)) { 14880 if (BuildAndDiagnose) { 14881 SourceLocation VarLoc = Var->getLocation(); 14882 S.Diag(Loc, diag::warn_block_capture_autoreleasing); 14883 S.Diag(VarLoc, diag::note_declare_parameter_strong); 14884 } 14885 } 14886 } 14887 14888 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>(); 14889 if (HasBlocksAttr || CaptureType->isReferenceType() || 14890 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) { 14891 // Block capture by reference does not change the capture or 14892 // declaration reference types. 14893 ByRef = true; 14894 } else { 14895 // Block capture by copy introduces 'const'. 14896 CaptureType = CaptureType.getNonReferenceType().withConst(); 14897 DeclRefType = CaptureType; 14898 14899 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) { 14900 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) { 14901 // The capture logic needs the destructor, so make sure we mark it. 14902 // Usually this is unnecessary because most local variables have 14903 // their destructors marked at declaration time, but parameters are 14904 // an exception because it's technically only the call site that 14905 // actually requires the destructor. 14906 if (isa<ParmVarDecl>(Var)) 14907 S.FinalizeVarWithDestructor(Var, Record); 14908 14909 // Enter a new evaluation context to insulate the copy 14910 // full-expression. 14911 EnterExpressionEvaluationContext scope( 14912 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 14913 14914 // According to the blocks spec, the capture of a variable from 14915 // the stack requires a const copy constructor. This is not true 14916 // of the copy/move done to move a __block variable to the heap. 14917 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested, 14918 DeclRefType.withConst(), 14919 VK_LValue, Loc); 14920 14921 ExprResult Result 14922 = S.PerformCopyInitialization( 14923 InitializedEntity::InitializeBlock(Var->getLocation(), 14924 CaptureType, false), 14925 Loc, DeclRef); 14926 14927 // Build a full-expression copy expression if initialization 14928 // succeeded and used a non-trivial constructor. Recover from 14929 // errors by pretending that the copy isn't necessary. 14930 if (!Result.isInvalid() && 14931 !cast<CXXConstructExpr>(Result.get())->getConstructor() 14932 ->isTrivial()) { 14933 Result = S.MaybeCreateExprWithCleanups(Result); 14934 CopyExpr = Result.get(); 14935 } 14936 } 14937 } 14938 } 14939 14940 // Actually capture the variable. 14941 if (BuildAndDiagnose) 14942 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 14943 SourceLocation(), CaptureType, CopyExpr); 14944 14945 return true; 14946 14947 } 14948 14949 14950 /// Capture the given variable in the captured region. 14951 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, 14952 VarDecl *Var, 14953 SourceLocation Loc, 14954 const bool BuildAndDiagnose, 14955 QualType &CaptureType, 14956 QualType &DeclRefType, 14957 const bool RefersToCapturedVariable, 14958 Sema &S) { 14959 // By default, capture variables by reference. 14960 bool ByRef = true; 14961 // Using an LValue reference type is consistent with Lambdas (see below). 14962 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) { 14963 if (S.isOpenMPCapturedDecl(Var)) { 14964 bool HasConst = DeclRefType.isConstQualified(); 14965 DeclRefType = DeclRefType.getUnqualifiedType(); 14966 // Don't lose diagnostics about assignments to const. 14967 if (HasConst) 14968 DeclRefType.addConst(); 14969 } 14970 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel); 14971 } 14972 14973 if (ByRef) 14974 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 14975 else 14976 CaptureType = DeclRefType; 14977 14978 Expr *CopyExpr = nullptr; 14979 if (BuildAndDiagnose) { 14980 // The current implementation assumes that all variables are captured 14981 // by references. Since there is no capture by copy, no expression 14982 // evaluation will be needed. 14983 RecordDecl *RD = RSI->TheRecordDecl; 14984 14985 FieldDecl *Field 14986 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType, 14987 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc), 14988 nullptr, false, ICIS_NoInit); 14989 Field->setImplicit(true); 14990 Field->setAccess(AS_private); 14991 RD->addDecl(Field); 14992 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 14993 S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel); 14994 14995 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable, 14996 DeclRefType, VK_LValue, Loc); 14997 Var->setReferenced(true); 14998 Var->markUsed(S.Context); 14999 } 15000 15001 // Actually capture the variable. 15002 if (BuildAndDiagnose) 15003 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc, 15004 SourceLocation(), CaptureType, CopyExpr); 15005 15006 15007 return true; 15008 } 15009 15010 /// Create a field within the lambda class for the variable 15011 /// being captured. 15012 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, 15013 QualType FieldType, QualType DeclRefType, 15014 SourceLocation Loc, 15015 bool RefersToCapturedVariable) { 15016 CXXRecordDecl *Lambda = LSI->Lambda; 15017 15018 // Build the non-static data member. 15019 FieldDecl *Field 15020 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType, 15021 S.Context.getTrivialTypeSourceInfo(FieldType, Loc), 15022 nullptr, false, ICIS_NoInit); 15023 // If the variable being captured has an invalid type, mark the lambda class 15024 // as invalid as well. 15025 if (!FieldType->isDependentType()) { 15026 if (S.RequireCompleteType(Loc, FieldType, diag::err_field_incomplete)) { 15027 Lambda->setInvalidDecl(); 15028 Field->setInvalidDecl(); 15029 } else { 15030 NamedDecl *Def; 15031 FieldType->isIncompleteType(&Def); 15032 if (Def && Def->isInvalidDecl()) { 15033 Lambda->setInvalidDecl(); 15034 Field->setInvalidDecl(); 15035 } 15036 } 15037 } 15038 Field->setImplicit(true); 15039 Field->setAccess(AS_private); 15040 Lambda->addDecl(Field); 15041 } 15042 15043 /// Capture the given variable in the lambda. 15044 static bool captureInLambda(LambdaScopeInfo *LSI, 15045 VarDecl *Var, 15046 SourceLocation Loc, 15047 const bool BuildAndDiagnose, 15048 QualType &CaptureType, 15049 QualType &DeclRefType, 15050 const bool RefersToCapturedVariable, 15051 const Sema::TryCaptureKind Kind, 15052 SourceLocation EllipsisLoc, 15053 const bool IsTopScope, 15054 Sema &S) { 15055 15056 // Determine whether we are capturing by reference or by value. 15057 bool ByRef = false; 15058 if (IsTopScope && Kind != Sema::TryCapture_Implicit) { 15059 ByRef = (Kind == Sema::TryCapture_ExplicitByRef); 15060 } else { 15061 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref); 15062 } 15063 15064 // Compute the type of the field that will capture this variable. 15065 if (ByRef) { 15066 // C++11 [expr.prim.lambda]p15: 15067 // An entity is captured by reference if it is implicitly or 15068 // explicitly captured but not captured by copy. It is 15069 // unspecified whether additional unnamed non-static data 15070 // members are declared in the closure type for entities 15071 // captured by reference. 15072 // 15073 // FIXME: It is not clear whether we want to build an lvalue reference 15074 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears 15075 // to do the former, while EDG does the latter. Core issue 1249 will 15076 // clarify, but for now we follow GCC because it's a more permissive and 15077 // easily defensible position. 15078 CaptureType = S.Context.getLValueReferenceType(DeclRefType); 15079 } else { 15080 // C++11 [expr.prim.lambda]p14: 15081 // For each entity captured by copy, an unnamed non-static 15082 // data member is declared in the closure type. The 15083 // declaration order of these members is unspecified. The type 15084 // of such a data member is the type of the corresponding 15085 // captured entity if the entity is not a reference to an 15086 // object, or the referenced type otherwise. [Note: If the 15087 // captured entity is a reference to a function, the 15088 // corresponding data member is also a reference to a 15089 // function. - end note ] 15090 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){ 15091 if (!RefType->getPointeeType()->isFunctionType()) 15092 CaptureType = RefType->getPointeeType(); 15093 } 15094 15095 // Forbid the lambda copy-capture of autoreleasing variables. 15096 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) { 15097 if (BuildAndDiagnose) { 15098 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1; 15099 S.Diag(Var->getLocation(), diag::note_previous_decl) 15100 << Var->getDeclName(); 15101 } 15102 return false; 15103 } 15104 15105 // Make sure that by-copy captures are of a complete and non-abstract type. 15106 if (BuildAndDiagnose) { 15107 if (!CaptureType->isDependentType() && 15108 S.RequireCompleteType(Loc, CaptureType, 15109 diag::err_capture_of_incomplete_type, 15110 Var->getDeclName())) 15111 return false; 15112 15113 if (S.RequireNonAbstractType(Loc, CaptureType, 15114 diag::err_capture_of_abstract_type)) 15115 return false; 15116 } 15117 } 15118 15119 // Capture this variable in the lambda. 15120 if (BuildAndDiagnose) 15121 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc, 15122 RefersToCapturedVariable); 15123 15124 // Compute the type of a reference to this captured variable. 15125 if (ByRef) 15126 DeclRefType = CaptureType.getNonReferenceType(); 15127 else { 15128 // C++ [expr.prim.lambda]p5: 15129 // The closure type for a lambda-expression has a public inline 15130 // function call operator [...]. This function call operator is 15131 // declared const (9.3.1) if and only if the lambda-expression's 15132 // parameter-declaration-clause is not followed by mutable. 15133 DeclRefType = CaptureType.getNonReferenceType(); 15134 if (!LSI->Mutable && !CaptureType->isReferenceType()) 15135 DeclRefType.addConst(); 15136 } 15137 15138 // Add the capture. 15139 if (BuildAndDiagnose) 15140 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable, 15141 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr); 15142 15143 return true; 15144 } 15145 15146 bool Sema::tryCaptureVariable( 15147 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind, 15148 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, 15149 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) { 15150 // An init-capture is notionally from the context surrounding its 15151 // declaration, but its parent DC is the lambda class. 15152 DeclContext *VarDC = Var->getDeclContext(); 15153 if (Var->isInitCapture()) 15154 VarDC = VarDC->getParent(); 15155 15156 DeclContext *DC = CurContext; 15157 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 15158 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1; 15159 // We need to sync up the Declaration Context with the 15160 // FunctionScopeIndexToStopAt 15161 if (FunctionScopeIndexToStopAt) { 15162 unsigned FSIndex = FunctionScopes.size() - 1; 15163 while (FSIndex != MaxFunctionScopesIndex) { 15164 DC = getLambdaAwareParentOfDeclContext(DC); 15165 --FSIndex; 15166 } 15167 } 15168 15169 15170 // If the variable is declared in the current context, there is no need to 15171 // capture it. 15172 if (VarDC == DC) return true; 15173 15174 // Capture global variables if it is required to use private copy of this 15175 // variable. 15176 bool IsGlobal = !Var->hasLocalStorage(); 15177 if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var))) 15178 return true; 15179 Var = Var->getCanonicalDecl(); 15180 15181 // Walk up the stack to determine whether we can capture the variable, 15182 // performing the "simple" checks that don't depend on type. We stop when 15183 // we've either hit the declared scope of the variable or find an existing 15184 // capture of that variable. We start from the innermost capturing-entity 15185 // (the DC) and ensure that all intervening capturing-entities 15186 // (blocks/lambdas etc.) between the innermost capturer and the variable`s 15187 // declcontext can either capture the variable or have already captured 15188 // the variable. 15189 CaptureType = Var->getType(); 15190 DeclRefType = CaptureType.getNonReferenceType(); 15191 bool Nested = false; 15192 bool Explicit = (Kind != TryCapture_Implicit); 15193 unsigned FunctionScopesIndex = MaxFunctionScopesIndex; 15194 do { 15195 // Only block literals, captured statements, and lambda expressions can 15196 // capture; other scopes don't work. 15197 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var, 15198 ExprLoc, 15199 BuildAndDiagnose, 15200 *this); 15201 // We need to check for the parent *first* because, if we *have* 15202 // private-captured a global variable, we need to recursively capture it in 15203 // intermediate blocks, lambdas, etc. 15204 if (!ParentDC) { 15205 if (IsGlobal) { 15206 FunctionScopesIndex = MaxFunctionScopesIndex - 1; 15207 break; 15208 } 15209 return true; 15210 } 15211 15212 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex]; 15213 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI); 15214 15215 15216 // Check whether we've already captured it. 15217 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType, 15218 DeclRefType)) { 15219 CSI->getCapture(Var).markUsed(BuildAndDiagnose); 15220 break; 15221 } 15222 // If we are instantiating a generic lambda call operator body, 15223 // we do not want to capture new variables. What was captured 15224 // during either a lambdas transformation or initial parsing 15225 // should be used. 15226 if (isGenericLambdaCallOperatorSpecialization(DC)) { 15227 if (BuildAndDiagnose) { 15228 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15229 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) { 15230 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15231 Diag(Var->getLocation(), diag::note_previous_decl) 15232 << Var->getDeclName(); 15233 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl); 15234 } else 15235 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC); 15236 } 15237 return true; 15238 } 15239 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture 15240 // certain types of variables (unnamed, variably modified types etc.) 15241 // so check for eligibility. 15242 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this)) 15243 return true; 15244 15245 // Try to capture variable-length arrays types. 15246 if (Var->getType()->isVariablyModifiedType()) { 15247 // We're going to walk down into the type and look for VLA 15248 // expressions. 15249 QualType QTy = Var->getType(); 15250 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var)) 15251 QTy = PVD->getOriginalType(); 15252 captureVariablyModifiedType(Context, QTy, CSI); 15253 } 15254 15255 if (getLangOpts().OpenMP) { 15256 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15257 // OpenMP private variables should not be captured in outer scope, so 15258 // just break here. Similarly, global variables that are captured in a 15259 // target region should not be captured outside the scope of the region. 15260 if (RSI->CapRegionKind == CR_OpenMP) { 15261 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel); 15262 auto IsTargetCap = !IsOpenMPPrivateDecl && 15263 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel); 15264 // When we detect target captures we are looking from inside the 15265 // target region, therefore we need to propagate the capture from the 15266 // enclosing region. Therefore, the capture is not initially nested. 15267 if (IsTargetCap) 15268 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel); 15269 15270 if (IsTargetCap || IsOpenMPPrivateDecl) { 15271 Nested = !IsTargetCap; 15272 DeclRefType = DeclRefType.getUnqualifiedType(); 15273 CaptureType = Context.getLValueReferenceType(DeclRefType); 15274 break; 15275 } 15276 } 15277 } 15278 } 15279 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) { 15280 // No capture-default, and this is not an explicit capture 15281 // so cannot capture this variable. 15282 if (BuildAndDiagnose) { 15283 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName(); 15284 Diag(Var->getLocation(), diag::note_previous_decl) 15285 << Var->getDeclName(); 15286 if (cast<LambdaScopeInfo>(CSI)->Lambda) 15287 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(), 15288 diag::note_lambda_decl); 15289 // FIXME: If we error out because an outer lambda can not implicitly 15290 // capture a variable that an inner lambda explicitly captures, we 15291 // should have the inner lambda do the explicit capture - because 15292 // it makes for cleaner diagnostics later. This would purely be done 15293 // so that the diagnostic does not misleadingly claim that a variable 15294 // can not be captured by a lambda implicitly even though it is captured 15295 // explicitly. Suggestion: 15296 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit 15297 // at the function head 15298 // - cache the StartingDeclContext - this must be a lambda 15299 // - captureInLambda in the innermost lambda the variable. 15300 } 15301 return true; 15302 } 15303 15304 FunctionScopesIndex--; 15305 DC = ParentDC; 15306 Explicit = false; 15307 } while (!VarDC->Equals(DC)); 15308 15309 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda) 15310 // computing the type of the capture at each step, checking type-specific 15311 // requirements, and adding captures if requested. 15312 // If the variable had already been captured previously, we start capturing 15313 // at the lambda nested within that one. 15314 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N; 15315 ++I) { 15316 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]); 15317 15318 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) { 15319 if (!captureInBlock(BSI, Var, ExprLoc, 15320 BuildAndDiagnose, CaptureType, 15321 DeclRefType, Nested, *this)) 15322 return true; 15323 Nested = true; 15324 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) { 15325 if (!captureInCapturedRegion(RSI, Var, ExprLoc, 15326 BuildAndDiagnose, CaptureType, 15327 DeclRefType, Nested, *this)) 15328 return true; 15329 Nested = true; 15330 } else { 15331 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI); 15332 if (!captureInLambda(LSI, Var, ExprLoc, 15333 BuildAndDiagnose, CaptureType, 15334 DeclRefType, Nested, Kind, EllipsisLoc, 15335 /*IsTopScope*/I == N - 1, *this)) 15336 return true; 15337 Nested = true; 15338 } 15339 } 15340 return false; 15341 } 15342 15343 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 15344 TryCaptureKind Kind, SourceLocation EllipsisLoc) { 15345 QualType CaptureType; 15346 QualType DeclRefType; 15347 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc, 15348 /*BuildAndDiagnose=*/true, CaptureType, 15349 DeclRefType, nullptr); 15350 } 15351 15352 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) { 15353 QualType CaptureType; 15354 QualType DeclRefType; 15355 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15356 /*BuildAndDiagnose=*/false, CaptureType, 15357 DeclRefType, nullptr); 15358 } 15359 15360 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) { 15361 QualType CaptureType; 15362 QualType DeclRefType; 15363 15364 // Determine whether we can capture this variable. 15365 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(), 15366 /*BuildAndDiagnose=*/false, CaptureType, 15367 DeclRefType, nullptr)) 15368 return QualType(); 15369 15370 return DeclRefType; 15371 } 15372 15373 15374 15375 // If either the type of the variable or the initializer is dependent, 15376 // return false. Otherwise, determine whether the variable is a constant 15377 // expression. Use this if you need to know if a variable that might or 15378 // might not be dependent is truly a constant expression. 15379 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var, 15380 ASTContext &Context) { 15381 15382 if (Var->getType()->isDependentType()) 15383 return false; 15384 const VarDecl *DefVD = nullptr; 15385 Var->getAnyInitializer(DefVD); 15386 if (!DefVD) 15387 return false; 15388 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 15389 Expr *Init = cast<Expr>(Eval->Value); 15390 if (Init->isValueDependent()) 15391 return false; 15392 return IsVariableAConstantExpression(Var, Context); 15393 } 15394 15395 15396 void Sema::UpdateMarkingForLValueToRValue(Expr *E) { 15397 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 15398 // an object that satisfies the requirements for appearing in a 15399 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) 15400 // is immediately applied." This function handles the lvalue-to-rvalue 15401 // conversion part. 15402 MaybeODRUseExprs.erase(E->IgnoreParens()); 15403 15404 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers 15405 // to a variable that is a constant expression, and if so, identify it as 15406 // a reference to a variable that does not involve an odr-use of that 15407 // variable. 15408 if (LambdaScopeInfo *LSI = getCurLambda()) { 15409 Expr *SansParensExpr = E->IgnoreParens(); 15410 VarDecl *Var = nullptr; 15411 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr)) 15412 Var = dyn_cast<VarDecl>(DRE->getFoundDecl()); 15413 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr)) 15414 Var = dyn_cast<VarDecl>(ME->getMemberDecl()); 15415 15416 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context)) 15417 LSI->markVariableExprAsNonODRUsed(SansParensExpr); 15418 } 15419 } 15420 15421 ExprResult Sema::ActOnConstantExpression(ExprResult Res) { 15422 Res = CorrectDelayedTyposInExpr(Res); 15423 15424 if (!Res.isUsable()) 15425 return Res; 15426 15427 // If a constant-expression is a reference to a variable where we delay 15428 // deciding whether it is an odr-use, just assume we will apply the 15429 // lvalue-to-rvalue conversion. In the one case where this doesn't happen 15430 // (a non-type template argument), we have special handling anyway. 15431 UpdateMarkingForLValueToRValue(Res.get()); 15432 return Res; 15433 } 15434 15435 void Sema::CleanupVarDeclMarking() { 15436 for (Expr *E : MaybeODRUseExprs) { 15437 VarDecl *Var; 15438 SourceLocation Loc; 15439 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 15440 Var = cast<VarDecl>(DRE->getDecl()); 15441 Loc = DRE->getLocation(); 15442 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 15443 Var = cast<VarDecl>(ME->getMemberDecl()); 15444 Loc = ME->getMemberLoc(); 15445 } else { 15446 llvm_unreachable("Unexpected expression"); 15447 } 15448 15449 MarkVarDeclODRUsed(Var, Loc, *this, 15450 /*MaxFunctionScopeIndex Pointer*/ nullptr); 15451 } 15452 15453 MaybeODRUseExprs.clear(); 15454 } 15455 15456 15457 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, 15458 VarDecl *Var, Expr *E) { 15459 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) && 15460 "Invalid Expr argument to DoMarkVarDeclReferenced"); 15461 Var->setReferenced(); 15462 15463 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 15464 15465 bool OdrUseContext = isOdrUseContext(SemaRef); 15466 bool UsableInConstantExpr = 15467 Var->isUsableInConstantExpressions(SemaRef.Context); 15468 bool NeedDefinition = 15469 OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr); 15470 15471 VarTemplateSpecializationDecl *VarSpec = 15472 dyn_cast<VarTemplateSpecializationDecl>(Var); 15473 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) && 15474 "Can't instantiate a partial template specialization."); 15475 15476 // If this might be a member specialization of a static data member, check 15477 // the specialization is visible. We already did the checks for variable 15478 // template specializations when we created them. 15479 if (NeedDefinition && TSK != TSK_Undeclared && 15480 !isa<VarTemplateSpecializationDecl>(Var)) 15481 SemaRef.checkSpecializationVisibility(Loc, Var); 15482 15483 // Perform implicit instantiation of static data members, static data member 15484 // templates of class templates, and variable template specializations. Delay 15485 // instantiations of variable templates, except for those that could be used 15486 // in a constant expression. 15487 if (NeedDefinition && isTemplateInstantiation(TSK)) { 15488 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit 15489 // instantiation declaration if a variable is usable in a constant 15490 // expression (among other cases). 15491 bool TryInstantiating = 15492 TSK == TSK_ImplicitInstantiation || 15493 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr); 15494 15495 if (TryInstantiating) { 15496 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation(); 15497 bool FirstInstantiation = PointOfInstantiation.isInvalid(); 15498 if (FirstInstantiation) { 15499 PointOfInstantiation = Loc; 15500 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); 15501 } 15502 15503 bool InstantiationDependent = false; 15504 bool IsNonDependent = 15505 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments( 15506 VarSpec->getTemplateArgsInfo(), InstantiationDependent) 15507 : true; 15508 15509 // Do not instantiate specializations that are still type-dependent. 15510 if (IsNonDependent) { 15511 if (UsableInConstantExpr) { 15512 // Do not defer instantiations of variables that could be used in a 15513 // constant expression. 15514 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var); 15515 } else if (FirstInstantiation || 15516 isa<VarTemplateSpecializationDecl>(Var)) { 15517 // FIXME: For a specialization of a variable template, we don't 15518 // distinguish between "declaration and type implicitly instantiated" 15519 // and "implicit instantiation of definition requested", so we have 15520 // no direct way to avoid enqueueing the pending instantiation 15521 // multiple times. 15522 SemaRef.PendingInstantiations 15523 .push_back(std::make_pair(Var, PointOfInstantiation)); 15524 } 15525 } 15526 } 15527 } 15528 15529 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies 15530 // the requirements for appearing in a constant expression (5.19) and, if 15531 // it is an object, the lvalue-to-rvalue conversion (4.1) 15532 // is immediately applied." We check the first part here, and 15533 // Sema::UpdateMarkingForLValueToRValue deals with the second part. 15534 // Note that we use the C++11 definition everywhere because nothing in 15535 // C++03 depends on whether we get the C++03 version correct. The second 15536 // part does not apply to references, since they are not objects. 15537 if (OdrUseContext && E && 15538 IsVariableAConstantExpression(Var, SemaRef.Context)) { 15539 // A reference initialized by a constant expression can never be 15540 // odr-used, so simply ignore it. 15541 if (!Var->getType()->isReferenceType() || 15542 (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var))) 15543 SemaRef.MaybeODRUseExprs.insert(E); 15544 } else if (OdrUseContext) { 15545 MarkVarDeclODRUsed(Var, Loc, SemaRef, 15546 /*MaxFunctionScopeIndex ptr*/ nullptr); 15547 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) { 15548 // If this is a dependent context, we don't need to mark variables as 15549 // odr-used, but we may still need to track them for lambda capture. 15550 // FIXME: Do we also need to do this inside dependent typeid expressions 15551 // (which are modeled as unevaluated at this point)? 15552 const bool RefersToEnclosingScope = 15553 (SemaRef.CurContext != Var->getDeclContext() && 15554 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage()); 15555 if (RefersToEnclosingScope) { 15556 LambdaScopeInfo *const LSI = 15557 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true); 15558 if (LSI && (!LSI->CallOperator || 15559 !LSI->CallOperator->Encloses(Var->getDeclContext()))) { 15560 // If a variable could potentially be odr-used, defer marking it so 15561 // until we finish analyzing the full expression for any 15562 // lvalue-to-rvalue 15563 // or discarded value conversions that would obviate odr-use. 15564 // Add it to the list of potential captures that will be analyzed 15565 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking 15566 // unless the variable is a reference that was initialized by a constant 15567 // expression (this will never need to be captured or odr-used). 15568 assert(E && "Capture variable should be used in an expression."); 15569 if (!Var->getType()->isReferenceType() || 15570 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context)) 15571 LSI->addPotentialCapture(E->IgnoreParens()); 15572 } 15573 } 15574 } 15575 } 15576 15577 /// Mark a variable referenced, and check whether it is odr-used 15578 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be 15579 /// used directly for normal expressions referring to VarDecl. 15580 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) { 15581 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr); 15582 } 15583 15584 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, 15585 Decl *D, Expr *E, bool MightBeOdrUse) { 15586 if (SemaRef.isInOpenMPDeclareTargetContext()) 15587 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D); 15588 15589 if (VarDecl *Var = dyn_cast<VarDecl>(D)) { 15590 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E); 15591 return; 15592 } 15593 15594 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse); 15595 15596 // If this is a call to a method via a cast, also mark the method in the 15597 // derived class used in case codegen can devirtualize the call. 15598 const MemberExpr *ME = dyn_cast<MemberExpr>(E); 15599 if (!ME) 15600 return; 15601 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl()); 15602 if (!MD) 15603 return; 15604 // Only attempt to devirtualize if this is truly a virtual call. 15605 bool IsVirtualCall = MD->isVirtual() && 15606 ME->performsVirtualDispatch(SemaRef.getLangOpts()); 15607 if (!IsVirtualCall) 15608 return; 15609 15610 // If it's possible to devirtualize the call, mark the called function 15611 // referenced. 15612 CXXMethodDecl *DM = MD->getDevirtualizedMethod( 15613 ME->getBase(), SemaRef.getLangOpts().AppleKext); 15614 if (DM) 15615 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse); 15616 } 15617 15618 /// Perform reference-marking and odr-use handling for a DeclRefExpr. 15619 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) { 15620 // TODO: update this with DR# once a defect report is filed. 15621 // C++11 defect. The address of a pure member should not be an ODR use, even 15622 // if it's a qualified reference. 15623 bool OdrUse = true; 15624 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl())) 15625 if (Method->isVirtual() && 15626 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) 15627 OdrUse = false; 15628 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse); 15629 } 15630 15631 /// Perform reference-marking and odr-use handling for a MemberExpr. 15632 void Sema::MarkMemberReferenced(MemberExpr *E) { 15633 // C++11 [basic.def.odr]p2: 15634 // A non-overloaded function whose name appears as a potentially-evaluated 15635 // expression or a member of a set of candidate functions, if selected by 15636 // overload resolution when referred to from a potentially-evaluated 15637 // expression, is odr-used, unless it is a pure virtual function and its 15638 // name is not explicitly qualified. 15639 bool MightBeOdrUse = true; 15640 if (E->performsVirtualDispatch(getLangOpts())) { 15641 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) 15642 if (Method->isPure()) 15643 MightBeOdrUse = false; 15644 } 15645 SourceLocation Loc = 15646 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc(); 15647 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse); 15648 } 15649 15650 /// Perform marking for a reference to an arbitrary declaration. It 15651 /// marks the declaration referenced, and performs odr-use checking for 15652 /// functions and variables. This method should not be used when building a 15653 /// normal expression which refers to a variable. 15654 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, 15655 bool MightBeOdrUse) { 15656 if (MightBeOdrUse) { 15657 if (auto *VD = dyn_cast<VarDecl>(D)) { 15658 MarkVariableReferenced(Loc, VD); 15659 return; 15660 } 15661 } 15662 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 15663 MarkFunctionReferenced(Loc, FD, MightBeOdrUse); 15664 return; 15665 } 15666 D->setReferenced(); 15667 } 15668 15669 namespace { 15670 // Mark all of the declarations used by a type as referenced. 15671 // FIXME: Not fully implemented yet! We need to have a better understanding 15672 // of when we're entering a context we should not recurse into. 15673 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to 15674 // TreeTransforms rebuilding the type in a new context. Rather than 15675 // duplicating the TreeTransform logic, we should consider reusing it here. 15676 // Currently that causes problems when rebuilding LambdaExprs. 15677 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> { 15678 Sema &S; 15679 SourceLocation Loc; 15680 15681 public: 15682 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited; 15683 15684 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { } 15685 15686 bool TraverseTemplateArgument(const TemplateArgument &Arg); 15687 }; 15688 } 15689 15690 bool MarkReferencedDecls::TraverseTemplateArgument( 15691 const TemplateArgument &Arg) { 15692 { 15693 // A non-type template argument is a constant-evaluated context. 15694 EnterExpressionEvaluationContext Evaluated( 15695 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 15696 if (Arg.getKind() == TemplateArgument::Declaration) { 15697 if (Decl *D = Arg.getAsDecl()) 15698 S.MarkAnyDeclReferenced(Loc, D, true); 15699 } else if (Arg.getKind() == TemplateArgument::Expression) { 15700 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false); 15701 } 15702 } 15703 15704 return Inherited::TraverseTemplateArgument(Arg); 15705 } 15706 15707 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) { 15708 MarkReferencedDecls Marker(*this, Loc); 15709 Marker.TraverseType(T); 15710 } 15711 15712 namespace { 15713 /// Helper class that marks all of the declarations referenced by 15714 /// potentially-evaluated subexpressions as "referenced". 15715 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> { 15716 Sema &S; 15717 bool SkipLocalVariables; 15718 15719 public: 15720 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited; 15721 15722 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 15723 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { } 15724 15725 void VisitDeclRefExpr(DeclRefExpr *E) { 15726 // If we were asked not to visit local variables, don't. 15727 if (SkipLocalVariables) { 15728 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 15729 if (VD->hasLocalStorage()) 15730 return; 15731 } 15732 15733 S.MarkDeclRefReferenced(E); 15734 } 15735 15736 void VisitMemberExpr(MemberExpr *E) { 15737 S.MarkMemberReferenced(E); 15738 Inherited::VisitMemberExpr(E); 15739 } 15740 15741 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 15742 S.MarkFunctionReferenced( 15743 E->getBeginLoc(), 15744 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor())); 15745 Visit(E->getSubExpr()); 15746 } 15747 15748 void VisitCXXNewExpr(CXXNewExpr *E) { 15749 if (E->getOperatorNew()) 15750 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew()); 15751 if (E->getOperatorDelete()) 15752 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 15753 Inherited::VisitCXXNewExpr(E); 15754 } 15755 15756 void VisitCXXDeleteExpr(CXXDeleteExpr *E) { 15757 if (E->getOperatorDelete()) 15758 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete()); 15759 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType()); 15760 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) { 15761 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl()); 15762 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record)); 15763 } 15764 15765 Inherited::VisitCXXDeleteExpr(E); 15766 } 15767 15768 void VisitCXXConstructExpr(CXXConstructExpr *E) { 15769 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor()); 15770 Inherited::VisitCXXConstructExpr(E); 15771 } 15772 15773 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 15774 Visit(E->getExpr()); 15775 } 15776 15777 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 15778 Inherited::VisitImplicitCastExpr(E); 15779 15780 if (E->getCastKind() == CK_LValueToRValue) 15781 S.UpdateMarkingForLValueToRValue(E->getSubExpr()); 15782 } 15783 }; 15784 } 15785 15786 /// Mark any declarations that appear within this expression or any 15787 /// potentially-evaluated subexpressions as "referenced". 15788 /// 15789 /// \param SkipLocalVariables If true, don't mark local variables as 15790 /// 'referenced'. 15791 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 15792 bool SkipLocalVariables) { 15793 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E); 15794 } 15795 15796 /// Emit a diagnostic that describes an effect on the run-time behavior 15797 /// of the program being compiled. 15798 /// 15799 /// This routine emits the given diagnostic when the code currently being 15800 /// type-checked is "potentially evaluated", meaning that there is a 15801 /// possibility that the code will actually be executable. Code in sizeof() 15802 /// expressions, code used only during overload resolution, etc., are not 15803 /// potentially evaluated. This routine will suppress such diagnostics or, 15804 /// in the absolutely nutty case of potentially potentially evaluated 15805 /// expressions (C++ typeid), queue the diagnostic to potentially emit it 15806 /// later. 15807 /// 15808 /// This routine should be used for all diagnostics that describe the run-time 15809 /// behavior of a program, such as passing a non-POD value through an ellipsis. 15810 /// Failure to do so will likely result in spurious diagnostics or failures 15811 /// during overload resolution or within sizeof/alignof/typeof/typeid. 15812 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 15813 const PartialDiagnostic &PD) { 15814 switch (ExprEvalContexts.back().Context) { 15815 case ExpressionEvaluationContext::Unevaluated: 15816 case ExpressionEvaluationContext::UnevaluatedList: 15817 case ExpressionEvaluationContext::UnevaluatedAbstract: 15818 case ExpressionEvaluationContext::DiscardedStatement: 15819 // The argument will never be evaluated, so don't complain. 15820 break; 15821 15822 case ExpressionEvaluationContext::ConstantEvaluated: 15823 // Relevant diagnostics should be produced by constant evaluation. 15824 break; 15825 15826 case ExpressionEvaluationContext::PotentiallyEvaluated: 15827 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: 15828 if (Statement && getCurFunctionOrMethodDecl()) { 15829 FunctionScopes.back()->PossiblyUnreachableDiags. 15830 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement)); 15831 return true; 15832 } 15833 15834 // The initializer of a constexpr variable or of the first declaration of a 15835 // static data member is not syntactically a constant evaluated constant, 15836 // but nonetheless is always required to be a constant expression, so we 15837 // can skip diagnosing. 15838 // FIXME: Using the mangling context here is a hack. 15839 if (auto *VD = dyn_cast_or_null<VarDecl>( 15840 ExprEvalContexts.back().ManglingContextDecl)) { 15841 if (VD->isConstexpr() || 15842 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline())) 15843 break; 15844 // FIXME: For any other kind of variable, we should build a CFG for its 15845 // initializer and check whether the context in question is reachable. 15846 } 15847 15848 Diag(Loc, PD); 15849 return true; 15850 } 15851 15852 return false; 15853 } 15854 15855 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 15856 CallExpr *CE, FunctionDecl *FD) { 15857 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType()) 15858 return false; 15859 15860 // If we're inside a decltype's expression, don't check for a valid return 15861 // type or construct temporaries until we know whether this is the last call. 15862 if (ExprEvalContexts.back().ExprContext == 15863 ExpressionEvaluationContextRecord::EK_Decltype) { 15864 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE); 15865 return false; 15866 } 15867 15868 class CallReturnIncompleteDiagnoser : public TypeDiagnoser { 15869 FunctionDecl *FD; 15870 CallExpr *CE; 15871 15872 public: 15873 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE) 15874 : FD(FD), CE(CE) { } 15875 15876 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 15877 if (!FD) { 15878 S.Diag(Loc, diag::err_call_incomplete_return) 15879 << T << CE->getSourceRange(); 15880 return; 15881 } 15882 15883 S.Diag(Loc, diag::err_call_function_incomplete_return) 15884 << CE->getSourceRange() << FD->getDeclName() << T; 15885 S.Diag(FD->getLocation(), diag::note_entity_declared_at) 15886 << FD->getDeclName(); 15887 } 15888 } Diagnoser(FD, CE); 15889 15890 if (RequireCompleteType(Loc, ReturnType, Diagnoser)) 15891 return true; 15892 15893 return false; 15894 } 15895 15896 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses 15897 // will prevent this condition from triggering, which is what we want. 15898 void Sema::DiagnoseAssignmentAsCondition(Expr *E) { 15899 SourceLocation Loc; 15900 15901 unsigned diagnostic = diag::warn_condition_is_assignment; 15902 bool IsOrAssign = false; 15903 15904 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 15905 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign) 15906 return; 15907 15908 IsOrAssign = Op->getOpcode() == BO_OrAssign; 15909 15910 // Greylist some idioms by putting them into a warning subcategory. 15911 if (ObjCMessageExpr *ME 15912 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) { 15913 Selector Sel = ME->getSelector(); 15914 15915 // self = [<foo> init...] 15916 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init) 15917 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15918 15919 // <foo> = [<bar> nextObject] 15920 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject") 15921 diagnostic = diag::warn_condition_is_idiomatic_assignment; 15922 } 15923 15924 Loc = Op->getOperatorLoc(); 15925 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 15926 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual) 15927 return; 15928 15929 IsOrAssign = Op->getOperator() == OO_PipeEqual; 15930 Loc = Op->getOperatorLoc(); 15931 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) 15932 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm()); 15933 else { 15934 // Not an assignment. 15935 return; 15936 } 15937 15938 Diag(Loc, diagnostic) << E->getSourceRange(); 15939 15940 SourceLocation Open = E->getBeginLoc(); 15941 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd()); 15942 Diag(Loc, diag::note_condition_assign_silence) 15943 << FixItHint::CreateInsertion(Open, "(") 15944 << FixItHint::CreateInsertion(Close, ")"); 15945 15946 if (IsOrAssign) 15947 Diag(Loc, diag::note_condition_or_assign_to_comparison) 15948 << FixItHint::CreateReplacement(Loc, "!="); 15949 else 15950 Diag(Loc, diag::note_condition_assign_to_comparison) 15951 << FixItHint::CreateReplacement(Loc, "=="); 15952 } 15953 15954 /// Redundant parentheses over an equality comparison can indicate 15955 /// that the user intended an assignment used as condition. 15956 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) { 15957 // Don't warn if the parens came from a macro. 15958 SourceLocation parenLoc = ParenE->getBeginLoc(); 15959 if (parenLoc.isInvalid() || parenLoc.isMacroID()) 15960 return; 15961 // Don't warn for dependent expressions. 15962 if (ParenE->isTypeDependent()) 15963 return; 15964 15965 Expr *E = ParenE->IgnoreParens(); 15966 15967 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E)) 15968 if (opE->getOpcode() == BO_EQ && 15969 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context) 15970 == Expr::MLV_Valid) { 15971 SourceLocation Loc = opE->getOperatorLoc(); 15972 15973 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange(); 15974 SourceRange ParenERange = ParenE->getSourceRange(); 15975 Diag(Loc, diag::note_equality_comparison_silence) 15976 << FixItHint::CreateRemoval(ParenERange.getBegin()) 15977 << FixItHint::CreateRemoval(ParenERange.getEnd()); 15978 Diag(Loc, diag::note_equality_comparison_to_assign) 15979 << FixItHint::CreateReplacement(Loc, "="); 15980 } 15981 } 15982 15983 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E, 15984 bool IsConstexpr) { 15985 DiagnoseAssignmentAsCondition(E); 15986 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E)) 15987 DiagnoseEqualityWithExtraParens(parenE); 15988 15989 ExprResult result = CheckPlaceholderExpr(E); 15990 if (result.isInvalid()) return ExprError(); 15991 E = result.get(); 15992 15993 if (!E->isTypeDependent()) { 15994 if (getLangOpts().CPlusPlus) 15995 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4 15996 15997 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E); 15998 if (ERes.isInvalid()) 15999 return ExprError(); 16000 E = ERes.get(); 16001 16002 QualType T = E->getType(); 16003 if (!T->isScalarType()) { // C99 6.8.4.1p1 16004 Diag(Loc, diag::err_typecheck_statement_requires_scalar) 16005 << T << E->getSourceRange(); 16006 return ExprError(); 16007 } 16008 CheckBoolLikeConversion(E, Loc); 16009 } 16010 16011 return E; 16012 } 16013 16014 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc, 16015 Expr *SubExpr, ConditionKind CK) { 16016 // Empty conditions are valid in for-statements. 16017 if (!SubExpr) 16018 return ConditionResult(); 16019 16020 ExprResult Cond; 16021 switch (CK) { 16022 case ConditionKind::Boolean: 16023 Cond = CheckBooleanCondition(Loc, SubExpr); 16024 break; 16025 16026 case ConditionKind::ConstexprIf: 16027 Cond = CheckBooleanCondition(Loc, SubExpr, true); 16028 break; 16029 16030 case ConditionKind::Switch: 16031 Cond = CheckSwitchCondition(Loc, SubExpr); 16032 break; 16033 } 16034 if (Cond.isInvalid()) 16035 return ConditionError(); 16036 16037 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead. 16038 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc); 16039 if (!FullExpr.get()) 16040 return ConditionError(); 16041 16042 return ConditionResult(*this, nullptr, FullExpr, 16043 CK == ConditionKind::ConstexprIf); 16044 } 16045 16046 namespace { 16047 /// A visitor for rebuilding a call to an __unknown_any expression 16048 /// to have an appropriate type. 16049 struct RebuildUnknownAnyFunction 16050 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> { 16051 16052 Sema &S; 16053 16054 RebuildUnknownAnyFunction(Sema &S) : S(S) {} 16055 16056 ExprResult VisitStmt(Stmt *S) { 16057 llvm_unreachable("unexpected statement!"); 16058 } 16059 16060 ExprResult VisitExpr(Expr *E) { 16061 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call) 16062 << E->getSourceRange(); 16063 return ExprError(); 16064 } 16065 16066 /// Rebuild an expression which simply semantically wraps another 16067 /// expression which it shares the type and value kind of. 16068 template <class T> ExprResult rebuildSugarExpr(T *E) { 16069 ExprResult SubResult = Visit(E->getSubExpr()); 16070 if (SubResult.isInvalid()) return ExprError(); 16071 16072 Expr *SubExpr = SubResult.get(); 16073 E->setSubExpr(SubExpr); 16074 E->setType(SubExpr->getType()); 16075 E->setValueKind(SubExpr->getValueKind()); 16076 assert(E->getObjectKind() == OK_Ordinary); 16077 return E; 16078 } 16079 16080 ExprResult VisitParenExpr(ParenExpr *E) { 16081 return rebuildSugarExpr(E); 16082 } 16083 16084 ExprResult VisitUnaryExtension(UnaryOperator *E) { 16085 return rebuildSugarExpr(E); 16086 } 16087 16088 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 16089 ExprResult SubResult = Visit(E->getSubExpr()); 16090 if (SubResult.isInvalid()) return ExprError(); 16091 16092 Expr *SubExpr = SubResult.get(); 16093 E->setSubExpr(SubExpr); 16094 E->setType(S.Context.getPointerType(SubExpr->getType())); 16095 assert(E->getValueKind() == VK_RValue); 16096 assert(E->getObjectKind() == OK_Ordinary); 16097 return E; 16098 } 16099 16100 ExprResult resolveDecl(Expr *E, ValueDecl *VD) { 16101 if (!isa<FunctionDecl>(VD)) return VisitExpr(E); 16102 16103 E->setType(VD->getType()); 16104 16105 assert(E->getValueKind() == VK_RValue); 16106 if (S.getLangOpts().CPlusPlus && 16107 !(isa<CXXMethodDecl>(VD) && 16108 cast<CXXMethodDecl>(VD)->isInstance())) 16109 E->setValueKind(VK_LValue); 16110 16111 return E; 16112 } 16113 16114 ExprResult VisitMemberExpr(MemberExpr *E) { 16115 return resolveDecl(E, E->getMemberDecl()); 16116 } 16117 16118 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 16119 return resolveDecl(E, E->getDecl()); 16120 } 16121 }; 16122 } 16123 16124 /// Given a function expression of unknown-any type, try to rebuild it 16125 /// to have a function type. 16126 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) { 16127 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr); 16128 if (Result.isInvalid()) return ExprError(); 16129 return S.DefaultFunctionArrayConversion(Result.get()); 16130 } 16131 16132 namespace { 16133 /// A visitor for rebuilding an expression of type __unknown_anytype 16134 /// into one which resolves the type directly on the referring 16135 /// expression. Strict preservation of the original source 16136 /// structure is not a goal. 16137 struct RebuildUnknownAnyExpr 16138 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> { 16139 16140 Sema &S; 16141 16142 /// The current destination type. 16143 QualType DestType; 16144 16145 RebuildUnknownAnyExpr(Sema &S, QualType CastType) 16146 : S(S), DestType(CastType) {} 16147 16148 ExprResult VisitStmt(Stmt *S) { 16149 llvm_unreachable("unexpected statement!"); 16150 } 16151 16152 ExprResult VisitExpr(Expr *E) { 16153 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 16154 << E->getSourceRange(); 16155 return ExprError(); 16156 } 16157 16158 ExprResult VisitCallExpr(CallExpr *E); 16159 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E); 16160 16161 /// Rebuild an expression which simply semantically wraps another 16162 /// expression which it shares the type and value kind of. 16163 template <class T> ExprResult rebuildSugarExpr(T *E) { 16164 ExprResult SubResult = Visit(E->getSubExpr()); 16165 if (SubResult.isInvalid()) return ExprError(); 16166 Expr *SubExpr = SubResult.get(); 16167 E->setSubExpr(SubExpr); 16168 E->setType(SubExpr->getType()); 16169 E->setValueKind(SubExpr->getValueKind()); 16170 assert(E->getObjectKind() == OK_Ordinary); 16171 return E; 16172 } 16173 16174 ExprResult VisitParenExpr(ParenExpr *E) { 16175 return rebuildSugarExpr(E); 16176 } 16177 16178 ExprResult VisitUnaryExtension(UnaryOperator *E) { 16179 return rebuildSugarExpr(E); 16180 } 16181 16182 ExprResult VisitUnaryAddrOf(UnaryOperator *E) { 16183 const PointerType *Ptr = DestType->getAs<PointerType>(); 16184 if (!Ptr) { 16185 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof) 16186 << E->getSourceRange(); 16187 return ExprError(); 16188 } 16189 16190 if (isa<CallExpr>(E->getSubExpr())) { 16191 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call) 16192 << E->getSourceRange(); 16193 return ExprError(); 16194 } 16195 16196 assert(E->getValueKind() == VK_RValue); 16197 assert(E->getObjectKind() == OK_Ordinary); 16198 E->setType(DestType); 16199 16200 // Build the sub-expression as if it were an object of the pointee type. 16201 DestType = Ptr->getPointeeType(); 16202 ExprResult SubResult = Visit(E->getSubExpr()); 16203 if (SubResult.isInvalid()) return ExprError(); 16204 E->setSubExpr(SubResult.get()); 16205 return E; 16206 } 16207 16208 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E); 16209 16210 ExprResult resolveDecl(Expr *E, ValueDecl *VD); 16211 16212 ExprResult VisitMemberExpr(MemberExpr *E) { 16213 return resolveDecl(E, E->getMemberDecl()); 16214 } 16215 16216 ExprResult VisitDeclRefExpr(DeclRefExpr *E) { 16217 return resolveDecl(E, E->getDecl()); 16218 } 16219 }; 16220 } 16221 16222 /// Rebuilds a call expression which yielded __unknown_anytype. 16223 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) { 16224 Expr *CalleeExpr = E->getCallee(); 16225 16226 enum FnKind { 16227 FK_MemberFunction, 16228 FK_FunctionPointer, 16229 FK_BlockPointer 16230 }; 16231 16232 FnKind Kind; 16233 QualType CalleeType = CalleeExpr->getType(); 16234 if (CalleeType == S.Context.BoundMemberTy) { 16235 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)); 16236 Kind = FK_MemberFunction; 16237 CalleeType = Expr::findBoundMemberType(CalleeExpr); 16238 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) { 16239 CalleeType = Ptr->getPointeeType(); 16240 Kind = FK_FunctionPointer; 16241 } else { 16242 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType(); 16243 Kind = FK_BlockPointer; 16244 } 16245 const FunctionType *FnType = CalleeType->castAs<FunctionType>(); 16246 16247 // Verify that this is a legal result type of a function. 16248 if (DestType->isArrayType() || DestType->isFunctionType()) { 16249 unsigned diagID = diag::err_func_returning_array_function; 16250 if (Kind == FK_BlockPointer) 16251 diagID = diag::err_block_returning_array_function; 16252 16253 S.Diag(E->getExprLoc(), diagID) 16254 << DestType->isFunctionType() << DestType; 16255 return ExprError(); 16256 } 16257 16258 // Otherwise, go ahead and set DestType as the call's result. 16259 E->setType(DestType.getNonLValueExprType(S.Context)); 16260 E->setValueKind(Expr::getValueKindForType(DestType)); 16261 assert(E->getObjectKind() == OK_Ordinary); 16262 16263 // Rebuild the function type, replacing the result type with DestType. 16264 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType); 16265 if (Proto) { 16266 // __unknown_anytype(...) is a special case used by the debugger when 16267 // it has no idea what a function's signature is. 16268 // 16269 // We want to build this call essentially under the K&R 16270 // unprototyped rules, but making a FunctionNoProtoType in C++ 16271 // would foul up all sorts of assumptions. However, we cannot 16272 // simply pass all arguments as variadic arguments, nor can we 16273 // portably just call the function under a non-variadic type; see 16274 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic. 16275 // However, it turns out that in practice it is generally safe to 16276 // call a function declared as "A foo(B,C,D);" under the prototype 16277 // "A foo(B,C,D,...);". The only known exception is with the 16278 // Windows ABI, where any variadic function is implicitly cdecl 16279 // regardless of its normal CC. Therefore we change the parameter 16280 // types to match the types of the arguments. 16281 // 16282 // This is a hack, but it is far superior to moving the 16283 // corresponding target-specific code from IR-gen to Sema/AST. 16284 16285 ArrayRef<QualType> ParamTypes = Proto->getParamTypes(); 16286 SmallVector<QualType, 8> ArgTypes; 16287 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case 16288 ArgTypes.reserve(E->getNumArgs()); 16289 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) { 16290 Expr *Arg = E->getArg(i); 16291 QualType ArgType = Arg->getType(); 16292 if (E->isLValue()) { 16293 ArgType = S.Context.getLValueReferenceType(ArgType); 16294 } else if (E->isXValue()) { 16295 ArgType = S.Context.getRValueReferenceType(ArgType); 16296 } 16297 ArgTypes.push_back(ArgType); 16298 } 16299 ParamTypes = ArgTypes; 16300 } 16301 DestType = S.Context.getFunctionType(DestType, ParamTypes, 16302 Proto->getExtProtoInfo()); 16303 } else { 16304 DestType = S.Context.getFunctionNoProtoType(DestType, 16305 FnType->getExtInfo()); 16306 } 16307 16308 // Rebuild the appropriate pointer-to-function type. 16309 switch (Kind) { 16310 case FK_MemberFunction: 16311 // Nothing to do. 16312 break; 16313 16314 case FK_FunctionPointer: 16315 DestType = S.Context.getPointerType(DestType); 16316 break; 16317 16318 case FK_BlockPointer: 16319 DestType = S.Context.getBlockPointerType(DestType); 16320 break; 16321 } 16322 16323 // Finally, we can recurse. 16324 ExprResult CalleeResult = Visit(CalleeExpr); 16325 if (!CalleeResult.isUsable()) return ExprError(); 16326 E->setCallee(CalleeResult.get()); 16327 16328 // Bind a temporary if necessary. 16329 return S.MaybeBindToTemporary(E); 16330 } 16331 16332 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) { 16333 // Verify that this is a legal result type of a call. 16334 if (DestType->isArrayType() || DestType->isFunctionType()) { 16335 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function) 16336 << DestType->isFunctionType() << DestType; 16337 return ExprError(); 16338 } 16339 16340 // Rewrite the method result type if available. 16341 if (ObjCMethodDecl *Method = E->getMethodDecl()) { 16342 assert(Method->getReturnType() == S.Context.UnknownAnyTy); 16343 Method->setReturnType(DestType); 16344 } 16345 16346 // Change the type of the message. 16347 E->setType(DestType.getNonReferenceType()); 16348 E->setValueKind(Expr::getValueKindForType(DestType)); 16349 16350 return S.MaybeBindToTemporary(E); 16351 } 16352 16353 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) { 16354 // The only case we should ever see here is a function-to-pointer decay. 16355 if (E->getCastKind() == CK_FunctionToPointerDecay) { 16356 assert(E->getValueKind() == VK_RValue); 16357 assert(E->getObjectKind() == OK_Ordinary); 16358 16359 E->setType(DestType); 16360 16361 // Rebuild the sub-expression as the pointee (function) type. 16362 DestType = DestType->castAs<PointerType>()->getPointeeType(); 16363 16364 ExprResult Result = Visit(E->getSubExpr()); 16365 if (!Result.isUsable()) return ExprError(); 16366 16367 E->setSubExpr(Result.get()); 16368 return E; 16369 } else if (E->getCastKind() == CK_LValueToRValue) { 16370 assert(E->getValueKind() == VK_RValue); 16371 assert(E->getObjectKind() == OK_Ordinary); 16372 16373 assert(isa<BlockPointerType>(E->getType())); 16374 16375 E->setType(DestType); 16376 16377 // The sub-expression has to be a lvalue reference, so rebuild it as such. 16378 DestType = S.Context.getLValueReferenceType(DestType); 16379 16380 ExprResult Result = Visit(E->getSubExpr()); 16381 if (!Result.isUsable()) return ExprError(); 16382 16383 E->setSubExpr(Result.get()); 16384 return E; 16385 } else { 16386 llvm_unreachable("Unhandled cast type!"); 16387 } 16388 } 16389 16390 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) { 16391 ExprValueKind ValueKind = VK_LValue; 16392 QualType Type = DestType; 16393 16394 // We know how to make this work for certain kinds of decls: 16395 16396 // - functions 16397 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) { 16398 if (const PointerType *Ptr = Type->getAs<PointerType>()) { 16399 DestType = Ptr->getPointeeType(); 16400 ExprResult Result = resolveDecl(E, VD); 16401 if (Result.isInvalid()) return ExprError(); 16402 return S.ImpCastExprToType(Result.get(), Type, 16403 CK_FunctionToPointerDecay, VK_RValue); 16404 } 16405 16406 if (!Type->isFunctionType()) { 16407 S.Diag(E->getExprLoc(), diag::err_unknown_any_function) 16408 << VD << E->getSourceRange(); 16409 return ExprError(); 16410 } 16411 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) { 16412 // We must match the FunctionDecl's type to the hack introduced in 16413 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown 16414 // type. See the lengthy commentary in that routine. 16415 QualType FDT = FD->getType(); 16416 const FunctionType *FnType = FDT->castAs<FunctionType>(); 16417 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType); 16418 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E); 16419 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) { 16420 SourceLocation Loc = FD->getLocation(); 16421 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(), 16422 FD->getDeclContext(), 16423 Loc, Loc, FD->getNameInfo().getName(), 16424 DestType, FD->getTypeSourceInfo(), 16425 SC_None, false/*isInlineSpecified*/, 16426 FD->hasPrototype(), 16427 false/*isConstexprSpecified*/); 16428 16429 if (FD->getQualifier()) 16430 NewFD->setQualifierInfo(FD->getQualifierLoc()); 16431 16432 SmallVector<ParmVarDecl*, 16> Params; 16433 for (const auto &AI : FT->param_types()) { 16434 ParmVarDecl *Param = 16435 S.BuildParmVarDeclForTypedef(FD, Loc, AI); 16436 Param->setScopeInfo(0, Params.size()); 16437 Params.push_back(Param); 16438 } 16439 NewFD->setParams(Params); 16440 DRE->setDecl(NewFD); 16441 VD = DRE->getDecl(); 16442 } 16443 } 16444 16445 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 16446 if (MD->isInstance()) { 16447 ValueKind = VK_RValue; 16448 Type = S.Context.BoundMemberTy; 16449 } 16450 16451 // Function references aren't l-values in C. 16452 if (!S.getLangOpts().CPlusPlus) 16453 ValueKind = VK_RValue; 16454 16455 // - variables 16456 } else if (isa<VarDecl>(VD)) { 16457 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) { 16458 Type = RefTy->getPointeeType(); 16459 } else if (Type->isFunctionType()) { 16460 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type) 16461 << VD << E->getSourceRange(); 16462 return ExprError(); 16463 } 16464 16465 // - nothing else 16466 } else { 16467 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl) 16468 << VD << E->getSourceRange(); 16469 return ExprError(); 16470 } 16471 16472 // Modifying the declaration like this is friendly to IR-gen but 16473 // also really dangerous. 16474 VD->setType(DestType); 16475 E->setType(Type); 16476 E->setValueKind(ValueKind); 16477 return E; 16478 } 16479 16480 /// Check a cast of an unknown-any type. We intentionally only 16481 /// trigger this for C-style casts. 16482 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 16483 Expr *CastExpr, CastKind &CastKind, 16484 ExprValueKind &VK, CXXCastPath &Path) { 16485 // The type we're casting to must be either void or complete. 16486 if (!CastType->isVoidType() && 16487 RequireCompleteType(TypeRange.getBegin(), CastType, 16488 diag::err_typecheck_cast_to_incomplete)) 16489 return ExprError(); 16490 16491 // Rewrite the casted expression from scratch. 16492 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr); 16493 if (!result.isUsable()) return ExprError(); 16494 16495 CastExpr = result.get(); 16496 VK = CastExpr->getValueKind(); 16497 CastKind = CK_NoOp; 16498 16499 return CastExpr; 16500 } 16501 16502 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) { 16503 return RebuildUnknownAnyExpr(*this, ToType).Visit(E); 16504 } 16505 16506 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc, 16507 Expr *arg, QualType ¶mType) { 16508 // If the syntactic form of the argument is not an explicit cast of 16509 // any sort, just do default argument promotion. 16510 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens()); 16511 if (!castArg) { 16512 ExprResult result = DefaultArgumentPromotion(arg); 16513 if (result.isInvalid()) return ExprError(); 16514 paramType = result.get()->getType(); 16515 return result; 16516 } 16517 16518 // Otherwise, use the type that was written in the explicit cast. 16519 assert(!arg->hasPlaceholderType()); 16520 paramType = castArg->getTypeAsWritten(); 16521 16522 // Copy-initialize a parameter of that type. 16523 InitializedEntity entity = 16524 InitializedEntity::InitializeParameter(Context, paramType, 16525 /*consumed*/ false); 16526 return PerformCopyInitialization(entity, callLoc, arg); 16527 } 16528 16529 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) { 16530 Expr *orig = E; 16531 unsigned diagID = diag::err_uncasted_use_of_unknown_any; 16532 while (true) { 16533 E = E->IgnoreParenImpCasts(); 16534 if (CallExpr *call = dyn_cast<CallExpr>(E)) { 16535 E = call->getCallee(); 16536 diagID = diag::err_uncasted_call_of_unknown_any; 16537 } else { 16538 break; 16539 } 16540 } 16541 16542 SourceLocation loc; 16543 NamedDecl *d; 16544 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) { 16545 loc = ref->getLocation(); 16546 d = ref->getDecl(); 16547 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) { 16548 loc = mem->getMemberLoc(); 16549 d = mem->getMemberDecl(); 16550 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) { 16551 diagID = diag::err_uncasted_call_of_unknown_any; 16552 loc = msg->getSelectorStartLoc(); 16553 d = msg->getMethodDecl(); 16554 if (!d) { 16555 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method) 16556 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector() 16557 << orig->getSourceRange(); 16558 return ExprError(); 16559 } 16560 } else { 16561 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr) 16562 << E->getSourceRange(); 16563 return ExprError(); 16564 } 16565 16566 S.Diag(loc, diagID) << d << orig->getSourceRange(); 16567 16568 // Never recoverable. 16569 return ExprError(); 16570 } 16571 16572 /// Check for operands with placeholder types and complain if found. 16573 /// Returns ExprError() if there was an error and no recovery was possible. 16574 ExprResult Sema::CheckPlaceholderExpr(Expr *E) { 16575 if (!getLangOpts().CPlusPlus) { 16576 // C cannot handle TypoExpr nodes on either side of a binop because it 16577 // doesn't handle dependent types properly, so make sure any TypoExprs have 16578 // been dealt with before checking the operands. 16579 ExprResult Result = CorrectDelayedTyposInExpr(E); 16580 if (!Result.isUsable()) return ExprError(); 16581 E = Result.get(); 16582 } 16583 16584 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType(); 16585 if (!placeholderType) return E; 16586 16587 switch (placeholderType->getKind()) { 16588 16589 // Overloaded expressions. 16590 case BuiltinType::Overload: { 16591 // Try to resolve a single function template specialization. 16592 // This is obligatory. 16593 ExprResult Result = E; 16594 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false)) 16595 return Result; 16596 16597 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization 16598 // leaves Result unchanged on failure. 16599 Result = E; 16600 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result)) 16601 return Result; 16602 16603 // If that failed, try to recover with a call. 16604 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable), 16605 /*complain*/ true); 16606 return Result; 16607 } 16608 16609 // Bound member functions. 16610 case BuiltinType::BoundMember: { 16611 ExprResult result = E; 16612 const Expr *BME = E->IgnoreParens(); 16613 PartialDiagnostic PD = PDiag(diag::err_bound_member_function); 16614 // Try to give a nicer diagnostic if it is a bound member that we recognize. 16615 if (isa<CXXPseudoDestructorExpr>(BME)) { 16616 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1; 16617 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) { 16618 if (ME->getMemberNameInfo().getName().getNameKind() == 16619 DeclarationName::CXXDestructorName) 16620 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0; 16621 } 16622 tryToRecoverWithCall(result, PD, 16623 /*complain*/ true); 16624 return result; 16625 } 16626 16627 // ARC unbridged casts. 16628 case BuiltinType::ARCUnbridgedCast: { 16629 Expr *realCast = stripARCUnbridgedCast(E); 16630 diagnoseARCUnbridgedCast(realCast); 16631 return realCast; 16632 } 16633 16634 // Expressions of unknown type. 16635 case BuiltinType::UnknownAny: 16636 return diagnoseUnknownAnyExpr(*this, E); 16637 16638 // Pseudo-objects. 16639 case BuiltinType::PseudoObject: 16640 return checkPseudoObjectRValue(E); 16641 16642 case BuiltinType::BuiltinFn: { 16643 // Accept __noop without parens by implicitly converting it to a call expr. 16644 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()); 16645 if (DRE) { 16646 auto *FD = cast<FunctionDecl>(DRE->getDecl()); 16647 if (FD->getBuiltinID() == Builtin::BI__noop) { 16648 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()), 16649 CK_BuiltinFnToFnPtr).get(); 16650 return new (Context) CallExpr(Context, E, None, Context.IntTy, 16651 VK_RValue, SourceLocation()); 16652 } 16653 } 16654 16655 Diag(E->getBeginLoc(), diag::err_builtin_fn_use); 16656 return ExprError(); 16657 } 16658 16659 // Expressions of unknown type. 16660 case BuiltinType::OMPArraySection: 16661 Diag(E->getBeginLoc(), diag::err_omp_array_section_use); 16662 return ExprError(); 16663 16664 // Everything else should be impossible. 16665 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 16666 case BuiltinType::Id: 16667 #include "clang/Basic/OpenCLImageTypes.def" 16668 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 16669 case BuiltinType::Id: 16670 #include "clang/Basic/OpenCLExtensionTypes.def" 16671 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id: 16672 #define PLACEHOLDER_TYPE(Id, SingletonId) 16673 #include "clang/AST/BuiltinTypes.def" 16674 break; 16675 } 16676 16677 llvm_unreachable("invalid placeholder type!"); 16678 } 16679 16680 bool Sema::CheckCaseExpression(Expr *E) { 16681 if (E->isTypeDependent()) 16682 return true; 16683 if (E->isValueDependent() || E->isIntegerConstantExpr(Context)) 16684 return E->getType()->isIntegralOrEnumerationType(); 16685 return false; 16686 } 16687 16688 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 16689 ExprResult 16690 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 16691 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && 16692 "Unknown Objective-C Boolean value!"); 16693 QualType BoolT = Context.ObjCBuiltinBoolTy; 16694 if (!Context.getBOOLDecl()) { 16695 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc, 16696 Sema::LookupOrdinaryName); 16697 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) { 16698 NamedDecl *ND = Result.getFoundDecl(); 16699 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 16700 Context.setBOOLDecl(TD); 16701 } 16702 } 16703 if (Context.getBOOLDecl()) 16704 BoolT = Context.getBOOLType(); 16705 return new (Context) 16706 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc); 16707 } 16708 16709 ExprResult Sema::ActOnObjCAvailabilityCheckExpr( 16710 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, 16711 SourceLocation RParen) { 16712 16713 StringRef Platform = getASTContext().getTargetInfo().getPlatformName(); 16714 16715 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(), 16716 [&](const AvailabilitySpec &Spec) { 16717 return Spec.getPlatform() == Platform; 16718 }); 16719 16720 VersionTuple Version; 16721 if (Spec != AvailSpecs.end()) 16722 Version = Spec->getVersion(); 16723 16724 // The use of `@available` in the enclosing function should be analyzed to 16725 // warn when it's used inappropriately (i.e. not if(@available)). 16726 if (getCurFunctionOrMethodDecl()) 16727 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 16728 else if (getCurBlock() || getCurLambda()) 16729 getCurFunction()->HasPotentialAvailabilityViolations = true; 16730 16731 return new (Context) 16732 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy); 16733 } 16734