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