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