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