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