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