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