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