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