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