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