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