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