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