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