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