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