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