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