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