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