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"
43 using namespace clang;
64 DiscardCleanupsInEvaluationContext();
69 bool HasLeadingEmptyMacro) {
70 return new (Context)
NullStmt(SemiLoc, HasLeadingEmptyMacro);
80 return new (Context)
DeclStmt(DG, StartLoc, EndLoc);
98 Diag(
decl->getLocation(), diag::err_non_variable_decl_in_for);
99 decl->setInvalidDecl();
105 var->setInit(
nullptr);
110 if (getLangOpts().ObjCAutoRefCount) {
118 var->setType(
type.withConst());
119 var->setARCPseudoStrong(
true);
135 if (!Op->isComparisonOp())
138 if (Op->getOpcode() == BO_EQ)
140 else if (Op->getOpcode() == BO_NE)
142 else if (Op->getOpcode() == BO_Cmp)
145 assert(Op->isRelationalOp());
148 Loc = Op->getOperatorLoc();
149 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
151 switch (Op->getOperator()) {
155 case OO_ExclaimEqual:
160 case OO_GreaterEqual:
171 Loc = Op->getOperatorLoc();
172 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
183 S.
Diag(Loc, diag::warn_unused_comparison)
189 if (
Kind == Inequality)
190 S.
Diag(Loc, diag::note_inequality_comparison_to_or_assign)
193 S.
Diag(Loc, diag::note_equality_comparison_to_assign)
205 StringRef Msg = A->getMessage();
209 return S.
Diag(Loc, diag::warn_unused_constructor) << A << R1 << R2;
210 return S.
Diag(Loc, diag::warn_unused_result) << A << R1 << R2;
214 return S.
Diag(Loc, diag::warn_unused_constructor_msg) << A << Msg << R1
216 return S.
Diag(Loc, diag::warn_unused_result_msg) << A << Msg << R1 << R2;
221 return DiagnoseUnusedExprResult(
Label->getSubStmt(), DiagID);
223 const Expr *E = dyn_cast_or_null<Expr>(S);
229 if (isUnevaluatedContext())
238 bool ShouldSuppress =
239 SourceMgr.isMacroBodyExpansion(ExprLoc) ||
240 SourceMgr.isInSystemMacro(ExprLoc);
242 const Expr *WarnExpr;
260 if (findMacroSpelling(SpellLoc,
"UNREFERENCED_PARAMETER"))
267 if (
const FullExpr *Temps = dyn_cast<FullExpr>(E))
268 E = Temps->getSubExpr();
270 E = TempExpr->getSubExpr();
276 if (
const auto *
Cast = dyn_cast<CastExpr>(E))
277 if (
Cast->getCastKind() == CK_NoOp ||
278 Cast->getCastKind() == CK_ConstructorConversion)
279 E =
Cast->getSubExpr()->IgnoreImpCasts();
281 if (
const CallExpr *CE = dyn_cast<CallExpr>(E)) {
286 CE->getUnusedResultAttr(Context)),
294 if (
const Decl *FD = CE->getCalleeDecl()) {
297 if (FD->hasAttr<PureAttr>()) {
298 Diag(Loc, diag::warn_unused_call) << R1 << R2 <<
"pure";
301 if (FD->hasAttr<ConstAttr>()) {
302 Diag(Loc, diag::warn_unused_call) << R1 << R2 <<
"const";
306 }
else if (
const auto *CE = dyn_cast<CXXConstructExpr>(E)) {
308 const auto *A = Ctor->getAttr<WarnUnusedResultAttr>();
309 A = A ? A : Ctor->getParent()->getAttr<WarnUnusedResultAttr>();
313 }
else if (
const auto *ILE = dyn_cast<InitListExpr>(E)) {
314 if (
const TagDecl *TD = ILE->getType()->getAsTagDecl()) {
320 }
else if (ShouldSuppress)
325 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
326 Diag(Loc, diag::err_arc_unused_init_message) << R1;
336 const Expr *Source = POE->getSyntacticForm();
338 if (LangOpts.OpenMP && isa<CallExpr>(Source) &&
339 POE->getNumSemanticExprs() == 1 &&
340 isa<CallExpr>(POE->getSemanticExpr(0)))
341 return DiagnoseUnusedExprResult(POE->getSemanticExpr(0), DiagID);
342 if (isa<ObjCSubscriptRefExpr>(Source))
343 DiagID = diag::warn_unused_container_subscript_expr;
344 else if (isa<ObjCPropertyRefExpr>(Source))
345 DiagID = diag::warn_unused_property_expr;
347 = dyn_cast<CXXFunctionalCastExpr>(E)) {
348 const Expr *E = FC->getSubExpr();
350 E = TE->getSubExpr();
351 if (isa<CXXTemporaryObjectExpr>(E))
354 if (
const CXXRecordDecl *RD = CE->getType()->getAsCXXRecordDecl())
355 if (!RD->getAttr<WarnUnusedAttr>())
359 else if (
const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
367 Diag(Loc, diag::warn_unused_voidptr)
377 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
384 if (DiagID != diag::warn_unused_comma_left_operand || !isSFINAEContext())
385 DiagIfReachable(Loc, S ? llvm::makeArrayRef(S) : llvm::None,
386 PDiag(DiagID) << R1 << R2);
390 PushCompoundScope(IsStmtExpr);
394 if (getCurFPFeatures().isFPConstrained()) {
406 return getCurFunction()->CompoundScopes.back();
411 const unsigned NumElts = Elts.size();
416 const unsigned MixedDeclsCodeID = getLangOpts().C99
417 ? diag::warn_mixed_decls_code
418 : diag::ext_mixed_decls_code;
419 if (!getLangOpts().
CPlusPlus && !Diags.isIgnored(MixedDeclsCodeID, L)) {
423 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
427 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
431 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
439 if (NumElts != 0 && !CurrentInstantiationScope &&
440 getCurCompoundScope().HasEmptyLoopBodies) {
441 for (
unsigned i = 0; i != NumElts - 1; ++i)
442 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
453 if (DiagnoseUnexpandedParameterPack(Val.
get()))
458 if (getCurFunction()->SwitchStack.empty())
463 getCurFunction()->SwitchStack.back().getPointer()->getCond();
468 auto CheckAndFinish = [&](
Expr *E) {
472 if (getLangOpts().CPlusPlus11) {
481 if (!E->isValueDependent())
482 ER = VerifyIntegerConstantExpression(E, AllowFold);
484 ER = DefaultLvalueConversion(ER.
get());
486 ER = ImpCastExprToType(ER.
get(), CondType, CK_IntegralCast);
492 ExprResult Converted = CorrectDelayedTyposInExpr(
495 if (Converted.
get() == Val.
get())
496 Converted = CheckAndFinish(Val.
get());
504 assert((LHSVal.
isInvalid() || LHSVal.
get()) &&
"missing LHS value");
507 "missing RHS value");
509 if (getCurFunction()->SwitchStack.empty()) {
510 Diag(CaseLoc, diag::err_case_not_in_switch);
515 getCurFunction()->SwitchStack.back().setInt(
true);
520 CaseLoc, DotDotDotLoc, ColonLoc);
521 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(CS);
527 cast<CaseStmt>(S)->setSubStmt(SubStmt);
533 if (getCurFunction()->SwitchStack.empty()) {
534 Diag(DefaultLoc, diag::err_default_not_in_switch);
539 getCurFunction()->SwitchStack.back().getPointer()->addSwitchCase(DS);
548 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->
getDeclName();
556 Diag(IdentLoc, diag::warn_reserved_extern_symbol)
557 << TheDecl << static_cast<int>(Status);
578 for (
const auto *A : Attrs) {
579 if (A->getKind() == attr::MustTail) {
580 if (!checkAndRewriteMustTailAttr(SubStmt, *A)) {
583 setFunctionHasMustTail();
593 ProcessStmtAttributes(SubStmt, Attrs, SemanticAttrs);
594 if (!SemanticAttrs.empty())
595 return BuildAttributedStmt(Attrs.
Range.
getBegin(), SemanticAttrs, SubStmt);
610 if (!checkMustTailAttr(St, MTA))
616 auto IgnoreImplicitAsWritten = [](
Expr *E) ->
Expr * {
627 bool Sema::checkMustTailAttr(
const Stmt *St,
const Attr &MTA) {
628 assert(!CurContext->isDependentContext() &&
629 "musttail cannot be checked from a dependent context");
632 auto IgnoreParenImplicitAsWritten = [](
const Expr *E) ->
const Expr * {
638 const Expr *E = cast<ReturnStmt>(St)->getRetValue();
639 const auto *CE = dyn_cast_or_null<CallExpr>(IgnoreParenImplicitAsWritten(E));
646 if (
const auto *EWC = dyn_cast<ExprWithCleanups>(E)) {
647 if (EWC->cleanupsHaveSideEffects()) {
648 Diag(St->
getBeginLoc(), diag::err_musttail_needs_trivial_args) << &MTA;
659 ft_non_static_member,
660 ft_pointer_to_member,
661 } MemberType = ft_non_member;
666 } CallerType, CalleeType;
669 bool IsCallee) ->
bool {
670 if (isa<CXXConstructorDecl, CXXDestructorDecl>(CMD)) {
672 << IsCallee << isa<CXXDestructorDecl>(CMD);
674 Diag(CMD->getBeginLoc(), diag::note_musttail_structors_forbidden)
675 << isa<CXXDestructorDecl>(CMD);
680 Type.MemberType = FuncType::ft_static_member;
683 Type.MemberType = FuncType::ft_non_static_member;
689 const auto *CallerDecl = dyn_cast<FunctionDecl>(CurContext);
694 if (isa<BlockDecl>(CurContext))
696 else if (isa<ObjCMethodDecl>(CurContext))
700 Diag(St->
getBeginLoc(), diag::err_musttail_forbidden_from_this_context)
703 }
else if (
const auto *CMD = dyn_cast<CXXMethodDecl>(CurContext)) {
705 if (!GetMethodType(CMD, CallerType,
false))
713 const auto *CalleeBinOp = dyn_cast<BinaryOperator>(CalleeExpr);
715 ? CE->getCalleeDecl()->getBeginLoc()
720 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl())) {
722 if (!GetMethodType(CMD, CalleeType,
true))
724 }
else if (CalleeBinOp && CalleeBinOp->isPtrMemOp()) {
728 CalleeType.This =
QualType(MPT->getClass(), 0);
730 CalleeType.MemberType = FuncType::ft_pointer_to_member;
731 }
else if (isa<CXXPseudoDestructorExpr>(CalleeExpr)) {
743 if (!CalleeType.Func || !CallerType.Func) {
745 if (!CalleeType.Func && CE->getDirectCallee()) {
746 Diag(CE->getDirectCallee()->getBeginLoc(),
747 diag::note_musttail_fix_non_prototype);
749 if (!CallerType.Func)
750 Diag(CallerDecl->getBeginLoc(), diag::note_musttail_fix_non_prototype);
761 if (CallerType.Func->getCallConv() != CalleeType.Func->getCallConv()) {
762 if (
const auto *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl()))
764 <<
true << ND->getDeclName();
766 Diag(St->
getBeginLoc(), diag::err_musttail_callconv_mismatch) <<
false;
767 Diag(CalleeLoc, diag::note_musttail_callconv_mismatch)
774 if (CalleeType.Func->isVariadic() || CallerType.Func->isVariadic()) {
780 if (CallerType.This.isNull() != CalleeType.This.isNull()) {
781 if (
const auto *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
783 << CallerType.MemberType << CalleeType.MemberType <<
true
784 << ND->getDeclName();
785 Diag(CalleeLoc, diag::note_musttail_callee_defined_here)
786 << ND->getDeclName();
789 << CallerType.MemberType << CalleeType.MemberType <<
false;
794 auto CheckTypesMatch = [
this](FuncType CallerType, FuncType CalleeType,
804 unsigned Select) ->
bool {
812 if (!CallerType.This.isNull() &&
816 if (!DoTypesMatch(CallerType.Func->getReturnType(),
820 if (CallerType.Func->getNumParams() != CalleeType.Func->getNumParams()) {
822 << CalleeType.Func->getNumParams();
828 size_t N = CallerType.Func->getNumParams();
829 for (
size_t I = 0; I < N; I++) {
830 if (!DoTypesMatch(CalleeParams[I], CallerParams[I],
832 PD << static_cast<int>(I) + 1;
841 if (!CheckTypesMatch(CallerType, CalleeType, PD)) {
842 if (
const auto *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl()))
844 <<
true << ND->getDeclName();
860 CommaVisitor(
Sema &SemaRef) : Inherited(SemaRef.Context), SemaRef(SemaRef) {}
878 bool ConstevalOrNegatedConsteval =
882 Expr *CondExpr = Cond.
get().second;
883 assert((CondExpr || ConstevalOrNegatedConsteval) &&
884 "If statement: missing condition");
886 if (CondExpr && (getLangOpts().
C99 || getLangOpts().
CPlusPlus) &&
887 !Diags.isIgnored(diag::warn_comma_operator, CondExpr->
getExprLoc()))
888 CommaVisitor(*this).Visit(CondExpr);
890 if (!ConstevalOrNegatedConsteval && !elseStmt)
891 DiagnoseEmptyStmtBody(CondExpr->
getEndLoc(), thenStmt,
892 diag::warn_empty_if_body);
894 if (ConstevalOrNegatedConsteval ||
896 auto DiagnoseLikelihood = [&](
const Stmt *S) {
898 Diags.Report(A->getLocation(),
899 diag::warn_attribute_has_no_effect_on_compile_time_if)
900 << A << ConstevalOrNegatedConsteval << A->getRange();
902 diag::note_attribute_has_no_effect_on_compile_time_if_here)
903 << ConstevalOrNegatedConsteval
910 DiagnoseLikelihood(thenStmt);
911 DiagnoseLikelihood(elseStmt);
913 std::tuple<bool, const Attr *, const Attr *> LHC =
915 if (std::get<0>(LHC)) {
916 const Attr *ThenAttr = std::get<1>(LHC);
917 const Attr *ElseAttr = std::get<2>(LHC);
919 diag::warn_attributes_likelihood_ifstmt_conflict)
920 << ThenAttr << ThenAttr->
getRange();
921 Diags.Report(ElseAttr->
getLocation(), diag::note_conflicting_attribute)
922 << ElseAttr << ElseAttr->
getRange();
926 if (ConstevalOrNegatedConsteval) {
927 bool Immediate = isImmediateFunctionContext();
928 if (CurContext->isFunctionOrMethod()) {
931 if (FD && FD->isConsteval())
934 if (isUnevaluatedContext() || Immediate)
935 Diags.Report(IfLoc, diag::warn_consteval_if_always_true) << Immediate;
938 return BuildIfStmt(IfLoc, StatementKind, LParenLoc, InitStmt, Cond, RParenLoc,
939 thenStmt, ElseLoc, elseStmt);
952 isa<ObjCAvailabilityCheckExpr>(Cond.
get().second))
953 setFunctionHasBranchProtectedScope();
956 Cond.
get().first, Cond.
get().second, LParenLoc,
957 RParenLoc, thenStmt, ElseLoc, elseStmt);
961 struct CaseCompareFunctor {
962 bool operator()(
const std::pair<llvm::APSInt, CaseStmt*> &LHS,
964 return LHS.first < RHS;
966 bool operator()(
const std::pair<llvm::APSInt, CaseStmt*> &LHS,
967 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
968 return LHS.first < RHS.first;
971 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
972 return LHS < RHS.first;
979 static bool CmpCaseVals(
const std::pair<llvm::APSInt, CaseStmt*>& lhs,
980 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
981 if (lhs.first < rhs.first)
984 if (lhs.first == rhs.first &&
985 lhs.second->getCaseLoc() < rhs.second->getCaseLoc())
992 static bool CmpEnumVals(
const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
993 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
995 return lhs.first < rhs.first;
1000 static bool EqEnumVals(
const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
1001 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
1003 return lhs.first == rhs.first;
1009 if (
const auto *FE = dyn_cast<FullExpr>(E))
1010 E = FE->getSubExpr();
1011 while (
const auto *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
1012 if (ImpCast->getCastKind() != CK_IntegralCast)
break;
1013 E = ImpCast->getSubExpr();
1023 SwitchConvertDiagnoser(
Expr *Cond)
1029 return S.
Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
1034 return S.
Diag(Loc, diag::err_switch_incomplete_class_type)
1040 return S.
Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
1051 return S.
Diag(Loc, diag::err_switch_multiple_conversions) << T;
1062 llvm_unreachable(
"conversion functions are permitted");
1064 } SwitchDiagnoser(Cond);
1067 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
1073 Cond = CondResult.
get();
1079 return UsualUnaryConversions(Cond);
1086 Expr *CondExpr = Cond.
get().second;
1087 assert((Cond.
isInvalid() || CondExpr) &&
"switch with no condition");
1100 Diag(SwitchLoc, diag::warn_bool_switch_condition)
1105 setFunctionHasBranchIntoScope();
1108 LParenLoc, RParenLoc);
1109 getCurFunction()->SwitchStack.push_back(
1115 Val = Val.extOrTrunc(BitWidth);
1116 Val.setIsSigned(IsSigned);
1122 unsigned UnpromotedWidth,
bool UnpromotedSign) {
1130 if (UnpromotedWidth < Val.getBitWidth()) {
1132 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign);
1133 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned());
1138 S.
Diag(Loc, diag::warn_case_value_overflow) <<
toString(Val, 10)
1149 const Expr *CaseExpr,
1150 EnumValsTy::iterator &EI,
1151 EnumValsTy::iterator &EIEnd,
1158 if (
const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
1167 if (ED->
hasAttr<FlagEnumAttr>())
1170 while (EI != EIEnd && EI->first < Val)
1173 if (EI != EIEnd && EI->first == Val)
1186 if (!CondEnumType || !CaseEnumType)
1193 if (!CaseEnumType->getDecl()->getIdentifier() &&
1194 !CaseEnumType->getDecl()->getTypedefNameForAnonDecl())
1200 S.
Diag(Case->
getExprLoc(), diag::warn_comparison_of_mixed_enum_types_switch)
1209 bool CaseListIsIncomplete = getCurFunction()->SwitchStack.back().getInt();
1210 assert(SS == getCurFunction()->SwitchStack.back().getPointer() &&
1211 "switch stack missing push/pop!");
1213 getCurFunction()->SwitchStack.pop_back();
1216 SS->
setBody(BodyStmt, SwitchLoc);
1230 const Expr *CondExprBeforePromotion = CondExpr;
1236 bool HasDependentValue
1238 unsigned CondWidth = HasDependentValue ? 0 : Context.
getIntWidth(CondType);
1245 unsigned CondWidthBeforePromotion
1246 = HasDependentValue ? 0 : Context.
getIntWidth(CondTypeBeforePromotion);
1247 bool CondIsSignedBeforePromotion
1254 CaseValsTy CaseVals;
1257 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
1258 CaseRangesTy CaseRanges;
1262 bool CaseListIsErroneous =
false;
1267 if (
DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
1268 if (TheDefaultStmt) {
1269 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
1276 CaseListIsErroneous =
true;
1278 TheDefaultStmt = DS;
1286 HasDependentValue =
true;
1292 const Expr *LoBeforePromotion = Lo;
1299 CondIsSignedBeforePromotion);
1311 HasDependentValue =
true;
1314 CaseRanges.push_back(std::make_pair(LoVal, CS));
1316 CaseVals.push_back(std::make_pair(LoVal, CS));
1320 if (!HasDependentValue) {
1324 bool HasConstantCond =
false;
1325 if (!TheDefaultStmt) {
1329 if (Result.Val.isInt())
1330 ConstantCondValue = Result.Val.getInt();
1331 assert(!HasConstantCond ||
1332 (ConstantCondValue.getBitWidth() == CondWidth &&
1333 ConstantCondValue.isSigned() == CondIsSigned));
1335 bool ShouldCheckConstantCond = HasConstantCond;
1340 if (!CaseVals.empty()) {
1341 for (
unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
1342 if (ShouldCheckConstantCond &&
1343 CaseVals[i].first == ConstantCondValue)
1344 ShouldCheckConstantCond =
false;
1346 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
1349 StringRef PrevString, CurrString;
1352 if (
DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
1353 PrevString = DeclRef->getDecl()->getName();
1355 if (
DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
1356 CurrString = DeclRef->getDecl()->getName();
1359 CaseVals[i-1].first.toString(CaseValStr);
1361 if (PrevString == CurrString)
1362 Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
1363 diag::err_duplicate_case)
1364 << (PrevString.empty() ? CaseValStr.str() : PrevString);
1366 Diag(CaseVals[i].second->getLHS()->getBeginLoc(),
1367 diag::err_duplicate_case_differing_expr)
1368 << (PrevString.empty() ? CaseValStr.str() : PrevString)
1369 << (CurrString.empty() ? CaseValStr.str() : CurrString)
1372 Diag(CaseVals[i - 1].second->getLHS()->getBeginLoc(),
1373 diag::note_duplicate_case_prev);
1376 CaseListIsErroneous =
true;
1383 if (!CaseRanges.empty()) {
1386 llvm::stable_sort(CaseRanges);
1389 std::vector<llvm::APSInt> HiVals;
1390 for (
unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1392 CaseStmt *CR = CaseRanges[i].second;
1395 const Expr *HiBeforePromotion = Hi;
1402 CondWidthBeforePromotion, CondIsSignedBeforePromotion);
1408 if (LoVal > HiVal) {
1411 CaseRanges.erase(CaseRanges.begin()+i);
1417 if (ShouldCheckConstantCond &&
1418 LoVal <= ConstantCondValue &&
1419 ConstantCondValue <= HiVal)
1420 ShouldCheckConstantCond =
false;
1422 HiVals.push_back(HiVal);
1428 for (
unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
1431 CaseStmt *CR = CaseRanges[i].second;
1440 CaseValsTy::iterator I =
1441 llvm::lower_bound(CaseVals, CRLo, CaseCompareFunctor());
1442 if (I != CaseVals.end() && I->first < CRHi) {
1443 OverlapVal = I->first;
1444 OverlapStmt = I->second;
1448 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
1449 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
1450 OverlapVal = (I-1)->first;
1451 OverlapStmt = (I-1)->second;
1456 if (i && CRLo <= HiVals[i-1]) {
1457 OverlapVal = HiVals[i-1];
1458 OverlapStmt = CaseRanges[i-1].second;
1466 diag::note_duplicate_case_prev);
1469 CaseListIsErroneous =
true;
1475 if (!CaseListIsErroneous && !CaseListIsIncomplete &&
1476 ShouldCheckConstantCond) {
1479 Diag(CondExpr->
getExprLoc(), diag::warn_missing_case_for_condition)
1492 if (!CaseListIsErroneous && !CaseListIsIncomplete && !HasConstantCond &&
1503 EnumVals.push_back(std::make_pair(Val, EDI));
1506 auto EI = EnumVals.begin(), EIEnd =
1507 std::unique(EnumVals.begin(), EnumVals.end(),
EqEnumVals);
1510 for (CaseValsTy::const_iterator CI = CaseVals.begin();
1511 CI != CaseVals.end(); CI++) {
1512 Expr *CaseExpr = CI->second->getLHS();
1516 << CondTypeBeforePromotion;
1520 EI = EnumVals.begin();
1521 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1522 RI != CaseRanges.end(); RI++) {
1523 Expr *CaseExpr = RI->second->getLHS();
1527 << CondTypeBeforePromotion;
1530 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1533 CaseExpr = RI->second->getRHS();
1537 << CondTypeBeforePromotion;
1541 auto CI = CaseVals.begin();
1542 auto RI = CaseRanges.begin();
1543 bool hasCasesNotInSwitch =
false;
1547 for (EI = EnumVals.begin(); EI != EIEnd; EI++) {
1549 switch (EI->second->getAvailability()) {
1562 if (EI->second->hasAttr<UnusedAttr>())
1566 while (CI != CaseVals.end() && CI->first < EI->first)
1569 if (CI != CaseVals.end() && CI->first == EI->first)
1573 for (; RI != CaseRanges.end(); RI++) {
1575 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1577 if (EI->first <= Hi)
1581 if (RI == CaseRanges.end() || EI->first < RI->first) {
1582 hasCasesNotInSwitch =
true;
1583 UnhandledNames.push_back(EI->second->getDeclName());
1587 if (TheDefaultStmt && UnhandledNames.empty() && ED->
isClosedNonFlag())
1591 if (!UnhandledNames.empty()) {
1593 ? diag::warn_def_missing_case
1594 : diag::warn_missing_case)
1597 for (
size_t I = 0, E =
std::min(UnhandledNames.size(), (
size_t)3);
1599 DB << UnhandledNames[I];
1602 if (!hasCasesNotInSwitch)
1608 DiagnoseEmptyStmtBody(CondExpr->
getEndLoc(), BodyStmt,
1609 diag::warn_empty_switch_body);
1613 if (CaseListIsErroneous)
1622 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->
getExprLoc()))
1636 const EnumDecl *ED = ET->getDecl();
1641 if (ED->
hasAttr<FlagEnumAttr>()) {
1642 if (!IsValueInFlagEnum(ED, RhsVal,
true))
1655 EnumVals.push_back(std::make_pair(Val, EDI));
1657 if (EnumVals.empty())
1660 EnumValsTy::iterator EIend =
1661 std::unique(EnumVals.begin(), EnumVals.end(),
EqEnumVals);
1664 EnumValsTy::const_iterator EI = EnumVals.begin();
1665 while (EI != EIend && EI->first < RhsVal)
1667 if (EI == EIend || EI->first != RhsVal) {
1682 auto CondVal = Cond.
get();
1683 CheckBreakContinueBinding(CondVal.second);
1685 if (CondVal.second &&
1686 !Diags.isIgnored(diag::warn_comma_operator, CondVal.second->getExprLoc()))
1687 CommaVisitor(*this).Visit(CondVal.second);
1689 if (isa<NullStmt>(Body))
1690 getCurCompoundScope().setHasEmptyLoopBodies();
1693 WhileLoc, LParenLoc, RParenLoc);
1700 assert(Cond &&
"ActOnDoStmt(): missing expression");
1702 CheckBreakContinueBinding(Cond);
1703 ExprResult CondResult = CheckBooleanCondition(DoLoc, Cond);
1706 Cond = CondResult.
get();
1708 CondResult = ActOnFinishFullExpr(Cond, DoLoc,
false);
1711 Cond = CondResult.
get();
1714 if (Cond && !getLangOpts().
C99 && !getLangOpts().
CPlusPlus &&
1715 !Diags.isIgnored(diag::warn_comma_operator, Cond->
getExprLoc()))
1716 CommaVisitor(*this).Visit(Cond);
1718 return new (Context)
DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
1723 using DeclSetVector =
1724 llvm::SetVector<VarDecl *, llvm::SmallVector<VarDecl *, 8>,
1731 DeclSetVector &Decls;
1737 DeclExtractor(
Sema &S, DeclSetVector &Decls,
1739 Inherited(S.Context),
1744 bool isSimple() {
return Simple; }
1812 DeclSetVector &Decls;
1818 DeclMatcher(
Sema &S, DeclSetVector &Decls,
Stmt *Statement) :
1819 Inherited(S.Context), Decls(Decls), FoundDecl(
false) {
1820 if (!Statement)
return;
1844 void CheckLValueToRValueCast(
Expr *E) {
1847 if (isa<DeclRefExpr>(E)) {
1852 Visit(CO->getCond());
1853 CheckLValueToRValueCast(CO->getTrueExpr());
1854 CheckLValueToRValueCast(CO->getFalseExpr());
1859 dyn_cast<BinaryConditionalOperator>(E)) {
1860 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1861 CheckLValueToRValueCast(BCO->getFalseExpr());
1870 if (Decls.count(VD))
1878 if (
auto *OVE = dyn_cast<OpaqueValueExpr>(S))
1880 Visit(OVE->getSourceExpr());
1886 bool FoundDeclInUse() {
return FoundDecl; }
1890 void CheckForLoopConditionalStatement(
Sema &S,
Expr *Second,
1893 if (!Second)
return;
1900 DeclSetVector Decls;
1902 DeclExtractor DE(S, Decls, Ranges);
1906 if (!DE.isSimple())
return;
1909 if (Decls.size() == 0)
return;
1912 for (
auto *VD : Decls)
1916 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1917 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1918 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1922 if (Decls.size() > 4) {
1926 for (
auto *VD : Decls)
1930 for (
auto Range : Ranges)
1933 S.
Diag(Ranges.begin()->getBegin(), PDiag);
1938 bool ProcessIterationStmt(
Sema &S,
Stmt* Statement,
bool &Increment,
1940 if (
auto Cleanups = dyn_cast<ExprWithCleanups>(Statement))
1941 if (!Cleanups->cleanupsHaveSideEffects())
1944 if (
UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1945 switch (UO->getOpcode()) {
1946 default:
return false;
1956 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1964 default:
return false;
1972 DRE = dyn_cast<DeclRefExpr>(
Call->getArg(0));
1984 bool InSwitch =
false;
1987 BreakContinueFinder(
Sema &S,
const Stmt* Body) :
1988 Inherited(S.Context) {
1998 void VisitBreakStmt(
const BreakStmt* E) {
2004 if (
const Stmt *Init = S->getInit())
2006 if (
const Stmt *CondVar = S->getConditionVariableDeclStmt())
2008 if (
const Stmt *Cond = S->getCond())
2013 if (
const Stmt *Body = S->getBody())
2018 void VisitForStmt(
const ForStmt *S) {
2021 if (
const Stmt *Init = S->getInit())
2025 void VisitWhileStmt(
const WhileStmt *) {
2030 void VisitDoStmt(
const DoStmt *) {
2038 if (
const Stmt *Init = S->getInit())
2040 if (
const Stmt *Range = S->getRangeStmt())
2042 if (
const Stmt *
Begin = S->getBeginStmt())
2044 if (
const Stmt *
End = S->getEndStmt())
2051 if (
const Stmt *Element = S->getElement())
2053 if (
const Stmt *Collection = S->getCollection())
2057 bool ContinueFound() {
return ContinueLoc.
isValid(); }
2058 bool BreakFound() {
return BreakLoc.
isValid(); }
2069 void CheckForRedundantIteration(
Sema &S,
Expr *Third,
Stmt *Body) {
2071 if (!Body || !Third)
return;
2081 if (!LastStmt)
return;
2083 bool LoopIncrement, LastIncrement;
2086 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE))
return;
2087 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE))
return;
2091 if (LoopIncrement != LastIncrement ||
2094 if (BreakContinueFinder(S, Body).ContinueFound())
return;
2097 << LastDRE->
getDecl() << LastIncrement;
2105 void Sema::CheckBreakContinueBinding(
Expr *E) {
2108 BreakContinueFinder BCFinder(*
this, E);
2110 if (BCFinder.BreakFound() && BreakParent) {
2112 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
2114 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
2117 }
else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
2118 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
2135 const Decl *NonVarSeen =
nullptr;
2136 bool VarDeclSeen =
false;
2137 for (
auto *DI : DS->decls()) {
2138 if (
VarDecl *VD = dyn_cast<VarDecl>(DI)) {
2141 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
2142 DI->setInvalidDecl();
2144 }
else if (!NonVarSeen) {
2154 if (NonVarSeen && !VarDeclSeen)
2159 CheckBreakContinueBinding(Second.
get().second);
2160 CheckBreakContinueBinding(third.
get());
2162 if (!Second.
get().first)
2163 CheckForLoopConditionalStatement(*
this, Second.
get().second, third.
get(),
2165 CheckForRedundantIteration(*
this, third.
get(), Body);
2167 if (Second.
get().second &&
2168 !Diags.isIgnored(diag::warn_comma_operator,
2169 Second.
get().second->getExprLoc()))
2170 CommaVisitor(*this).Visit(Second.
get().second);
2173 if (isa<NullStmt>(Body))
2174 getCurCompoundScope().setHasEmptyLoopBodies();
2176 return new (Context)
2178 Body, ForLoc, LParenLoc, RParenLoc);
2203 ExprResult result = CorrectDelayedTyposInExpr(collection);
2206 collection = result.
get();
2212 result = DefaultFunctionArrayLvalueConversion(collection);
2215 collection = result.
get();
2222 return Diag(forLoc, diag::err_collection_expr_type)
2233 (getLangOpts().ObjCAutoRefCount
2234 ? RequireCompleteType(forLoc,
QualType(objectType, 0),
2235 diag::err_arc_collection_forward, collection)
2236 : !isCompleteType(forLoc,
QualType(objectType, 0)))) {
2239 }
else if (iface || !objectType->
qual_empty()) {
2241 &Context.
Idents.
get(
"countByEnumeratingWithState"),
2257 method = LookupMethodInQualifiedType(selector,
pointerType,
2262 Diag(forLoc, diag::warn_collection_expr_type)
2277 setFunctionHasBranchProtectedScope();
2280 CheckObjCForCollectionOperand(ForLoc, collection);
2285 if (!DS->isSingleDecl())
2287 diag::err_toomany_element_decls));
2289 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
2299 diag::err_non_local_variable_decl_in_for));
2305 Expr *DeducedInit = &OpaqueId;
2308 DiagnoseAutoDeductionFailure(D, DeducedInit);
2309 if (FirstType.
isNull()) {
2316 if (!inTemplateInstantiation()) {
2319 Diag(Loc, diag::warn_auto_var_is_id)
2328 Diag(
First->getBeginLoc(), diag::err_selector_element_not_lvalue)
2329 <<
First->getSourceRange());
2331 FirstType =
static_cast<Expr*
>(
First)->getType();
2333 Diag(ForLoc, diag::err_selector_element_const_type)
2334 << FirstType <<
First->getSourceRange();
2339 return StmtError(
Diag(ForLoc, diag::err_selector_element_type)
2340 << FirstType <<
First->getSourceRange());
2346 CollectionExprResult =
2347 ActOnFinishFullExpr(CollectionExprResult.
get(),
false);
2352 nullptr, ForLoc, RParenLoc);
2359 if (
Decl->getType()->isUndeducedType()) {
2371 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
2374 SemaRef.
Diag(Loc, DiagID) << Init->getType();
2379 Decl->setType(InitType);
2397 enum BeginEndFunction {
2406 void NoteForRangeBeginEndFunction(
Sema &SemaRef,
Expr *E,
2407 BeginEndFunction BEF) {
2408 CallExpr *CE = dyn_cast<CallExpr>(E);
2417 bool IsTemplate =
false;
2424 SemaRef.
Diag(Loc, diag::note_for_range_begin_end)
2425 << BEF << IsTemplate << Description << E->
getType();
2477 return Diag(InitStmt->
getBeginLoc(), diag::err_objc_for_range_init_stmt)
2479 return ActOnObjCForCollectionStmt(ForLoc,
First, Range, RParenLoc);
2483 assert(DS &&
"first part of for range not a decl stmt");
2494 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
2495 ActOnInitializerError(LoopVar);
2502 if (!ActOnCoroutineBodyStart(S, CoawaitLoc,
"co_await")) {
2503 ActOnInitializerError(LoopVar);
2510 const auto DepthStr = std::to_string(S->getDepth() / 2);
2512 VarDecl *RangeVar = BuildForRangeVarDecl(*
this, RangeLoc,
2516 diag::err_for_range_deduction_failure)) {
2517 ActOnInitializerError(LoopVar);
2524 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
2526 ActOnInitializerError(LoopVar);
2531 ForLoc, CoawaitLoc, InitStmt, ColonLoc, RangeDecl.
get(),
2533 nullptr,
nullptr, DS, RParenLoc,
Kind);
2535 ActOnInitializerError(LoopVar);
2556 ExprResult *EndExpr, BeginEndFunction *BEF) {
2566 auto BuildBegin = [&] {
2570 BeginMemberLookup, CandidateSet,
2571 BeginRange, BeginExpr);
2576 << ColonLoc << BEF_begin << BeginRange->
getType();
2589 diag::err_for_range_iter_deduction_failure)) {
2590 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->
get(), *BEF);
2596 auto BuildEnd = [&] {
2600 EndMemberLookup, CandidateSet,
2605 << ColonLoc << BEF_end << EndRange->
getType();
2609 diag::err_for_range_iter_deduction_failure)) {
2610 NoteForRangeBeginEndFunction(SemaRef, EndExpr->
get(), *BEF);
2630 if (BeginMemberLookup.
empty() != EndMemberLookup.
empty()) {
2635 auto BuildNonmember = [&](
2645 switch (BuildFound()) {
2652 SemaRef.
PDiag(diag::err_for_range_invalid)
2653 << BeginRange->
getType() << BEFFound),
2660 diag::note_for_range_member_begin_end_ignored)
2661 << BeginRange->
getType() << BEFFound;
2665 llvm_unreachable(
"unexpected ForRangeStatus");
2667 if (BeginMemberLookup.
empty())
2668 return BuildNonmember(BEF_end, EndMemberLookup, BuildEnd, BuildBegin);
2669 return BuildNonmember(BEF_begin, BeginMemberLookup, BuildBegin, BuildEnd);
2701 AdjustedRange = SemaRef.
BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2706 S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2715 SemaRef.
Diag(RangeLoc, diag::err_for_range_dereference)
2718 S, ForLoc, CoawaitLoc, InitStmt, LoopVarDecl, ColonLoc,
2739 Scope *S = getCurScope();
2741 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2745 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2759 if (
auto *DD = dyn_cast<DecompositionDecl>(LoopVar))
2760 for (
auto *Binding : DD->bindings())
2764 }
else if (!BeginDeclStmt.
get()) {
2769 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2774 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2783 QualType RangeType = Range->getType();
2785 if (RequireCompleteType(RangeLoc, RangeType,
2786 diag::err_for_range_incomplete_type))
2791 const auto DepthStr = std::to_string(S->getDepth() / 2);
2806 BeginExpr = BeginRangeRef;
2808 BeginExpr = ActOnCoawaitExpr(S, ColonLoc, BeginExpr.
get());
2813 diag::err_for_range_iter_deduction_failure)) {
2814 NoteForRangeBeginEndFunction(*
this, BeginExpr.
get(), BEF_begin);
2824 dyn_cast<VariableArrayType>(UnqAT)) {
2847 ExprResult SizeOfVLAExprR = ActOnUnaryExprOrTypeTraitExpr(
2851 VAT->desugar(), RangeLoc))
2857 ExprResult SizeOfEachElementExprR = ActOnUnaryExprOrTypeTraitExpr(
2860 CreateParsedType(VAT->desugar(),
2862 VAT->getElementType(), RangeLoc))
2870 SizeOfVLAExprR.
get(), SizeOfEachElementExprR.
get());
2877 llvm_unreachable(
"Unexpected array type in for-range");
2881 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.
get(),
2886 diag::err_for_range_iter_deduction_failure)) {
2887 NoteForRangeBeginEndFunction(*
this, EndExpr.
get(), BEF_end);
2893 BeginEndFunction BEFFailure;
2895 *
this, BeginRangeRef.
get(), EndRangeRef.
get(), RangeType, BeginVar,
2896 EndVar, ColonLoc, CoawaitLoc, &CandidateSet, &BeginExpr, &EndExpr,
2899 if (
Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2900 BEFFailure == BEF_begin) {
2903 if (
DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2905 QualType ArrayTy = PVD->getOriginalType();
2906 QualType PointerTy = PVD->getType();
2908 Diag(Range->getBeginLoc(), diag::err_range_on_array_parameter)
2909 << RangeLoc << PVD << ArrayTy << PointerTy;
2910 Diag(PVD->getLocation(), diag::note_declared_at);
2919 CoawaitLoc, InitStmt,
2920 LoopVarDecl, ColonLoc,
2928 if (RangeStatus == FRS_NoViableFunction) {
2929 Expr *Range = BEFFailure ? EndRangeRef.
get() : BeginRangeRef.
get();
2932 PDiag(diag::err_for_range_invalid)
2933 << RangeLoc << Range->getType()
2938 if (RangeStatus != FRS_Success)
2943 "invalid range expression in for loop");
2950 ? diag::warn_for_range_begin_end_types_differ
2951 : diag::ext_for_range_begin_end_types_differ)
2952 << BeginType << EndType;
2953 NoteForRangeBeginEndFunction(*
this, BeginExpr.
get(), BEF_begin);
2954 NoteForRangeBeginEndFunction(*
this, EndExpr.
get(), BEF_end);
2958 ActOnDeclStmt(ConvertDeclToDeclGroup(BeginVar), ColonLoc, ColonLoc);
2960 ActOnDeclStmt(ConvertDeclToDeclGroup(EndVar), ColonLoc, ColonLoc);
2963 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2968 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2974 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2975 BeginRef.
get(), EndRef.
get());
2977 NotEqExpr = CheckBooleanCondition(ColonLoc, NotEqExpr.
get());
2980 ActOnFinishFullExpr(NotEqExpr.
get(),
false);
2982 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2983 << RangeLoc << 0 << BeginRangeRef.
get()->
getType();
2984 NoteForRangeBeginEndFunction(*
this, BeginExpr.
get(), BEF_begin);
2986 NoteForRangeBeginEndFunction(*
this, EndExpr.
get(), BEF_end);
2991 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2996 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.
get());
2997 if (!IncrExpr.isInvalid() && CoawaitLoc.
isValid())
3001 IncrExpr = ActOnCoawaitExpr(S, CoawaitLoc, IncrExpr.get());
3002 if (!IncrExpr.isInvalid())
3003 IncrExpr = ActOnFinishFullExpr(IncrExpr.get(),
false);
3004 if (IncrExpr.isInvalid()) {
3005 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
3006 << RangeLoc << 2 << BeginRangeRef.
get()->
getType() ;
3007 NoteForRangeBeginEndFunction(*
this, BeginExpr.
get(), BEF_begin);
3012 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
3017 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.
get());
3019 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
3020 << RangeLoc << 1 << BeginRangeRef.
get()->
getType();
3021 NoteForRangeBeginEndFunction(*
this, BeginExpr.
get(), BEF_begin);
3028 AddInitializerToDecl(LoopVar, DerefExpr.
get(),
false);
3031 NoteForRangeBeginEndFunction(*
this, BeginExpr.
get(), BEF_begin);
3037 if (
Kind == BFRK_Check)
3042 if (getLangOpts().OpenMP >= 50 && BeginDeclStmt.
isUsable())
3043 ActOnOpenMPLoopInitialization(ForLoc, BeginDeclStmt.
get());
3046 InitStmt, RangeDS, cast_or_null<DeclStmt>(BeginDeclStmt.
get()),
3047 cast_or_null<DeclStmt>(EndDeclStmt.
get()), NotEqExpr.
get(),
3048 IncrExpr.get(), LoopVarDS,
nullptr, ForLoc, CoawaitLoc,
3049 ColonLoc, RParenLoc);
3079 if (
auto Cleanups = dyn_cast<ExprWithCleanups>(InitExpr))
3080 if (!Cleanups->cleanupsHaveSideEffects())
3081 InitExpr = Cleanups->getSubExpr();
3084 dyn_cast<MaterializeTemporaryExpr>(InitExpr);
3094 while (!isa<CXXOperatorCallExpr>(E) && !isa<UnaryOperator>(E)) {
3098 const MemberExpr *ME = cast<MemberExpr>(Call->getCallee());
3108 if (isa<UnaryOperator>(E)) {
3115 ReferenceReturnType = ReturnType;
3118 if (!ReferenceReturnType.
isNull()) {
3123 diag::warn_for_range_const_ref_binds_temp_built_from_ref)
3124 << VD << VariableType << ReferenceReturnType;
3137 SemaRef.
Diag(VD->
getLocation(), diag::warn_for_range_ref_binds_ret_temp)
3138 << VD << RangeInitType;
3151 return RD->hasAttr<TrivialABIAttr>();
3168 if (!CE->getConstructor()->isCopyConstructor())
3170 }
else if (
const CastExpr *CE = dyn_cast<CastExpr>(InitExpr)) {
3171 if (CE->getCastKind() != CK_LValueToRValue)
3189 << VD << VariableType;
3210 diag::warn_for_range_const_ref_binds_temp_built_from_ref,
3237 ForStmt->getRangeInit()->getType());
3251 if (isa<ObjCForCollectionStmt>(S))
3252 return FinishObjCForCollectionStmt(S, B);
3258 diag::warn_empty_range_based_for_body);
3268 setFunctionHasBranchIntoScope();
3270 return new (Context)
GotoStmt(TheDecl, GotoLoc, LabelLoc);
3282 CheckSingleAssignmentConstraints(DestTy, ExprRes);
3286 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
3290 ExprResult ExprRes = ActOnFinishFullExpr(E,
false);
3295 setFunctionHasIndirectGoto();
3301 const Scope &DestScope) {
3304 S.
Diag(Loc, diag::warn_jump_out_of_seh_finally);
3313 return StmtError(
Diag(ContinueLoc, diag::err_continue_not_in_loop));
3315 if (S->isConditionVarScope()) {
3319 return StmtError(
Diag(ContinueLoc, diag::err_continue_from_cond_var_init));
3331 return StmtError(
Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
3333 if (S->isOpenMPLoopScope())
3334 return StmtError(
Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
3338 return new (Context)
BreakStmt(BreakLoc);
3361 const auto *DR = dyn_cast<DeclRefExpr>(E->
IgnoreParens());
3362 if (!DR || DR->refersToEnclosingVariableOrCapture())
3364 const auto *VD = dyn_cast<VarDecl>(DR->getDecl());
3369 (Mode == SimplerImplicitMoveMode::ForceOn ||
3370 (Mode != SimplerImplicitMoveMode::ForceOff &&
3388 NamedReturnInfo Info{VD, NamedReturnInfo::MoveEligibleAndCopyElidable};
3393 if (VD->
getKind() == Decl::ParmVar)
3394 Info.S = NamedReturnInfo::MoveEligible;
3395 else if (VD->
getKind() != Decl::Var)
3400 Info.S = NamedReturnInfo::MoveEligible;
3408 if (VD->
hasAttr<BlocksAttr>())
3425 Info.S = NamedReturnInfo::MoveEligible;
3434 Info.S = NamedReturnInfo::MoveEligible;
3453 auto invalidNRVO = [&] {
3462 if ((ReturnType->
getTypeClass() == Type::TypeClass::Auto &&
3465 return invalidNRVO();
3471 return invalidNRVO();
3478 Info.
S = NamedReturnInfo::MoveEligible;
3491 const auto *Step = llvm::find_if(Seq.
steps(), [](
const auto &Step) {
3492 return Step.Kind == InitializationSequence::SK_ConstructorInitialization ||
3493 Step.Kind == InitializationSequence::SK_UserConversion;
3496 const auto *FD = Step->Function.Function;
3497 if (isa<CXXConstructorDecl>(FD)
3499 : cast<CXXMethodDecl>(FD)->getRefQualifier() ==
RQ_None)
3513 bool SupressSimplerImplicitMoves) {
3515 (!getLangOpts().
CPlusPlus2b || SupressSimplerImplicitMoves) &&
3519 Expr *InitExpr = &AsRvalue;
3521 Value->getBeginLoc());
3557 bool SupressSimplerImplicitMoves) {
3563 bool HasDeducedReturnType =
3566 if (ExprEvalContexts.back().isDiscardedStatementContext() &&
3570 ActOnFinishFullExpr(RetValExp, ReturnLoc,
false);
3573 RetValExp = ER.
get();
3579 if (HasDeducedReturnType) {
3592 assert(AT &&
"lost auto type from lambda return type");
3593 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
3604 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
3605 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
3606 if (Result.isInvalid())
3608 RetValExp = Result.get();
3614 if (!CurContext->isDependentContext())
3623 Diag(ReturnLoc, diag::err_lambda_return_init_list)
3627 FnRetType = Context.
VoidTy;
3635 const VarDecl *NRVOCandidate = getCopyElisionCandidate(NRInfo, FnRetType);
3637 if (
auto *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
3639 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
3642 }
else if (
auto *CurRegion = dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
3643 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
3646 assert(CurLambda &&
"unknown kind of captured scope");
3650 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
3662 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
3668 Diag(ReturnLoc, diag::ext_return_has_void_expr) <<
"literal" << 2;
3670 Diag(ReturnLoc, diag::err_return_block_has_expr);
3671 RetValExp =
nullptr;
3674 }
else if (!RetValExp) {
3675 return StmtError(
Diag(ReturnLoc, diag::err_block_return_missing_expr));
3687 ExprResult Res = PerformMoveOrCopyInitialization(
3688 Entity, NRInfo, RetValExp, SupressSimplerImplicitMoves);
3693 RetValExp = Res.
get();
3694 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
3699 ActOnFinishFullExpr(RetValExp, ReturnLoc,
false);
3702 RetValExp = ER.
get();
3711 FunctionScopes.back()->Returns.push_back(Result);
3713 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
3714 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
3732 class LocalTypedefNameReferencer
3735 LocalTypedefNameReferencer(
Sema &S) : S(S) {}
3740 bool LocalTypedefNameReferencer::VisitRecordType(
const RecordType *RT) {
3741 auto *R = dyn_cast<CXXRecordDecl>(RT->
getDecl());
3742 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() ||
3743 R->isDependentType())
3745 for (
auto *TmpD : R->decls())
3746 if (
auto *T = dyn_cast<TypedefNameDecl>(TmpD))
3747 if (T->getAccess() !=
AS_private || R->hasFriends())
3772 TypeLoc OrigResultType = getReturnTypeLoc(FD);
3775 if (RetExpr && isa<InitListExpr>(RetExpr)) {
3779 getCurLambda() ? diag::err_lambda_return_init_list
3780 : diag::err_auto_fn_return_init_list)
3790 assert(AT->
isDeduced() &&
"should have deduced to dependent type");
3803 if (DAR != DAR_Succeeded)
3808 LocalTypedefNameReferencer Referencer(*
this);
3809 Referencer.TraverseType(RetExpr->
getType());
3815 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
3827 Diag(ReturnLoc, diag::err_auto_fn_deduction_failure)
3830 if (DAR != DAR_Succeeded)
3835 if (getLangOpts().
CUDA)
3861 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
3865 Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
3884 ExprResult RetVal = CorrectDelayedTyposInExpr(
3885 RetValExp,
nullptr,
true);
3889 BuildReturnStmt(ReturnLoc, RetVal.
get(),
true);
3890 if (R.
isInvalid() || ExprEvalContexts.back().isDiscardedStatementContext())
3894 const_cast<VarDecl*
>(cast<ReturnStmt>(R.
get())->getNRVOCandidate())) {
3920 bool AllowRecovery) {
3922 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
3928 bool SupressSimplerImplicitMoves =
3931 RetValExp, SupressSimplerImplicitMoves ? SimplerImplicitMoveMode::ForceOff
3932 : SimplerImplicitMoveMode::Normal);
3934 if (isa<CapturingScopeInfo>(getCurFunction()))
3935 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp, NRInfo,
3936 SupressSimplerImplicitMoves);
3940 const AttrVec *Attrs =
nullptr;
3941 bool isObjCMethod =
false;
3948 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) << FD;
3949 if (FD->
isMain() && RetValExp)
3950 if (isa<CXXBoolLiteralExpr>(RetValExp))
3951 Diag(ReturnLoc, diag::warn_main_returns_bool_literal)
3953 if (FD->
hasAttr<CmseNSEntryAttr>() && RetValExp) {
3960 FnRetType = MD->getReturnType();
3961 isObjCMethod =
true;
3963 Attrs = &MD->getAttrs();
3964 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
3976 if (ExprEvalContexts.back().isDiscardedStatementContext() &&
3980 ActOnFinishFullExpr(RetValExp, ReturnLoc,
false);
3983 RetValExp = ER.
get();
3999 DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
4007 auto Recovery = CreateRecoveryExpr(
4009 AT->isDeduced() ? FnRetType :
QualType());
4010 if (Recovery.isInvalid())
4012 RetValExp = Recovery.get();
4021 const VarDecl *NRVOCandidate = getCopyElisionCandidate(NRInfo, FnRetType);
4028 if (
auto *ILE = dyn_cast<InitListExpr>(RetValExp)) {
4032 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
4033 int FunctionKind = 0;
4034 if (isa<ObjCMethodDecl>(CurDecl))
4036 else if (isa<CXXConstructorDecl>(CurDecl))
4038 else if (isa<CXXDestructorDecl>(CurDecl))
4041 Diag(ReturnLoc, diag::err_return_init_list)
4045 RetValExp = AllowRecovery
4046 ? CreateRecoveryExpr(ILE->getLBraceLoc(),
4047 ILE->getRBraceLoc(), ILE->inits())
4052 unsigned D = diag::ext_return_has_expr;
4054 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
4055 if (isa<CXXConstructorDecl>(CurDecl) ||
4056 isa<CXXDestructorDecl>(CurDecl))
4057 D = diag::err_ctor_dtor_returns_void;
4059 D = diag::ext_return_has_void_expr;
4063 Result = IgnoredValueConversions(Result.get());
4064 if (Result.isInvalid())
4066 RetValExp = Result.get();
4067 RetValExp = ImpCastExprToType(RetValExp,
4068 Context.
VoidTy, CK_ToVoid).get();
4071 if (D == diag::err_ctor_dtor_returns_void) {
4072 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
4073 Diag(ReturnLoc, D) << CurDecl << isa<CXXDestructorDecl>(CurDecl)
4077 else if (D != diag::ext_return_has_void_expr ||
4079 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
4081 int FunctionKind = 0;
4082 if (isa<ObjCMethodDecl>(CurDecl))
4084 else if (isa<CXXConstructorDecl>(CurDecl))
4086 else if (isa<CXXDestructorDecl>(CurDecl))
4096 ActOnFinishFullExpr(RetValExp, ReturnLoc,
false);
4099 RetValExp = ER.
get();
4105 }
else if (!RetValExp && !HasDependentReturnType) {
4112 Diag(ReturnLoc, diag::err_constexpr_return_missing_expr)
4118 unsigned DiagID = getLangOpts().C99 ? diag::ext_return_missing_expr
4119 : diag::warn_return_missing_expr;
4122 assert((getCurFunctionDecl() || getCurMethodDecl()) &&
4123 "Not in a FunctionDecl or ObjCMethodDecl?");
4124 bool IsMethod = FD ==
nullptr;
4126 IsMethod ? cast<NamedDecl>(getCurMethodDecl()) : cast<NamedDecl>(FD);
4127 Diag(ReturnLoc, DiagID) << ND << IsMethod;
4133 assert(RetValExp || HasDependentReturnType);
4134 QualType RetType = RelatedRetType.
isNull() ? FnRetType : RelatedRetType;
4146 ExprResult Res = PerformMoveOrCopyInitialization(
4147 Entity, NRInfo, RetValExp, SupressSimplerImplicitMoves);
4149 Res = CreateRecoveryExpr(RetValExp->
getBeginLoc(),
4150 RetValExp->
getEndLoc(), RetValExp, RetType);
4161 if (!RelatedRetType.
isNull()) {
4164 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
4172 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
4173 getCurFunctionDecl());
4178 ActOnFinishFullExpr(RetValExp, ReturnLoc,
false);
4181 RetValExp = ER.
get();
4188 if (Result->getNRVOCandidate())
4189 FunctionScopes.back()->Returns.push_back(Result);
4191 if (FunctionScopes.back()->FirstReturnLoc.isInvalid())
4192 FunctionScopes.back()->FirstReturnLoc = ReturnLoc;
4201 VarDecl *Var = cast_or_null<VarDecl>(Parm);
4216 if (!getLangOpts().ObjCExceptions)
4217 Diag(AtLoc, diag::err_objc_exceptions_disabled) <<
"@try";
4222 Diag(AtLoc, diag::err_mixing_cxx_try_seh_try) << 1;
4227 unsigned NumCatchStmts = CatchStmts.size();
4229 NumCatchStmts, Finally);
4234 ExprResult Result = DefaultLvalueConversion(Throw);
4235 if (Result.isInvalid())
4238 Result = ActOnFinishFullExpr(Result.get(),
false);
4239 if (Result.isInvalid())
4241 Throw = Result.get();
4249 return StmtError(
Diag(AtLoc, diag::err_objc_throw_expects_object)
4260 if (!getLangOpts().ObjCExceptions)
4261 Diag(AtLoc, diag::err_objc_exceptions_disabled) <<
"@throw";
4266 Scope *AtCatchParent = CurScope;
4268 AtCatchParent = AtCatchParent->
getParent();
4270 return StmtError(
Diag(AtLoc, diag::err_rethrow_used_outside_catch));
4272 return BuildObjCAtThrowStmt(AtLoc, Throw);
4277 ExprResult result = DefaultLvalueConversion(operand);
4280 operand = result.
get();
4284 if (!
type->isDependentType() &&
4285 !
type->isObjCObjectPointerType()) {
4288 if (getLangOpts().CPlusPlus) {
4289 if (RequireCompleteType(atLoc,
type,
4290 diag::err_incomplete_receiver_type))
4291 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
4294 ExprResult result = PerformContextuallyConvertToObjCPointer(operand);
4298 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
4301 operand = result.
get();
4303 return Diag(atLoc, diag::err_objc_synchronized_expects_object)
4310 return ActOnFinishFullExpr(operand,
false);
4317 setFunctionHasBranchProtectedScope();
4325 Stmt *HandlerBlock) {
4327 return new (Context)
4328 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
4333 setFunctionHasBranchProtectedScope();
4338 class CatchHandlerType {
4340 unsigned IsPointer : 1;
4344 friend struct llvm::DenseMapInfo<CatchHandlerType>;
4345 enum Unique { ForDenseMap };
4346 CatchHandlerType(
QualType QT, Unique) : QT(QT), IsPointer(
false) {}
4364 CatchHandlerType(
QualType QT,
bool IsPointer)
4365 : QT(QT), IsPointer(IsPointer) {}
4367 QualType underlying()
const {
return QT; }
4368 bool isPointer()
const {
return IsPointer; }
4370 friend bool operator==(
const CatchHandlerType &LHS,
4371 const CatchHandlerType &RHS) {
4373 if (LHS.IsPointer != RHS.IsPointer)
4376 return LHS.QT == RHS.QT;
4382 template <>
struct DenseMapInfo<CatchHandlerType> {
4384 return CatchHandlerType(DenseMapInfo<QualType>::getEmptyKey(),
4385 CatchHandlerType::ForDenseMap);
4389 return CatchHandlerType(DenseMapInfo<QualType>::getTombstoneKey(),
4390 CatchHandlerType::ForDenseMap);
4394 return DenseMapInfo<QualType>::getHashValue(
Base.underlying());
4398 const CatchHandlerType &RHS) {
4405 class CatchTypePublicBases {
4407 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &TypesToCheck;
4408 const bool CheckAgainstPointer;
4414 CatchTypePublicBases(
4416 const llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> &T,
bool C)
4417 : Ctx(Ctx), TypesToCheck(T), CheckAgainstPointer(
C),
4418 FoundHandler(nullptr) {}
4420 CXXCatchStmt *getFoundHandler()
const {
return FoundHandler; }
4421 CanQualType getFoundHandlerType()
const {
return FoundHandlerType; }
4425 CatchHandlerType Check(S->getType(), CheckAgainstPointer);
4426 const auto &M = TypesToCheck;
4427 auto I = M.find(Check);
4429 FoundHandler = I->second;
4444 if (!getLangOpts().CXXExceptions &&
4445 !getSourceManager().isInSystemHeader(TryLoc) && !getLangOpts().
CUDA) {
4447 targetDiag(TryLoc, diag::err_exceptions_disabled) <<
"try";
4451 if (getLangOpts().
CUDA)
4452 CUDADiagIfDeviceCode(TryLoc, diag::err_cuda_device_exceptions)
4453 <<
"try" << CurrentCUDATarget();
4455 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
4456 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) <<
"try";
4462 Diag(TryLoc, diag::err_mixing_cxx_try_seh_try) << 0;
4466 const unsigned NumHandlers = Handlers.size();
4467 assert(!Handlers.empty() &&
4468 "The parser shouldn't call this if there are no handlers.");
4470 llvm::DenseMap<CatchHandlerType, CXXCatchStmt *> HandledTypes;
4471 for (
unsigned i = 0; i < NumHandlers; ++i) {
4478 if (i < NumHandlers - 1)
4487 CatchHandlerType HandlerCHT =
4493 QualType Underlying = HandlerCHT.underlying();
4495 if (!RD->hasDefinition())
4503 Paths.setOrigin(RD);
4504 CatchTypePublicBases CTPB(Context, HandledTypes, HandlerCHT.isPointer());
4505 if (RD->lookupInBases(CTPB, Paths)) {
4507 if (!Paths.isAmbiguous(CTPB.getFoundHandlerType())) {
4509 diag::warn_exception_caught_by_earlier_handler)
4512 diag::note_previous_exception_handler)
4520 auto R = HandledTypes.insert(std::make_pair(H->
getCaughtType(), H));
4524 diag::warn_exception_caught_by_earlier_handler)
4527 diag::note_previous_exception_handler)
4539 assert(TryBlock && Handler);
4545 if (!getLangOpts().Borland) {
4566 Diag(TryLoc, diag::err_seh_try_outside_functions);
4570 Diag(TryLoc, diag::err_seh_try_unsupported);
4577 assert(FilterExpr &&
Block);
4581 Diag(FilterExpr->
getExprLoc(), diag::err_filter_expression_integral)
4588 CurrentSEHFinally.push_back(CurScope);
4592 CurrentSEHFinally.pop_back();
4597 CurrentSEHFinally.pop_back();
4603 Scope *SEHTryParent = CurScope;
4605 SEHTryParent = SEHTryParent->
getParent();
4607 return StmtError(
Diag(Loc, diag::err_ms___leave_not_in___try));
4620 QualifierLoc, NameInfo,
4621 cast<CompoundStmt>(Nested));
4630 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
4632 GetNameFromUnqualifiedId(Name),
4638 unsigned NumParams) {
4655 assert(NumParams > 0 &&
"CapturedStmt requires context parameter");
4698 CaptureInits.push_back(Init.get());
4705 unsigned NumParams) {
4707 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
4721 PushCapturedRegionScope(CurScope, CD, RD,
Kind);
4724 PushDeclContext(CurScope, CD);
4728 PushExpressionEvaluationContext(
4729 ExpressionEvaluationContext::PotentiallyEvaluated);
4735 unsigned OpenMPCaptureLevel) {
4737 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
4741 bool ContextIsFound =
false;
4742 unsigned ParamNum = 0;
4745 I != E; ++I, ++ParamNum) {
4746 if (I->second.isNull()) {
4747 assert(!ContextIsFound &&
4748 "null type has been found already for '__context' parameter");
4758 ContextIsFound =
true;
4768 assert(ContextIsFound &&
"no null type for '__context' parameter");
4769 if (!ContextIsFound) {
4780 PushCapturedRegionScope(CurScope, CD, RD,
Kind, OpenMPCaptureLevel);
4783 PushDeclContext(CurScope, CD);
4787 PushExpressionEvaluationContext(
4788 ExpressionEvaluationContext::PotentiallyEvaluated);
4792 DiscardCleanupsInEvaluationContext();
4793 PopExpressionEvaluationContext();
4802 ActOnFields(
nullptr, Record->
getLocation(), Record, Fields,
4809 DiscardCleanupsInEvaluationContext();
4810 PopExpressionEvaluationContext();
4825 Captures, CaptureInits, CD, RD);