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