1 //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for statements. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTContext.h" 14 #include "clang/AST/ASTDiagnostic.h" 15 #include "clang/AST/ASTLambda.h" 16 #include "clang/AST/CXXInheritance.h" 17 #include "clang/AST/CharUnits.h" 18 #include "clang/AST/DeclObjC.h" 19 #include "clang/AST/EvaluatedExprVisitor.h" 20 #include "clang/AST/ExprCXX.h" 21 #include "clang/AST/ExprObjC.h" 22 #include "clang/AST/IgnoreExpr.h" 23 #include "clang/AST/RecursiveASTVisitor.h" 24 #include "clang/AST/StmtCXX.h" 25 #include "clang/AST/StmtObjC.h" 26 #include "clang/AST/TypeLoc.h" 27 #include "clang/AST/TypeOrdering.h" 28 #include "clang/Basic/TargetInfo.h" 29 #include "clang/Lex/Preprocessor.h" 30 #include "clang/Sema/Initialization.h" 31 #include "clang/Sema/Lookup.h" 32 #include "clang/Sema/Ownership.h" 33 #include "clang/Sema/Scope.h" 34 #include "clang/Sema/ScopeInfo.h" 35 #include "clang/Sema/SemaInternal.h" 36 #include "llvm/ADT/ArrayRef.h" 37 #include "llvm/ADT/DenseMap.h" 38 #include "llvm/ADT/STLExtras.h" 39 #include "llvm/ADT/SmallPtrSet.h" 40 #include "llvm/ADT/SmallString.h" 41 #include "llvm/ADT/SmallVector.h" 42 #include "llvm/ADT/StringExtras.h" 43 44 using namespace clang; 45 using namespace sema; 46 47 StmtResult Sema::ActOnExprStmt(ExprResult FE, bool DiscardedValue) { 48 if (FE.isInvalid()) 49 return StmtError(); 50 51 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(), DiscardedValue); 52 if (FE.isInvalid()) 53 return StmtError(); 54 55 // C99 6.8.3p2: The expression in an expression statement is evaluated as a 56 // void expression for its side effects. Conversion to void allows any 57 // operand, even incomplete types. 58 59 // Same thing in for stmt first clause (when expr) and third clause. 60 return StmtResult(FE.getAs<Stmt>()); 61 } 62 63 64 StmtResult Sema::ActOnExprStmtError() { 65 DiscardCleanupsInEvaluationContext(); 66 return StmtError(); 67 } 68 69 StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc, 70 bool HasLeadingEmptyMacro) { 71 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro); 72 } 73 74 StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc, 75 SourceLocation EndLoc) { 76 DeclGroupRef DG = dg.get(); 77 78 // If we have an invalid decl, just return an error. 79 if (DG.isNull()) return StmtError(); 80 81 return new (Context) DeclStmt(DG, StartLoc, EndLoc); 82 } 83 84 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) { 85 DeclGroupRef DG = dg.get(); 86 87 // If we don't have a declaration, or we have an invalid declaration, 88 // just return. 89 if (DG.isNull() || !DG.isSingleDecl()) 90 return; 91 92 Decl *decl = DG.getSingleDecl(); 93 if (!decl || decl->isInvalidDecl()) 94 return; 95 96 // Only variable declarations are permitted. 97 VarDecl *var = dyn_cast<VarDecl>(decl); 98 if (!var) { 99 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for); 100 decl->setInvalidDecl(); 101 return; 102 } 103 104 // foreach variables are never actually initialized in the way that 105 // the parser came up with. 106 var->setInit(nullptr); 107 108 // In ARC, we don't need to retain the iteration variable of a fast 109 // enumeration loop. Rather than actually trying to catch that 110 // during declaration processing, we remove the consequences here. 111 if (getLangOpts().ObjCAutoRefCount) { 112 QualType type = var->getType(); 113 114 // Only do this if we inferred the lifetime. Inferred lifetime 115 // will show up as a local qualifier because explicit lifetime 116 // should have shown up as an AttributedType instead. 117 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) { 118 // Add 'const' and mark the variable as pseudo-strong. 119 var->setType(type.withConst()); 120 var->setARCPseudoStrong(true); 121 } 122 } 123 } 124 125 /// Diagnose unused comparisons, both builtin and overloaded operators. 126 /// For '==' and '!=', suggest fixits for '=' or '|='. 127 /// 128 /// Adding a cast to void (or other expression wrappers) will prevent the 129 /// warning from firing. 130 static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) { 131 SourceLocation Loc; 132 bool CanAssign; 133 enum { Equality, Inequality, Relational, ThreeWay } Kind; 134 135 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 136 if (!Op->isComparisonOp()) 137 return false; 138 139 if (Op->getOpcode() == BO_EQ) 140 Kind = Equality; 141 else if (Op->getOpcode() == BO_NE) 142 Kind = Inequality; 143 else if (Op->getOpcode() == BO_Cmp) 144 Kind = ThreeWay; 145 else { 146 assert(Op->isRelationalOp()); 147 Kind = Relational; 148 } 149 Loc = Op->getOperatorLoc(); 150 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue(); 151 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 152 switch (Op->getOperator()) { 153 case OO_EqualEqual: 154 Kind = Equality; 155 break; 156 case OO_ExclaimEqual: 157 Kind = Inequality; 158 break; 159 case OO_Less: 160 case OO_Greater: 161 case OO_GreaterEqual: 162 case OO_LessEqual: 163 Kind = Relational; 164 break; 165 case OO_Spaceship: 166 Kind = ThreeWay; 167 break; 168 default: 169 return false; 170 } 171 172 Loc = Op->getOperatorLoc(); 173 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue(); 174 } else { 175 // Not a typo-prone comparison. 176 return false; 177 } 178 179 // Suppress warnings when the operator, suspicious as it may be, comes from 180 // a macro expansion. 181 if (S.SourceMgr.isMacroBodyExpansion(Loc)) 182 return false; 183 184 S.Diag(Loc, diag::warn_unused_comparison) 185 << (unsigned)Kind << E->getSourceRange(); 186 187 // If the LHS is a plausible entity to assign to, provide a fixit hint to 188 // correct common typos. 189 if (CanAssign) { 190 if (Kind == Inequality) 191 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign) 192 << FixItHint::CreateReplacement(Loc, "|="); 193 else if (Kind == Equality) 194 S.Diag(Loc, diag::note_equality_comparison_to_assign) 195 << FixItHint::CreateReplacement(Loc, "="); 196 } 197 198 return true; 199 } 200 201 static bool DiagnoseNoDiscard(Sema &S, const WarnUnusedResultAttr *A, 202 SourceLocation Loc, SourceRange R1, 203 SourceRange R2, bool IsCtor) { 204 if (!A) 205 return false; 206 StringRef Msg = A->getMessage(); 207 208 if (Msg.empty()) { 209 if (IsCtor) 210 return S.Diag(Loc, diag::warn_unused_constructor) << A << R1 << R2; 211 return S.Diag(Loc, diag::warn_unused_result) << A << R1 << R2; 212 } 213 214 if (IsCtor) 215 return S.Diag(Loc, diag::warn_unused_constructor_msg) << A << Msg << R1 216 << R2; 217 return S.Diag(Loc, diag::warn_unused_result_msg) << A << Msg << R1 << R2; 218 } 219 220 void Sema::DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID) { 221 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) 222 return DiagnoseUnusedExprResult(Label->getSubStmt(), DiagID); 223 224 const Expr *E = dyn_cast_or_null<Expr>(S); 225 if (!E) 226 return; 227 228 // If we are in an unevaluated expression context, then there can be no unused 229 // results because the results aren't expected to be used in the first place. 230 if (isUnevaluatedContext()) 231 return; 232 233 SourceLocation ExprLoc = E->IgnoreParenImpCasts()->getExprLoc(); 234 // In most cases, we don't want to warn if the expression is written in a 235 // macro body, or if the macro comes from a system header. If the offending 236 // expression is a call to a function with the warn_unused_result attribute, 237 // we warn no matter the location. Because of the order in which the various 238 // checks need to happen, we factor out the macro-related test here. 239 bool ShouldSuppress = 240 SourceMgr.isMacroBodyExpansion(ExprLoc) || 241 SourceMgr.isInSystemMacro(ExprLoc); 242 243 const Expr *WarnExpr; 244 SourceLocation Loc; 245 SourceRange R1, R2; 246 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context)) 247 return; 248 249 // If this is a GNU statement expression expanded from a macro, it is probably 250 // unused because it is a function-like macro that can be used as either an 251 // expression or statement. Don't warn, because it is almost certainly a 252 // false positive. 253 if (isa<StmtExpr>(E) && Loc.isMacroID()) 254 return; 255 256 // Check if this is the UNREFERENCED_PARAMETER from the Microsoft headers. 257 // That macro is frequently used to suppress "unused parameter" warnings, 258 // but its implementation makes clang's -Wunused-value fire. Prevent this. 259 if (isa<ParenExpr>(E->IgnoreImpCasts()) && Loc.isMacroID()) { 260 SourceLocation SpellLoc = Loc; 261 if (findMacroSpelling(SpellLoc, "UNREFERENCED_PARAMETER")) 262 return; 263 } 264 265 // Okay, we have an unused result. Depending on what the base expression is, 266 // we might want to make a more specific diagnostic. Check for one of these 267 // cases now. 268 if (const FullExpr *Temps = dyn_cast<FullExpr>(E)) 269 E = Temps->getSubExpr(); 270 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E)) 271 E = TempExpr->getSubExpr(); 272 273 if (DiagnoseUnusedComparison(*this, E)) 274 return; 275 276 E = WarnExpr; 277 if (const auto *Cast = dyn_cast<CastExpr>(E)) 278 if (Cast->getCastKind() == CK_NoOp || 279 Cast->getCastKind() == CK_ConstructorConversion) 280 E = Cast->getSubExpr()->IgnoreImpCasts(); 281 282 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 283 if (E->getType()->isVoidType()) 284 return; 285 286 if (DiagnoseNoDiscard(*this, cast_or_null<WarnUnusedResultAttr>( 287 CE->getUnusedResultAttr(Context)), 288 Loc, R1, R2, /*isCtor=*/false)) 289 return; 290 291 // If the callee has attribute pure, const, or warn_unused_result, warn with 292 // a more specific message to make it clear what is happening. If the call 293 // is written in a macro body, only warn if it has the warn_unused_result 294 // attribute. 295 if (const Decl *FD = CE->getCalleeDecl()) { 296 if (ShouldSuppress) 297 return; 298 if (FD->hasAttr<PureAttr>()) { 299 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure"; 300 return; 301 } 302 if (FD->hasAttr<ConstAttr>()) { 303 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const"; 304 return; 305 } 306 } 307 } else if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) { 308 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) { 309 const auto *A = Ctor->getAttr<WarnUnusedResultAttr>(); 310 A = A ? A : Ctor->getParent()->getAttr<WarnUnusedResultAttr>(); 311 if (DiagnoseNoDiscard(*this, A, Loc, R1, R2, /*isCtor=*/true)) 312 return; 313 } 314 } else if (const auto *ILE = dyn_cast<InitListExpr>(E)) { 315 if (const TagDecl *TD = ILE->getType()->getAsTagDecl()) { 316 317 if (DiagnoseNoDiscard(*this, TD->getAttr<WarnUnusedResultAttr>(), Loc, R1, 318 R2, /*isCtor=*/false)) 319 return; 320 } 321 } else if (ShouldSuppress) 322 return; 323 324 E = WarnExpr; 325 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) { 326 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) { 327 Diag(Loc, diag::err_arc_unused_init_message) << R1; 328 return; 329 } 330 const ObjCMethodDecl *MD = ME->getMethodDecl(); 331 if (MD) { 332 if (DiagnoseNoDiscard(*this, MD->getAttr<WarnUnusedResultAttr>(), Loc, R1, 333 R2, /*isCtor=*/false)) 334 return; 335 } 336 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 337 const Expr *Source = POE->getSyntacticForm(); 338 // Handle the actually selected call of an OpenMP specialized call. 339 if (LangOpts.OpenMP && isa<CallExpr>(Source) && 340 POE->getNumSemanticExprs() == 1 && 341 isa<CallExpr>(POE->getSemanticExpr(0))) 342 return DiagnoseUnusedExprResult(POE->getSemanticExpr(0), DiagID); 343 if (isa<ObjCSubscriptRefExpr>(Source)) 344 DiagID = diag::warn_unused_container_subscript_expr; 345 else if (isa<ObjCPropertyRefExpr>(Source)) 346 DiagID = diag::warn_unused_property_expr; 347 } else if (const CXXFunctionalCastExpr *FC 348 = dyn_cast<CXXFunctionalCastExpr>(E)) { 349 const Expr *E = FC->getSubExpr(); 350 if (const CXXBindTemporaryExpr *TE = dyn_cast<CXXBindTemporaryExpr>(E)) 351 E = TE->getSubExpr(); 352 if (isa<CXXTemporaryObjectExpr>(E)) 353 return; 354 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(E)) 355 if (const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl()) 356 if (!RD->getAttr<WarnUnusedAttr>()) 357 return; 358 } 359 // Diagnose "(void*) blah" as a typo for "(void) blah". 360 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) { 361 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 362 QualType T = TI->getType(); 363 364 // We really do want to use the non-canonical type here. 365 if (T == Context.VoidPtrTy) { 366 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>(); 367 368 Diag(Loc, diag::warn_unused_voidptr) 369 << FixItHint::CreateRemoval(TL.getStarLoc()); 370 return; 371 } 372 } 373 374 // Tell the user to assign it into a variable to force a volatile load if this 375 // isn't an array. 376 if (E->isGLValue() && E->getType().isVolatileQualified() && 377 !E->getType()->isArrayType()) { 378 Diag(Loc, diag::warn_unused_volatile) << R1 << R2; 379 return; 380 } 381 382 // Do not diagnose use of a comma operator in a SFINAE context because the 383 // type of the left operand could be used for SFINAE, so technically it is 384 // *used*. 385 if (DiagID != diag::warn_unused_comma_left_operand || !isSFINAEContext()) 386 DiagIfReachable(Loc, S ? llvm::ArrayRef(S) : std::nullopt, 387 PDiag(DiagID) << R1 << R2); 388 } 389 390 void Sema::ActOnStartOfCompoundStmt(bool IsStmtExpr) { 391 PushCompoundScope(IsStmtExpr); 392 } 393 394 void Sema::ActOnAfterCompoundStatementLeadingPragmas() { 395 if (getCurFPFeatures().isFPConstrained()) { 396 FunctionScopeInfo *FSI = getCurFunction(); 397 assert(FSI); 398 FSI->setUsesFPIntrin(); 399 } 400 } 401 402 void Sema::ActOnFinishOfCompoundStmt() { 403 PopCompoundScope(); 404 } 405 406 sema::CompoundScopeInfo &Sema::getCurCompoundScope() const { 407 return getCurFunction()->CompoundScopes.back(); 408 } 409 410 StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R, 411 ArrayRef<Stmt *> Elts, bool isStmtExpr) { 412 const unsigned NumElts = Elts.size(); 413 414 // If we're in C mode, check that we don't have any decls after stmts. If 415 // so, emit an extension diagnostic in C89 and potentially a warning in later 416 // versions. 417 const unsigned MixedDeclsCodeID = getLangOpts().C99 418 ? diag::warn_mixed_decls_code 419 : diag::ext_mixed_decls_code; 420 if (!getLangOpts().CPlusPlus && !Diags.isIgnored(MixedDeclsCodeID, L)) { 421 // Note that __extension__ can be around a decl. 422 unsigned i = 0; 423 // Skip over all declarations. 424 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i) 425 /*empty*/; 426 427 // We found the end of the list or a statement. Scan for another declstmt. 428 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i) 429 /*empty*/; 430 431 if (i != NumElts) { 432 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin(); 433 Diag(D->getLocation(), MixedDeclsCodeID); 434 } 435 } 436 437 // Check for suspicious empty body (null statement) in `for' and `while' 438 // statements. Don't do anything for template instantiations, this just adds 439 // noise. 440 if (NumElts != 0 && !CurrentInstantiationScope && 441 getCurCompoundScope().HasEmptyLoopBodies) { 442 for (unsigned i = 0; i != NumElts - 1; ++i) 443 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]); 444 } 445 446 // Calculate difference between FP options in this compound statement and in 447 // the enclosing one. If this is a function body, take the difference against 448 // default options. In this case the difference will indicate options that are 449 // changed upon entry to the statement. 450 FPOptions FPO = (getCurFunction()->CompoundScopes.size() == 1) 451 ? FPOptions(getLangOpts()) 452 : getCurCompoundScope().InitialFPFeatures; 453 FPOptionsOverride FPDiff = getCurFPFeatures().getChangesFrom(FPO); 454 455 return CompoundStmt::Create(Context, Elts, FPDiff, L, R); 456 } 457 458 ExprResult 459 Sema::ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val) { 460 if (!Val.get()) 461 return Val; 462 463 if (DiagnoseUnexpandedParameterPack(Val.get())) 464 return ExprError(); 465 466 // If we're not inside a switch, let the 'case' statement handling diagnose 467 // this. Just clean up after the expression as best we can. 468 if (getCurFunction()->SwitchStack.empty()) 469 return ActOnFinishFullExpr(Val.get(), Val.get()->getExprLoc(), false, 470 getLangOpts().CPlusPlus11); 471 472 Expr *CondExpr = 473 getCurFunction()->SwitchStack.back().getPointer()->getCond(); 474 if (!CondExpr) 475 return ExprError(); 476 QualType CondType = CondExpr->getType(); 477 478 auto CheckAndFinish = [&](Expr *E) { 479 if (CondType->isDependentType() || E->isTypeDependent()) 480 return ExprResult(E); 481 482 if (getLangOpts().CPlusPlus11) { 483 // C++11 [stmt.switch]p2: the constant-expression shall be a converted 484 // constant expression of the promoted type of the switch condition. 485 llvm::APSInt TempVal; 486 return CheckConvertedConstantExpression(E, CondType, TempVal, 487 CCEK_CaseValue); 488 } 489 490 ExprResult ER = E; 491 if (!E->isValueDependent()) 492 ER = VerifyIntegerConstantExpression(E, AllowFold); 493 if (!ER.isInvalid()) 494 ER = DefaultLvalueConversion(ER.get()); 495 if (!ER.isInvalid()) 496 ER = ImpCastExprToType(ER.get(), CondType, CK_IntegralCast); 497 if (!ER.isInvalid()) 498 ER = ActOnFinishFullExpr(ER.get(), ER.get()->getExprLoc(), false); 499 return ER; 500 }; 501 502 ExprResult Converted = CorrectDelayedTyposInExpr( 503 Val, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false, 504 CheckAndFinish); 505 if (Converted.get() == Val.get()) 506 Converted = CheckAndFinish(Val.get()); 507 return Converted; 508 } 509 510 StmtResult 511 Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHSVal, 512 SourceLocation DotDotDotLoc, ExprResult RHSVal, 513 SourceLocation ColonLoc) { 514 assert((LHSVal.isInvalid() || LHSVal.get()) && "missing LHS value"); 515 assert((DotDotDotLoc.isInvalid() ? RHSVal.isUnset() 516 : RHSVal.isInvalid() || RHSVal.get()) && 517 "missing RHS value"); 518 519 if (getCurFunction()->SwitchStack.empty()) { 520 Diag(CaseLoc, diag::err_case_not_in_switch); 521 return StmtError(); 522 } 523 524 if (LHSVal.isInvalid() || RHSVal.isInvalid()) { 525 getCurFunction()->SwitchStack.back().setInt(true); 526 return StmtError(); 527 } 528 529 auto *CS = CaseStmt::Create(Context, LHSVal.get(), RHSVal.get(), 530 CaseLoc, DotDotDotLoc, ColonLoc); 531 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS); 532 return CS; 533 } 534 535 /// ActOnCaseStmtBody - This installs a statement as the body of a case. 536 void Sema::ActOnCaseStmtBody(Stmt *S, Stmt *SubStmt) { 537 cast<CaseStmt>(S)->setSubStmt(SubStmt); 538 } 539 540 StmtResult 541 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, 542 Stmt *SubStmt, Scope *CurScope) { 543 if (getCurFunction()->SwitchStack.empty()) { 544 Diag(DefaultLoc, diag::err_default_not_in_switch); 545 return SubStmt; 546 } 547 548 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt); 549 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(DS); 550 return DS; 551 } 552 553 StmtResult 554 Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 555 SourceLocation ColonLoc, Stmt *SubStmt) { 556 // If the label was multiply defined, reject it now. 557 if (TheDecl->getStmt()) { 558 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName(); 559 Diag(TheDecl->getLocation(), diag::note_previous_definition); 560 return SubStmt; 561 } 562 563 ReservedIdentifierStatus Status = TheDecl->isReserved(getLangOpts()); 564 if (isReservedInAllContexts(Status) && 565 !Context.getSourceManager().isInSystemHeader(IdentLoc)) 566 Diag(IdentLoc, diag::warn_reserved_extern_symbol) 567 << TheDecl << static_cast<int>(Status); 568 569 // Otherwise, things are good. Fill in the declaration and return it. 570 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt); 571 TheDecl->setStmt(LS); 572 if (!TheDecl->isGnuLocal()) { 573 TheDecl->setLocStart(IdentLoc); 574 if (!TheDecl->isMSAsmLabel()) { 575 // Don't update the location of MS ASM labels. These will result in 576 // a diagnostic, and changing the location here will mess that up. 577 TheDecl->setLocation(IdentLoc); 578 } 579 } 580 return LS; 581 } 582 583 StmtResult Sema::BuildAttributedStmt(SourceLocation AttrsLoc, 584 ArrayRef<const Attr *> Attrs, 585 Stmt *SubStmt) { 586 // FIXME: this code should move when a planned refactoring around statement 587 // attributes lands. 588 for (const auto *A : Attrs) { 589 if (A->getKind() == attr::MustTail) { 590 if (!checkAndRewriteMustTailAttr(SubStmt, *A)) { 591 return SubStmt; 592 } 593 setFunctionHasMustTail(); 594 } 595 } 596 597 return AttributedStmt::Create(Context, AttrsLoc, Attrs, SubStmt); 598 } 599 600 StmtResult Sema::ActOnAttributedStmt(const ParsedAttributes &Attrs, 601 Stmt *SubStmt) { 602 SmallVector<const Attr *, 1> SemanticAttrs; 603 ProcessStmtAttributes(SubStmt, Attrs, SemanticAttrs); 604 if (!SemanticAttrs.empty()) 605 return BuildAttributedStmt(Attrs.Range.getBegin(), SemanticAttrs, SubStmt); 606 // If none of the attributes applied, that's fine, we can recover by 607 // returning the substatement directly instead of making an AttributedStmt 608 // with no attributes on it. 609 return SubStmt; 610 } 611 612 bool Sema::checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA) { 613 ReturnStmt *R = cast<ReturnStmt>(St); 614 Expr *E = R->getRetValue(); 615 616 if (CurContext->isDependentContext() || (E && E->isInstantiationDependent())) 617 // We have to suspend our check until template instantiation time. 618 return true; 619 620 if (!checkMustTailAttr(St, MTA)) 621 return false; 622 623 // FIXME: Replace Expr::IgnoreImplicitAsWritten() with this function. 624 // Currently it does not skip implicit constructors in an initialization 625 // context. 626 auto IgnoreImplicitAsWritten = [](Expr *E) -> Expr * { 627 return IgnoreExprNodes(E, IgnoreImplicitAsWrittenSingleStep, 628 IgnoreElidableImplicitConstructorSingleStep); 629 }; 630 631 // Now that we have verified that 'musttail' is valid here, rewrite the 632 // return value to remove all implicit nodes, but retain parentheses. 633 R->setRetValue(IgnoreImplicitAsWritten(E)); 634 return true; 635 } 636 637 bool Sema::checkMustTailAttr(const Stmt *St, const Attr &MTA) { 638 assert(!CurContext->isDependentContext() && 639 "musttail cannot be checked from a dependent context"); 640 641 // FIXME: Add Expr::IgnoreParenImplicitAsWritten() with this definition. 642 auto IgnoreParenImplicitAsWritten = [](const Expr *E) -> const Expr * { 643 return IgnoreExprNodes(const_cast<Expr *>(E), IgnoreParensSingleStep, 644 IgnoreImplicitAsWrittenSingleStep, 645 IgnoreElidableImplicitConstructorSingleStep); 646 }; 647 648 const Expr *E = cast<ReturnStmt>(St)->getRetValue(); 649 const auto *CE = dyn_cast_or_null<CallExpr>(IgnoreParenImplicitAsWritten(E)); 650 651 if (!CE) { 652 Diag(St->getBeginLoc(), diag::err_musttail_needs_call) << &MTA; 653 return false; 654 } 655 656 if (const auto *EWC = dyn_cast<ExprWithCleanups>(E)) { 657 if (EWC->cleanupsHaveSideEffects()) { 658 Diag(St->getBeginLoc(), diag::err_musttail_needs_trivial_args) << &MTA; 659 return false; 660 } 661 } 662 663 // We need to determine the full function type (including "this" type, if any) 664 // for both caller and callee. 665 struct FuncType { 666 enum { 667 ft_non_member, 668 ft_static_member, 669 ft_non_static_member, 670 ft_pointer_to_member, 671 } MemberType = ft_non_member; 672 673 QualType This; 674 const FunctionProtoType *Func; 675 const CXXMethodDecl *Method = nullptr; 676 } CallerType, CalleeType; 677 678 auto GetMethodType = [this, St, MTA](const CXXMethodDecl *CMD, FuncType &Type, 679 bool IsCallee) -> bool { 680 if (isa<CXXConstructorDecl, CXXDestructorDecl>(CMD)) { 681 Diag(St->getBeginLoc(), diag::err_musttail_structors_forbidden) 682 << IsCallee << isa<CXXDestructorDecl>(CMD); 683 if (IsCallee) 684 Diag(CMD->getBeginLoc(), diag::note_musttail_structors_forbidden) 685 << isa<CXXDestructorDecl>(CMD); 686 Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA; 687 return false; 688 } 689 if (CMD->isStatic()) 690 Type.MemberType = FuncType::ft_static_member; 691 else { 692 Type.This = CMD->getFunctionObjectParameterType(); 693 Type.MemberType = FuncType::ft_non_static_member; 694 } 695 Type.Func = CMD->getType()->castAs<FunctionProtoType>(); 696 return true; 697 }; 698 699 const auto *CallerDecl = dyn_cast<FunctionDecl>(CurContext); 700 701 // Find caller function signature. 702 if (!CallerDecl) { 703 int ContextType; 704 if (isa<BlockDecl>(CurContext)) 705 ContextType = 0; 706 else if (isa<ObjCMethodDecl>(CurContext)) 707 ContextType = 1; 708 else 709 ContextType = 2; 710 Diag(St->getBeginLoc(), diag::err_musttail_forbidden_from_this_context) 711 << &MTA << ContextType; 712 return false; 713 } else if (const auto *CMD = dyn_cast<CXXMethodDecl>(CurContext)) { 714 // Caller is a class/struct method. 715 if (!GetMethodType(CMD, CallerType, false)) 716 return false; 717 } else { 718 // Caller is a non-method function. 719 CallerType.Func = CallerDecl->getType()->getAs<FunctionProtoType>(); 720 } 721 722 const Expr *CalleeExpr = CE->getCallee()->IgnoreParens(); 723 const auto *CalleeBinOp = dyn_cast<BinaryOperator>(CalleeExpr); 724 SourceLocation CalleeLoc = CE->getCalleeDecl() 725 ? CE->getCalleeDecl()->getBeginLoc() 726 : St->getBeginLoc(); 727 728 // Find callee function signature. 729 if (const CXXMethodDecl *CMD = 730 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl())) { 731 // Call is: obj.method(), obj->method(), functor(), etc. 732 if (!GetMethodType(CMD, CalleeType, true)) 733 return false; 734 } else if (CalleeBinOp && CalleeBinOp->isPtrMemOp()) { 735 // Call is: obj->*method_ptr or obj.*method_ptr 736 const auto *MPT = 737 CalleeBinOp->getRHS()->getType()->castAs<MemberPointerType>(); 738 CalleeType.This = QualType(MPT->getClass(), 0); 739 CalleeType.Func = MPT->getPointeeType()->castAs<FunctionProtoType>(); 740 CalleeType.MemberType = FuncType::ft_pointer_to_member; 741 } else if (isa<CXXPseudoDestructorExpr>(CalleeExpr)) { 742 Diag(St->getBeginLoc(), diag::err_musttail_structors_forbidden) 743 << /* IsCallee = */ 1 << /* IsDestructor = */ 1; 744 Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA; 745 return false; 746 } else { 747 // Non-method function. 748 CalleeType.Func = 749 CalleeExpr->getType()->getPointeeType()->getAs<FunctionProtoType>(); 750 } 751 752 // Both caller and callee must have a prototype (no K&R declarations). 753 if (!CalleeType.Func || !CallerType.Func) { 754 Diag(St->getBeginLoc(), diag::err_musttail_needs_prototype) << &MTA; 755 if (!CalleeType.Func && CE->getDirectCallee()) { 756 Diag(CE->getDirectCallee()->getBeginLoc(), 757 diag::note_musttail_fix_non_prototype); 758 } 759 if (!CallerType.Func) 760 Diag(CallerDecl->getBeginLoc(), diag::note_musttail_fix_non_prototype); 761 return false; 762 } 763 764 // Caller and callee must have matching calling conventions. 765 // 766 // Some calling conventions are physically capable of supporting tail calls 767 // even if the function types don't perfectly match. LLVM is currently too 768 // strict to allow this, but if LLVM added support for this in the future, we 769 // could exit early here and skip the remaining checks if the functions are 770 // using such a calling convention. 771 if (CallerType.Func->getCallConv() != CalleeType.Func->getCallConv()) { 772 if (const auto *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) 773 Diag(St->getBeginLoc(), diag::err_musttail_callconv_mismatch) 774 << true << ND->getDeclName(); 775 else 776 Diag(St->getBeginLoc(), diag::err_musttail_callconv_mismatch) << false; 777 Diag(CalleeLoc, diag::note_musttail_callconv_mismatch) 778 << FunctionType::getNameForCallConv(CallerType.Func->getCallConv()) 779 << FunctionType::getNameForCallConv(CalleeType.Func->getCallConv()); 780 Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA; 781 return false; 782 } 783 784 if (CalleeType.Func->isVariadic() || CallerType.Func->isVariadic()) { 785 Diag(St->getBeginLoc(), diag::err_musttail_no_variadic) << &MTA; 786 return false; 787 } 788 789 // Caller and callee must match in whether they have a "this" parameter. 790 if (CallerType.This.isNull() != CalleeType.This.isNull()) { 791 if (const auto *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 792 Diag(St->getBeginLoc(), diag::err_musttail_member_mismatch) 793 << CallerType.MemberType << CalleeType.MemberType << true 794 << ND->getDeclName(); 795 Diag(CalleeLoc, diag::note_musttail_callee_defined_here) 796 << ND->getDeclName(); 797 } else 798 Diag(St->getBeginLoc(), diag::err_musttail_member_mismatch) 799 << CallerType.MemberType << CalleeType.MemberType << false; 800 Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA; 801 return false; 802 } 803 804 auto CheckTypesMatch = [this](FuncType CallerType, FuncType CalleeType, 805 PartialDiagnostic &PD) -> bool { 806 enum { 807 ft_different_class, 808 ft_parameter_arity, 809 ft_parameter_mismatch, 810 ft_return_type, 811 }; 812 813 auto DoTypesMatch = [this, &PD](QualType A, QualType B, 814 unsigned Select) -> bool { 815 if (!Context.hasSimilarType(A, B)) { 816 PD << Select << A.getUnqualifiedType() << B.getUnqualifiedType(); 817 return false; 818 } 819 return true; 820 }; 821 822 if (!CallerType.This.isNull() && 823 !DoTypesMatch(CallerType.This, CalleeType.This, ft_different_class)) 824 return false; 825 826 if (!DoTypesMatch(CallerType.Func->getReturnType(), 827 CalleeType.Func->getReturnType(), ft_return_type)) 828 return false; 829 830 if (CallerType.Func->getNumParams() != CalleeType.Func->getNumParams()) { 831 PD << ft_parameter_arity << CallerType.Func->getNumParams() 832 << CalleeType.Func->getNumParams(); 833 return false; 834 } 835 836 ArrayRef<QualType> CalleeParams = CalleeType.Func->getParamTypes(); 837 ArrayRef<QualType> CallerParams = CallerType.Func->getParamTypes(); 838 size_t N = CallerType.Func->getNumParams(); 839 for (size_t I = 0; I < N; I++) { 840 if (!DoTypesMatch(CalleeParams[I], CallerParams[I], 841 ft_parameter_mismatch)) { 842 PD << static_cast<int>(I) + 1; 843 return false; 844 } 845 } 846 847 return true; 848 }; 849 850 PartialDiagnostic PD = PDiag(diag::note_musttail_mismatch); 851 if (!CheckTypesMatch(CallerType, CalleeType, PD)) { 852 if (const auto *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) 853 Diag(St->getBeginLoc(), diag::err_musttail_mismatch) 854 << true << ND->getDeclName(); 855 else 856 Diag(St->getBeginLoc(), diag::err_musttail_mismatch) << false; 857 Diag(CalleeLoc, PD); 858 Diag(MTA.getLocation(), diag::note_tail_call_required) << &MTA; 859 return false; 860 } 861 862 return true; 863 } 864 865 namespace { 866 class CommaVisitor : public EvaluatedExprVisitor<CommaVisitor> { 867 typedef EvaluatedExprVisitor<CommaVisitor> Inherited; 868 Sema &SemaRef; 869 public: 870 CommaVisitor(Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {} 871 void VisitBinaryOperator(BinaryOperator *E) { 872 if (E->getOpcode() == BO_Comma) 873 SemaRef.DiagnoseCommaOperator(E->getLHS(), E->getExprLoc()); 874 EvaluatedExprVisitor<CommaVisitor>::VisitBinaryOperator(E); 875 } 876 }; 877 } 878 879 StmtResult Sema::ActOnIfStmt(SourceLocation IfLoc, 880 IfStatementKind StatementKind, 881 SourceLocation LParenLoc, Stmt *InitStmt, 882 ConditionResult Cond, SourceLocation RParenLoc, 883 Stmt *thenStmt, SourceLocation ElseLoc, 884 Stmt *elseStmt) { 885 if (Cond.isInvalid()) 886 return StmtError(); 887 888 bool ConstevalOrNegatedConsteval = 889 StatementKind == IfStatementKind::ConstevalNonNegated || 890 StatementKind == IfStatementKind::ConstevalNegated; 891 892 Expr *CondExpr = Cond.get().second; 893 assert((CondExpr || ConstevalOrNegatedConsteval) && 894 "If statement: missing condition"); 895 // Only call the CommaVisitor when not C89 due to differences in scope flags. 896 if (CondExpr && (getLangOpts().C99 || getLangOpts().CPlusPlus) && 897 !Diags.isIgnored(diag::warn_comma_operator, CondExpr->getExprLoc())) 898 CommaVisitor(*this).Visit(CondExpr); 899 900 if (!ConstevalOrNegatedConsteval && !elseStmt) 901 DiagnoseEmptyStmtBody(RParenLoc, thenStmt, diag::warn_empty_if_body); 902 903 if (ConstevalOrNegatedConsteval || 904 StatementKind == IfStatementKind::Constexpr) { 905 auto DiagnoseLikelihood = [&](const Stmt *S) { 906 if (const Attr *A = Stmt::getLikelihoodAttr(S)) { 907 Diags.Report(A->getLocation(), 908 diag::warn_attribute_has_no_effect_on_compile_time_if) 909 << A << ConstevalOrNegatedConsteval << A->getRange(); 910 Diags.Report(IfLoc, 911 diag::note_attribute_has_no_effect_on_compile_time_if_here) 912 << ConstevalOrNegatedConsteval 913 << SourceRange(IfLoc, (ConstevalOrNegatedConsteval 914 ? thenStmt->getBeginLoc() 915 : LParenLoc) 916 .getLocWithOffset(-1)); 917 } 918 }; 919 DiagnoseLikelihood(thenStmt); 920 DiagnoseLikelihood(elseStmt); 921 } else { 922 std::tuple<bool, const Attr *, const Attr *> LHC = 923 Stmt::determineLikelihoodConflict(thenStmt, elseStmt); 924 if (std::get<0>(LHC)) { 925 const Attr *ThenAttr = std::get<1>(LHC); 926 const Attr *ElseAttr = std::get<2>(LHC); 927 Diags.Report(ThenAttr->getLocation(), 928 diag::warn_attributes_likelihood_ifstmt_conflict) 929 << ThenAttr << ThenAttr->getRange(); 930 Diags.Report(ElseAttr->getLocation(), diag::note_conflicting_attribute) 931 << ElseAttr << ElseAttr->getRange(); 932 } 933 } 934 935 if (ConstevalOrNegatedConsteval) { 936 bool Immediate = ExprEvalContexts.back().Context == 937 ExpressionEvaluationContext::ImmediateFunctionContext; 938 if (CurContext->isFunctionOrMethod()) { 939 const auto *FD = 940 dyn_cast<FunctionDecl>(Decl::castFromDeclContext(CurContext)); 941 if (FD && FD->isImmediateFunction()) 942 Immediate = true; 943 } 944 if (isUnevaluatedContext() || Immediate) 945 Diags.Report(IfLoc, diag::warn_consteval_if_always_true) << Immediate; 946 } 947 948 return BuildIfStmt(IfLoc, StatementKind, LParenLoc, InitStmt, Cond, RParenLoc, 949 thenStmt, ElseLoc, elseStmt); 950 } 951 952 StmtResult Sema::BuildIfStmt(SourceLocation IfLoc, 953 IfStatementKind StatementKind, 954 SourceLocation LParenLoc, Stmt *InitStmt, 955 ConditionResult Cond, SourceLocation RParenLoc, 956 Stmt *thenStmt, SourceLocation ElseLoc, 957 Stmt *elseStmt) { 958 if (Cond.isInvalid()) 959 return StmtError(); 960 961 if (StatementKind != IfStatementKind::Ordinary || 962 isa<ObjCAvailabilityCheckExpr>(Cond.get().second)) 963 setFunctionHasBranchProtectedScope(); 964 965 return IfStmt::Create(Context, IfLoc, StatementKind, InitStmt, 966 Cond.get().first, Cond.get().second, LParenLoc, 967 RParenLoc, thenStmt, ElseLoc, elseStmt); 968 } 969 970 namespace { 971 struct CaseCompareFunctor { 972 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 973 const llvm::APSInt &RHS) { 974 return LHS.first < RHS; 975 } 976 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 977 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 978 return LHS.first < RHS.first; 979 } 980 bool operator()(const llvm::APSInt &LHS, 981 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 982 return LHS < RHS.first; 983 } 984 }; 985 } 986 987 /// CmpCaseVals - Comparison predicate for sorting case values. 988 /// 989 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs, 990 const std::pair<llvm::APSInt, CaseStmt*>& rhs) { 991 if (lhs.first < rhs.first) 992 return true; 993 994 if (lhs.first == rhs.first && 995 lhs.second->getCaseLoc() < rhs.second->getCaseLoc()) 996 return true; 997 return false; 998 } 999 1000 /// CmpEnumVals - Comparison predicate for sorting enumeration values. 1001 /// 1002 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 1003 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 1004 { 1005 return lhs.first < rhs.first; 1006 } 1007 1008 /// EqEnumVals - Comparison preficate for uniqing enumeration values. 1009 /// 1010 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 1011 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 1012 { 1013 return lhs.first == rhs.first; 1014 } 1015 1016 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of 1017 /// potentially integral-promoted expression @p expr. 1018 static QualType GetTypeBeforeIntegralPromotion(const Expr *&E) { 1019 if (const auto *FE = dyn_cast<FullExpr>(E)) 1020 E = FE->getSubExpr(); 1021 while (const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) { 1022 if (ImpCast->getCastKind() != CK_IntegralCast) break; 1023 E = ImpCast->getSubExpr(); 1024 } 1025 return E->getType(); 1026 } 1027 1028 ExprResult Sema::CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond) { 1029 class SwitchConvertDiagnoser : public ICEConvertDiagnoser { 1030 Expr *Cond; 1031 1032 public: 1033 SwitchConvertDiagnoser(Expr *Cond) 1034 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true), 1035 Cond(Cond) {} 1036 1037 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 1038 QualType T) override { 1039 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T; 1040 } 1041 1042 SemaDiagnosticBuilder diagnoseIncomplete( 1043 Sema &S, SourceLocation Loc, QualType T) override { 1044 return S.Diag(Loc, diag::err_switch_incomplete_class_type) 1045 << T << Cond->getSourceRange(); 1046 } 1047 1048 SemaDiagnosticBuilder diagnoseExplicitConv( 1049 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 1050 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy; 1051 } 1052 1053 SemaDiagnosticBuilder noteExplicitConv( 1054 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 1055 return S.Diag(Conv->getLocation(), diag::note_switch_conversion) 1056 << ConvTy->isEnumeralType() << ConvTy; 1057 } 1058 1059 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 1060 QualType T) override { 1061 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T; 1062 } 1063 1064 SemaDiagnosticBuilder noteAmbiguous( 1065 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 1066 return S.Diag(Conv->getLocation(), diag::note_switch_conversion) 1067 << ConvTy->isEnumeralType() << ConvTy; 1068 } 1069 1070 SemaDiagnosticBuilder diagnoseConversion( 1071 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 1072 llvm_unreachable("conversion functions are permitted"); 1073 } 1074 } SwitchDiagnoser(Cond); 1075 1076 ExprResult CondResult = 1077 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser); 1078 if (CondResult.isInvalid()) 1079 return ExprError(); 1080 1081 // FIXME: PerformContextualImplicitConversion doesn't always tell us if it 1082 // failed and produced a diagnostic. 1083 Cond = CondResult.get(); 1084 if (!Cond->isTypeDependent() && 1085 !Cond->getType()->isIntegralOrEnumerationType()) 1086 return ExprError(); 1087 1088 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr. 1089 return UsualUnaryConversions(Cond); 1090 } 1091 1092 StmtResult Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, 1093 SourceLocation LParenLoc, 1094 Stmt *InitStmt, ConditionResult Cond, 1095 SourceLocation RParenLoc) { 1096 Expr *CondExpr = Cond.get().second; 1097 assert((Cond.isInvalid() || CondExpr) && "switch with no condition"); 1098 1099 if (CondExpr && !CondExpr->isTypeDependent()) { 1100 // We have already converted the expression to an integral or enumeration 1101 // type, when we parsed the switch condition. There are cases where we don't 1102 // have an appropriate type, e.g. a typo-expr Cond was corrected to an 1103 // inappropriate-type expr, we just return an error. 1104 if (!CondExpr->getType()->isIntegralOrEnumerationType()) 1105 return StmtError(); 1106 if (CondExpr->isKnownToHaveBooleanValue()) { 1107 // switch(bool_expr) {...} is often a programmer error, e.g. 1108 // switch(n && mask) { ... } // Doh - should be "n & mask". 1109 // One can always use an if statement instead of switch(bool_expr). 1110 Diag(SwitchLoc, diag::warn_bool_switch_condition) 1111 << CondExpr->getSourceRange(); 1112 } 1113 } 1114 1115 setFunctionHasBranchIntoScope(); 1116 1117 auto *SS = SwitchStmt::Create(Context, InitStmt, Cond.get().first, CondExpr, 1118 LParenLoc, RParenLoc); 1119 getCurFunction()->SwitchStack.push_back( 1120 FunctionScopeInfo::SwitchInfo(SS, false)); 1121 return SS; 1122 } 1123 1124 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) { 1125 Val = Val.extOrTrunc(BitWidth); 1126 Val.setIsSigned(IsSigned); 1127 } 1128 1129 /// Check the specified case value is in range for the given unpromoted switch 1130 /// type. 1131 static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val, 1132 unsigned UnpromotedWidth, bool UnpromotedSign) { 1133 // In C++11 onwards, this is checked by the language rules. 1134 if (S.getLangOpts().CPlusPlus11) 1135 return; 1136 1137 // If the case value was signed and negative and the switch expression is 1138 // unsigned, don't bother to warn: this is implementation-defined behavior. 1139 // FIXME: Introduce a second, default-ignored warning for this case? 1140 if (UnpromotedWidth < Val.getBitWidth()) { 1141 llvm::APSInt ConvVal(Val); 1142 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign); 1143 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned()); 1144 // FIXME: Use different diagnostics for overflow in conversion to promoted 1145 // type versus "switch expression cannot have this value". Use proper 1146 // IntRange checking rather than just looking at the unpromoted type here. 1147 if (ConvVal != Val) 1148 S.Diag(Loc, diag::warn_case_value_overflow) << toString(Val, 10) 1149 << toString(ConvVal, 10); 1150 } 1151 } 1152 1153 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy; 1154 1155 /// Returns true if we should emit a diagnostic about this case expression not 1156 /// being a part of the enum used in the switch controlling expression. 1157 static bool ShouldDiagnoseSwitchCaseNotInEnum(const Sema &S, 1158 const EnumDecl *ED, 1159 const Expr *CaseExpr, 1160 EnumValsTy::iterator &EI, 1161 EnumValsTy::iterator &EIEnd, 1162 const llvm::APSInt &Val) { 1163 if (!ED->isClosed()) 1164 return false; 1165 1166 if (const DeclRefExpr *DRE = 1167 dyn_cast<DeclRefExpr>(CaseExpr->IgnoreParenImpCasts())) { 1168 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 1169 QualType VarType = VD->getType(); 1170 QualType EnumType = S.Context.getTypeDeclType(ED); 1171 if (VD->hasGlobalStorage() && VarType.isConstQualified() && 1172 S.Context.hasSameUnqualifiedType(EnumType, VarType)) 1173 return false; 1174 } 1175 } 1176 1177 if (ED->hasAttr<FlagEnumAttr>()) 1178 return !S.IsValueInFlagEnum(ED, Val, false); 1179 1180 while (EI != EIEnd && EI->first < Val) 1181 EI++; 1182 1183 if (EI != EIEnd && EI->first == Val) 1184 return false; 1185 1186 return true; 1187 } 1188 1189 static void checkEnumTypesInSwitchStmt(Sema &S, const Expr *Cond, 1190 const Expr *Case) { 1191 QualType CondType = Cond->getType(); 1192 QualType CaseType = Case->getType(); 1193 1194 const EnumType *CondEnumType = CondType->getAs<EnumType>(); 1195 const EnumType *CaseEnumType = CaseType->getAs<EnumType>(); 1196 if (!CondEnumType || !CaseEnumType) 1197 return; 1198 1199 // Ignore anonymous enums. 1200 if (!CondEnumType->getDecl()->getIdentifier() && 1201 !CondEnumType->getDecl()->getTypedefNameForAnonDecl()) 1202 return; 1203 if (!CaseEnumType->getDecl()->getIdentifier() && 1204 !CaseEnumType->getDecl()->getTypedefNameForAnonDecl()) 1205 return; 1206 1207 if (S.Context.hasSameUnqualifiedType(CondType, CaseType)) 1208 return; 1209 1210 S.Diag(Case->getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch) 1211 << CondType << CaseType << Cond->getSourceRange() 1212 << Case->getSourceRange(); 1213 } 1214 1215 StmtResult 1216 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, 1217 Stmt *BodyStmt) { 1218 SwitchStmt *SS = cast<SwitchStmt>(Switch); 1219 bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt(); 1220 assert(SS == getCurFunction()->SwitchStack.back().getPointer() && 1221 "switch stack missing push/pop!"); 1222 1223 getCurFunction()->SwitchStack.pop_back(); 1224 1225 if (!BodyStmt) return StmtError(); 1226 SS->setBody(BodyStmt, SwitchLoc); 1227 1228 Expr *CondExpr = SS->getCond(); 1229 if (!CondExpr) return StmtError(); 1230 1231 QualType CondType = CondExpr->getType(); 1232 1233 // C++ 6.4.2.p2: 1234 // Integral promotions are performed (on the switch condition). 1235 // 1236 // A case value unrepresentable by the original switch condition 1237 // type (before the promotion) doesn't make sense, even when it can 1238 // be represented by the promoted type. Therefore we need to find 1239 // the pre-promotion type of the switch condition. 1240 const Expr *CondExprBeforePromotion = CondExpr; 1241 QualType CondTypeBeforePromotion = 1242 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion); 1243 1244 // Get the bitwidth of the switched-on value after promotions. We must 1245 // convert the integer case values to this width before comparison. 1246 bool HasDependentValue 1247 = CondExpr->isTypeDependent() || CondExpr->isValueDependent(); 1248 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType); 1249 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType(); 1250 1251 // Get the width and signedness that the condition might actually have, for 1252 // warning purposes. 1253 // FIXME: Grab an IntRange for the condition rather than using the unpromoted 1254 // type. 1255 unsigned CondWidthBeforePromotion 1256 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion); 1257 bool CondIsSignedBeforePromotion 1258 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType(); 1259 1260 // Accumulate all of the case values in a vector so that we can sort them 1261 // and detect duplicates. This vector contains the APInt for the case after 1262 // it has been converted to the condition type. 1263 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy; 1264 CaseValsTy CaseVals; 1265 1266 // Keep track of any GNU case ranges we see. The APSInt is the low value. 1267 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy; 1268 CaseRangesTy CaseRanges; 1269 1270 DefaultStmt *TheDefaultStmt = nullptr; 1271 1272 bool CaseListIsErroneous = false; 1273 1274 // FIXME: We'd better diagnose missing or duplicate default labels even 1275 // in the dependent case. Because default labels themselves are never 1276 // dependent. 1277 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue; 1278 SC = SC->getNextSwitchCase()) { 1279 1280 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) { 1281 if (TheDefaultStmt) { 1282 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined); 1283 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev); 1284 1285 // FIXME: Remove the default statement from the switch block so that 1286 // we'll return a valid AST. This requires recursing down the AST and 1287 // finding it, not something we are set up to do right now. For now, 1288 // just lop the entire switch stmt out of the AST. 1289 CaseListIsErroneous = true; 1290 } 1291 TheDefaultStmt = DS; 1292 1293 } else { 1294 CaseStmt *CS = cast<CaseStmt>(SC); 1295 1296 Expr *Lo = CS->getLHS(); 1297 1298 if (Lo->isValueDependent()) { 1299 HasDependentValue = true; 1300 break; 1301 } 1302 1303 // We already verified that the expression has a constant value; 1304 // get that value (prior to conversions). 1305 const Expr *LoBeforePromotion = Lo; 1306 GetTypeBeforeIntegralPromotion(LoBeforePromotion); 1307 llvm::APSInt LoVal = LoBeforePromotion->EvaluateKnownConstInt(Context); 1308 1309 // Check the unconverted value is within the range of possible values of 1310 // the switch expression. 1311 checkCaseValue(*this, Lo->getBeginLoc(), LoVal, CondWidthBeforePromotion, 1312 CondIsSignedBeforePromotion); 1313 1314 // FIXME: This duplicates the check performed for warn_not_in_enum below. 1315 checkEnumTypesInSwitchStmt(*this, CondExprBeforePromotion, 1316 LoBeforePromotion); 1317 1318 // Convert the value to the same width/sign as the condition. 1319 AdjustAPSInt(LoVal, CondWidth, CondIsSigned); 1320 1321 // If this is a case range, remember it in CaseRanges, otherwise CaseVals. 1322 if (CS->getRHS()) { 1323 if (CS->getRHS()->isValueDependent()) { 1324 HasDependentValue = true; 1325 break; 1326 } 1327 CaseRanges.push_back(std::make_pair(LoVal, CS)); 1328 } else 1329 CaseVals.push_back(std::make_pair(LoVal, CS)); 1330 } 1331 } 1332 1333 if (!HasDependentValue) { 1334 // If we don't have a default statement, check whether the 1335 // condition is constant. 1336 llvm::APSInt ConstantCondValue; 1337 bool HasConstantCond = false; 1338 if (!TheDefaultStmt) { 1339 Expr::EvalResult Result; 1340 HasConstantCond = CondExpr->EvaluateAsInt(Result, Context, 1341 Expr::SE_AllowSideEffects); 1342 if (Result.Val.isInt()) 1343 ConstantCondValue = Result.Val.getInt(); 1344 assert(!HasConstantCond || 1345 (ConstantCondValue.getBitWidth() == CondWidth && 1346 ConstantCondValue.isSigned() == CondIsSigned)); 1347 Diag(SwitchLoc, diag::warn_switch_default); 1348 } 1349 bool ShouldCheckConstantCond = HasConstantCond; 1350 1351 // Sort all the scalar case values so we can easily detect duplicates. 1352 llvm::stable_sort(CaseVals, CmpCaseVals); 1353 1354 if (!CaseVals.empty()) { 1355 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) { 1356 if (ShouldCheckConstantCond && 1357 CaseVals[i].first == ConstantCondValue) 1358 ShouldCheckConstantCond = false; 1359 1360 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) { 1361 // If we have a duplicate, report it. 1362 // First, determine if either case value has a name 1363 StringRef PrevString, CurrString; 1364 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts(); 1365 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts(); 1366 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) { 1367 PrevString = DeclRef->getDecl()->getName(); 1368 } 1369 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) { 1370 CurrString = DeclRef->getDecl()->getName(); 1371 } 1372 SmallString<16> CaseValStr; 1373 CaseVals[i-1].first.toString(CaseValStr); 1374 1375 if (PrevString == CurrString) 1376 Diag(CaseVals[i].second->getLHS()->getBeginLoc(), 1377 diag::err_duplicate_case) 1378 << (PrevString.empty() ? CaseValStr.str() : PrevString); 1379 else 1380 Diag(CaseVals[i].second->getLHS()->getBeginLoc(), 1381 diag::err_duplicate_case_differing_expr) 1382 << (PrevString.empty() ? CaseValStr.str() : PrevString) 1383 << (CurrString.empty() ? CaseValStr.str() : CurrString) 1384 << CaseValStr; 1385 1386 Diag(CaseVals[i - 1].second->getLHS()->getBeginLoc(), 1387 diag::note_duplicate_case_prev); 1388 // FIXME: We really want to remove the bogus case stmt from the 1389 // substmt, but we have no way to do this right now. 1390 CaseListIsErroneous = true; 1391 } 1392 } 1393 } 1394 1395 // Detect duplicate case ranges, which usually don't exist at all in 1396 // the first place. 1397 if (!CaseRanges.empty()) { 1398 // Sort all the case ranges by their low value so we can easily detect 1399 // overlaps between ranges. 1400 llvm::stable_sort(CaseRanges); 1401 1402 // Scan the ranges, computing the high values and removing empty ranges. 1403 std::vector<llvm::APSInt> HiVals; 1404 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 1405 llvm::APSInt &LoVal = CaseRanges[i].first; 1406 CaseStmt *CR = CaseRanges[i].second; 1407 Expr *Hi = CR->getRHS(); 1408 1409 const Expr *HiBeforePromotion = Hi; 1410 GetTypeBeforeIntegralPromotion(HiBeforePromotion); 1411 llvm::APSInt HiVal = HiBeforePromotion->EvaluateKnownConstInt(Context); 1412 1413 // Check the unconverted value is within the range of possible values of 1414 // the switch expression. 1415 checkCaseValue(*this, Hi->getBeginLoc(), HiVal, 1416 CondWidthBeforePromotion, CondIsSignedBeforePromotion); 1417 1418 // Convert the value to the same width/sign as the condition. 1419 AdjustAPSInt(HiVal, CondWidth, CondIsSigned); 1420 1421 // If the low value is bigger than the high value, the case is empty. 1422 if (LoVal > HiVal) { 1423 Diag(CR->getLHS()->getBeginLoc(), diag::warn_case_empty_range) 1424 << SourceRange(CR->getLHS()->getBeginLoc(), Hi->getEndLoc()); 1425 CaseRanges.erase(CaseRanges.begin()+i); 1426 --i; 1427 --e; 1428 continue; 1429 } 1430 1431 if (ShouldCheckConstantCond && 1432 LoVal <= ConstantCondValue && 1433 ConstantCondValue <= HiVal) 1434 ShouldCheckConstantCond = false; 1435 1436 HiVals.push_back(HiVal); 1437 } 1438 1439 // Rescan the ranges, looking for overlap with singleton values and other 1440 // ranges. Since the range list is sorted, we only need to compare case 1441 // ranges with their neighbors. 1442 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 1443 llvm::APSInt &CRLo = CaseRanges[i].first; 1444 llvm::APSInt &CRHi = HiVals[i]; 1445 CaseStmt *CR = CaseRanges[i].second; 1446 1447 // Check to see whether the case range overlaps with any 1448 // singleton cases. 1449 CaseStmt *OverlapStmt = nullptr; 1450 llvm::APSInt OverlapVal(32); 1451 1452 // Find the smallest value >= the lower bound. If I is in the 1453 // case range, then we have overlap. 1454 CaseValsTy::iterator I = 1455 llvm::lower_bound(CaseVals, CRLo, CaseCompareFunctor()); 1456 if (I != CaseVals.end() && I->first < CRHi) { 1457 OverlapVal = I->first; // Found overlap with scalar. 1458 OverlapStmt = I->second; 1459 } 1460 1461 // Find the smallest value bigger than the upper bound. 1462 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor()); 1463 if (I != CaseVals.begin() && (I-1)->first >= CRLo) { 1464 OverlapVal = (I-1)->first; // Found overlap with scalar. 1465 OverlapStmt = (I-1)->second; 1466 } 1467 1468 // Check to see if this case stmt overlaps with the subsequent 1469 // case range. 1470 if (i && CRLo <= HiVals[i-1]) { 1471 OverlapVal = HiVals[i-1]; // Found overlap with range. 1472 OverlapStmt = CaseRanges[i-1].second; 1473 } 1474 1475 if (OverlapStmt) { 1476 // If we have a duplicate, report it. 1477 Diag(CR->getLHS()->getBeginLoc(), diag::err_duplicate_case) 1478 << toString(OverlapVal, 10); 1479 Diag(OverlapStmt->getLHS()->getBeginLoc(), 1480 diag::note_duplicate_case_prev); 1481 // FIXME: We really want to remove the bogus case stmt from the 1482 // substmt, but we have no way to do this right now. 1483 CaseListIsErroneous = true; 1484 } 1485 } 1486 } 1487 1488 // Complain if we have a constant condition and we didn't find a match. 1489 if (!CaseListIsErroneous && !CaseListIsIncomplete && 1490 ShouldCheckConstantCond) { 1491 // TODO: it would be nice if we printed enums as enums, chars as 1492 // chars, etc. 1493 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition) 1494 << toString(ConstantCondValue, 10) 1495 << CondExpr->getSourceRange(); 1496 } 1497 1498 // Check to see if switch is over an Enum and handles all of its 1499 // values. We only issue a warning if there is not 'default:', but 1500 // we still do the analysis to preserve this information in the AST 1501 // (which can be used by flow-based analyes). 1502 // 1503 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>(); 1504 1505 // If switch has default case, then ignore it. 1506 if (!CaseListIsErroneous && !CaseListIsIncomplete && !HasConstantCond && 1507 ET && ET->getDecl()->isCompleteDefinition() && 1508 !ET->getDecl()->enumerators().empty()) { 1509 const EnumDecl *ED = ET->getDecl(); 1510 EnumValsTy EnumVals; 1511 1512 // Gather all enum values, set their type and sort them, 1513 // allowing easier comparison with CaseVals. 1514 for (auto *EDI : ED->enumerators()) { 1515 llvm::APSInt Val = EDI->getInitVal(); 1516 AdjustAPSInt(Val, CondWidth, CondIsSigned); 1517 EnumVals.push_back(std::make_pair(Val, EDI)); 1518 } 1519 llvm::stable_sort(EnumVals, CmpEnumVals); 1520 auto EI = EnumVals.begin(), EIEnd = 1521 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals); 1522 1523 // See which case values aren't in enum. 1524 for (CaseValsTy::const_iterator CI = CaseVals.begin(); 1525 CI != CaseVals.end(); CI++) { 1526 Expr *CaseExpr = CI->second->getLHS(); 1527 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd, 1528 CI->first)) 1529 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum) 1530 << CondTypeBeforePromotion; 1531 } 1532 1533 // See which of case ranges aren't in enum 1534 EI = EnumVals.begin(); 1535 for (CaseRangesTy::const_iterator RI = CaseRanges.begin(); 1536 RI != CaseRanges.end(); RI++) { 1537 Expr *CaseExpr = RI->second->getLHS(); 1538 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd, 1539 RI->first)) 1540 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum) 1541 << CondTypeBeforePromotion; 1542 1543 llvm::APSInt Hi = 1544 RI->second->getRHS()->EvaluateKnownConstInt(Context); 1545 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 1546 1547 CaseExpr = RI->second->getRHS(); 1548 if (ShouldDiagnoseSwitchCaseNotInEnum(*this, ED, CaseExpr, EI, EIEnd, 1549 Hi)) 1550 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum) 1551 << CondTypeBeforePromotion; 1552 } 1553 1554 // Check which enum vals aren't in switch 1555 auto CI = CaseVals.begin(); 1556 auto RI = CaseRanges.begin(); 1557 bool hasCasesNotInSwitch = false; 1558 1559 SmallVector<DeclarationName,8> UnhandledNames; 1560 1561 for (EI = EnumVals.begin(); EI != EIEnd; EI++) { 1562 // Don't warn about omitted unavailable EnumConstantDecls. 1563 switch (EI->second->getAvailability()) { 1564 case AR_Deprecated: 1565 // Omitting a deprecated constant is ok; it should never materialize. 1566 case AR_Unavailable: 1567 continue; 1568 1569 case AR_NotYetIntroduced: 1570 // Partially available enum constants should be present. Note that we 1571 // suppress -Wunguarded-availability diagnostics for such uses. 1572 case AR_Available: 1573 break; 1574 } 1575 1576 if (EI->second->hasAttr<UnusedAttr>()) 1577 continue; 1578 1579 // Drop unneeded case values 1580 while (CI != CaseVals.end() && CI->first < EI->first) 1581 CI++; 1582 1583 if (CI != CaseVals.end() && CI->first == EI->first) 1584 continue; 1585 1586 // Drop unneeded case ranges 1587 for (; RI != CaseRanges.end(); RI++) { 1588 llvm::APSInt Hi = 1589 RI->second->getRHS()->EvaluateKnownConstInt(Context); 1590 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 1591 if (EI->first <= Hi) 1592 break; 1593 } 1594 1595 if (RI == CaseRanges.end() || EI->first < RI->first) { 1596 hasCasesNotInSwitch = true; 1597 UnhandledNames.push_back(EI->second->getDeclName()); 1598 } 1599 } 1600 1601 if (TheDefaultStmt && UnhandledNames.empty() && ED->isClosedNonFlag()) 1602 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default); 1603 1604 // Produce a nice diagnostic if multiple values aren't handled. 1605 if (!UnhandledNames.empty()) { 1606 auto DB = Diag(CondExpr->getExprLoc(), TheDefaultStmt 1607 ? diag::warn_def_missing_case 1608 : diag::warn_missing_case) 1609 << CondExpr->getSourceRange() << (int)UnhandledNames.size(); 1610 1611 for (size_t I = 0, E = std::min(UnhandledNames.size(), (size_t)3); 1612 I != E; ++I) 1613 DB << UnhandledNames[I]; 1614 } 1615 1616 if (!hasCasesNotInSwitch) 1617 SS->setAllEnumCasesCovered(); 1618 } 1619 } 1620 1621 if (BodyStmt) 1622 DiagnoseEmptyStmtBody(CondExpr->getEndLoc(), BodyStmt, 1623 diag::warn_empty_switch_body); 1624 1625 // FIXME: If the case list was broken is some way, we don't have a good system 1626 // to patch it up. Instead, just return the whole substmt as broken. 1627 if (CaseListIsErroneous) 1628 return StmtError(); 1629 1630 return SS; 1631 } 1632 1633 void 1634 Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, 1635 Expr *SrcExpr) { 1636 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc())) 1637 return; 1638 1639 if (const EnumType *ET = DstType->getAs<EnumType>()) 1640 if (!Context.hasSameUnqualifiedType(SrcType, DstType) && 1641 SrcType->isIntegerType()) { 1642 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() && 1643 SrcExpr->isIntegerConstantExpr(Context)) { 1644 // Get the bitwidth of the enum value before promotions. 1645 unsigned DstWidth = Context.getIntWidth(DstType); 1646 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType(); 1647 1648 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context); 1649 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned); 1650 const EnumDecl *ED = ET->getDecl(); 1651 1652 if (!ED->isClosed()) 1653 return; 1654 1655 if (ED->hasAttr<FlagEnumAttr>()) { 1656 if (!IsValueInFlagEnum(ED, RhsVal, true)) 1657 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment) 1658 << DstType.getUnqualifiedType(); 1659 } else { 1660 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64> 1661 EnumValsTy; 1662 EnumValsTy EnumVals; 1663 1664 // Gather all enum values, set their type and sort them, 1665 // allowing easier comparison with rhs constant. 1666 for (auto *EDI : ED->enumerators()) { 1667 llvm::APSInt Val = EDI->getInitVal(); 1668 AdjustAPSInt(Val, DstWidth, DstIsSigned); 1669 EnumVals.push_back(std::make_pair(Val, EDI)); 1670 } 1671 if (EnumVals.empty()) 1672 return; 1673 llvm::stable_sort(EnumVals, CmpEnumVals); 1674 EnumValsTy::iterator EIend = 1675 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals); 1676 1677 // See which values aren't in the enum. 1678 EnumValsTy::const_iterator EI = EnumVals.begin(); 1679 while (EI != EIend && EI->first < RhsVal) 1680 EI++; 1681 if (EI == EIend || EI->first != RhsVal) { 1682 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment) 1683 << DstType.getUnqualifiedType(); 1684 } 1685 } 1686 } 1687 } 1688 } 1689 1690 StmtResult Sema::ActOnWhileStmt(SourceLocation WhileLoc, 1691 SourceLocation LParenLoc, ConditionResult Cond, 1692 SourceLocation RParenLoc, Stmt *Body) { 1693 if (Cond.isInvalid()) 1694 return StmtError(); 1695 1696 auto CondVal = Cond.get(); 1697 CheckBreakContinueBinding(CondVal.second); 1698 1699 if (CondVal.second && 1700 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc())) 1701 CommaVisitor(*this).Visit(CondVal.second); 1702 1703 if (isa<NullStmt>(Body)) 1704 getCurCompoundScope().setHasEmptyLoopBodies(); 1705 1706 return WhileStmt::Create(Context, CondVal.first, CondVal.second, Body, 1707 WhileLoc, LParenLoc, RParenLoc); 1708 } 1709 1710 StmtResult 1711 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 1712 SourceLocation WhileLoc, SourceLocation CondLParen, 1713 Expr *Cond, SourceLocation CondRParen) { 1714 assert(Cond && "ActOnDoStmt(): missing expression"); 1715 1716 CheckBreakContinueBinding(Cond); 1717 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond); 1718 if (CondResult.isInvalid()) 1719 return StmtError(); 1720 Cond = CondResult.get(); 1721 1722 CondResult = ActOnFinishFullExpr(Cond, DoLoc, /*DiscardedValue*/ false); 1723 if (CondResult.isInvalid()) 1724 return StmtError(); 1725 Cond = CondResult.get(); 1726 1727 // Only call the CommaVisitor for C89 due to differences in scope flags. 1728 if (Cond && !getLangOpts().C99 && !getLangOpts().CPlusPlus && 1729 !Diags.isIgnored(diag::warn_comma_operator, Cond->getExprLoc())) 1730 CommaVisitor(*this).Visit(Cond); 1731 1732 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen); 1733 } 1734 1735 namespace { 1736 // Use SetVector since the diagnostic cares about the ordering of the Decl's. 1737 using DeclSetVector = llvm::SmallSetVector<VarDecl *, 8>; 1738 1739 // This visitor will traverse a conditional statement and store all 1740 // the evaluated decls into a vector. Simple is set to true if none 1741 // of the excluded constructs are used. 1742 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> { 1743 DeclSetVector &Decls; 1744 SmallVectorImpl<SourceRange> &Ranges; 1745 bool Simple; 1746 public: 1747 typedef EvaluatedExprVisitor<DeclExtractor> Inherited; 1748 1749 DeclExtractor(Sema &S, DeclSetVector &Decls, 1750 SmallVectorImpl<SourceRange> &Ranges) : 1751 Inherited(S.Context), 1752 Decls(Decls), 1753 Ranges(Ranges), 1754 Simple(true) {} 1755 1756 bool isSimple() { return Simple; } 1757 1758 // Replaces the method in EvaluatedExprVisitor. 1759 void VisitMemberExpr(MemberExpr* E) { 1760 Simple = false; 1761 } 1762 1763 // Any Stmt not explicitly listed will cause the condition to be marked 1764 // complex. 1765 void VisitStmt(Stmt *S) { Simple = false; } 1766 1767 void VisitBinaryOperator(BinaryOperator *E) { 1768 Visit(E->getLHS()); 1769 Visit(E->getRHS()); 1770 } 1771 1772 void VisitCastExpr(CastExpr *E) { 1773 Visit(E->getSubExpr()); 1774 } 1775 1776 void VisitUnaryOperator(UnaryOperator *E) { 1777 // Skip checking conditionals with derefernces. 1778 if (E->getOpcode() == UO_Deref) 1779 Simple = false; 1780 else 1781 Visit(E->getSubExpr()); 1782 } 1783 1784 void VisitConditionalOperator(ConditionalOperator *E) { 1785 Visit(E->getCond()); 1786 Visit(E->getTrueExpr()); 1787 Visit(E->getFalseExpr()); 1788 } 1789 1790 void VisitParenExpr(ParenExpr *E) { 1791 Visit(E->getSubExpr()); 1792 } 1793 1794 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 1795 Visit(E->getOpaqueValue()->getSourceExpr()); 1796 Visit(E->getFalseExpr()); 1797 } 1798 1799 void VisitIntegerLiteral(IntegerLiteral *E) { } 1800 void VisitFloatingLiteral(FloatingLiteral *E) { } 1801 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { } 1802 void VisitCharacterLiteral(CharacterLiteral *E) { } 1803 void VisitGNUNullExpr(GNUNullExpr *E) { } 1804 void VisitImaginaryLiteral(ImaginaryLiteral *E) { } 1805 1806 void VisitDeclRefExpr(DeclRefExpr *E) { 1807 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()); 1808 if (!VD) { 1809 // Don't allow unhandled Decl types. 1810 Simple = false; 1811 return; 1812 } 1813 1814 Ranges.push_back(E->getSourceRange()); 1815 1816 Decls.insert(VD); 1817 } 1818 1819 }; // end class DeclExtractor 1820 1821 // DeclMatcher checks to see if the decls are used in a non-evaluated 1822 // context. 1823 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> { 1824 DeclSetVector &Decls; 1825 bool FoundDecl; 1826 1827 public: 1828 typedef EvaluatedExprVisitor<DeclMatcher> Inherited; 1829 1830 DeclMatcher(Sema &S, DeclSetVector &Decls, Stmt *Statement) : 1831 Inherited(S.Context), Decls(Decls), FoundDecl(false) { 1832 if (!Statement) return; 1833 1834 Visit(Statement); 1835 } 1836 1837 void VisitReturnStmt(ReturnStmt *S) { 1838 FoundDecl = true; 1839 } 1840 1841 void VisitBreakStmt(BreakStmt *S) { 1842 FoundDecl = true; 1843 } 1844 1845 void VisitGotoStmt(GotoStmt *S) { 1846 FoundDecl = true; 1847 } 1848 1849 void VisitCastExpr(CastExpr *E) { 1850 if (E->getCastKind() == CK_LValueToRValue) 1851 CheckLValueToRValueCast(E->getSubExpr()); 1852 else 1853 Visit(E->getSubExpr()); 1854 } 1855 1856 void CheckLValueToRValueCast(Expr *E) { 1857 E = E->IgnoreParenImpCasts(); 1858 1859 if (isa<DeclRefExpr>(E)) { 1860 return; 1861 } 1862 1863 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 1864 Visit(CO->getCond()); 1865 CheckLValueToRValueCast(CO->getTrueExpr()); 1866 CheckLValueToRValueCast(CO->getFalseExpr()); 1867 return; 1868 } 1869 1870 if (BinaryConditionalOperator *BCO = 1871 dyn_cast<BinaryConditionalOperator>(E)) { 1872 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr()); 1873 CheckLValueToRValueCast(BCO->getFalseExpr()); 1874 return; 1875 } 1876 1877 Visit(E); 1878 } 1879 1880 void VisitDeclRefExpr(DeclRefExpr *E) { 1881 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 1882 if (Decls.count(VD)) 1883 FoundDecl = true; 1884 } 1885 1886 void VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 1887 // Only need to visit the semantics for POE. 1888 // SyntaticForm doesn't really use the Decal. 1889 for (auto *S : POE->semantics()) { 1890 if (auto *OVE = dyn_cast<OpaqueValueExpr>(S)) 1891 // Look past the OVE into the expression it binds. 1892 Visit(OVE->getSourceExpr()); 1893 else 1894 Visit(S); 1895 } 1896 } 1897 1898 bool FoundDeclInUse() { return FoundDecl; } 1899 1900 }; // end class DeclMatcher 1901 1902 void CheckForLoopConditionalStatement(Sema &S, Expr *Second, 1903 Expr *Third, Stmt *Body) { 1904 // Condition is empty 1905 if (!Second) return; 1906 1907 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body, 1908 Second->getBeginLoc())) 1909 return; 1910 1911 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body); 1912 DeclSetVector Decls; 1913 SmallVector<SourceRange, 10> Ranges; 1914 DeclExtractor DE(S, Decls, Ranges); 1915 DE.Visit(Second); 1916 1917 // Don't analyze complex conditionals. 1918 if (!DE.isSimple()) return; 1919 1920 // No decls found. 1921 if (Decls.size() == 0) return; 1922 1923 // Don't warn on volatile, static, or global variables. 1924 for (auto *VD : Decls) 1925 if (VD->getType().isVolatileQualified() || VD->hasGlobalStorage()) 1926 return; 1927 1928 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() || 1929 DeclMatcher(S, Decls, Third).FoundDeclInUse() || 1930 DeclMatcher(S, Decls, Body).FoundDeclInUse()) 1931 return; 1932 1933 // Load decl names into diagnostic. 1934 if (Decls.size() > 4) { 1935 PDiag << 0; 1936 } else { 1937 PDiag << (unsigned)Decls.size(); 1938 for (auto *VD : Decls) 1939 PDiag << VD->getDeclName(); 1940 } 1941 1942 for (auto Range : Ranges) 1943 PDiag << Range; 1944 1945 S.Diag(Ranges.begin()->getBegin(), PDiag); 1946 } 1947 1948 // If Statement is an incemement or decrement, return true and sets the 1949 // variables Increment and DRE. 1950 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment, 1951 DeclRefExpr *&DRE) { 1952 if (auto Cleanups = dyn_cast<ExprWithCleanups>(Statement)) 1953 if (!Cleanups->cleanupsHaveSideEffects()) 1954 Statement = Cleanups->getSubExpr(); 1955 1956 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) { 1957 switch (UO->getOpcode()) { 1958 default: return false; 1959 case UO_PostInc: 1960 case UO_PreInc: 1961 Increment = true; 1962 break; 1963 case UO_PostDec: 1964 case UO_PreDec: 1965 Increment = false; 1966 break; 1967 } 1968 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()); 1969 return DRE; 1970 } 1971 1972 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) { 1973 FunctionDecl *FD = Call->getDirectCallee(); 1974 if (!FD || !FD->isOverloadedOperator()) return false; 1975 switch (FD->getOverloadedOperator()) { 1976 default: return false; 1977 case OO_PlusPlus: 1978 Increment = true; 1979 break; 1980 case OO_MinusMinus: 1981 Increment = false; 1982 break; 1983 } 1984 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0)); 1985 return DRE; 1986 } 1987 1988 return false; 1989 } 1990 1991 // A visitor to determine if a continue or break statement is a 1992 // subexpression. 1993 class BreakContinueFinder : public ConstEvaluatedExprVisitor<BreakContinueFinder> { 1994 SourceLocation BreakLoc; 1995 SourceLocation ContinueLoc; 1996 bool InSwitch = false; 1997 1998 public: 1999 BreakContinueFinder(Sema &S, const Stmt* Body) : 2000 Inherited(S.Context) { 2001 Visit(Body); 2002 } 2003 2004 typedef ConstEvaluatedExprVisitor<BreakContinueFinder> Inherited; 2005 2006 void VisitContinueStmt(const ContinueStmt* E) { 2007 ContinueLoc = E->getContinueLoc(); 2008 } 2009 2010 void VisitBreakStmt(const BreakStmt* E) { 2011 if (!InSwitch) 2012 BreakLoc = E->getBreakLoc(); 2013 } 2014 2015 void VisitSwitchStmt(const SwitchStmt* S) { 2016 if (const Stmt *Init = S->getInit()) 2017 Visit(Init); 2018 if (const Stmt *CondVar = S->getConditionVariableDeclStmt()) 2019 Visit(CondVar); 2020 if (const Stmt *Cond = S->getCond()) 2021 Visit(Cond); 2022 2023 // Don't return break statements from the body of a switch. 2024 InSwitch = true; 2025 if (const Stmt *Body = S->getBody()) 2026 Visit(Body); 2027 InSwitch = false; 2028 } 2029 2030 void VisitForStmt(const ForStmt *S) { 2031 // Only visit the init statement of a for loop; the body 2032 // has a different break/continue scope. 2033 if (const Stmt *Init = S->getInit()) 2034 Visit(Init); 2035 } 2036 2037 void VisitWhileStmt(const WhileStmt *) { 2038 // Do nothing; the children of a while loop have a different 2039 // break/continue scope. 2040 } 2041 2042 void VisitDoStmt(const DoStmt *) { 2043 // Do nothing; the children of a while loop have a different 2044 // break/continue scope. 2045 } 2046 2047 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) { 2048 // Only visit the initialization of a for loop; the body 2049 // has a different break/continue scope. 2050 if (const Stmt *Init = S->getInit()) 2051 Visit(Init); 2052 if (const Stmt *Range = S->getRangeStmt()) 2053 Visit(Range); 2054 if (const Stmt *Begin = S->getBeginStmt()) 2055 Visit(Begin); 2056 if (const Stmt *End = S->getEndStmt()) 2057 Visit(End); 2058 } 2059 2060 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) { 2061 // Only visit the initialization of a for loop; the body 2062 // has a different break/continue scope. 2063 if (const Stmt *Element = S->getElement()) 2064 Visit(Element); 2065 if (const Stmt *Collection = S->getCollection()) 2066 Visit(Collection); 2067 } 2068 2069 bool ContinueFound() { return ContinueLoc.isValid(); } 2070 bool BreakFound() { return BreakLoc.isValid(); } 2071 SourceLocation GetContinueLoc() { return ContinueLoc; } 2072 SourceLocation GetBreakLoc() { return BreakLoc; } 2073 2074 }; // end class BreakContinueFinder 2075 2076 // Emit a warning when a loop increment/decrement appears twice per loop 2077 // iteration. The conditions which trigger this warning are: 2078 // 1) The last statement in the loop body and the third expression in the 2079 // for loop are both increment or both decrement of the same variable 2080 // 2) No continue statements in the loop body. 2081 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) { 2082 // Return when there is nothing to check. 2083 if (!Body || !Third) return; 2084 2085 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration, 2086 Third->getBeginLoc())) 2087 return; 2088 2089 // Get the last statement from the loop body. 2090 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body); 2091 if (!CS || CS->body_empty()) return; 2092 Stmt *LastStmt = CS->body_back(); 2093 if (!LastStmt) return; 2094 2095 bool LoopIncrement, LastIncrement; 2096 DeclRefExpr *LoopDRE, *LastDRE; 2097 2098 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return; 2099 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return; 2100 2101 // Check that the two statements are both increments or both decrements 2102 // on the same variable. 2103 if (LoopIncrement != LastIncrement || 2104 LoopDRE->getDecl() != LastDRE->getDecl()) return; 2105 2106 if (BreakContinueFinder(S, Body).ContinueFound()) return; 2107 2108 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration) 2109 << LastDRE->getDecl() << LastIncrement; 2110 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here) 2111 << LoopIncrement; 2112 } 2113 2114 } // end namespace 2115 2116 2117 void Sema::CheckBreakContinueBinding(Expr *E) { 2118 if (!E || getLangOpts().CPlusPlus) 2119 return; 2120 BreakContinueFinder BCFinder(*this, E); 2121 Scope *BreakParent = CurScope->getBreakParent(); 2122 if (BCFinder.BreakFound() && BreakParent) { 2123 if (BreakParent->getFlags() & Scope::SwitchScope) { 2124 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch); 2125 } else { 2126 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner) 2127 << "break"; 2128 } 2129 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) { 2130 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner) 2131 << "continue"; 2132 } 2133 } 2134 2135 StmtResult Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 2136 Stmt *First, ConditionResult Second, 2137 FullExprArg third, SourceLocation RParenLoc, 2138 Stmt *Body) { 2139 if (Second.isInvalid()) 2140 return StmtError(); 2141 2142 if (!getLangOpts().CPlusPlus) { 2143 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) { 2144 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 2145 // declare identifiers for objects having storage class 'auto' or 2146 // 'register'. 2147 const Decl *NonVarSeen = nullptr; 2148 bool VarDeclSeen = false; 2149 for (auto *DI : DS->decls()) { 2150 if (VarDecl *VD = dyn_cast<VarDecl>(DI)) { 2151 VarDeclSeen = true; 2152 if (VD->isLocalVarDecl() && !VD->hasLocalStorage()) { 2153 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for); 2154 DI->setInvalidDecl(); 2155 } 2156 } else if (!NonVarSeen) { 2157 // Keep track of the first non-variable declaration we saw so that 2158 // we can diagnose if we don't see any variable declarations. This 2159 // covers a case like declaring a typedef, function, or structure 2160 // type rather than a variable. 2161 NonVarSeen = DI; 2162 } 2163 } 2164 // Diagnose if we saw a non-variable declaration but no variable 2165 // declarations. 2166 if (NonVarSeen && !VarDeclSeen) 2167 Diag(NonVarSeen->getLocation(), diag::err_non_variable_decl_in_for); 2168 } 2169 } 2170 2171 CheckBreakContinueBinding(Second.get().second); 2172 CheckBreakContinueBinding(third.get()); 2173 2174 if (!Second.get().first) 2175 CheckForLoopConditionalStatement(*this, Second.get().second, third.get(), 2176 Body); 2177 CheckForRedundantIteration(*this, third.get(), Body); 2178 2179 if (Second.get().second && 2180 !Diags.isIgnored(diag::warn_comma_operator, 2181 Second.get().second->getExprLoc())) 2182 CommaVisitor(*this).Visit(Second.get().second); 2183 2184 Expr *Third = third.release().getAs<Expr>(); 2185 if (isa<NullStmt>(Body)) 2186 getCurCompoundScope().setHasEmptyLoopBodies(); 2187 2188 return new (Context) 2189 ForStmt(Context, First, Second.get().second, Second.get().first, Third, 2190 Body, ForLoc, LParenLoc, RParenLoc); 2191 } 2192 2193 /// In an Objective C collection iteration statement: 2194 /// for (x in y) 2195 /// x can be an arbitrary l-value expression. Bind it up as a 2196 /// full-expression. 2197 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) { 2198 // Reduce placeholder expressions here. Note that this rejects the 2199 // use of pseudo-object l-values in this position. 2200 ExprResult result = CheckPlaceholderExpr(E); 2201 if (result.isInvalid()) return StmtError(); 2202 E = result.get(); 2203 2204 ExprResult FullExpr = ActOnFinishFullExpr(E, /*DiscardedValue*/ false); 2205 if (FullExpr.isInvalid()) 2206 return StmtError(); 2207 return StmtResult(static_cast<Stmt*>(FullExpr.get())); 2208 } 2209 2210 ExprResult 2211 Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) { 2212 if (!collection) 2213 return ExprError(); 2214 2215 ExprResult result = CorrectDelayedTyposInExpr(collection); 2216 if (!result.isUsable()) 2217 return ExprError(); 2218 collection = result.get(); 2219 2220 // Bail out early if we've got a type-dependent expression. 2221 if (collection->isTypeDependent()) return collection; 2222 2223 // Perform normal l-value conversion. 2224 result = DefaultFunctionArrayLvalueConversion(collection); 2225 if (result.isInvalid()) 2226 return ExprError(); 2227 collection = result.get(); 2228 2229 // The operand needs to have object-pointer type. 2230 // TODO: should we do a contextual conversion? 2231 const ObjCObjectPointerType *pointerType = 2232 collection->getType()->getAs<ObjCObjectPointerType>(); 2233 if (!pointerType) 2234 return Diag(forLoc, diag::err_collection_expr_type) 2235 << collection->getType() << collection->getSourceRange(); 2236 2237 // Check that the operand provides 2238 // - countByEnumeratingWithState:objects:count: 2239 const ObjCObjectType *objectType = pointerType->getObjectType(); 2240 ObjCInterfaceDecl *iface = objectType->getInterface(); 2241 2242 // If we have a forward-declared type, we can't do this check. 2243 // Under ARC, it is an error not to have a forward-declared class. 2244 if (iface && 2245 (getLangOpts().ObjCAutoRefCount 2246 ? RequireCompleteType(forLoc, QualType(objectType, 0), 2247 diag::err_arc_collection_forward, collection) 2248 : !isCompleteType(forLoc, QualType(objectType, 0)))) { 2249 // Otherwise, if we have any useful type information, check that 2250 // the type declares the appropriate method. 2251 } else if (iface || !objectType->qual_empty()) { 2252 IdentifierInfo *selectorIdents[] = { 2253 &Context.Idents.get("countByEnumeratingWithState"), 2254 &Context.Idents.get("objects"), 2255 &Context.Idents.get("count") 2256 }; 2257 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]); 2258 2259 ObjCMethodDecl *method = nullptr; 2260 2261 // If there's an interface, look in both the public and private APIs. 2262 if (iface) { 2263 method = iface->lookupInstanceMethod(selector); 2264 if (!method) method = iface->lookupPrivateMethod(selector); 2265 } 2266 2267 // Also check protocol qualifiers. 2268 if (!method) 2269 method = LookupMethodInQualifiedType(selector, pointerType, 2270 /*instance*/ true); 2271 2272 // If we didn't find it anywhere, give up. 2273 if (!method) { 2274 Diag(forLoc, diag::warn_collection_expr_type) 2275 << collection->getType() << selector << collection->getSourceRange(); 2276 } 2277 2278 // TODO: check for an incompatible signature? 2279 } 2280 2281 // Wrap up any cleanups in the expression. 2282 return collection; 2283 } 2284 2285 StmtResult 2286 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc, 2287 Stmt *First, Expr *collection, 2288 SourceLocation RParenLoc) { 2289 setFunctionHasBranchProtectedScope(); 2290 2291 ExprResult CollectionExprResult = 2292 CheckObjCForCollectionOperand(ForLoc, collection); 2293 2294 if (First) { 2295 QualType FirstType; 2296 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) { 2297 if (!DS->isSingleDecl()) 2298 return StmtError(Diag((*DS->decl_begin())->getLocation(), 2299 diag::err_toomany_element_decls)); 2300 2301 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl()); 2302 if (!D || D->isInvalidDecl()) 2303 return StmtError(); 2304 2305 FirstType = D->getType(); 2306 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 2307 // declare identifiers for objects having storage class 'auto' or 2308 // 'register'. 2309 if (!D->hasLocalStorage()) 2310 return StmtError(Diag(D->getLocation(), 2311 diag::err_non_local_variable_decl_in_for)); 2312 2313 // If the type contained 'auto', deduce the 'auto' to 'id'. 2314 if (FirstType->getContainedAutoType()) { 2315 SourceLocation Loc = D->getLocation(); 2316 OpaqueValueExpr OpaqueId(Loc, Context.getObjCIdType(), VK_PRValue); 2317 Expr *DeducedInit = &OpaqueId; 2318 TemplateDeductionInfo Info(Loc); 2319 FirstType = QualType(); 2320 TemplateDeductionResult Result = DeduceAutoType( 2321 D->getTypeSourceInfo()->getTypeLoc(), DeducedInit, FirstType, Info); 2322 if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed) 2323 DiagnoseAutoDeductionFailure(D, DeducedInit); 2324 if (FirstType.isNull()) { 2325 D->setInvalidDecl(); 2326 return StmtError(); 2327 } 2328 2329 D->setType(FirstType); 2330 2331 if (!inTemplateInstantiation()) { 2332 SourceLocation Loc = 2333 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 2334 Diag(Loc, diag::warn_auto_var_is_id) 2335 << D->getDeclName(); 2336 } 2337 } 2338 2339 } else { 2340 Expr *FirstE = cast<Expr>(First); 2341 if (!FirstE->isTypeDependent() && !FirstE->isLValue()) 2342 return StmtError( 2343 Diag(First->getBeginLoc(), diag::err_selector_element_not_lvalue) 2344 << First->getSourceRange()); 2345 2346 FirstType = static_cast<Expr*>(First)->getType(); 2347 if (FirstType.isConstQualified()) 2348 Diag(ForLoc, diag::err_selector_element_const_type) 2349 << FirstType << First->getSourceRange(); 2350 } 2351 if (!FirstType->isDependentType() && 2352 !FirstType->isObjCObjectPointerType() && 2353 !FirstType->isBlockPointerType()) 2354 return StmtError(Diag(ForLoc, diag::err_selector_element_type) 2355 << FirstType << First->getSourceRange()); 2356 } 2357 2358 if (CollectionExprResult.isInvalid()) 2359 return StmtError(); 2360 2361 CollectionExprResult = 2362 ActOnFinishFullExpr(CollectionExprResult.get(), /*DiscardedValue*/ false); 2363 if (CollectionExprResult.isInvalid()) 2364 return StmtError(); 2365 2366 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(), 2367 nullptr, ForLoc, RParenLoc); 2368 } 2369 2370 /// Finish building a variable declaration for a for-range statement. 2371 /// \return true if an error occurs. 2372 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init, 2373 SourceLocation Loc, int DiagID) { 2374 if (Decl->getType()->isUndeducedType()) { 2375 ExprResult Res = SemaRef.CorrectDelayedTyposInExpr(Init); 2376 if (!Res.isUsable()) { 2377 Decl->setInvalidDecl(); 2378 return true; 2379 } 2380 Init = Res.get(); 2381 } 2382 2383 // Deduce the type for the iterator variable now rather than leaving it to 2384 // AddInitializerToDecl, so we can produce a more suitable diagnostic. 2385 QualType InitType; 2386 if (!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) { 2387 SemaRef.Diag(Loc, DiagID) << Init->getType(); 2388 } else { 2389 TemplateDeductionInfo Info(Init->getExprLoc()); 2390 Sema::TemplateDeductionResult Result = SemaRef.DeduceAutoType( 2391 Decl->getTypeSourceInfo()->getTypeLoc(), Init, InitType, Info); 2392 if (Result != Sema::TDK_Success && Result != Sema::TDK_AlreadyDiagnosed) 2393 SemaRef.Diag(Loc, DiagID) << Init->getType(); 2394 } 2395 2396 if (InitType.isNull()) { 2397 Decl->setInvalidDecl(); 2398 return true; 2399 } 2400 Decl->setType(InitType); 2401 2402 // In ARC, infer lifetime. 2403 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if 2404 // we're doing the equivalent of fast iteration. 2405 if (SemaRef.getLangOpts().ObjCAutoRefCount && 2406 SemaRef.inferObjCARCLifetime(Decl)) 2407 Decl->setInvalidDecl(); 2408 2409 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false); 2410 SemaRef.FinalizeDeclaration(Decl); 2411 SemaRef.CurContext->addHiddenDecl(Decl); 2412 return false; 2413 } 2414 2415 namespace { 2416 // An enum to represent whether something is dealing with a call to begin() 2417 // or a call to end() in a range-based for loop. 2418 enum BeginEndFunction { 2419 BEF_begin, 2420 BEF_end 2421 }; 2422 2423 /// Produce a note indicating which begin/end function was implicitly called 2424 /// by a C++11 for-range statement. This is often not obvious from the code, 2425 /// nor from the diagnostics produced when analysing the implicit expressions 2426 /// required in a for-range statement. 2427 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E, 2428 BeginEndFunction BEF) { 2429 CallExpr *CE = dyn_cast<CallExpr>(E); 2430 if (!CE) 2431 return; 2432 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl()); 2433 if (!D) 2434 return; 2435 SourceLocation Loc = D->getLocation(); 2436 2437 std::string Description; 2438 bool IsTemplate = false; 2439 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) { 2440 Description = SemaRef.getTemplateArgumentBindingsText( 2441 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs()); 2442 IsTemplate = true; 2443 } 2444 2445 SemaRef.Diag(Loc, diag::note_for_range_begin_end) 2446 << BEF << IsTemplate << Description << E->getType(); 2447 } 2448 2449 /// Build a variable declaration for a for-range statement. 2450 VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc, 2451 QualType Type, StringRef Name) { 2452 DeclContext *DC = SemaRef.CurContext; 2453 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 2454 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 2455 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, 2456 TInfo, SC_None); 2457 Decl->setImplicit(); 2458 return Decl; 2459 } 2460 2461 } 2462 2463 static bool ObjCEnumerationCollection(Expr *Collection) { 2464 return !Collection->isTypeDependent() 2465 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr; 2466 } 2467 2468 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement. 2469 /// 2470 /// C++11 [stmt.ranged]: 2471 /// A range-based for statement is equivalent to 2472 /// 2473 /// { 2474 /// auto && __range = range-init; 2475 /// for ( auto __begin = begin-expr, 2476 /// __end = end-expr; 2477 /// __begin != __end; 2478 /// ++__begin ) { 2479 /// for-range-declaration = *__begin; 2480 /// statement 2481 /// } 2482 /// } 2483 /// 2484 /// The body of the loop is not available yet, since it cannot be analysed until 2485 /// we have determined the type of the for-range-declaration. 2486 StmtResult Sema::ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, 2487 SourceLocation CoawaitLoc, Stmt *InitStmt, 2488 Stmt *First, SourceLocation ColonLoc, 2489 Expr *Range, SourceLocation RParenLoc, 2490 BuildForRangeKind Kind) { 2491 // FIXME: recover in order to allow the body to be parsed. 2492 if (!First) 2493 return StmtError(); 2494 2495 if (Range && ObjCEnumerationCollection(Range)) { 2496 // FIXME: Support init-statements in Objective-C++20 ranged for statement. 2497 if (InitStmt) 2498 return Diag(InitStmt->getBeginLoc(), diag::err_objc_for_range_init_stmt) 2499 << InitStmt->getSourceRange(); 2500 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc); 2501 } 2502 2503 DeclStmt *DS = dyn_cast<DeclStmt>(First); 2504 assert(DS && "first part of for range not a decl stmt"); 2505 2506 if (!DS->isSingleDecl()) { 2507 Diag(DS->getBeginLoc(), diag::err_type_defined_in_for_range); 2508 return StmtError(); 2509 } 2510 2511 // This function is responsible for attaching an initializer to LoopVar. We 2512 // must call ActOnInitializerError if we fail to do so. 2513 Decl *LoopVar = DS->getSingleDecl(); 2514 if (LoopVar->isInvalidDecl() || !Range || 2515 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) { 2516 ActOnInitializerError(LoopVar); 2517 return StmtError(); 2518 } 2519 2520 // Build the coroutine state immediately and not later during template 2521 // instantiation 2522 if (!CoawaitLoc.isInvalid()) { 2523 if (!ActOnCoroutineBodyStart(S, CoawaitLoc, "co_await")) { 2524 ActOnInitializerError(LoopVar); 2525 return StmtError(); 2526 } 2527 } 2528 2529 // Build auto && __range = range-init 2530 // Divide by 2, since the variables are in the inner scope (loop body). 2531 const auto DepthStr = std::to_string(S->getDepth() / 2); 2532 SourceLocation RangeLoc = Range->getBeginLoc(); 2533 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc, 2534 Context.getAutoRRefDeductType(), 2535 std::string("__range") + DepthStr); 2536 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc, 2537 diag::err_for_range_deduction_failure)) { 2538 ActOnInitializerError(LoopVar); 2539 return StmtError(); 2540 } 2541 2542 // Claim the type doesn't contain auto: we've already done the checking. 2543 DeclGroupPtrTy RangeGroup = 2544 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1)); 2545 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc); 2546 if (RangeDecl.isInvalid()) { 2547 ActOnInitializerError(LoopVar); 2548 return StmtError(); 2549 } 2550 2551 StmtResult R = BuildCXXForRangeStmt( 2552 ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl.get(), 2553 /*BeginStmt=*/nullptr, /*EndStmt=*/nullptr, 2554 /*Cond=*/nullptr, /*Inc=*/nullptr, DS, RParenLoc, Kind); 2555 if (R.isInvalid()) { 2556 ActOnInitializerError(LoopVar); 2557 return StmtError(); 2558 } 2559 2560 return R; 2561 } 2562 2563 /// Create the initialization, compare, and increment steps for 2564 /// the range-based for loop expression. 2565 /// This function does not handle array-based for loops, 2566 /// which are created in Sema::BuildCXXForRangeStmt. 2567 /// 2568 /// \returns a ForRangeStatus indicating success or what kind of error occurred. 2569 /// BeginExpr and EndExpr are set and FRS_Success is returned on success; 2570 /// CandidateSet and BEF are set and some non-success value is returned on 2571 /// failure. 2572 static Sema::ForRangeStatus 2573 BuildNonArrayForRange(Sema &SemaRef, Expr *BeginRange, Expr *EndRange, 2574 QualType RangeType, VarDecl *BeginVar, VarDecl *EndVar, 2575 SourceLocation ColonLoc, SourceLocation CoawaitLoc, 2576 OverloadCandidateSet *CandidateSet, ExprResult *BeginExpr, 2577 ExprResult *EndExpr, BeginEndFunction *BEF) { 2578 DeclarationNameInfo BeginNameInfo( 2579 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc); 2580 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"), 2581 ColonLoc); 2582 2583 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo, 2584 Sema::LookupMemberName); 2585 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName); 2586 2587 auto BuildBegin = [&] { 2588 *BEF = BEF_begin; 2589 Sema::ForRangeStatus RangeStatus = 2590 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, BeginNameInfo, 2591 BeginMemberLookup, CandidateSet, 2592 BeginRange, BeginExpr); 2593 2594 if (RangeStatus != Sema::FRS_Success) { 2595 if (RangeStatus == Sema::FRS_DiagnosticIssued) 2596 SemaRef.Diag(BeginRange->getBeginLoc(), diag::note_in_for_range) 2597 << ColonLoc << BEF_begin << BeginRange->getType(); 2598 return RangeStatus; 2599 } 2600 if (!CoawaitLoc.isInvalid()) { 2601 // FIXME: getCurScope() should not be used during template instantiation. 2602 // We should pick up the set of unqualified lookup results for operator 2603 // co_await during the initial parse. 2604 *BeginExpr = SemaRef.ActOnCoawaitExpr(SemaRef.getCurScope(), ColonLoc, 2605 BeginExpr->get()); 2606 if (BeginExpr->isInvalid()) 2607 return Sema::FRS_DiagnosticIssued; 2608 } 2609 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc, 2610 diag::err_for_range_iter_deduction_failure)) { 2611 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF); 2612 return Sema::FRS_DiagnosticIssued; 2613 } 2614 return Sema::FRS_Success; 2615 }; 2616 2617 auto BuildEnd = [&] { 2618 *BEF = BEF_end; 2619 Sema::ForRangeStatus RangeStatus = 2620 SemaRef.BuildForRangeBeginEndCall(ColonLoc, ColonLoc, EndNameInfo, 2621 EndMemberLookup, CandidateSet, 2622 EndRange, EndExpr); 2623 if (RangeStatus != Sema::FRS_Success) { 2624 if (RangeStatus == Sema::FRS_DiagnosticIssued) 2625 SemaRef.Diag(EndRange->getBeginLoc(), diag::note_in_for_range) 2626 << ColonLoc << BEF_end << EndRange->getType(); 2627 return RangeStatus; 2628 } 2629 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc, 2630 diag::err_for_range_iter_deduction_failure)) { 2631 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF); 2632 return Sema::FRS_DiagnosticIssued; 2633 } 2634 return Sema::FRS_Success; 2635 }; 2636 2637 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) { 2638 // - if _RangeT is a class type, the unqualified-ids begin and end are 2639 // looked up in the scope of class _RangeT as if by class member access 2640 // lookup (3.4.5), and if either (or both) finds at least one 2641 // declaration, begin-expr and end-expr are __range.begin() and 2642 // __range.end(), respectively; 2643 SemaRef.LookupQualifiedName(BeginMemberLookup, D); 2644 if (BeginMemberLookup.isAmbiguous()) 2645 return Sema::FRS_DiagnosticIssued; 2646 2647 SemaRef.LookupQualifiedName(EndMemberLookup, D); 2648 if (EndMemberLookup.isAmbiguous()) 2649 return Sema::FRS_DiagnosticIssued; 2650 2651 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) { 2652 // Look up the non-member form of the member we didn't find, first. 2653 // This way we prefer a "no viable 'end'" diagnostic over a "i found 2654 // a 'begin' but ignored it because there was no member 'end'" 2655 // diagnostic. 2656 auto BuildNonmember = [&]( 2657 BeginEndFunction BEFFound, LookupResult &Found, 2658 llvm::function_ref<Sema::ForRangeStatus()> BuildFound, 2659 llvm::function_ref<Sema::ForRangeStatus()> BuildNotFound) { 2660 LookupResult OldFound = std::move(Found); 2661 Found.clear(); 2662 2663 if (Sema::ForRangeStatus Result = BuildNotFound()) 2664 return Result; 2665 2666 switch (BuildFound()) { 2667 case Sema::FRS_Success: 2668 return Sema::FRS_Success; 2669 2670 case Sema::FRS_NoViableFunction: 2671 CandidateSet->NoteCandidates( 2672 PartialDiagnosticAt(BeginRange->getBeginLoc(), 2673 SemaRef.PDiag(diag::err_for_range_invalid) 2674 << BeginRange->getType() << BEFFound), 2675 SemaRef, OCD_AllCandidates, BeginRange); 2676 [[fallthrough]]; 2677 2678 case Sema::FRS_DiagnosticIssued: 2679 for (NamedDecl *D : OldFound) { 2680 SemaRef.Diag(D->getLocation(), 2681 diag::note_for_range_member_begin_end_ignored) 2682 << BeginRange->getType() << BEFFound; 2683 } 2684 return Sema::FRS_DiagnosticIssued; 2685 } 2686 llvm_unreachable("unexpected ForRangeStatus"); 2687 }; 2688 if (BeginMemberLookup.empty()) 2689 return BuildNonmember(BEF_end, EndMemberLookup, BuildEnd, BuildBegin); 2690 return BuildNonmember(BEF_begin, BeginMemberLookup, BuildBegin, BuildEnd); 2691 } 2692 } else { 2693 // - otherwise, begin-expr and end-expr are begin(__range) and 2694 // end(__range), respectively, where begin and end are looked up with 2695 // argument-dependent lookup (3.4.2). For the purposes of this name 2696 // lookup, namespace std is an associated namespace. 2697 } 2698 2699 if (Sema::ForRangeStatus Result = BuildBegin()) 2700 return Result; 2701 return BuildEnd(); 2702 } 2703 2704 /// Speculatively attempt to dereference an invalid range expression. 2705 /// If the attempt fails, this function will return a valid, null StmtResult 2706 /// and emit no diagnostics. 2707 static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S, 2708 SourceLocation ForLoc, 2709 SourceLocation CoawaitLoc, 2710 Stmt *InitStmt, 2711 Stmt *LoopVarDecl, 2712 SourceLocation ColonLoc, 2713 Expr *Range, 2714 SourceLocation RangeLoc, 2715 SourceLocation RParenLoc) { 2716 // Determine whether we can rebuild the for-range statement with a 2717 // dereferenced range expression. 2718 ExprResult AdjustedRange; 2719 { 2720 Sema::SFINAETrap Trap(SemaRef); 2721 2722 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range); 2723 if (AdjustedRange.isInvalid()) 2724 return StmtResult(); 2725 2726 StmtResult SR = SemaRef.ActOnCXXForRangeStmt( 2727 S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc, 2728 AdjustedRange.get(), RParenLoc, Sema::BFRK_Check); 2729 if (SR.isInvalid()) 2730 return StmtResult(); 2731 } 2732 2733 // The attempt to dereference worked well enough that it could produce a valid 2734 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in 2735 // case there are any other (non-fatal) problems with it. 2736 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference) 2737 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*"); 2738 return SemaRef.ActOnCXXForRangeStmt( 2739 S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc, 2740 AdjustedRange.get(), RParenLoc, Sema::BFRK_Rebuild); 2741 } 2742 2743 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement. 2744 StmtResult Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, 2745 SourceLocation CoawaitLoc, Stmt *InitStmt, 2746 SourceLocation ColonLoc, Stmt *RangeDecl, 2747 Stmt *Begin, Stmt *End, Expr *Cond, 2748 Expr *Inc, Stmt *LoopVarDecl, 2749 SourceLocation RParenLoc, 2750 BuildForRangeKind Kind) { 2751 // FIXME: This should not be used during template instantiation. We should 2752 // pick up the set of unqualified lookup results for the != and + operators 2753 // in the initial parse. 2754 // 2755 // Testcase (accepts-invalid): 2756 // template<typename T> void f() { for (auto x : T()) {} } 2757 // namespace N { struct X { X begin(); X end(); int operator*(); }; } 2758 // bool operator!=(N::X, N::X); void operator++(N::X); 2759 // void g() { f<N::X>(); } 2760 Scope *S = getCurScope(); 2761 2762 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl); 2763 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl()); 2764 QualType RangeVarType = RangeVar->getType(); 2765 2766 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl); 2767 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl()); 2768 2769 StmtResult BeginDeclStmt = Begin; 2770 StmtResult EndDeclStmt = End; 2771 ExprResult NotEqExpr = Cond, IncrExpr = Inc; 2772 2773 if (RangeVarType->isDependentType()) { 2774 // The range is implicitly used as a placeholder when it is dependent. 2775 RangeVar->markUsed(Context); 2776 2777 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill 2778 // them in properly when we instantiate the loop. 2779 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) { 2780 if (auto *DD = dyn_cast<DecompositionDecl>(LoopVar)) 2781 for (auto *Binding : DD->bindings()) 2782 Binding->setType(Context.DependentTy); 2783 LoopVar->setType(SubstAutoTypeDependent(LoopVar->getType())); 2784 } 2785 } else if (!BeginDeclStmt.get()) { 2786 SourceLocation RangeLoc = RangeVar->getLocation(); 2787 2788 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType(); 2789 2790 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType, 2791 VK_LValue, ColonLoc); 2792 if (BeginRangeRef.isInvalid()) 2793 return StmtError(); 2794 2795 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType, 2796 VK_LValue, ColonLoc); 2797 if (EndRangeRef.isInvalid()) 2798 return StmtError(); 2799 2800 QualType AutoType = Context.getAutoDeductType(); 2801 Expr *Range = RangeVar->getInit(); 2802 if (!Range) 2803 return StmtError(); 2804 QualType RangeType = Range->getType(); 2805 2806 if (RequireCompleteType(RangeLoc, RangeType, 2807 diag::err_for_range_incomplete_type)) 2808 return StmtError(); 2809 2810 // Build auto __begin = begin-expr, __end = end-expr. 2811 // Divide by 2, since the variables are in the inner scope (loop body). 2812 const auto DepthStr = std::to_string(S->getDepth() / 2); 2813 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, 2814 std::string("__begin") + DepthStr); 2815 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, 2816 std::string("__end") + DepthStr); 2817 2818 // Build begin-expr and end-expr and attach to __begin and __end variables. 2819 ExprResult BeginExpr, EndExpr; 2820 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) { 2821 // - if _RangeT is an array type, begin-expr and end-expr are __range and 2822 // __range + __bound, respectively, where __bound is the array bound. If 2823 // _RangeT is an array of unknown size or an array of incomplete type, 2824 // the program is ill-formed; 2825 2826 // begin-expr is __range. 2827 BeginExpr = BeginRangeRef; 2828 if (!CoawaitLoc.isInvalid()) { 2829 BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.get()); 2830 if (BeginExpr.isInvalid()) 2831 return StmtError(); 2832 } 2833 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc, 2834 diag::err_for_range_iter_deduction_failure)) { 2835 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 2836 return StmtError(); 2837 } 2838 2839 // Find the array bound. 2840 ExprResult BoundExpr; 2841 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT)) 2842 BoundExpr = IntegerLiteral::Create( 2843 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc); 2844 else if (const VariableArrayType *VAT = 2845 dyn_cast<VariableArrayType>(UnqAT)) { 2846 // For a variably modified type we can't just use the expression within 2847 // the array bounds, since we don't want that to be re-evaluated here. 2848 // Rather, we need to determine what it was when the array was first 2849 // created - so we resort to using sizeof(vla)/sizeof(element). 2850 // For e.g. 2851 // void f(int b) { 2852 // int vla[b]; 2853 // b = -1; <-- This should not affect the num of iterations below 2854 // for (int &c : vla) { .. } 2855 // } 2856 2857 // FIXME: This results in codegen generating IR that recalculates the 2858 // run-time number of elements (as opposed to just using the IR Value 2859 // that corresponds to the run-time value of each bound that was 2860 // generated when the array was created.) If this proves too embarrassing 2861 // even for unoptimized IR, consider passing a magic-value/cookie to 2862 // codegen that then knows to simply use that initial llvm::Value (that 2863 // corresponds to the bound at time of array creation) within 2864 // getelementptr. But be prepared to pay the price of increasing a 2865 // customized form of coupling between the two components - which could 2866 // be hard to maintain as the codebase evolves. 2867 2868 ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr( 2869 EndVar->getLocation(), UETT_SizeOf, 2870 /*IsType=*/true, 2871 CreateParsedType(VAT->desugar(), Context.getTrivialTypeSourceInfo( 2872 VAT->desugar(), RangeLoc)) 2873 .getAsOpaquePtr(), 2874 EndVar->getSourceRange()); 2875 if (SizeOfVLAExprR.isInvalid()) 2876 return StmtError(); 2877 2878 ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr( 2879 EndVar->getLocation(), UETT_SizeOf, 2880 /*IsType=*/true, 2881 CreateParsedType(VAT->desugar(), 2882 Context.getTrivialTypeSourceInfo( 2883 VAT->getElementType(), RangeLoc)) 2884 .getAsOpaquePtr(), 2885 EndVar->getSourceRange()); 2886 if (SizeOfEachElementExprR.isInvalid()) 2887 return StmtError(); 2888 2889 BoundExpr = 2890 ActOnBinOp(S, EndVar->getLocation(), tok::slash, 2891 SizeOfVLAExprR.get(), SizeOfEachElementExprR.get()); 2892 if (BoundExpr.isInvalid()) 2893 return StmtError(); 2894 2895 } else { 2896 // Can't be a DependentSizedArrayType or an IncompleteArrayType since 2897 // UnqAT is not incomplete and Range is not type-dependent. 2898 llvm_unreachable("Unexpected array type in for-range"); 2899 } 2900 2901 // end-expr is __range + __bound. 2902 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(), 2903 BoundExpr.get()); 2904 if (EndExpr.isInvalid()) 2905 return StmtError(); 2906 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc, 2907 diag::err_for_range_iter_deduction_failure)) { 2908 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 2909 return StmtError(); 2910 } 2911 } else { 2912 OverloadCandidateSet CandidateSet(RangeLoc, 2913 OverloadCandidateSet::CSK_Normal); 2914 BeginEndFunction BEFFailure; 2915 ForRangeStatus RangeStatus = BuildNonArrayForRange( 2916 *this, BeginRangeRef.get(), EndRangeRef.get(), RangeType, BeginVar, 2917 EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr, 2918 &BEFFailure); 2919 2920 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction && 2921 BEFFailure == BEF_begin) { 2922 // If the range is being built from an array parameter, emit a 2923 // a diagnostic that it is being treated as a pointer. 2924 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) { 2925 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 2926 QualType ArrayTy = PVD->getOriginalType(); 2927 QualType PointerTy = PVD->getType(); 2928 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) { 2929 Diag(Range->getBeginLoc(), diag::err_range_on_array_parameter) 2930 << RangeLoc << PVD << ArrayTy << PointerTy; 2931 Diag(PVD->getLocation(), diag::note_declared_at); 2932 return StmtError(); 2933 } 2934 } 2935 } 2936 2937 // If building the range failed, try dereferencing the range expression 2938 // unless a diagnostic was issued or the end function is problematic. 2939 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc, 2940 CoawaitLoc, InitStmt, 2941 LoopVarDecl, ColonLoc, 2942 Range, RangeLoc, 2943 RParenLoc); 2944 if (SR.isInvalid() || SR.isUsable()) 2945 return SR; 2946 } 2947 2948 // Otherwise, emit diagnostics if we haven't already. 2949 if (RangeStatus == FRS_NoViableFunction) { 2950 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get(); 2951 CandidateSet.NoteCandidates( 2952 PartialDiagnosticAt(Range->getBeginLoc(), 2953 PDiag(diag::err_for_range_invalid) 2954 << RangeLoc << Range->getType() 2955 << BEFFailure), 2956 *this, OCD_AllCandidates, Range); 2957 } 2958 // Return an error if no fix was discovered. 2959 if (RangeStatus != FRS_Success) 2960 return StmtError(); 2961 } 2962 2963 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() && 2964 "invalid range expression in for loop"); 2965 2966 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same. 2967 // C++1z removes this restriction. 2968 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType(); 2969 if (!Context.hasSameType(BeginType, EndType)) { 2970 Diag(RangeLoc, getLangOpts().CPlusPlus17 2971 ? diag::warn_for_range_begin_end_types_differ 2972 : diag::ext_for_range_begin_end_types_differ) 2973 << BeginType << EndType; 2974 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 2975 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 2976 } 2977 2978 BeginDeclStmt = 2979 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc); 2980 EndDeclStmt = 2981 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc); 2982 2983 const QualType BeginRefNonRefType = BeginType.getNonReferenceType(); 2984 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 2985 VK_LValue, ColonLoc); 2986 if (BeginRef.isInvalid()) 2987 return StmtError(); 2988 2989 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(), 2990 VK_LValue, ColonLoc); 2991 if (EndRef.isInvalid()) 2992 return StmtError(); 2993 2994 // Build and check __begin != __end expression. 2995 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal, 2996 BeginRef.get(), EndRef.get()); 2997 if (!NotEqExpr.isInvalid()) 2998 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.get()); 2999 if (!NotEqExpr.isInvalid()) 3000 NotEqExpr = 3001 ActOnFinishFullExpr(NotEqExpr.get(), /*DiscardedValue*/ false); 3002 if (NotEqExpr.isInvalid()) { 3003 Diag(RangeLoc, diag::note_for_range_invalid_iterator) 3004 << RangeLoc << 0 << BeginRangeRef.get()->getType(); 3005 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 3006 if (!Context.hasSameType(BeginType, EndType)) 3007 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 3008 return StmtError(); 3009 } 3010 3011 // Build and check ++__begin expression. 3012 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 3013 VK_LValue, ColonLoc); 3014 if (BeginRef.isInvalid()) 3015 return StmtError(); 3016 3017 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get()); 3018 if (!IncrExpr.isInvalid() && CoawaitLoc.isValid()) 3019 // FIXME: getCurScope() should not be used during template instantiation. 3020 // We should pick up the set of unqualified lookup results for operator 3021 // co_await during the initial parse. 3022 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get()); 3023 if (!IncrExpr.isInvalid()) 3024 IncrExpr = ActOnFinishFullExpr(IncrExpr.get(), /*DiscardedValue*/ false); 3025 if (IncrExpr.isInvalid()) { 3026 Diag(RangeLoc, diag::note_for_range_invalid_iterator) 3027 << RangeLoc << 2 << BeginRangeRef.get()->getType() ; 3028 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 3029 return StmtError(); 3030 } 3031 3032 // Build and check *__begin expression. 3033 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 3034 VK_LValue, ColonLoc); 3035 if (BeginRef.isInvalid()) 3036 return StmtError(); 3037 3038 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get()); 3039 if (DerefExpr.isInvalid()) { 3040 Diag(RangeLoc, diag::note_for_range_invalid_iterator) 3041 << RangeLoc << 1 << BeginRangeRef.get()->getType(); 3042 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 3043 return StmtError(); 3044 } 3045 3046 // Attach *__begin as initializer for VD. Don't touch it if we're just 3047 // trying to determine whether this would be a valid range. 3048 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) { 3049 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false); 3050 if (LoopVar->isInvalidDecl() || 3051 (LoopVar->getInit() && LoopVar->getInit()->containsErrors())) 3052 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 3053 } 3054 } 3055 3056 // Don't bother to actually allocate the result if we're just trying to 3057 // determine whether it would be valid. 3058 if (Kind == BFRK_Check) 3059 return StmtResult(); 3060 3061 // In OpenMP loop region loop control variable must be private. Perform 3062 // analysis of first part (if any). 3063 if (getLangOpts().OpenMP >= 50 && BeginDeclStmt.isUsable()) 3064 ActOnOpenMPLoopInitialization(ForLoc, BeginDeclStmt.get()); 3065 3066 return new (Context) CXXForRangeStmt( 3067 InitStmt, RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.get()), 3068 cast_or_null<DeclStmt>(EndDeclStmt.get()), NotEqExpr.get(), 3069 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, CoawaitLoc, 3070 ColonLoc, RParenLoc); 3071 } 3072 3073 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach 3074 /// statement. 3075 StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) { 3076 if (!S || !B) 3077 return StmtError(); 3078 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S); 3079 3080 ForStmt->setBody(B); 3081 return S; 3082 } 3083 3084 // Warn when the loop variable is a const reference that creates a copy. 3085 // Suggest using the non-reference type for copies. If a copy can be prevented 3086 // suggest the const reference type that would do so. 3087 // For instance, given "for (const &Foo : Range)", suggest 3088 // "for (const Foo : Range)" to denote a copy is made for the loop. If 3089 // possible, also suggest "for (const &Bar : Range)" if this type prevents 3090 // the copy altogether. 3091 static void DiagnoseForRangeReferenceVariableCopies(Sema &SemaRef, 3092 const VarDecl *VD, 3093 QualType RangeInitType) { 3094 const Expr *InitExpr = VD->getInit(); 3095 if (!InitExpr) 3096 return; 3097 3098 QualType VariableType = VD->getType(); 3099 3100 if (auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr)) 3101 if (!Cleanups->cleanupsHaveSideEffects()) 3102 InitExpr = Cleanups->getSubExpr(); 3103 3104 const MaterializeTemporaryExpr *MTE = 3105 dyn_cast<MaterializeTemporaryExpr>(InitExpr); 3106 3107 // No copy made. 3108 if (!MTE) 3109 return; 3110 3111 const Expr *E = MTE->getSubExpr()->IgnoreImpCasts(); 3112 3113 // Searching for either UnaryOperator for dereference of a pointer or 3114 // CXXOperatorCallExpr for handling iterators. 3115 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) { 3116 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(E)) { 3117 E = CCE->getArg(0); 3118 } else if (const CXXMemberCallExpr *Call = dyn_cast<CXXMemberCallExpr>(E)) { 3119 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee()); 3120 E = ME->getBase(); 3121 } else { 3122 const MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E); 3123 E = MTE->getSubExpr(); 3124 } 3125 E = E->IgnoreImpCasts(); 3126 } 3127 3128 QualType ReferenceReturnType; 3129 if (isa<UnaryOperator>(E)) { 3130 ReferenceReturnType = SemaRef.Context.getLValueReferenceType(E->getType()); 3131 } else { 3132 const CXXOperatorCallExpr *Call = cast<CXXOperatorCallExpr>(E); 3133 const FunctionDecl *FD = Call->getDirectCallee(); 3134 QualType ReturnType = FD->getReturnType(); 3135 if (ReturnType->isReferenceType()) 3136 ReferenceReturnType = ReturnType; 3137 } 3138 3139 if (!ReferenceReturnType.isNull()) { 3140 // Loop variable creates a temporary. Suggest either to go with 3141 // non-reference loop variable to indicate a copy is made, or 3142 // the correct type to bind a const reference. 3143 SemaRef.Diag(VD->getLocation(), 3144 diag::warn_for_range_const_ref_binds_temp_built_from_ref) 3145 << VD << VariableType << ReferenceReturnType; 3146 QualType NonReferenceType = VariableType.getNonReferenceType(); 3147 NonReferenceType.removeLocalConst(); 3148 QualType NewReferenceType = 3149 SemaRef.Context.getLValueReferenceType(E->getType().withConst()); 3150 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_type_or_non_reference) 3151 << NonReferenceType << NewReferenceType << VD->getSourceRange() 3152 << FixItHint::CreateRemoval(VD->getTypeSpecEndLoc()); 3153 } else if (!VariableType->isRValueReferenceType()) { 3154 // The range always returns a copy, so a temporary is always created. 3155 // Suggest removing the reference from the loop variable. 3156 // If the type is a rvalue reference do not warn since that changes the 3157 // semantic of the code. 3158 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_ref_binds_ret_temp) 3159 << VD << RangeInitType; 3160 QualType NonReferenceType = VariableType.getNonReferenceType(); 3161 NonReferenceType.removeLocalConst(); 3162 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_non_reference_type) 3163 << NonReferenceType << VD->getSourceRange() 3164 << FixItHint::CreateRemoval(VD->getTypeSpecEndLoc()); 3165 } 3166 } 3167 3168 /// Determines whether the @p VariableType's declaration is a record with the 3169 /// clang::trivial_abi attribute. 3170 static bool hasTrivialABIAttr(QualType VariableType) { 3171 if (CXXRecordDecl *RD = VariableType->getAsCXXRecordDecl()) 3172 return RD->hasAttr<TrivialABIAttr>(); 3173 3174 return false; 3175 } 3176 3177 // Warns when the loop variable can be changed to a reference type to 3178 // prevent a copy. For instance, if given "for (const Foo x : Range)" suggest 3179 // "for (const Foo &x : Range)" if this form does not make a copy. 3180 static void DiagnoseForRangeConstVariableCopies(Sema &SemaRef, 3181 const VarDecl *VD) { 3182 const Expr *InitExpr = VD->getInit(); 3183 if (!InitExpr) 3184 return; 3185 3186 QualType VariableType = VD->getType(); 3187 3188 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(InitExpr)) { 3189 if (!CE->getConstructor()->isCopyConstructor()) 3190 return; 3191 } else if (const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) { 3192 if (CE->getCastKind() != CK_LValueToRValue) 3193 return; 3194 } else { 3195 return; 3196 } 3197 3198 // Small trivially copyable types are cheap to copy. Do not emit the 3199 // diagnostic for these instances. 64 bytes is a common size of a cache line. 3200 // (The function `getTypeSize` returns the size in bits.) 3201 ASTContext &Ctx = SemaRef.Context; 3202 if (Ctx.getTypeSize(VariableType) <= 64 * 8 && 3203 (VariableType.isTriviallyCopyableType(Ctx) || 3204 hasTrivialABIAttr(VariableType))) 3205 return; 3206 3207 // Suggest changing from a const variable to a const reference variable 3208 // if doing so will prevent a copy. 3209 SemaRef.Diag(VD->getLocation(), diag::warn_for_range_copy) 3210 << VD << VariableType; 3211 SemaRef.Diag(VD->getBeginLoc(), diag::note_use_reference_type) 3212 << SemaRef.Context.getLValueReferenceType(VariableType) 3213 << VD->getSourceRange() 3214 << FixItHint::CreateInsertion(VD->getLocation(), "&"); 3215 } 3216 3217 /// DiagnoseForRangeVariableCopies - Diagnose three cases and fixes for them. 3218 /// 1) for (const foo &x : foos) where foos only returns a copy. Suggest 3219 /// using "const foo x" to show that a copy is made 3220 /// 2) for (const bar &x : foos) where bar is a temporary initialized by bar. 3221 /// Suggest either "const bar x" to keep the copying or "const foo& x" to 3222 /// prevent the copy. 3223 /// 3) for (const foo x : foos) where x is constructed from a reference foo. 3224 /// Suggest "const foo &x" to prevent the copy. 3225 static void DiagnoseForRangeVariableCopies(Sema &SemaRef, 3226 const CXXForRangeStmt *ForStmt) { 3227 if (SemaRef.inTemplateInstantiation()) 3228 return; 3229 3230 if (SemaRef.Diags.isIgnored( 3231 diag::warn_for_range_const_ref_binds_temp_built_from_ref, 3232 ForStmt->getBeginLoc()) && 3233 SemaRef.Diags.isIgnored(diag::warn_for_range_ref_binds_ret_temp, 3234 ForStmt->getBeginLoc()) && 3235 SemaRef.Diags.isIgnored(diag::warn_for_range_copy, 3236 ForStmt->getBeginLoc())) { 3237 return; 3238 } 3239 3240 const VarDecl *VD = ForStmt->getLoopVariable(); 3241 if (!VD) 3242 return; 3243 3244 QualType VariableType = VD->getType(); 3245 3246 if (VariableType->isIncompleteType()) 3247 return; 3248 3249 const Expr *InitExpr = VD->getInit(); 3250 if (!InitExpr) 3251 return; 3252 3253 if (InitExpr->getExprLoc().isMacroID()) 3254 return; 3255 3256 if (VariableType->isReferenceType()) { 3257 DiagnoseForRangeReferenceVariableCopies(SemaRef, VD, 3258 ForStmt->getRangeInit()->getType()); 3259 } else if (VariableType.isConstQualified()) { 3260 DiagnoseForRangeConstVariableCopies(SemaRef, VD); 3261 } 3262 } 3263 3264 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement. 3265 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the 3266 /// body cannot be performed until after the type of the range variable is 3267 /// determined. 3268 StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) { 3269 if (!S || !B) 3270 return StmtError(); 3271 3272 if (isa<ObjCForCollectionStmt>(S)) 3273 return FinishObjCForCollectionStmt(S, B); 3274 3275 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S); 3276 ForStmt->setBody(B); 3277 3278 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B, 3279 diag::warn_empty_range_based_for_body); 3280 3281 DiagnoseForRangeVariableCopies(*this, ForStmt); 3282 3283 return S; 3284 } 3285 3286 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc, 3287 SourceLocation LabelLoc, 3288 LabelDecl *TheDecl) { 3289 setFunctionHasBranchIntoScope(); 3290 TheDecl->markUsed(Context); 3291 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc); 3292 } 3293 3294 StmtResult 3295 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, 3296 Expr *E) { 3297 // Convert operand to void* 3298 if (!E->isTypeDependent()) { 3299 QualType ETy = E->getType(); 3300 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst()); 3301 ExprResult ExprRes = E; 3302 AssignConvertType ConvTy = 3303 CheckSingleAssignmentConstraints(DestTy, ExprRes); 3304 if (ExprRes.isInvalid()) 3305 return StmtError(); 3306 E = ExprRes.get(); 3307 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing)) 3308 return StmtError(); 3309 } 3310 3311 ExprResult ExprRes = ActOnFinishFullExpr(E, /*DiscardedValue*/ false); 3312 if (ExprRes.isInvalid()) 3313 return StmtError(); 3314 E = ExprRes.get(); 3315 3316 setFunctionHasIndirectGoto(); 3317 3318 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E); 3319 } 3320 3321 static void CheckJumpOutOfSEHFinally(Sema &S, SourceLocation Loc, 3322 const Scope &DestScope) { 3323 if (!S.CurrentSEHFinally.empty() && 3324 DestScope.Contains(*S.CurrentSEHFinally.back())) { 3325 S.Diag(Loc, diag::warn_jump_out_of_seh_finally); 3326 } 3327 } 3328 3329 StmtResult 3330 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) { 3331 Scope *S = CurScope->getContinueParent(); 3332 if (!S) { 3333 // C99 6.8.6.2p1: A break shall appear only in or as a loop body. 3334 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop)); 3335 } 3336 if (S->isConditionVarScope()) { 3337 // We cannot 'continue;' from within a statement expression in the 3338 // initializer of a condition variable because we would jump past the 3339 // initialization of that variable. 3340 return StmtError(Diag(ContinueLoc, diag::err_continue_from_cond_var_init)); 3341 } 3342 CheckJumpOutOfSEHFinally(*this, ContinueLoc, *S); 3343 3344 return new (Context) ContinueStmt(ContinueLoc); 3345 } 3346 3347 StmtResult 3348 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) { 3349 Scope *S = CurScope->getBreakParent(); 3350 if (!S) { 3351 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body. 3352 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch)); 3353 } 3354 if (S->isOpenMPLoopScope()) 3355 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt) 3356 << "break"); 3357 CheckJumpOutOfSEHFinally(*this, BreakLoc, *S); 3358 3359 return new (Context) BreakStmt(BreakLoc); 3360 } 3361 3362 /// Determine whether the given expression might be move-eligible or 3363 /// copy-elidable in either a (co_)return statement or throw expression, 3364 /// without considering function return type, if applicable. 3365 /// 3366 /// \param E The expression being returned from the function or block, 3367 /// being thrown, or being co_returned from a coroutine. This expression 3368 /// might be modified by the implementation. 3369 /// 3370 /// \param Mode Overrides detection of current language mode 3371 /// and uses the rules for C++23. 3372 /// 3373 /// \returns An aggregate which contains the Candidate and isMoveEligible 3374 /// and isCopyElidable methods. If Candidate is non-null, it means 3375 /// isMoveEligible() would be true under the most permissive language standard. 3376 Sema::NamedReturnInfo Sema::getNamedReturnInfo(Expr *&E, 3377 SimplerImplicitMoveMode Mode) { 3378 if (!E) 3379 return NamedReturnInfo(); 3380 // - in a return statement in a function [where] ... 3381 // ... the expression is the name of a non-volatile automatic object ... 3382 const auto *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens()); 3383 if (!DR || DR->refersToEnclosingVariableOrCapture()) 3384 return NamedReturnInfo(); 3385 const auto *VD = dyn_cast<VarDecl>(DR->getDecl()); 3386 if (!VD) 3387 return NamedReturnInfo(); 3388 NamedReturnInfo Res = getNamedReturnInfo(VD); 3389 if (Res.Candidate && !E->isXValue() && 3390 (Mode == SimplerImplicitMoveMode::ForceOn || 3391 (Mode != SimplerImplicitMoveMode::ForceOff && 3392 getLangOpts().CPlusPlus23))) { 3393 E = ImplicitCastExpr::Create(Context, VD->getType().getNonReferenceType(), 3394 CK_NoOp, E, nullptr, VK_XValue, 3395 FPOptionsOverride()); 3396 } 3397 return Res; 3398 } 3399 3400 /// Determine whether the given NRVO candidate variable is move-eligible or 3401 /// copy-elidable, without considering function return type. 3402 /// 3403 /// \param VD The NRVO candidate variable. 3404 /// 3405 /// \returns An aggregate which contains the Candidate and isMoveEligible 3406 /// and isCopyElidable methods. If Candidate is non-null, it means 3407 /// isMoveEligible() would be true under the most permissive language standard. 3408 Sema::NamedReturnInfo Sema::getNamedReturnInfo(const VarDecl *VD) { 3409 NamedReturnInfo Info{VD, NamedReturnInfo::MoveEligibleAndCopyElidable}; 3410 3411 // C++20 [class.copy.elision]p3: 3412 // - in a return statement in a function with ... 3413 // (other than a function ... parameter) 3414 if (VD->getKind() == Decl::ParmVar) 3415 Info.S = NamedReturnInfo::MoveEligible; 3416 else if (VD->getKind() != Decl::Var) 3417 return NamedReturnInfo(); 3418 3419 // (other than ... a catch-clause parameter) 3420 if (VD->isExceptionVariable()) 3421 Info.S = NamedReturnInfo::MoveEligible; 3422 3423 // ...automatic... 3424 if (!VD->hasLocalStorage()) 3425 return NamedReturnInfo(); 3426 3427 // We don't want to implicitly move out of a __block variable during a return 3428 // because we cannot assume the variable will no longer be used. 3429 if (VD->hasAttr<BlocksAttr>()) 3430 return NamedReturnInfo(); 3431 3432 QualType VDType = VD->getType(); 3433 if (VDType->isObjectType()) { 3434 // C++17 [class.copy.elision]p3: 3435 // ...non-volatile automatic object... 3436 if (VDType.isVolatileQualified()) 3437 return NamedReturnInfo(); 3438 } else if (VDType->isRValueReferenceType()) { 3439 // C++20 [class.copy.elision]p3: 3440 // ...either a non-volatile object or an rvalue reference to a non-volatile 3441 // object type... 3442 QualType VDReferencedType = VDType.getNonReferenceType(); 3443 if (VDReferencedType.isVolatileQualified() || 3444 !VDReferencedType->isObjectType()) 3445 return NamedReturnInfo(); 3446 Info.S = NamedReturnInfo::MoveEligible; 3447 } else { 3448 return NamedReturnInfo(); 3449 } 3450 3451 // Variables with higher required alignment than their type's ABI 3452 // alignment cannot use NRVO. 3453 if (!VD->hasDependentAlignment() && 3454 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VDType)) 3455 Info.S = NamedReturnInfo::MoveEligible; 3456 3457 return Info; 3458 } 3459 3460 /// Updates given NamedReturnInfo's move-eligible and 3461 /// copy-elidable statuses, considering the function 3462 /// return type criteria as applicable to return statements. 3463 /// 3464 /// \param Info The NamedReturnInfo object to update. 3465 /// 3466 /// \param ReturnType This is the return type of the function. 3467 /// \returns The copy elision candidate, in case the initial return expression 3468 /// was copy elidable, or nullptr otherwise. 3469 const VarDecl *Sema::getCopyElisionCandidate(NamedReturnInfo &Info, 3470 QualType ReturnType) { 3471 if (!Info.Candidate) 3472 return nullptr; 3473 3474 auto invalidNRVO = [&] { 3475 Info = NamedReturnInfo(); 3476 return nullptr; 3477 }; 3478 3479 // If we got a non-deduced auto ReturnType, we are in a dependent context and 3480 // there is no point in allowing copy elision since we won't have it deduced 3481 // by the point the VardDecl is instantiated, which is the last chance we have 3482 // of deciding if the candidate is really copy elidable. 3483 if ((ReturnType->getTypeClass() == Type::TypeClass::Auto && 3484 ReturnType->isCanonicalUnqualified()) || 3485 ReturnType->isSpecificBuiltinType(BuiltinType::Dependent)) 3486 return invalidNRVO(); 3487 3488 if (!ReturnType->isDependentType()) { 3489 // - in a return statement in a function with ... 3490 // ... a class return type ... 3491 if (!ReturnType->isRecordType()) 3492 return invalidNRVO(); 3493 3494 QualType VDType = Info.Candidate->getType(); 3495 // ... the same cv-unqualified type as the function return type ... 3496 // When considering moving this expression out, allow dissimilar types. 3497 if (!VDType->isDependentType() && 3498 !Context.hasSameUnqualifiedType(ReturnType, VDType)) 3499 Info.S = NamedReturnInfo::MoveEligible; 3500 } 3501 return Info.isCopyElidable() ? Info.Candidate : nullptr; 3502 } 3503 3504 /// Verify that the initialization sequence that was picked for the 3505 /// first overload resolution is permissible under C++98. 3506 /// 3507 /// Reject (possibly converting) constructors not taking an rvalue reference, 3508 /// or user conversion operators which are not ref-qualified. 3509 static bool 3510 VerifyInitializationSequenceCXX98(const Sema &S, 3511 const InitializationSequence &Seq) { 3512 const auto *Step = llvm::find_if(Seq.steps(), [](const auto &Step) { 3513 return Step.Kind == InitializationSequence::SK_ConstructorInitialization || 3514 Step.Kind == InitializationSequence::SK_UserConversion; 3515 }); 3516 if (Step != Seq.step_end()) { 3517 const auto *FD = Step->Function.Function; 3518 if (isa<CXXConstructorDecl>(FD) 3519 ? !FD->getParamDecl(0)->getType()->isRValueReferenceType() 3520 : cast<CXXMethodDecl>(FD)->getRefQualifier() == RQ_None) 3521 return false; 3522 } 3523 return true; 3524 } 3525 3526 /// Perform the initialization of a potentially-movable value, which 3527 /// is the result of return value. 3528 /// 3529 /// This routine implements C++20 [class.copy.elision]p3, which attempts to 3530 /// treat returned lvalues as rvalues in certain cases (to prefer move 3531 /// construction), then falls back to treating them as lvalues if that failed. 3532 ExprResult Sema::PerformMoveOrCopyInitialization( 3533 const InitializedEntity &Entity, const NamedReturnInfo &NRInfo, Expr *Value, 3534 bool SupressSimplerImplicitMoves) { 3535 if (getLangOpts().CPlusPlus && 3536 (!getLangOpts().CPlusPlus23 || SupressSimplerImplicitMoves) && 3537 NRInfo.isMoveEligible()) { 3538 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, Value->getType(), 3539 CK_NoOp, Value, VK_XValue, FPOptionsOverride()); 3540 Expr *InitExpr = &AsRvalue; 3541 auto Kind = InitializationKind::CreateCopy(Value->getBeginLoc(), 3542 Value->getBeginLoc()); 3543 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3544 auto Res = Seq.getFailedOverloadResult(); 3545 if ((Res == OR_Success || Res == OR_Deleted) && 3546 (getLangOpts().CPlusPlus11 || 3547 VerifyInitializationSequenceCXX98(*this, Seq))) { 3548 // Promote "AsRvalue" to the heap, since we now need this 3549 // expression node to persist. 3550 Value = 3551 ImplicitCastExpr::Create(Context, Value->getType(), CK_NoOp, Value, 3552 nullptr, VK_XValue, FPOptionsOverride()); 3553 // Complete type-checking the initialization of the return type 3554 // using the constructor we found. 3555 return Seq.Perform(*this, Entity, Kind, Value); 3556 } 3557 } 3558 // Either we didn't meet the criteria for treating an lvalue as an rvalue, 3559 // above, or overload resolution failed. Either way, we need to try 3560 // (again) now with the return value expression as written. 3561 return PerformCopyInitialization(Entity, SourceLocation(), Value); 3562 } 3563 3564 /// Determine whether the declared return type of the specified function 3565 /// contains 'auto'. 3566 static bool hasDeducedReturnType(FunctionDecl *FD) { 3567 const FunctionProtoType *FPT = 3568 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 3569 return FPT->getReturnType()->isUndeducedType(); 3570 } 3571 3572 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements 3573 /// for capturing scopes. 3574 /// 3575 StmtResult Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, 3576 Expr *RetValExp, 3577 NamedReturnInfo &NRInfo, 3578 bool SupressSimplerImplicitMoves) { 3579 // If this is the first return we've seen, infer the return type. 3580 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules. 3581 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction()); 3582 QualType FnRetType = CurCap->ReturnType; 3583 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap); 3584 if (CurLambda && CurLambda->CallOperator->getType().isNull()) 3585 return StmtError(); 3586 bool HasDeducedReturnType = 3587 CurLambda && hasDeducedReturnType(CurLambda->CallOperator); 3588 3589 if (ExprEvalContexts.back().isDiscardedStatementContext() && 3590 (HasDeducedReturnType || CurCap->HasImplicitReturnType)) { 3591 if (RetValExp) { 3592 ExprResult ER = 3593 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false); 3594 if (ER.isInvalid()) 3595 return StmtError(); 3596 RetValExp = ER.get(); 3597 } 3598 return ReturnStmt::Create(Context, ReturnLoc, RetValExp, 3599 /* NRVOCandidate=*/nullptr); 3600 } 3601 3602 if (HasDeducedReturnType) { 3603 FunctionDecl *FD = CurLambda->CallOperator; 3604 // If we've already decided this lambda is invalid, e.g. because 3605 // we saw a `return` whose expression had an error, don't keep 3606 // trying to deduce its return type. 3607 if (FD->isInvalidDecl()) 3608 return StmtError(); 3609 // In C++1y, the return type may involve 'auto'. 3610 // FIXME: Blocks might have a return type of 'auto' explicitly specified. 3611 if (CurCap->ReturnType.isNull()) 3612 CurCap->ReturnType = FD->getReturnType(); 3613 3614 AutoType *AT = CurCap->ReturnType->getContainedAutoType(); 3615 assert(AT && "lost auto type from lambda return type"); 3616 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) { 3617 FD->setInvalidDecl(); 3618 // FIXME: preserve the ill-formed return expression. 3619 return StmtError(); 3620 } 3621 CurCap->ReturnType = FnRetType = FD->getReturnType(); 3622 } else if (CurCap->HasImplicitReturnType) { 3623 // For blocks/lambdas with implicit return types, we check each return 3624 // statement individually, and deduce the common return type when the block 3625 // or lambda is completed. 3626 // FIXME: Fold this into the 'auto' codepath above. 3627 if (RetValExp && !isa<InitListExpr>(RetValExp)) { 3628 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp); 3629 if (Result.isInvalid()) 3630 return StmtError(); 3631 RetValExp = Result.get(); 3632 3633 // DR1048: even prior to C++14, we should use the 'auto' deduction rules 3634 // when deducing a return type for a lambda-expression (or by extension 3635 // for a block). These rules differ from the stated C++11 rules only in 3636 // that they remove top-level cv-qualifiers. 3637 if (!CurContext->isDependentContext()) 3638 FnRetType = RetValExp->getType().getUnqualifiedType(); 3639 else 3640 FnRetType = CurCap->ReturnType = Context.DependentTy; 3641 } else { 3642 if (RetValExp) { 3643 // C++11 [expr.lambda.prim]p4 bans inferring the result from an 3644 // initializer list, because it is not an expression (even 3645 // though we represent it as one). We still deduce 'void'. 3646 Diag(ReturnLoc, diag::err_lambda_return_init_list) 3647 << RetValExp->getSourceRange(); 3648 } 3649 3650 FnRetType = Context.VoidTy; 3651 } 3652 3653 // Although we'll properly infer the type of the block once it's completed, 3654 // make sure we provide a return type now for better error recovery. 3655 if (CurCap->ReturnType.isNull()) 3656 CurCap->ReturnType = FnRetType; 3657 } 3658 const VarDecl *NRVOCandidate = getCopyElisionCandidate(NRInfo, FnRetType); 3659 3660 if (auto *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) { 3661 if (CurBlock->FunctionType->castAs<FunctionType>()->getNoReturnAttr()) { 3662 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr); 3663 return StmtError(); 3664 } 3665 } else if (auto *CurRegion = dyn_cast<CapturedRegionScopeInfo>(CurCap)) { 3666 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName(); 3667 return StmtError(); 3668 } else { 3669 assert(CurLambda && "unknown kind of captured scope"); 3670 if (CurLambda->CallOperator->getType() 3671 ->castAs<FunctionType>() 3672 ->getNoReturnAttr()) { 3673 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr); 3674 return StmtError(); 3675 } 3676 } 3677 3678 // Otherwise, verify that this result type matches the previous one. We are 3679 // pickier with blocks than for normal functions because we don't have GCC 3680 // compatibility to worry about here. 3681 if (FnRetType->isDependentType()) { 3682 // Delay processing for now. TODO: there are lots of dependent 3683 // types we can conclusively prove aren't void. 3684 } else if (FnRetType->isVoidType()) { 3685 if (RetValExp && !isa<InitListExpr>(RetValExp) && 3686 !(getLangOpts().CPlusPlus && 3687 (RetValExp->isTypeDependent() || 3688 RetValExp->getType()->isVoidType()))) { 3689 if (!getLangOpts().CPlusPlus && 3690 RetValExp->getType()->isVoidType()) 3691 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2; 3692 else { 3693 Diag(ReturnLoc, diag::err_return_block_has_expr); 3694 RetValExp = nullptr; 3695 } 3696 } 3697 } else if (!RetValExp) { 3698 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr)); 3699 } else if (!RetValExp->isTypeDependent()) { 3700 // we have a non-void block with an expression, continue checking 3701 3702 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 3703 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 3704 // function return. 3705 3706 // In C++ the return statement is handled via a copy initialization. 3707 // the C version of which boils down to CheckSingleAssignmentConstraints. 3708 InitializedEntity Entity = 3709 InitializedEntity::InitializeResult(ReturnLoc, FnRetType); 3710 ExprResult Res = PerformMoveOrCopyInitialization( 3711 Entity, NRInfo, RetValExp, SupressSimplerImplicitMoves); 3712 if (Res.isInvalid()) { 3713 // FIXME: Cleanup temporaries here, anyway? 3714 return StmtError(); 3715 } 3716 RetValExp = Res.get(); 3717 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc); 3718 } 3719 3720 if (RetValExp) { 3721 ExprResult ER = 3722 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false); 3723 if (ER.isInvalid()) 3724 return StmtError(); 3725 RetValExp = ER.get(); 3726 } 3727 auto *Result = 3728 ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate); 3729 3730 // If we need to check for the named return value optimization, 3731 // or if we need to infer the return type, 3732 // save the return statement in our scope for later processing. 3733 if (CurCap->HasImplicitReturnType || NRVOCandidate) 3734 FunctionScopes.back()->Returns.push_back(Result); 3735 3736 if (FunctionScopes.back()->FirstReturnLoc.isInvalid()) 3737 FunctionScopes.back()->FirstReturnLoc = ReturnLoc; 3738 3739 if (auto *CurBlock = dyn_cast<BlockScopeInfo>(CurCap); 3740 CurBlock && CurCap->HasImplicitReturnType && RetValExp && 3741 RetValExp->containsErrors()) 3742 CurBlock->TheDecl->setInvalidDecl(); 3743 3744 return Result; 3745 } 3746 3747 namespace { 3748 /// Marks all typedefs in all local classes in a type referenced. 3749 /// 3750 /// In a function like 3751 /// auto f() { 3752 /// struct S { typedef int a; }; 3753 /// return S(); 3754 /// } 3755 /// 3756 /// the local type escapes and could be referenced in some TUs but not in 3757 /// others. Pretend that all local typedefs are always referenced, to not warn 3758 /// on this. This isn't necessary if f has internal linkage, or the typedef 3759 /// is private. 3760 class LocalTypedefNameReferencer 3761 : public RecursiveASTVisitor<LocalTypedefNameReferencer> { 3762 public: 3763 LocalTypedefNameReferencer(Sema &S) : S(S) {} 3764 bool VisitRecordType(const RecordType *RT); 3765 private: 3766 Sema &S; 3767 }; 3768 bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) { 3769 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl()); 3770 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() || 3771 R->isDependentType()) 3772 return true; 3773 for (auto *TmpD : R->decls()) 3774 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 3775 if (T->getAccess() != AS_private || R->hasFriends()) 3776 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false); 3777 return true; 3778 } 3779 } 3780 3781 TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const { 3782 return FD->getTypeSourceInfo() 3783 ->getTypeLoc() 3784 .getAsAdjusted<FunctionProtoTypeLoc>() 3785 .getReturnLoc(); 3786 } 3787 3788 /// Deduce the return type for a function from a returned expression, per 3789 /// C++1y [dcl.spec.auto]p6. 3790 bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, 3791 SourceLocation ReturnLoc, 3792 Expr *RetExpr, const AutoType *AT) { 3793 // If this is the conversion function for a lambda, we choose to deduce its 3794 // type from the corresponding call operator, not from the synthesized return 3795 // statement within it. See Sema::DeduceReturnType. 3796 if (isLambdaConversionOperator(FD)) 3797 return false; 3798 3799 if (RetExpr && isa<InitListExpr>(RetExpr)) { 3800 // If the deduction is for a return statement and the initializer is 3801 // a braced-init-list, the program is ill-formed. 3802 Diag(RetExpr->getExprLoc(), 3803 getCurLambda() ? diag::err_lambda_return_init_list 3804 : diag::err_auto_fn_return_init_list) 3805 << RetExpr->getSourceRange(); 3806 return true; 3807 } 3808 3809 if (FD->isDependentContext()) { 3810 // C++1y [dcl.spec.auto]p12: 3811 // Return type deduction [...] occurs when the definition is 3812 // instantiated even if the function body contains a return 3813 // statement with a non-type-dependent operand. 3814 assert(AT->isDeduced() && "should have deduced to dependent type"); 3815 return false; 3816 } 3817 3818 TypeLoc OrigResultType = getReturnTypeLoc(FD); 3819 // In the case of a return with no operand, the initializer is considered 3820 // to be void(). 3821 CXXScalarValueInitExpr VoidVal(Context.VoidTy, nullptr, SourceLocation()); 3822 if (!RetExpr) { 3823 // For a function with a deduced result type to return with omitted 3824 // expression, the result type as written must be 'auto' or 3825 // 'decltype(auto)', possibly cv-qualified or constrained, but not 3826 // ref-qualified. 3827 if (!OrigResultType.getType()->getAs<AutoType>()) { 3828 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto) 3829 << OrigResultType.getType(); 3830 return true; 3831 } 3832 RetExpr = &VoidVal; 3833 } 3834 3835 QualType Deduced = AT->getDeducedType(); 3836 { 3837 // Otherwise, [...] deduce a value for U using the rules of template 3838 // argument deduction. 3839 auto RetExprLoc = RetExpr->getExprLoc(); 3840 TemplateDeductionInfo Info(RetExprLoc); 3841 SourceLocation TemplateSpecLoc; 3842 if (RetExpr->getType() == Context.OverloadTy) { 3843 auto FindResult = OverloadExpr::find(RetExpr); 3844 if (FindResult.Expression) 3845 TemplateSpecLoc = FindResult.Expression->getNameLoc(); 3846 } 3847 TemplateSpecCandidateSet FailedTSC(TemplateSpecLoc); 3848 TemplateDeductionResult Res = DeduceAutoType( 3849 OrigResultType, RetExpr, Deduced, Info, /*DependentDeduction=*/false, 3850 /*IgnoreConstraints=*/false, &FailedTSC); 3851 if (Res != TDK_Success && FD->isInvalidDecl()) 3852 return true; 3853 switch (Res) { 3854 case TDK_Success: 3855 break; 3856 case TDK_AlreadyDiagnosed: 3857 return true; 3858 case TDK_Inconsistent: { 3859 // If a function with a declared return type that contains a placeholder 3860 // type has multiple return statements, the return type is deduced for 3861 // each return statement. [...] if the type deduced is not the same in 3862 // each deduction, the program is ill-formed. 3863 const LambdaScopeInfo *LambdaSI = getCurLambda(); 3864 if (LambdaSI && LambdaSI->HasImplicitReturnType) 3865 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible) 3866 << Info.SecondArg << Info.FirstArg << true /*IsLambda*/; 3867 else 3868 Diag(ReturnLoc, diag::err_auto_fn_different_deductions) 3869 << (AT->isDecltypeAuto() ? 1 : 0) << Info.SecondArg 3870 << Info.FirstArg; 3871 return true; 3872 } 3873 default: 3874 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure) 3875 << OrigResultType.getType() << RetExpr->getType(); 3876 FailedTSC.NoteCandidates(*this, RetExprLoc); 3877 return true; 3878 } 3879 } 3880 3881 // If a local type is part of the returned type, mark its fields as 3882 // referenced. 3883 LocalTypedefNameReferencer(*this).TraverseType(RetExpr->getType()); 3884 3885 // CUDA: Kernel function must have 'void' return type. 3886 if (getLangOpts().CUDA && FD->hasAttr<CUDAGlobalAttr>() && 3887 !Deduced->isVoidType()) { 3888 Diag(FD->getLocation(), diag::err_kern_type_not_void_return) 3889 << FD->getType() << FD->getSourceRange(); 3890 return true; 3891 } 3892 3893 if (!FD->isInvalidDecl() && AT->getDeducedType() != Deduced) 3894 // Update all declarations of the function to have the deduced return type. 3895 Context.adjustDeducedFunctionResultType(FD, Deduced); 3896 3897 return false; 3898 } 3899 3900 StmtResult 3901 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, 3902 Scope *CurScope) { 3903 // Correct typos, in case the containing function returns 'auto' and 3904 // RetValExp should determine the deduced type. 3905 ExprResult RetVal = CorrectDelayedTyposInExpr( 3906 RetValExp, nullptr, /*RecoverUncorrectedTypos=*/true); 3907 if (RetVal.isInvalid()) 3908 return StmtError(); 3909 StmtResult R = 3910 BuildReturnStmt(ReturnLoc, RetVal.get(), /*AllowRecovery=*/true); 3911 if (R.isInvalid() || ExprEvalContexts.back().isDiscardedStatementContext()) 3912 return R; 3913 3914 VarDecl *VD = 3915 const_cast<VarDecl *>(cast<ReturnStmt>(R.get())->getNRVOCandidate()); 3916 3917 CurScope->updateNRVOCandidate(VD); 3918 3919 CheckJumpOutOfSEHFinally(*this, ReturnLoc, *CurScope->getFnParent()); 3920 3921 return R; 3922 } 3923 3924 static bool CheckSimplerImplicitMovesMSVCWorkaround(const Sema &S, 3925 const Expr *E) { 3926 if (!E || !S.getLangOpts().CPlusPlus23 || !S.getLangOpts().MSVCCompat) 3927 return false; 3928 const Decl *D = E->getReferencedDeclOfCallee(); 3929 if (!D || !S.SourceMgr.isInSystemHeader(D->getLocation())) 3930 return false; 3931 for (const DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent()) { 3932 if (DC->isStdNamespace()) 3933 return true; 3934 } 3935 return false; 3936 } 3937 3938 StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, 3939 bool AllowRecovery) { 3940 // Check for unexpanded parameter packs. 3941 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp)) 3942 return StmtError(); 3943 3944 // HACK: We suppress simpler implicit move here in msvc compatibility mode 3945 // just as a temporary work around, as the MSVC STL has issues with 3946 // this change. 3947 bool SupressSimplerImplicitMoves = 3948 CheckSimplerImplicitMovesMSVCWorkaround(*this, RetValExp); 3949 NamedReturnInfo NRInfo = getNamedReturnInfo( 3950 RetValExp, SupressSimplerImplicitMoves ? SimplerImplicitMoveMode::ForceOff 3951 : SimplerImplicitMoveMode::Normal); 3952 3953 if (isa<CapturingScopeInfo>(getCurFunction())) 3954 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp, NRInfo, 3955 SupressSimplerImplicitMoves); 3956 3957 QualType FnRetType; 3958 QualType RelatedRetType; 3959 const AttrVec *Attrs = nullptr; 3960 bool isObjCMethod = false; 3961 3962 if (const FunctionDecl *FD = getCurFunctionDecl()) { 3963 FnRetType = FD->getReturnType(); 3964 if (FD->hasAttrs()) 3965 Attrs = &FD->getAttrs(); 3966 if (FD->isNoReturn()) 3967 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) << FD; 3968 if (FD->isMain() && RetValExp) 3969 if (isa<CXXBoolLiteralExpr>(RetValExp)) 3970 Diag(ReturnLoc, diag::warn_main_returns_bool_literal) 3971 << RetValExp->getSourceRange(); 3972 if (FD->hasAttr<CmseNSEntryAttr>() && RetValExp) { 3973 if (const auto *RT = dyn_cast<RecordType>(FnRetType.getCanonicalType())) { 3974 if (RT->getDecl()->isOrContainsUnion()) 3975 Diag(RetValExp->getBeginLoc(), diag::warn_cmse_nonsecure_union) << 1; 3976 } 3977 } 3978 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) { 3979 FnRetType = MD->getReturnType(); 3980 isObjCMethod = true; 3981 if (MD->hasAttrs()) 3982 Attrs = &MD->getAttrs(); 3983 if (MD->hasRelatedResultType() && MD->getClassInterface()) { 3984 // In the implementation of a method with a related return type, the 3985 // type used to type-check the validity of return statements within the 3986 // method body is a pointer to the type of the class being implemented. 3987 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface()); 3988 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType); 3989 } 3990 } else // If we don't have a function/method context, bail. 3991 return StmtError(); 3992 3993 if (RetValExp) { 3994 const auto *ATy = dyn_cast<ArrayType>(RetValExp->getType()); 3995 if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) { 3996 Diag(ReturnLoc, diag::err_wasm_table_art) << 1; 3997 return StmtError(); 3998 } 3999 } 4000 4001 // C++1z: discarded return statements are not considered when deducing a 4002 // return type. 4003 if (ExprEvalContexts.back().isDiscardedStatementContext() && 4004 FnRetType->getContainedAutoType()) { 4005 if (RetValExp) { 4006 ExprResult ER = 4007 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false); 4008 if (ER.isInvalid()) 4009 return StmtError(); 4010 RetValExp = ER.get(); 4011 } 4012 return ReturnStmt::Create(Context, ReturnLoc, RetValExp, 4013 /* NRVOCandidate=*/nullptr); 4014 } 4015 4016 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing 4017 // deduction. 4018 if (getLangOpts().CPlusPlus14) { 4019 if (AutoType *AT = FnRetType->getContainedAutoType()) { 4020 FunctionDecl *FD = cast<FunctionDecl>(CurContext); 4021 // If we've already decided this function is invalid, e.g. because 4022 // we saw a `return` whose expression had an error, don't keep 4023 // trying to deduce its return type. 4024 // (Some return values may be needlessly wrapped in RecoveryExpr). 4025 if (FD->isInvalidDecl() || 4026 DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) { 4027 FD->setInvalidDecl(); 4028 if (!AllowRecovery) 4029 return StmtError(); 4030 // The deduction failure is diagnosed and marked, try to recover. 4031 if (RetValExp) { 4032 // Wrap return value with a recovery expression of the previous type. 4033 // If no deduction yet, use DependentTy. 4034 auto Recovery = CreateRecoveryExpr( 4035 RetValExp->getBeginLoc(), RetValExp->getEndLoc(), RetValExp, 4036 AT->isDeduced() ? FnRetType : QualType()); 4037 if (Recovery.isInvalid()) 4038 return StmtError(); 4039 RetValExp = Recovery.get(); 4040 } else { 4041 // Nothing to do: a ReturnStmt with no value is fine recovery. 4042 } 4043 } else { 4044 FnRetType = FD->getReturnType(); 4045 } 4046 } 4047 } 4048 const VarDecl *NRVOCandidate = getCopyElisionCandidate(NRInfo, FnRetType); 4049 4050 bool HasDependentReturnType = FnRetType->isDependentType(); 4051 4052 ReturnStmt *Result = nullptr; 4053 if (FnRetType->isVoidType()) { 4054 if (RetValExp) { 4055 if (auto *ILE = dyn_cast<InitListExpr>(RetValExp)) { 4056 // We simply never allow init lists as the return value of void 4057 // functions. This is compatible because this was never allowed before, 4058 // so there's no legacy code to deal with. 4059 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 4060 int FunctionKind = 0; 4061 if (isa<ObjCMethodDecl>(CurDecl)) 4062 FunctionKind = 1; 4063 else if (isa<CXXConstructorDecl>(CurDecl)) 4064 FunctionKind = 2; 4065 else if (isa<CXXDestructorDecl>(CurDecl)) 4066 FunctionKind = 3; 4067 4068 Diag(ReturnLoc, diag::err_return_init_list) 4069 << CurDecl << FunctionKind << RetValExp->getSourceRange(); 4070 4071 // Preserve the initializers in the AST. 4072 RetValExp = AllowRecovery 4073 ? CreateRecoveryExpr(ILE->getLBraceLoc(), 4074 ILE->getRBraceLoc(), ILE->inits()) 4075 .get() 4076 : nullptr; 4077 } else if (!RetValExp->isTypeDependent()) { 4078 // C99 6.8.6.4p1 (ext_ since GCC warns) 4079 unsigned D = diag::ext_return_has_expr; 4080 if (RetValExp->getType()->isVoidType()) { 4081 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 4082 if (isa<CXXConstructorDecl>(CurDecl) || 4083 isa<CXXDestructorDecl>(CurDecl)) 4084 D = diag::err_ctor_dtor_returns_void; 4085 else 4086 D = diag::ext_return_has_void_expr; 4087 } 4088 else { 4089 ExprResult Result = RetValExp; 4090 Result = IgnoredValueConversions(Result.get()); 4091 if (Result.isInvalid()) 4092 return StmtError(); 4093 RetValExp = Result.get(); 4094 RetValExp = ImpCastExprToType(RetValExp, 4095 Context.VoidTy, CK_ToVoid).get(); 4096 } 4097 // return of void in constructor/destructor is illegal in C++. 4098 if (D == diag::err_ctor_dtor_returns_void) { 4099 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 4100 Diag(ReturnLoc, D) << CurDecl << isa<CXXDestructorDecl>(CurDecl) 4101 << RetValExp->getSourceRange(); 4102 } 4103 // return (some void expression); is legal in C++. 4104 else if (D != diag::ext_return_has_void_expr || 4105 !getLangOpts().CPlusPlus) { 4106 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 4107 4108 int FunctionKind = 0; 4109 if (isa<ObjCMethodDecl>(CurDecl)) 4110 FunctionKind = 1; 4111 else if (isa<CXXConstructorDecl>(CurDecl)) 4112 FunctionKind = 2; 4113 else if (isa<CXXDestructorDecl>(CurDecl)) 4114 FunctionKind = 3; 4115 4116 Diag(ReturnLoc, D) 4117 << CurDecl << FunctionKind << RetValExp->getSourceRange(); 4118 } 4119 } 4120 4121 if (RetValExp) { 4122 ExprResult ER = 4123 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false); 4124 if (ER.isInvalid()) 4125 return StmtError(); 4126 RetValExp = ER.get(); 4127 } 4128 } 4129 4130 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, 4131 /* NRVOCandidate=*/nullptr); 4132 } else if (!RetValExp && !HasDependentReturnType) { 4133 FunctionDecl *FD = getCurFunctionDecl(); 4134 4135 if ((FD && FD->isInvalidDecl()) || FnRetType->containsErrors()) { 4136 // The intended return type might have been "void", so don't warn. 4137 } else if (getLangOpts().CPlusPlus11 && FD && FD->isConstexpr()) { 4138 // C++11 [stmt.return]p2 4139 Diag(ReturnLoc, diag::err_constexpr_return_missing_expr) 4140 << FD << FD->isConsteval(); 4141 FD->setInvalidDecl(); 4142 } else { 4143 // C99 6.8.6.4p1 (ext_ since GCC warns) 4144 // C90 6.6.6.4p4 4145 unsigned DiagID = getLangOpts().C99 ? diag::ext_return_missing_expr 4146 : diag::warn_return_missing_expr; 4147 // Note that at this point one of getCurFunctionDecl() or 4148 // getCurMethodDecl() must be non-null (see above). 4149 assert((getCurFunctionDecl() || getCurMethodDecl()) && 4150 "Not in a FunctionDecl or ObjCMethodDecl?"); 4151 bool IsMethod = FD == nullptr; 4152 const NamedDecl *ND = 4153 IsMethod ? cast<NamedDecl>(getCurMethodDecl()) : cast<NamedDecl>(FD); 4154 Diag(ReturnLoc, DiagID) << ND << IsMethod; 4155 } 4156 4157 Result = ReturnStmt::Create(Context, ReturnLoc, /* RetExpr=*/nullptr, 4158 /* NRVOCandidate=*/nullptr); 4159 } else { 4160 assert(RetValExp || HasDependentReturnType); 4161 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType; 4162 4163 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 4164 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 4165 // function return. 4166 4167 // In C++ the return statement is handled via a copy initialization, 4168 // the C version of which boils down to CheckSingleAssignmentConstraints. 4169 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) { 4170 // we have a non-void function with an expression, continue checking 4171 InitializedEntity Entity = 4172 InitializedEntity::InitializeResult(ReturnLoc, RetType); 4173 ExprResult Res = PerformMoveOrCopyInitialization( 4174 Entity, NRInfo, RetValExp, SupressSimplerImplicitMoves); 4175 if (Res.isInvalid() && AllowRecovery) 4176 Res = CreateRecoveryExpr(RetValExp->getBeginLoc(), 4177 RetValExp->getEndLoc(), RetValExp, RetType); 4178 if (Res.isInvalid()) { 4179 // FIXME: Clean up temporaries here anyway? 4180 return StmtError(); 4181 } 4182 RetValExp = Res.getAs<Expr>(); 4183 4184 // If we have a related result type, we need to implicitly 4185 // convert back to the formal result type. We can't pretend to 4186 // initialize the result again --- we might end double-retaining 4187 // --- so instead we initialize a notional temporary. 4188 if (!RelatedRetType.isNull()) { 4189 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(), 4190 FnRetType); 4191 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp); 4192 if (Res.isInvalid()) { 4193 // FIXME: Clean up temporaries here anyway? 4194 return StmtError(); 4195 } 4196 RetValExp = Res.getAs<Expr>(); 4197 } 4198 4199 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs, 4200 getCurFunctionDecl()); 4201 } 4202 4203 if (RetValExp) { 4204 ExprResult ER = 4205 ActOnFinishFullExpr(RetValExp, ReturnLoc, /*DiscardedValue*/ false); 4206 if (ER.isInvalid()) 4207 return StmtError(); 4208 RetValExp = ER.get(); 4209 } 4210 Result = ReturnStmt::Create(Context, ReturnLoc, RetValExp, NRVOCandidate); 4211 } 4212 4213 // If we need to check for the named return value optimization, save the 4214 // return statement in our scope for later processing. 4215 if (Result->getNRVOCandidate()) 4216 FunctionScopes.back()->Returns.push_back(Result); 4217 4218 if (FunctionScopes.back()->FirstReturnLoc.isInvalid()) 4219 FunctionScopes.back()->FirstReturnLoc = ReturnLoc; 4220 4221 return Result; 4222 } 4223 4224 StmtResult 4225 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc, 4226 SourceLocation RParen, Decl *Parm, 4227 Stmt *Body) { 4228 VarDecl *Var = cast_or_null<VarDecl>(Parm); 4229 if (Var && Var->isInvalidDecl()) 4230 return StmtError(); 4231 4232 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body); 4233 } 4234 4235 StmtResult 4236 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) { 4237 return new (Context) ObjCAtFinallyStmt(AtLoc, Body); 4238 } 4239 4240 StmtResult 4241 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 4242 MultiStmtArg CatchStmts, Stmt *Finally) { 4243 if (!getLangOpts().ObjCExceptions) 4244 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try"; 4245 4246 // Objective-C try is incompatible with SEH __try. 4247 sema::FunctionScopeInfo *FSI = getCurFunction(); 4248 if (FSI->FirstSEHTryLoc.isValid()) { 4249 Diag(AtLoc, diag::err_mixing_cxx_try_seh_try) << 1; 4250 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'"; 4251 } 4252 4253 FSI->setHasObjCTry(AtLoc); 4254 unsigned NumCatchStmts = CatchStmts.size(); 4255 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(), 4256 NumCatchStmts, Finally); 4257 } 4258 4259 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) { 4260 if (Throw) { 4261 ExprResult Result = DefaultLvalueConversion(Throw); 4262 if (Result.isInvalid()) 4263 return StmtError(); 4264 4265 Result = ActOnFinishFullExpr(Result.get(), /*DiscardedValue*/ false); 4266 if (Result.isInvalid()) 4267 return StmtError(); 4268 Throw = Result.get(); 4269 4270 QualType ThrowType = Throw->getType(); 4271 // Make sure the expression type is an ObjC pointer or "void *". 4272 if (!ThrowType->isDependentType() && 4273 !ThrowType->isObjCObjectPointerType()) { 4274 const PointerType *PT = ThrowType->getAs<PointerType>(); 4275 if (!PT || !PT->getPointeeType()->isVoidType()) 4276 return StmtError(Diag(AtLoc, diag::err_objc_throw_expects_object) 4277 << Throw->getType() << Throw->getSourceRange()); 4278 } 4279 } 4280 4281 return new (Context) ObjCAtThrowStmt(AtLoc, Throw); 4282 } 4283 4284 StmtResult 4285 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 4286 Scope *CurScope) { 4287 if (!getLangOpts().ObjCExceptions) 4288 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw"; 4289 4290 if (!Throw) { 4291 // @throw without an expression designates a rethrow (which must occur 4292 // in the context of an @catch clause). 4293 Scope *AtCatchParent = CurScope; 4294 while (AtCatchParent && !AtCatchParent->isAtCatchScope()) 4295 AtCatchParent = AtCatchParent->getParent(); 4296 if (!AtCatchParent) 4297 return StmtError(Diag(AtLoc, diag::err_rethrow_used_outside_catch)); 4298 } 4299 return BuildObjCAtThrowStmt(AtLoc, Throw); 4300 } 4301 4302 ExprResult 4303 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) { 4304 ExprResult result = DefaultLvalueConversion(operand); 4305 if (result.isInvalid()) 4306 return ExprError(); 4307 operand = result.get(); 4308 4309 // Make sure the expression type is an ObjC pointer or "void *". 4310 QualType type = operand->getType(); 4311 if (!type->isDependentType() && 4312 !type->isObjCObjectPointerType()) { 4313 const PointerType *pointerType = type->getAs<PointerType>(); 4314 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) { 4315 if (getLangOpts().CPlusPlus) { 4316 if (RequireCompleteType(atLoc, type, 4317 diag::err_incomplete_receiver_type)) 4318 return Diag(atLoc, diag::err_objc_synchronized_expects_object) 4319 << type << operand->getSourceRange(); 4320 4321 ExprResult result = PerformContextuallyConvertToObjCPointer(operand); 4322 if (result.isInvalid()) 4323 return ExprError(); 4324 if (!result.isUsable()) 4325 return Diag(atLoc, diag::err_objc_synchronized_expects_object) 4326 << type << operand->getSourceRange(); 4327 4328 operand = result.get(); 4329 } else { 4330 return Diag(atLoc, diag::err_objc_synchronized_expects_object) 4331 << type << operand->getSourceRange(); 4332 } 4333 } 4334 } 4335 4336 // The operand to @synchronized is a full-expression. 4337 return ActOnFinishFullExpr(operand, /*DiscardedValue*/ false); 4338 } 4339 4340 StmtResult 4341 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr, 4342 Stmt *SyncBody) { 4343 // We can't jump into or indirect-jump out of a @synchronized block. 4344 setFunctionHasBranchProtectedScope(); 4345 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody); 4346 } 4347 4348 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block 4349 /// and creates a proper catch handler from them. 4350 StmtResult 4351 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, 4352 Stmt *HandlerBlock) { 4353 // There's nothing to test that ActOnExceptionDecl didn't already test. 4354 return new (Context) 4355 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock); 4356 } 4357 4358 StmtResult 4359 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) { 4360 setFunctionHasBranchProtectedScope(); 4361 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body); 4362 } 4363 4364 namespace { 4365 class CatchHandlerType { 4366 QualType QT; 4367 unsigned IsPointer : 1; 4368 4369 // This is a special constructor to be used only with DenseMapInfo's 4370 // getEmptyKey() and getTombstoneKey() functions. 4371 friend struct llvm::DenseMapInfo<CatchHandlerType>; 4372 enum Unique { ForDenseMap }; 4373 CatchHandlerType(QualType QT, Unique) : QT(QT), IsPointer(false) {} 4374 4375 public: 4376 /// Used when creating a CatchHandlerType from a handler type; will determine 4377 /// whether the type is a pointer or reference and will strip off the top 4378 /// level pointer and cv-qualifiers. 4379 CatchHandlerType(QualType Q) : QT(Q), IsPointer(false) { 4380 if (QT->isPointerType()) 4381 IsPointer = true; 4382 4383 QT = QT.getUnqualifiedType(); 4384 if (IsPointer || QT->isReferenceType()) 4385 QT = QT->getPointeeType(); 4386 } 4387 4388 /// Used when creating a CatchHandlerType from a base class type; pretends the 4389 /// type passed in had the pointer qualifier, does not need to get an 4390 /// unqualified type. 4391 CatchHandlerType(QualType QT, bool IsPointer) 4392 : QT(QT), IsPointer(IsPointer) {} 4393 4394 QualType underlying() const { return QT; } 4395 bool isPointer() const { return IsPointer; } 4396 4397 friend bool operator==(const CatchHandlerType &LHS, 4398 const CatchHandlerType &RHS) { 4399 // If the pointer qualification does not match, we can return early. 4400 if (LHS.IsPointer != RHS.IsPointer) 4401 return false; 4402 // Otherwise, check the underlying type without cv-qualifiers. 4403 return LHS.QT == RHS.QT; 4404 } 4405 }; 4406 } // namespace 4407 4408 namespace llvm { 4409 template <> struct DenseMapInfo<CatchHandlerType> { 4410 static CatchHandlerType getEmptyKey() { 4411 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(), 4412 CatchHandlerType::ForDenseMap); 4413 } 4414 4415 static CatchHandlerType getTombstoneKey() { 4416 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(), 4417 CatchHandlerType::ForDenseMap); 4418 } 4419 4420 static unsigned getHashValue(const CatchHandlerType &Base) { 4421 return DenseMapInfo<QualType>::getHashValue(Base.underlying()); 4422 } 4423 4424 static bool isEqual(const CatchHandlerType &LHS, 4425 const CatchHandlerType &RHS) { 4426 return LHS == RHS; 4427 } 4428 }; 4429 } 4430 4431 namespace { 4432 class CatchTypePublicBases { 4433 const llvm::DenseMap<QualType, CXXCatchStmt *> &TypesToCheck; 4434 4435 CXXCatchStmt *FoundHandler; 4436 QualType FoundHandlerType; 4437 QualType TestAgainstType; 4438 4439 public: 4440 CatchTypePublicBases(const llvm::DenseMap<QualType, CXXCatchStmt *> &T, 4441 QualType QT) 4442 : TypesToCheck(T), FoundHandler(nullptr), TestAgainstType(QT) {} 4443 4444 CXXCatchStmt *getFoundHandler() const { return FoundHandler; } 4445 QualType getFoundHandlerType() const { return FoundHandlerType; } 4446 4447 bool operator()(const CXXBaseSpecifier *S, CXXBasePath &) { 4448 if (S->getAccessSpecifier() == AccessSpecifier::AS_public) { 4449 QualType Check = S->getType().getCanonicalType(); 4450 const auto &M = TypesToCheck; 4451 auto I = M.find(Check); 4452 if (I != M.end()) { 4453 // We're pretty sure we found what we need to find. However, we still 4454 // need to make sure that we properly compare for pointers and 4455 // references, to handle cases like: 4456 // 4457 // } catch (Base *b) { 4458 // } catch (Derived &d) { 4459 // } 4460 // 4461 // where there is a qualification mismatch that disqualifies this 4462 // handler as a potential problem. 4463 if (I->second->getCaughtType()->isPointerType() == 4464 TestAgainstType->isPointerType()) { 4465 FoundHandler = I->second; 4466 FoundHandlerType = Check; 4467 return true; 4468 } 4469 } 4470 } 4471 return false; 4472 } 4473 }; 4474 } 4475 4476 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of 4477 /// handlers and creates a try statement from them. 4478 StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 4479 ArrayRef<Stmt *> Handlers) { 4480 const llvm::Triple &T = Context.getTargetInfo().getTriple(); 4481 const bool IsOpenMPGPUTarget = 4482 getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN()); 4483 // Don't report an error if 'try' is used in system headers or in an OpenMP 4484 // target region compiled for a GPU architecture. 4485 if (!IsOpenMPGPUTarget && !getLangOpts().CXXExceptions && 4486 !getSourceManager().isInSystemHeader(TryLoc) && !getLangOpts().CUDA) { 4487 // Delay error emission for the OpenMP device code. 4488 targetDiag(TryLoc, diag::err_exceptions_disabled) << "try"; 4489 } 4490 4491 // In OpenMP target regions, we assume that catch is never reached on GPU 4492 // targets. 4493 if (IsOpenMPGPUTarget) 4494 targetDiag(TryLoc, diag::warn_try_not_valid_on_target) << T.str(); 4495 4496 // Exceptions aren't allowed in CUDA device code. 4497 if (getLangOpts().CUDA) 4498 CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions) 4499 << "try" << CurrentCUDATarget(); 4500 4501 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope()) 4502 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try"; 4503 4504 sema::FunctionScopeInfo *FSI = getCurFunction(); 4505 4506 // C++ try is incompatible with SEH __try. 4507 if (!getLangOpts().Borland && FSI->FirstSEHTryLoc.isValid()) { 4508 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try) << 0; 4509 Diag(FSI->FirstSEHTryLoc, diag::note_conflicting_try_here) << "'__try'"; 4510 } 4511 4512 const unsigned NumHandlers = Handlers.size(); 4513 assert(!Handlers.empty() && 4514 "The parser shouldn't call this if there are no handlers."); 4515 4516 llvm::DenseMap<QualType, CXXCatchStmt *> HandledBaseTypes; 4517 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes; 4518 for (unsigned i = 0; i < NumHandlers; ++i) { 4519 CXXCatchStmt *H = cast<CXXCatchStmt>(Handlers[i]); 4520 4521 // Diagnose when the handler is a catch-all handler, but it isn't the last 4522 // handler for the try block. [except.handle]p5. Also, skip exception 4523 // declarations that are invalid, since we can't usefully report on them. 4524 if (!H->getExceptionDecl()) { 4525 if (i < NumHandlers - 1) 4526 return StmtError(Diag(H->getBeginLoc(), diag::err_early_catch_all)); 4527 continue; 4528 } else if (H->getExceptionDecl()->isInvalidDecl()) 4529 continue; 4530 4531 // Walk the type hierarchy to diagnose when this type has already been 4532 // handled (duplication), or cannot be handled (derivation inversion). We 4533 // ignore top-level cv-qualifiers, per [except.handle]p3 4534 CatchHandlerType HandlerCHT = H->getCaughtType().getCanonicalType(); 4535 4536 // We can ignore whether the type is a reference or a pointer; we need the 4537 // underlying declaration type in order to get at the underlying record 4538 // decl, if there is one. 4539 QualType Underlying = HandlerCHT.underlying(); 4540 if (auto *RD = Underlying->getAsCXXRecordDecl()) { 4541 if (!RD->hasDefinition()) 4542 continue; 4543 // Check that none of the public, unambiguous base classes are in the 4544 // map ([except.handle]p1). Give the base classes the same pointer 4545 // qualification as the original type we are basing off of. This allows 4546 // comparison against the handler type using the same top-level pointer 4547 // as the original type. 4548 CXXBasePaths Paths; 4549 Paths.setOrigin(RD); 4550 CatchTypePublicBases CTPB(HandledBaseTypes, 4551 H->getCaughtType().getCanonicalType()); 4552 if (RD->lookupInBases(CTPB, Paths)) { 4553 const CXXCatchStmt *Problem = CTPB.getFoundHandler(); 4554 if (!Paths.isAmbiguous( 4555 CanQualType::CreateUnsafe(CTPB.getFoundHandlerType()))) { 4556 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(), 4557 diag::warn_exception_caught_by_earlier_handler) 4558 << H->getCaughtType(); 4559 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(), 4560 diag::note_previous_exception_handler) 4561 << Problem->getCaughtType(); 4562 } 4563 } 4564 // Strip the qualifiers here because we're going to be comparing this 4565 // type to the base type specifiers of a class, which are ignored in a 4566 // base specifier per [class.derived.general]p2. 4567 HandledBaseTypes[Underlying.getUnqualifiedType()] = H; 4568 } 4569 4570 // Add the type the list of ones we have handled; diagnose if we've already 4571 // handled it. 4572 auto R = HandledTypes.insert( 4573 std::make_pair(H->getCaughtType().getCanonicalType(), H)); 4574 if (!R.second) { 4575 const CXXCatchStmt *Problem = R.first->second; 4576 Diag(H->getExceptionDecl()->getTypeSpecStartLoc(), 4577 diag::warn_exception_caught_by_earlier_handler) 4578 << H->getCaughtType(); 4579 Diag(Problem->getExceptionDecl()->getTypeSpecStartLoc(), 4580 diag::note_previous_exception_handler) 4581 << Problem->getCaughtType(); 4582 } 4583 } 4584 4585 FSI->setHasCXXTry(TryLoc); 4586 4587 return CXXTryStmt::Create(Context, TryLoc, cast<CompoundStmt>(TryBlock), 4588 Handlers); 4589 } 4590 4591 StmtResult Sema::ActOnSEHTryBlock(bool IsCXXTry, SourceLocation TryLoc, 4592 Stmt *TryBlock, Stmt *Handler) { 4593 assert(TryBlock && Handler); 4594 4595 sema::FunctionScopeInfo *FSI = getCurFunction(); 4596 4597 // SEH __try is incompatible with C++ try. Borland appears to support this, 4598 // however. 4599 if (!getLangOpts().Borland) { 4600 if (FSI->FirstCXXOrObjCTryLoc.isValid()) { 4601 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try) << FSI->FirstTryType; 4602 Diag(FSI->FirstCXXOrObjCTryLoc, diag::note_conflicting_try_here) 4603 << (FSI->FirstTryType == sema::FunctionScopeInfo::TryLocIsCXX 4604 ? "'try'" 4605 : "'@try'"); 4606 } 4607 } 4608 4609 FSI->setHasSEHTry(TryLoc); 4610 4611 // Reject __try in Obj-C methods, blocks, and captured decls, since we don't 4612 // track if they use SEH. 4613 DeclContext *DC = CurContext; 4614 while (DC && !DC->isFunctionOrMethod()) 4615 DC = DC->getParent(); 4616 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(DC); 4617 if (FD) 4618 FD->setUsesSEHTry(true); 4619 else 4620 Diag(TryLoc, diag::err_seh_try_outside_functions); 4621 4622 // Reject __try on unsupported targets. 4623 if (!Context.getTargetInfo().isSEHTrySupported()) 4624 Diag(TryLoc, diag::err_seh_try_unsupported); 4625 4626 return SEHTryStmt::Create(Context, IsCXXTry, TryLoc, TryBlock, Handler); 4627 } 4628 4629 StmtResult Sema::ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr, 4630 Stmt *Block) { 4631 assert(FilterExpr && Block); 4632 QualType FTy = FilterExpr->getType(); 4633 if (!FTy->isIntegerType() && !FTy->isDependentType()) { 4634 return StmtError( 4635 Diag(FilterExpr->getExprLoc(), diag::err_filter_expression_integral) 4636 << FTy); 4637 } 4638 return SEHExceptStmt::Create(Context, Loc, FilterExpr, Block); 4639 } 4640 4641 void Sema::ActOnStartSEHFinallyBlock() { 4642 CurrentSEHFinally.push_back(CurScope); 4643 } 4644 4645 void Sema::ActOnAbortSEHFinallyBlock() { 4646 CurrentSEHFinally.pop_back(); 4647 } 4648 4649 StmtResult Sema::ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block) { 4650 assert(Block); 4651 CurrentSEHFinally.pop_back(); 4652 return SEHFinallyStmt::Create(Context, Loc, Block); 4653 } 4654 4655 StmtResult 4656 Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) { 4657 Scope *SEHTryParent = CurScope; 4658 while (SEHTryParent && !SEHTryParent->isSEHTryScope()) 4659 SEHTryParent = SEHTryParent->getParent(); 4660 if (!SEHTryParent) 4661 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try)); 4662 CheckJumpOutOfSEHFinally(*this, Loc, *SEHTryParent); 4663 4664 return new (Context) SEHLeaveStmt(Loc); 4665 } 4666 4667 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc, 4668 bool IsIfExists, 4669 NestedNameSpecifierLoc QualifierLoc, 4670 DeclarationNameInfo NameInfo, 4671 Stmt *Nested) 4672 { 4673 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists, 4674 QualifierLoc, NameInfo, 4675 cast<CompoundStmt>(Nested)); 4676 } 4677 4678 4679 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, 4680 bool IsIfExists, 4681 CXXScopeSpec &SS, 4682 UnqualifiedId &Name, 4683 Stmt *Nested) { 4684 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists, 4685 SS.getWithLocInContext(Context), 4686 GetNameFromUnqualifiedId(Name), 4687 Nested); 4688 } 4689 4690 RecordDecl* 4691 Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, 4692 unsigned NumParams) { 4693 DeclContext *DC = CurContext; 4694 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext())) 4695 DC = DC->getParent(); 4696 4697 RecordDecl *RD = nullptr; 4698 if (getLangOpts().CPlusPlus) 4699 RD = CXXRecordDecl::Create(Context, TagTypeKind::Struct, DC, Loc, Loc, 4700 /*Id=*/nullptr); 4701 else 4702 RD = RecordDecl::Create(Context, TagTypeKind::Struct, DC, Loc, Loc, 4703 /*Id=*/nullptr); 4704 4705 RD->setCapturedRecord(); 4706 DC->addDecl(RD); 4707 RD->setImplicit(); 4708 RD->startDefinition(); 4709 4710 assert(NumParams > 0 && "CapturedStmt requires context parameter"); 4711 CD = CapturedDecl::Create(Context, CurContext, NumParams); 4712 DC->addDecl(CD); 4713 return RD; 4714 } 4715 4716 static bool 4717 buildCapturedStmtCaptureList(Sema &S, CapturedRegionScopeInfo *RSI, 4718 SmallVectorImpl<CapturedStmt::Capture> &Captures, 4719 SmallVectorImpl<Expr *> &CaptureInits) { 4720 for (const sema::Capture &Cap : RSI->Captures) { 4721 if (Cap.isInvalid()) 4722 continue; 4723 4724 // Form the initializer for the capture. 4725 ExprResult Init = S.BuildCaptureInit(Cap, Cap.getLocation(), 4726 RSI->CapRegionKind == CR_OpenMP); 4727 4728 // FIXME: Bail out now if the capture is not used and the initializer has 4729 // no side-effects. 4730 4731 // Create a field for this capture. 4732 FieldDecl *Field = S.BuildCaptureField(RSI->TheRecordDecl, Cap); 4733 4734 // Add the capture to our list of captures. 4735 if (Cap.isThisCapture()) { 4736 Captures.push_back(CapturedStmt::Capture(Cap.getLocation(), 4737 CapturedStmt::VCK_This)); 4738 } else if (Cap.isVLATypeCapture()) { 4739 Captures.push_back( 4740 CapturedStmt::Capture(Cap.getLocation(), CapturedStmt::VCK_VLAType)); 4741 } else { 4742 assert(Cap.isVariableCapture() && "unknown kind of capture"); 4743 4744 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) 4745 S.setOpenMPCaptureKind(Field, Cap.getVariable(), RSI->OpenMPLevel); 4746 4747 Captures.push_back(CapturedStmt::Capture( 4748 Cap.getLocation(), 4749 Cap.isReferenceCapture() ? CapturedStmt::VCK_ByRef 4750 : CapturedStmt::VCK_ByCopy, 4751 cast<VarDecl>(Cap.getVariable()))); 4752 } 4753 CaptureInits.push_back(Init.get()); 4754 } 4755 return false; 4756 } 4757 4758 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, 4759 CapturedRegionKind Kind, 4760 unsigned NumParams) { 4761 CapturedDecl *CD = nullptr; 4762 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams); 4763 4764 // Build the context parameter 4765 DeclContext *DC = CapturedDecl::castToDeclContext(CD); 4766 IdentifierInfo *ParamName = &Context.Idents.get("__context"); 4767 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD)); 4768 auto *Param = 4769 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType, 4770 ImplicitParamKind::CapturedContext); 4771 DC->addDecl(Param); 4772 4773 CD->setContextParam(0, Param); 4774 4775 // Enter the capturing scope for this captured region. 4776 PushCapturedRegionScope(CurScope, CD, RD, Kind); 4777 4778 if (CurScope) 4779 PushDeclContext(CurScope, CD); 4780 else 4781 CurContext = CD; 4782 4783 PushExpressionEvaluationContext( 4784 ExpressionEvaluationContext::PotentiallyEvaluated); 4785 ExprEvalContexts.back().InImmediateEscalatingFunctionContext = false; 4786 } 4787 4788 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, 4789 CapturedRegionKind Kind, 4790 ArrayRef<CapturedParamNameType> Params, 4791 unsigned OpenMPCaptureLevel) { 4792 CapturedDecl *CD = nullptr; 4793 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size()); 4794 4795 // Build the context parameter 4796 DeclContext *DC = CapturedDecl::castToDeclContext(CD); 4797 bool ContextIsFound = false; 4798 unsigned ParamNum = 0; 4799 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(), 4800 E = Params.end(); 4801 I != E; ++I, ++ParamNum) { 4802 if (I->second.isNull()) { 4803 assert(!ContextIsFound && 4804 "null type has been found already for '__context' parameter"); 4805 IdentifierInfo *ParamName = &Context.Idents.get("__context"); 4806 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD)) 4807 .withConst() 4808 .withRestrict(); 4809 auto *Param = 4810 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType, 4811 ImplicitParamKind::CapturedContext); 4812 DC->addDecl(Param); 4813 CD->setContextParam(ParamNum, Param); 4814 ContextIsFound = true; 4815 } else { 4816 IdentifierInfo *ParamName = &Context.Idents.get(I->first); 4817 auto *Param = 4818 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second, 4819 ImplicitParamKind::CapturedContext); 4820 DC->addDecl(Param); 4821 CD->setParam(ParamNum, Param); 4822 } 4823 } 4824 assert(ContextIsFound && "no null type for '__context' parameter"); 4825 if (!ContextIsFound) { 4826 // Add __context implicitly if it is not specified. 4827 IdentifierInfo *ParamName = &Context.Idents.get("__context"); 4828 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD)); 4829 auto *Param = 4830 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType, 4831 ImplicitParamKind::CapturedContext); 4832 DC->addDecl(Param); 4833 CD->setContextParam(ParamNum, Param); 4834 } 4835 // Enter the capturing scope for this captured region. 4836 PushCapturedRegionScope(CurScope, CD, RD, Kind, OpenMPCaptureLevel); 4837 4838 if (CurScope) 4839 PushDeclContext(CurScope, CD); 4840 else 4841 CurContext = CD; 4842 4843 PushExpressionEvaluationContext( 4844 ExpressionEvaluationContext::PotentiallyEvaluated); 4845 } 4846 4847 void Sema::ActOnCapturedRegionError() { 4848 DiscardCleanupsInEvaluationContext(); 4849 PopExpressionEvaluationContext(); 4850 PopDeclContext(); 4851 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(); 4852 CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get()); 4853 4854 RecordDecl *Record = RSI->TheRecordDecl; 4855 Record->setInvalidDecl(); 4856 4857 SmallVector<Decl*, 4> Fields(Record->fields()); 4858 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields, 4859 SourceLocation(), SourceLocation(), ParsedAttributesView()); 4860 } 4861 4862 StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) { 4863 // Leave the captured scope before we start creating captures in the 4864 // enclosing scope. 4865 DiscardCleanupsInEvaluationContext(); 4866 PopExpressionEvaluationContext(); 4867 PopDeclContext(); 4868 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(); 4869 CapturedRegionScopeInfo *RSI = cast<CapturedRegionScopeInfo>(ScopeRAII.get()); 4870 4871 SmallVector<CapturedStmt::Capture, 4> Captures; 4872 SmallVector<Expr *, 4> CaptureInits; 4873 if (buildCapturedStmtCaptureList(*this, RSI, Captures, CaptureInits)) 4874 return StmtError(); 4875 4876 CapturedDecl *CD = RSI->TheCapturedDecl; 4877 RecordDecl *RD = RSI->TheRecordDecl; 4878 4879 CapturedStmt *Res = CapturedStmt::Create( 4880 getASTContext(), S, static_cast<CapturedRegionKind>(RSI->CapRegionKind), 4881 Captures, CaptureInits, CD, RD); 4882 4883 CD->setBody(Res->getCapturedStmt()); 4884 RD->completeDefinition(); 4885 4886 return Res; 4887 } 4888