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