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