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