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