• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for statements.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTDiagnostic.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/StmtCXX.h"
23 #include "clang/AST/StmtObjC.h"
24 #include "clang/AST/TypeLoc.h"
25 #include "clang/Lex/Preprocessor.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/Scope.h"
29 #include "clang/Sema/ScopeInfo.h"
30 #include "llvm/ADT/ArrayRef.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallString.h"
34 #include "llvm/ADT/SmallVector.h"
35 using namespace clang;
36 using namespace sema;
37 
ActOnExprStmt(ExprResult FE)38 StmtResult Sema::ActOnExprStmt(ExprResult FE) {
39   if (FE.isInvalid())
40     return StmtError();
41 
42   FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(),
43                            /*DiscardedValue*/ true);
44   if (FE.isInvalid())
45     return StmtError();
46 
47   // C99 6.8.3p2: The expression in an expression statement is evaluated as a
48   // void expression for its side effects.  Conversion to void allows any
49   // operand, even incomplete types.
50 
51   // Same thing in for stmt first clause (when expr) and third clause.
52   return StmtResult(FE.getAs<Stmt>());
53 }
54 
55 
ActOnExprStmtError()56 StmtResult Sema::ActOnExprStmtError() {
57   DiscardCleanupsInEvaluationContext();
58   return StmtError();
59 }
60 
ActOnNullStmt(SourceLocation SemiLoc,bool HasLeadingEmptyMacro)61 StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
62                                bool HasLeadingEmptyMacro) {
63   return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro);
64 }
65 
ActOnDeclStmt(DeclGroupPtrTy dg,SourceLocation StartLoc,SourceLocation EndLoc)66 StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
67                                SourceLocation EndLoc) {
68   DeclGroupRef DG = dg.get();
69 
70   // If we have an invalid decl, just return an error.
71   if (DG.isNull()) return StmtError();
72 
73   return new (Context) DeclStmt(DG, StartLoc, EndLoc);
74 }
75 
ActOnForEachDeclStmt(DeclGroupPtrTy dg)76 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
77   DeclGroupRef DG = dg.get();
78 
79   // If we don't have a declaration, or we have an invalid declaration,
80   // just return.
81   if (DG.isNull() || !DG.isSingleDecl())
82     return;
83 
84   Decl *decl = DG.getSingleDecl();
85   if (!decl || decl->isInvalidDecl())
86     return;
87 
88   // Only variable declarations are permitted.
89   VarDecl *var = dyn_cast<VarDecl>(decl);
90   if (!var) {
91     Diag(decl->getLocation(), diag::err_non_variable_decl_in_for);
92     decl->setInvalidDecl();
93     return;
94   }
95 
96   // foreach variables are never actually initialized in the way that
97   // the parser came up with.
98   var->setInit(nullptr);
99 
100   // In ARC, we don't need to retain the iteration variable of a fast
101   // enumeration loop.  Rather than actually trying to catch that
102   // during declaration processing, we remove the consequences here.
103   if (getLangOpts().ObjCAutoRefCount) {
104     QualType type = var->getType();
105 
106     // Only do this if we inferred the lifetime.  Inferred lifetime
107     // will show up as a local qualifier because explicit lifetime
108     // should have shown up as an AttributedType instead.
109     if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
110       // Add 'const' and mark the variable as pseudo-strong.
111       var->setType(type.withConst());
112       var->setARCPseudoStrong(true);
113     }
114   }
115 }
116 
117 /// \brief Diagnose unused comparisons, both builtin and overloaded operators.
118 /// For '==' and '!=', suggest fixits for '=' or '|='.
119 ///
120 /// Adding a cast to void (or other expression wrappers) will prevent the
121 /// warning from firing.
DiagnoseUnusedComparison(Sema & S,const Expr * E)122 static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
123   SourceLocation Loc;
124   bool IsNotEqual, CanAssign, IsRelational;
125 
126   if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
127     if (!Op->isComparisonOp())
128       return false;
129 
130     IsRelational = Op->isRelationalOp();
131     Loc = Op->getOperatorLoc();
132     IsNotEqual = Op->getOpcode() == BO_NE;
133     CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
134   } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
135     switch (Op->getOperator()) {
136     default:
137       return false;
138     case OO_EqualEqual:
139     case OO_ExclaimEqual:
140       IsRelational = false;
141       break;
142     case OO_Less:
143     case OO_Greater:
144     case OO_GreaterEqual:
145     case OO_LessEqual:
146       IsRelational = true;
147       break;
148     }
149 
150     Loc = Op->getOperatorLoc();
151     IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
152     CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
153   } else {
154     // Not a typo-prone comparison.
155     return false;
156   }
157 
158   // Suppress warnings when the operator, suspicious as it may be, comes from
159   // a macro expansion.
160   if (S.SourceMgr.isMacroBodyExpansion(Loc))
161     return false;
162 
163   S.Diag(Loc, diag::warn_unused_comparison)
164     << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange();
165 
166   // If the LHS is a plausible entity to assign to, provide a fixit hint to
167   // correct common typos.
168   if (!IsRelational && CanAssign) {
169     if (IsNotEqual)
170       S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
171         << FixItHint::CreateReplacement(Loc, "|=");
172     else
173       S.Diag(Loc, diag::note_equality_comparison_to_assign)
174         << FixItHint::CreateReplacement(Loc, "=");
175   }
176 
177   return true;
178 }
179 
DiagnoseUnusedExprResult(const Stmt * S)180 void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
181   if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
182     return DiagnoseUnusedExprResult(Label->getSubStmt());
183 
184   const Expr *E = dyn_cast_or_null<Expr>(S);
185   if (!E)
186     return;
187   SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc();
188   // In most cases, we don't want to warn if the expression is written in a
189   // macro body, or if the macro comes from a system header. If the offending
190   // expression is a call to a function with the warn_unused_result attribute,
191   // we warn no matter the location. Because of the order in which the various
192   // checks need to happen, we factor out the macro-related test here.
193   bool ShouldSuppress =
194       SourceMgr.isMacroBodyExpansion(ExprLoc) ||
195       SourceMgr.isInSystemMacro(ExprLoc);
196 
197   const Expr *WarnExpr;
198   SourceLocation Loc;
199   SourceRange R1, R2;
200   if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
201     return;
202 
203   // If this is a GNU statement expression expanded from a macro, it is probably
204   // unused because it is a function-like macro that can be used as either an
205   // expression or statement.  Don't warn, because it is almost certainly a
206   // false positive.
207   if (isa<StmtExpr>(E) && Loc.isMacroID())
208     return;
209 
210   // Okay, we have an unused result.  Depending on what the base expression is,
211   // we might want to make a more specific diagnostic.  Check for one of these
212   // cases now.
213   unsigned DiagID = diag::warn_unused_expr;
214   if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
215     E = Temps->getSubExpr();
216   if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
217     E = TempExpr->getSubExpr();
218 
219   if (DiagnoseUnusedComparison(*this, E))
220     return;
221 
222   E = WarnExpr;
223   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
224     if (E->getType()->isVoidType())
225       return;
226 
227     // If the callee has attribute pure, const, or warn_unused_result, warn with
228     // a more specific message to make it clear what is happening. If the call
229     // is written in a macro body, only warn if it has the warn_unused_result
230     // attribute.
231     if (const Decl *FD = CE->getCalleeDecl()) {
232       if (FD->hasAttr<WarnUnusedResultAttr>()) {
233         Diag(Loc, diag::warn_unused_result) << R1 << R2;
234         return;
235       }
236       if (ShouldSuppress)
237         return;
238       if (FD->hasAttr<PureAttr>()) {
239         Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
240         return;
241       }
242       if (FD->hasAttr<ConstAttr>()) {
243         Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
244         return;
245       }
246     }
247   } else if (ShouldSuppress)
248     return;
249 
250   if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
251     if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
252       Diag(Loc, diag::err_arc_unused_init_message) << R1;
253       return;
254     }
255     const ObjCMethodDecl *MD = ME->getMethodDecl();
256     if (MD && MD->hasAttr<WarnUnusedResultAttr>()) {
257       Diag(Loc, diag::warn_unused_result) << R1 << R2;
258       return;
259     }
260   } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
261     const Expr *Source = POE->getSyntacticForm();
262     if (isa<ObjCSubscriptRefExpr>(Source))
263       DiagID = diag::warn_unused_container_subscript_expr;
264     else
265       DiagID = diag::warn_unused_property_expr;
266   } else if (const CXXFunctionalCastExpr *FC
267                                        = dyn_cast<CXXFunctionalCastExpr>(E)) {
268     if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
269         isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
270       return;
271   }
272   // Diagnose "(void*) blah" as a typo for "(void) blah".
273   else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
274     TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
275     QualType T = TI->getType();
276 
277     // We really do want to use the non-canonical type here.
278     if (T == Context.VoidPtrTy) {
279       PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>();
280 
281       Diag(Loc, diag::warn_unused_voidptr)
282         << FixItHint::CreateRemoval(TL.getStarLoc());
283       return;
284     }
285   }
286 
287   if (E->isGLValue() && E->getType().isVolatileQualified()) {
288     Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
289     return;
290   }
291 
292   DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2);
293 }
294 
ActOnStartOfCompoundStmt()295 void Sema::ActOnStartOfCompoundStmt() {
296   PushCompoundScope();
297 }
298 
ActOnFinishOfCompoundStmt()299 void Sema::ActOnFinishOfCompoundStmt() {
300   PopCompoundScope();
301 }
302 
getCurCompoundScope() const303 sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
304   return getCurFunction()->CompoundScopes.back();
305 }
306 
ActOnCompoundStmt(SourceLocation L,SourceLocation R,ArrayRef<Stmt * > Elts,bool isStmtExpr)307 StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
308                                    ArrayRef<Stmt *> Elts, bool isStmtExpr) {
309   const unsigned NumElts = Elts.size();
310 
311   // If we're in C89 mode, check that we don't have any decls after stmts.  If
312   // so, emit an extension diagnostic.
313   if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
314     // Note that __extension__ can be around a decl.
315     unsigned i = 0;
316     // Skip over all declarations.
317     for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
318       /*empty*/;
319 
320     // We found the end of the list or a statement.  Scan for another declstmt.
321     for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
322       /*empty*/;
323 
324     if (i != NumElts) {
325       Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
326       Diag(D->getLocation(), diag::ext_mixed_decls_code);
327     }
328   }
329   // Warn about unused expressions in statements.
330   for (unsigned i = 0; i != NumElts; ++i) {
331     // Ignore statements that are last in a statement expression.
332     if (isStmtExpr && i == NumElts - 1)
333       continue;
334 
335     DiagnoseUnusedExprResult(Elts[i]);
336   }
337 
338   // Check for suspicious empty body (null statement) in `for' and `while'
339   // statements.  Don't do anything for template instantiations, this just adds
340   // noise.
341   if (NumElts != 0 && !CurrentInstantiationScope &&
342       getCurCompoundScope().HasEmptyLoopBodies) {
343     for (unsigned i = 0; i != NumElts - 1; ++i)
344       DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
345   }
346 
347   return new (Context) CompoundStmt(Context, Elts, L, R);
348 }
349 
350 StmtResult
ActOnCaseStmt(SourceLocation CaseLoc,Expr * LHSVal,SourceLocation DotDotDotLoc,Expr * RHSVal,SourceLocation ColonLoc)351 Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
352                     SourceLocation DotDotDotLoc, Expr *RHSVal,
353                     SourceLocation ColonLoc) {
354   assert(LHSVal && "missing expression in case statement");
355 
356   if (getCurFunction()->SwitchStack.empty()) {
357     Diag(CaseLoc, diag::err_case_not_in_switch);
358     return StmtError();
359   }
360 
361   if (!getLangOpts().CPlusPlus11) {
362     // C99 6.8.4.2p3: The expression shall be an integer constant.
363     // However, GCC allows any evaluatable integer expression.
364     if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
365       LHSVal = VerifyIntegerConstantExpression(LHSVal).get();
366       if (!LHSVal)
367         return StmtError();
368     }
369 
370     // GCC extension: The expression shall be an integer constant.
371 
372     if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
373       RHSVal = VerifyIntegerConstantExpression(RHSVal).get();
374       // Recover from an error by just forgetting about it.
375     }
376   }
377 
378   LHSVal = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false,
379                                getLangOpts().CPlusPlus11).get();
380   if (RHSVal)
381     RHSVal = ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false,
382                                  getLangOpts().CPlusPlus11).get();
383 
384   CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
385                                         ColonLoc);
386   getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
387   return CS;
388 }
389 
390 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
ActOnCaseStmtBody(Stmt * caseStmt,Stmt * SubStmt)391 void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
392   DiagnoseUnusedExprResult(SubStmt);
393 
394   CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
395   CS->setSubStmt(SubStmt);
396 }
397 
398 StmtResult
ActOnDefaultStmt(SourceLocation DefaultLoc,SourceLocation ColonLoc,Stmt * SubStmt,Scope * CurScope)399 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
400                        Stmt *SubStmt, Scope *CurScope) {
401   DiagnoseUnusedExprResult(SubStmt);
402 
403   if (getCurFunction()->SwitchStack.empty()) {
404     Diag(DefaultLoc, diag::err_default_not_in_switch);
405     return SubStmt;
406   }
407 
408   DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
409   getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
410   return DS;
411 }
412 
413 StmtResult
ActOnLabelStmt(SourceLocation IdentLoc,LabelDecl * TheDecl,SourceLocation ColonLoc,Stmt * SubStmt)414 Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
415                      SourceLocation ColonLoc, Stmt *SubStmt) {
416   // If the label was multiply defined, reject it now.
417   if (TheDecl->getStmt()) {
418     Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
419     Diag(TheDecl->getLocation(), diag::note_previous_definition);
420     return SubStmt;
421   }
422 
423   // Otherwise, things are good.  Fill in the declaration and return it.
424   LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
425   TheDecl->setStmt(LS);
426   if (!TheDecl->isGnuLocal()) {
427     TheDecl->setLocStart(IdentLoc);
428     TheDecl->setLocation(IdentLoc);
429   }
430   return LS;
431 }
432 
ActOnAttributedStmt(SourceLocation AttrLoc,ArrayRef<const Attr * > Attrs,Stmt * SubStmt)433 StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
434                                      ArrayRef<const Attr*> Attrs,
435                                      Stmt *SubStmt) {
436   // Fill in the declaration and return it.
437   AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
438   return LS;
439 }
440 
441 StmtResult
ActOnIfStmt(SourceLocation IfLoc,FullExprArg CondVal,Decl * CondVar,Stmt * thenStmt,SourceLocation ElseLoc,Stmt * elseStmt)442 Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
443                   Stmt *thenStmt, SourceLocation ElseLoc,
444                   Stmt *elseStmt) {
445   // If the condition was invalid, discard the if statement.  We could recover
446   // better by replacing it with a valid expr, but don't do that yet.
447   if (!CondVal.get() && !CondVar) {
448     getCurFunction()->setHasDroppedStmt();
449     return StmtError();
450   }
451 
452   ExprResult CondResult(CondVal.release());
453 
454   VarDecl *ConditionVar = nullptr;
455   if (CondVar) {
456     ConditionVar = cast<VarDecl>(CondVar);
457     CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
458     if (CondResult.isInvalid())
459       return StmtError();
460   }
461   Expr *ConditionExpr = CondResult.getAs<Expr>();
462   if (!ConditionExpr)
463     return StmtError();
464 
465   DiagnoseUnusedExprResult(thenStmt);
466 
467   if (!elseStmt) {
468     DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
469                           diag::warn_empty_if_body);
470   }
471 
472   DiagnoseUnusedExprResult(elseStmt);
473 
474   return new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
475                               thenStmt, ElseLoc, elseStmt);
476 }
477 
478 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
479 /// the specified width and sign.  If an overflow occurs, detect it and emit
480 /// the specified diagnostic.
ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt & Val,unsigned NewWidth,bool NewSign,SourceLocation Loc,unsigned DiagID)481 void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
482                                               unsigned NewWidth, bool NewSign,
483                                               SourceLocation Loc,
484                                               unsigned DiagID) {
485   // Perform a conversion to the promoted condition type if needed.
486   if (NewWidth > Val.getBitWidth()) {
487     // If this is an extension, just do it.
488     Val = Val.extend(NewWidth);
489     Val.setIsSigned(NewSign);
490 
491     // If the input was signed and negative and the output is
492     // unsigned, don't bother to warn: this is implementation-defined
493     // behavior.
494     // FIXME: Introduce a second, default-ignored warning for this case?
495   } else if (NewWidth < Val.getBitWidth()) {
496     // If this is a truncation, check for overflow.
497     llvm::APSInt ConvVal(Val);
498     ConvVal = ConvVal.trunc(NewWidth);
499     ConvVal.setIsSigned(NewSign);
500     ConvVal = ConvVal.extend(Val.getBitWidth());
501     ConvVal.setIsSigned(Val.isSigned());
502     if (ConvVal != Val)
503       Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
504 
505     // Regardless of whether a diagnostic was emitted, really do the
506     // truncation.
507     Val = Val.trunc(NewWidth);
508     Val.setIsSigned(NewSign);
509   } else if (NewSign != Val.isSigned()) {
510     // Convert the sign to match the sign of the condition.  This can cause
511     // overflow as well: unsigned(INTMIN)
512     // We don't diagnose this overflow, because it is implementation-defined
513     // behavior.
514     // FIXME: Introduce a second, default-ignored warning for this case?
515     Val.setIsSigned(NewSign);
516   }
517 }
518 
519 namespace {
520   struct CaseCompareFunctor {
operator ()__anon199a60c30111::CaseCompareFunctor521     bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
522                     const llvm::APSInt &RHS) {
523       return LHS.first < RHS;
524     }
operator ()__anon199a60c30111::CaseCompareFunctor525     bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
526                     const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
527       return LHS.first < RHS.first;
528     }
operator ()__anon199a60c30111::CaseCompareFunctor529     bool operator()(const llvm::APSInt &LHS,
530                     const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
531       return LHS < RHS.first;
532     }
533   };
534 }
535 
536 /// CmpCaseVals - Comparison predicate for sorting case values.
537 ///
CmpCaseVals(const std::pair<llvm::APSInt,CaseStmt * > & lhs,const std::pair<llvm::APSInt,CaseStmt * > & rhs)538 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
539                         const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
540   if (lhs.first < rhs.first)
541     return true;
542 
543   if (lhs.first == rhs.first &&
544       lhs.second->getCaseLoc().getRawEncoding()
545        < rhs.second->getCaseLoc().getRawEncoding())
546     return true;
547   return false;
548 }
549 
550 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
551 ///
CmpEnumVals(const std::pair<llvm::APSInt,EnumConstantDecl * > & lhs,const std::pair<llvm::APSInt,EnumConstantDecl * > & rhs)552 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
553                         const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
554 {
555   return lhs.first < rhs.first;
556 }
557 
558 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
559 ///
EqEnumVals(const std::pair<llvm::APSInt,EnumConstantDecl * > & lhs,const std::pair<llvm::APSInt,EnumConstantDecl * > & rhs)560 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
561                        const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
562 {
563   return lhs.first == rhs.first;
564 }
565 
566 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
567 /// potentially integral-promoted expression @p expr.
GetTypeBeforeIntegralPromotion(Expr * & expr)568 static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
569   if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
570     expr = cleanups->getSubExpr();
571   while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
572     if (impcast->getCastKind() != CK_IntegralCast) break;
573     expr = impcast->getSubExpr();
574   }
575   return expr->getType();
576 }
577 
578 StmtResult
ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,Expr * Cond,Decl * CondVar)579 Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
580                              Decl *CondVar) {
581   ExprResult CondResult;
582 
583   VarDecl *ConditionVar = nullptr;
584   if (CondVar) {
585     ConditionVar = cast<VarDecl>(CondVar);
586     CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
587     if (CondResult.isInvalid())
588       return StmtError();
589 
590     Cond = CondResult.get();
591   }
592 
593   if (!Cond)
594     return StmtError();
595 
596   class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
597     Expr *Cond;
598 
599   public:
600     SwitchConvertDiagnoser(Expr *Cond)
601         : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true),
602           Cond(Cond) {}
603 
604     SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
605                                          QualType T) override {
606       return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
607     }
608 
609     SemaDiagnosticBuilder diagnoseIncomplete(
610         Sema &S, SourceLocation Loc, QualType T) override {
611       return S.Diag(Loc, diag::err_switch_incomplete_class_type)
612                << T << Cond->getSourceRange();
613     }
614 
615     SemaDiagnosticBuilder diagnoseExplicitConv(
616         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
617       return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
618     }
619 
620     SemaDiagnosticBuilder noteExplicitConv(
621         Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
622       return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
623         << ConvTy->isEnumeralType() << ConvTy;
624     }
625 
626     SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
627                                             QualType T) override {
628       return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
629     }
630 
631     SemaDiagnosticBuilder noteAmbiguous(
632         Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
633       return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
634       << ConvTy->isEnumeralType() << ConvTy;
635     }
636 
637     SemaDiagnosticBuilder diagnoseConversion(
638         Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
639       llvm_unreachable("conversion functions are permitted");
640     }
641   } SwitchDiagnoser(Cond);
642 
643   CondResult =
644       PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser);
645   if (CondResult.isInvalid()) return StmtError();
646   Cond = CondResult.get();
647 
648   // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
649   CondResult = UsualUnaryConversions(Cond);
650   if (CondResult.isInvalid()) return StmtError();
651   Cond = CondResult.get();
652 
653   if (!CondVar) {
654     CondResult = ActOnFinishFullExpr(Cond, SwitchLoc);
655     if (CondResult.isInvalid())
656       return StmtError();
657     Cond = CondResult.get();
658   }
659 
660   getCurFunction()->setHasBranchIntoScope();
661 
662   SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
663   getCurFunction()->SwitchStack.push_back(SS);
664   return SS;
665 }
666 
AdjustAPSInt(llvm::APSInt & Val,unsigned BitWidth,bool IsSigned)667 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
668   if (Val.getBitWidth() < BitWidth)
669     Val = Val.extend(BitWidth);
670   else if (Val.getBitWidth() > BitWidth)
671     Val = Val.trunc(BitWidth);
672   Val.setIsSigned(IsSigned);
673 }
674 
675 /// Returns true if we should emit a diagnostic about this case expression not
676 /// being a part of the enum used in the switch controlling expression.
ShouldDiagnoseSwitchCaseNotInEnum(const ASTContext & Ctx,const EnumDecl * ED,const Expr * CaseExpr)677 static bool ShouldDiagnoseSwitchCaseNotInEnum(const ASTContext &Ctx,
678                                               const EnumDecl *ED,
679                                               const Expr *CaseExpr) {
680   // Don't warn if the 'case' expression refers to a static const variable of
681   // the enum type.
682   CaseExpr = CaseExpr->IgnoreParenImpCasts();
683   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseExpr)) {
684     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
685       if (!VD->hasGlobalStorage())
686         return true;
687       QualType VarType = VD->getType();
688       if (!VarType.isConstQualified())
689         return true;
690       QualType EnumType = Ctx.getTypeDeclType(ED);
691       if (Ctx.hasSameUnqualifiedType(EnumType, VarType))
692         return false;
693     }
694   }
695   return true;
696 }
697 
698 StmtResult
ActOnFinishSwitchStmt(SourceLocation SwitchLoc,Stmt * Switch,Stmt * BodyStmt)699 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
700                             Stmt *BodyStmt) {
701   SwitchStmt *SS = cast<SwitchStmt>(Switch);
702   assert(SS == getCurFunction()->SwitchStack.back() &&
703          "switch stack missing push/pop!");
704 
705   if (!BodyStmt) return StmtError();
706   SS->setBody(BodyStmt, SwitchLoc);
707   getCurFunction()->SwitchStack.pop_back();
708 
709   Expr *CondExpr = SS->getCond();
710   if (!CondExpr) return StmtError();
711 
712   QualType CondType = CondExpr->getType();
713 
714   Expr *CondExprBeforePromotion = CondExpr;
715   QualType CondTypeBeforePromotion =
716       GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
717 
718   // C++ 6.4.2.p2:
719   // Integral promotions are performed (on the switch condition).
720   //
721   // A case value unrepresentable by the original switch condition
722   // type (before the promotion) doesn't make sense, even when it can
723   // be represented by the promoted type.  Therefore we need to find
724   // the pre-promotion type of the switch condition.
725   if (!CondExpr->isTypeDependent()) {
726     // We have already converted the expression to an integral or enumeration
727     // type, when we started the switch statement. If we don't have an
728     // appropriate type now, just return an error.
729     if (!CondType->isIntegralOrEnumerationType())
730       return StmtError();
731 
732     if (CondExpr->isKnownToHaveBooleanValue()) {
733       // switch(bool_expr) {...} is often a programmer error, e.g.
734       //   switch(n && mask) { ... }  // Doh - should be "n & mask".
735       // One can always use an if statement instead of switch(bool_expr).
736       Diag(SwitchLoc, diag::warn_bool_switch_condition)
737           << CondExpr->getSourceRange();
738     }
739   }
740 
741   // Get the bitwidth of the switched-on value before promotions.  We must
742   // convert the integer case values to this width before comparison.
743   bool HasDependentValue
744     = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
745   unsigned CondWidth
746     = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
747   bool CondIsSigned
748     = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
749 
750   // Accumulate all of the case values in a vector so that we can sort them
751   // and detect duplicates.  This vector contains the APInt for the case after
752   // it has been converted to the condition type.
753   typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
754   CaseValsTy CaseVals;
755 
756   // Keep track of any GNU case ranges we see.  The APSInt is the low value.
757   typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
758   CaseRangesTy CaseRanges;
759 
760   DefaultStmt *TheDefaultStmt = nullptr;
761 
762   bool CaseListIsErroneous = false;
763 
764   for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
765        SC = SC->getNextSwitchCase()) {
766 
767     if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
768       if (TheDefaultStmt) {
769         Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
770         Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
771 
772         // FIXME: Remove the default statement from the switch block so that
773         // we'll return a valid AST.  This requires recursing down the AST and
774         // finding it, not something we are set up to do right now.  For now,
775         // just lop the entire switch stmt out of the AST.
776         CaseListIsErroneous = true;
777       }
778       TheDefaultStmt = DS;
779 
780     } else {
781       CaseStmt *CS = cast<CaseStmt>(SC);
782 
783       Expr *Lo = CS->getLHS();
784 
785       if (Lo->isTypeDependent() || Lo->isValueDependent()) {
786         HasDependentValue = true;
787         break;
788       }
789 
790       llvm::APSInt LoVal;
791 
792       if (getLangOpts().CPlusPlus11) {
793         // C++11 [stmt.switch]p2: the constant-expression shall be a converted
794         // constant expression of the promoted type of the switch condition.
795         ExprResult ConvLo =
796           CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
797         if (ConvLo.isInvalid()) {
798           CaseListIsErroneous = true;
799           continue;
800         }
801         Lo = ConvLo.get();
802       } else {
803         // We already verified that the expression has a i-c-e value (C99
804         // 6.8.4.2p3) - get that value now.
805         LoVal = Lo->EvaluateKnownConstInt(Context);
806 
807         // If the LHS is not the same type as the condition, insert an implicit
808         // cast.
809         Lo = DefaultLvalueConversion(Lo).get();
810         Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get();
811       }
812 
813       // Convert the value to the same width/sign as the condition had prior to
814       // integral promotions.
815       //
816       // FIXME: This causes us to reject valid code:
817       //   switch ((char)c) { case 256: case 0: return 0; }
818       // Here we claim there is a duplicated condition value, but there is not.
819       ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
820                                          Lo->getLocStart(),
821                                          diag::warn_case_value_overflow);
822 
823       CS->setLHS(Lo);
824 
825       // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
826       if (CS->getRHS()) {
827         if (CS->getRHS()->isTypeDependent() ||
828             CS->getRHS()->isValueDependent()) {
829           HasDependentValue = true;
830           break;
831         }
832         CaseRanges.push_back(std::make_pair(LoVal, CS));
833       } else
834         CaseVals.push_back(std::make_pair(LoVal, CS));
835     }
836   }
837 
838   if (!HasDependentValue) {
839     // If we don't have a default statement, check whether the
840     // condition is constant.
841     llvm::APSInt ConstantCondValue;
842     bool HasConstantCond = false;
843     if (!HasDependentValue && !TheDefaultStmt) {
844       HasConstantCond
845         = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
846                                                  Expr::SE_AllowSideEffects);
847       assert(!HasConstantCond ||
848              (ConstantCondValue.getBitWidth() == CondWidth &&
849               ConstantCondValue.isSigned() == CondIsSigned));
850     }
851     bool ShouldCheckConstantCond = HasConstantCond;
852 
853     // Sort all the scalar case values so we can easily detect duplicates.
854     std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
855 
856     if (!CaseVals.empty()) {
857       for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
858         if (ShouldCheckConstantCond &&
859             CaseVals[i].first == ConstantCondValue)
860           ShouldCheckConstantCond = false;
861 
862         if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
863           // If we have a duplicate, report it.
864           // First, determine if either case value has a name
865           StringRef PrevString, CurrString;
866           Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
867           Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
868           if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
869             PrevString = DeclRef->getDecl()->getName();
870           }
871           if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
872             CurrString = DeclRef->getDecl()->getName();
873           }
874           SmallString<16> CaseValStr;
875           CaseVals[i-1].first.toString(CaseValStr);
876 
877           if (PrevString == CurrString)
878             Diag(CaseVals[i].second->getLHS()->getLocStart(),
879                  diag::err_duplicate_case) <<
880                  (PrevString.empty() ? CaseValStr.str() : PrevString);
881           else
882             Diag(CaseVals[i].second->getLHS()->getLocStart(),
883                  diag::err_duplicate_case_differing_expr) <<
884                  (PrevString.empty() ? CaseValStr.str() : PrevString) <<
885                  (CurrString.empty() ? CaseValStr.str() : CurrString) <<
886                  CaseValStr;
887 
888           Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
889                diag::note_duplicate_case_prev);
890           // FIXME: We really want to remove the bogus case stmt from the
891           // substmt, but we have no way to do this right now.
892           CaseListIsErroneous = true;
893         }
894       }
895     }
896 
897     // Detect duplicate case ranges, which usually don't exist at all in
898     // the first place.
899     if (!CaseRanges.empty()) {
900       // Sort all the case ranges by their low value so we can easily detect
901       // overlaps between ranges.
902       std::stable_sort(CaseRanges.begin(), CaseRanges.end());
903 
904       // Scan the ranges, computing the high values and removing empty ranges.
905       std::vector<llvm::APSInt> HiVals;
906       for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
907         llvm::APSInt &LoVal = CaseRanges[i].first;
908         CaseStmt *CR = CaseRanges[i].second;
909         Expr *Hi = CR->getRHS();
910         llvm::APSInt HiVal;
911 
912         if (getLangOpts().CPlusPlus11) {
913           // C++11 [stmt.switch]p2: the constant-expression shall be a converted
914           // constant expression of the promoted type of the switch condition.
915           ExprResult ConvHi =
916             CheckConvertedConstantExpression(Hi, CondType, HiVal,
917                                              CCEK_CaseValue);
918           if (ConvHi.isInvalid()) {
919             CaseListIsErroneous = true;
920             continue;
921           }
922           Hi = ConvHi.get();
923         } else {
924           HiVal = Hi->EvaluateKnownConstInt(Context);
925 
926           // If the RHS is not the same type as the condition, insert an
927           // implicit cast.
928           Hi = DefaultLvalueConversion(Hi).get();
929           Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get();
930         }
931 
932         // Convert the value to the same width/sign as the condition.
933         ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
934                                            Hi->getLocStart(),
935                                            diag::warn_case_value_overflow);
936 
937         CR->setRHS(Hi);
938 
939         // If the low value is bigger than the high value, the case is empty.
940         if (LoVal > HiVal) {
941           Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
942             << SourceRange(CR->getLHS()->getLocStart(),
943                            Hi->getLocEnd());
944           CaseRanges.erase(CaseRanges.begin()+i);
945           --i, --e;
946           continue;
947         }
948 
949         if (ShouldCheckConstantCond &&
950             LoVal <= ConstantCondValue &&
951             ConstantCondValue <= HiVal)
952           ShouldCheckConstantCond = false;
953 
954         HiVals.push_back(HiVal);
955       }
956 
957       // Rescan the ranges, looking for overlap with singleton values and other
958       // ranges.  Since the range list is sorted, we only need to compare case
959       // ranges with their neighbors.
960       for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
961         llvm::APSInt &CRLo = CaseRanges[i].first;
962         llvm::APSInt &CRHi = HiVals[i];
963         CaseStmt *CR = CaseRanges[i].second;
964 
965         // Check to see whether the case range overlaps with any
966         // singleton cases.
967         CaseStmt *OverlapStmt = nullptr;
968         llvm::APSInt OverlapVal(32);
969 
970         // Find the smallest value >= the lower bound.  If I is in the
971         // case range, then we have overlap.
972         CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
973                                                   CaseVals.end(), CRLo,
974                                                   CaseCompareFunctor());
975         if (I != CaseVals.end() && I->first < CRHi) {
976           OverlapVal  = I->first;   // Found overlap with scalar.
977           OverlapStmt = I->second;
978         }
979 
980         // Find the smallest value bigger than the upper bound.
981         I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
982         if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
983           OverlapVal  = (I-1)->first;      // Found overlap with scalar.
984           OverlapStmt = (I-1)->second;
985         }
986 
987         // Check to see if this case stmt overlaps with the subsequent
988         // case range.
989         if (i && CRLo <= HiVals[i-1]) {
990           OverlapVal  = HiVals[i-1];       // Found overlap with range.
991           OverlapStmt = CaseRanges[i-1].second;
992         }
993 
994         if (OverlapStmt) {
995           // If we have a duplicate, report it.
996           Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
997             << OverlapVal.toString(10);
998           Diag(OverlapStmt->getLHS()->getLocStart(),
999                diag::note_duplicate_case_prev);
1000           // FIXME: We really want to remove the bogus case stmt from the
1001           // substmt, but we have no way to do this right now.
1002           CaseListIsErroneous = true;
1003         }
1004       }
1005     }
1006 
1007     // Complain if we have a constant condition and we didn't find a match.
1008     if (!CaseListIsErroneous && ShouldCheckConstantCond) {
1009       // TODO: it would be nice if we printed enums as enums, chars as
1010       // chars, etc.
1011       Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
1012         << ConstantCondValue.toString(10)
1013         << CondExpr->getSourceRange();
1014     }
1015 
1016     // Check to see if switch is over an Enum and handles all of its
1017     // values.  We only issue a warning if there is not 'default:', but
1018     // we still do the analysis to preserve this information in the AST
1019     // (which can be used by flow-based analyes).
1020     //
1021     const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
1022 
1023     // If switch has default case, then ignore it.
1024     if (!CaseListIsErroneous  && !HasConstantCond && ET) {
1025       const EnumDecl *ED = ET->getDecl();
1026       typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
1027         EnumValsTy;
1028       EnumValsTy EnumVals;
1029 
1030       // Gather all enum values, set their type and sort them,
1031       // allowing easier comparison with CaseVals.
1032       for (auto *EDI : ED->enumerators()) {
1033         llvm::APSInt Val = EDI->getInitVal();
1034         AdjustAPSInt(Val, CondWidth, CondIsSigned);
1035         EnumVals.push_back(std::make_pair(Val, EDI));
1036       }
1037       std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1038       EnumValsTy::iterator EIend =
1039         std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1040 
1041       // See which case values aren't in enum.
1042       EnumValsTy::const_iterator EI = EnumVals.begin();
1043       for (CaseValsTy::const_iterator CI = CaseVals.begin();
1044            CI != CaseVals.end(); CI++) {
1045         while (EI != EIend && EI->first < CI->first)
1046           EI++;
1047         if (EI == EIend || EI->first > CI->first) {
1048           Expr *CaseExpr = CI->second->getLHS();
1049           if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1050             Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1051               << CondTypeBeforePromotion;
1052         }
1053       }
1054       // See which of case ranges aren't in enum
1055       EI = EnumVals.begin();
1056       for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
1057            RI != CaseRanges.end() && EI != EIend; RI++) {
1058         while (EI != EIend && EI->first < RI->first)
1059           EI++;
1060 
1061         if (EI == EIend || EI->first != RI->first) {
1062           Expr *CaseExpr = RI->second->getLHS();
1063           if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1064             Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1065               << CondTypeBeforePromotion;
1066         }
1067 
1068         llvm::APSInt Hi =
1069           RI->second->getRHS()->EvaluateKnownConstInt(Context);
1070         AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1071         while (EI != EIend && EI->first < Hi)
1072           EI++;
1073         if (EI == EIend || EI->first != Hi) {
1074           Expr *CaseExpr = RI->second->getRHS();
1075           if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr))
1076             Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum)
1077               << CondTypeBeforePromotion;
1078         }
1079       }
1080 
1081       // Check which enum vals aren't in switch
1082       CaseValsTy::const_iterator CI = CaseVals.begin();
1083       CaseRangesTy::const_iterator RI = CaseRanges.begin();
1084       bool hasCasesNotInSwitch = false;
1085 
1086       SmallVector<DeclarationName,8> UnhandledNames;
1087 
1088       for (EI = EnumVals.begin(); EI != EIend; EI++){
1089         // Drop unneeded case values
1090         while (CI != CaseVals.end() && CI->first < EI->first)
1091           CI++;
1092 
1093         if (CI != CaseVals.end() && CI->first == EI->first)
1094           continue;
1095 
1096         // Drop unneeded case ranges
1097         for (; RI != CaseRanges.end(); RI++) {
1098           llvm::APSInt Hi =
1099             RI->second->getRHS()->EvaluateKnownConstInt(Context);
1100           AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1101           if (EI->first <= Hi)
1102             break;
1103         }
1104 
1105         if (RI == CaseRanges.end() || EI->first < RI->first) {
1106           hasCasesNotInSwitch = true;
1107           UnhandledNames.push_back(EI->second->getDeclName());
1108         }
1109       }
1110 
1111       if (TheDefaultStmt && UnhandledNames.empty())
1112         Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1113 
1114       // Produce a nice diagnostic if multiple values aren't handled.
1115       switch (UnhandledNames.size()) {
1116       case 0: break;
1117       case 1:
1118         Diag(CondExpr->getExprLoc(), TheDefaultStmt
1119           ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
1120           << UnhandledNames[0];
1121         break;
1122       case 2:
1123         Diag(CondExpr->getExprLoc(), TheDefaultStmt
1124           ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
1125           << UnhandledNames[0] << UnhandledNames[1];
1126         break;
1127       case 3:
1128         Diag(CondExpr->getExprLoc(), TheDefaultStmt
1129           ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
1130           << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1131         break;
1132       default:
1133         Diag(CondExpr->getExprLoc(), TheDefaultStmt
1134           ? diag::warn_def_missing_cases : diag::warn_missing_cases)
1135           << (unsigned)UnhandledNames.size()
1136           << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1137         break;
1138       }
1139 
1140       if (!hasCasesNotInSwitch)
1141         SS->setAllEnumCasesCovered();
1142     }
1143   }
1144 
1145   if (BodyStmt)
1146     DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1147                           diag::warn_empty_switch_body);
1148 
1149   // FIXME: If the case list was broken is some way, we don't have a good system
1150   // to patch it up.  Instead, just return the whole substmt as broken.
1151   if (CaseListIsErroneous)
1152     return StmtError();
1153 
1154   return SS;
1155 }
1156 
1157 void
DiagnoseAssignmentEnum(QualType DstType,QualType SrcType,Expr * SrcExpr)1158 Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1159                              Expr *SrcExpr) {
1160   if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc()))
1161     return;
1162 
1163   if (const EnumType *ET = DstType->getAs<EnumType>())
1164     if (!Context.hasSameUnqualifiedType(SrcType, DstType) &&
1165         SrcType->isIntegerType()) {
1166       if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1167           SrcExpr->isIntegerConstantExpr(Context)) {
1168         // Get the bitwidth of the enum value before promotions.
1169         unsigned DstWidth = Context.getIntWidth(DstType);
1170         bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1171 
1172         llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1173         AdjustAPSInt(RhsVal, DstWidth, DstIsSigned);
1174         const EnumDecl *ED = ET->getDecl();
1175         typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64>
1176             EnumValsTy;
1177         EnumValsTy EnumVals;
1178 
1179         // Gather all enum values, set their type and sort them,
1180         // allowing easier comparison with rhs constant.
1181         for (auto *EDI : ED->enumerators()) {
1182           llvm::APSInt Val = EDI->getInitVal();
1183           AdjustAPSInt(Val, DstWidth, DstIsSigned);
1184           EnumVals.push_back(std::make_pair(Val, EDI));
1185         }
1186         if (EnumVals.empty())
1187           return;
1188         std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1189         EnumValsTy::iterator EIend =
1190             std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1191 
1192         // See which values aren't in the enum.
1193         EnumValsTy::const_iterator EI = EnumVals.begin();
1194         while (EI != EIend && EI->first < RhsVal)
1195           EI++;
1196         if (EI == EIend || EI->first != RhsVal) {
1197           Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment)
1198               << DstType.getUnqualifiedType();
1199         }
1200       }
1201     }
1202 }
1203 
1204 StmtResult
ActOnWhileStmt(SourceLocation WhileLoc,FullExprArg Cond,Decl * CondVar,Stmt * Body)1205 Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
1206                      Decl *CondVar, Stmt *Body) {
1207   ExprResult CondResult(Cond.release());
1208 
1209   VarDecl *ConditionVar = nullptr;
1210   if (CondVar) {
1211     ConditionVar = cast<VarDecl>(CondVar);
1212     CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
1213     if (CondResult.isInvalid())
1214       return StmtError();
1215   }
1216   Expr *ConditionExpr = CondResult.get();
1217   if (!ConditionExpr)
1218     return StmtError();
1219   CheckBreakContinueBinding(ConditionExpr);
1220 
1221   DiagnoseUnusedExprResult(Body);
1222 
1223   if (isa<NullStmt>(Body))
1224     getCurCompoundScope().setHasEmptyLoopBodies();
1225 
1226   return new (Context)
1227       WhileStmt(Context, ConditionVar, ConditionExpr, Body, WhileLoc);
1228 }
1229 
1230 StmtResult
ActOnDoStmt(SourceLocation DoLoc,Stmt * Body,SourceLocation WhileLoc,SourceLocation CondLParen,Expr * Cond,SourceLocation CondRParen)1231 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1232                   SourceLocation WhileLoc, SourceLocation CondLParen,
1233                   Expr *Cond, SourceLocation CondRParen) {
1234   assert(Cond && "ActOnDoStmt(): missing expression");
1235 
1236   CheckBreakContinueBinding(Cond);
1237   ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
1238   if (CondResult.isInvalid())
1239     return StmtError();
1240   Cond = CondResult.get();
1241 
1242   CondResult = ActOnFinishFullExpr(Cond, DoLoc);
1243   if (CondResult.isInvalid())
1244     return StmtError();
1245   Cond = CondResult.get();
1246 
1247   DiagnoseUnusedExprResult(Body);
1248 
1249   return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen);
1250 }
1251 
1252 namespace {
1253   // This visitor will traverse a conditional statement and store all
1254   // the evaluated decls into a vector.  Simple is set to true if none
1255   // of the excluded constructs are used.
1256   class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1257     llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1258     SmallVectorImpl<SourceRange> &Ranges;
1259     bool Simple;
1260   public:
1261     typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1262 
DeclExtractor(Sema & S,llvm::SmallPtrSet<VarDecl *,8> & Decls,SmallVectorImpl<SourceRange> & Ranges)1263     DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1264                   SmallVectorImpl<SourceRange> &Ranges) :
1265         Inherited(S.Context),
1266         Decls(Decls),
1267         Ranges(Ranges),
1268         Simple(true) {}
1269 
isSimple()1270     bool isSimple() { return Simple; }
1271 
1272     // Replaces the method in EvaluatedExprVisitor.
VisitMemberExpr(MemberExpr * E)1273     void VisitMemberExpr(MemberExpr* E) {
1274       Simple = false;
1275     }
1276 
1277     // Any Stmt not whitelisted will cause the condition to be marked complex.
VisitStmt(Stmt * S)1278     void VisitStmt(Stmt *S) {
1279       Simple = false;
1280     }
1281 
VisitBinaryOperator(BinaryOperator * E)1282     void VisitBinaryOperator(BinaryOperator *E) {
1283       Visit(E->getLHS());
1284       Visit(E->getRHS());
1285     }
1286 
VisitCastExpr(CastExpr * E)1287     void VisitCastExpr(CastExpr *E) {
1288       Visit(E->getSubExpr());
1289     }
1290 
VisitUnaryOperator(UnaryOperator * E)1291     void VisitUnaryOperator(UnaryOperator *E) {
1292       // Skip checking conditionals with derefernces.
1293       if (E->getOpcode() == UO_Deref)
1294         Simple = false;
1295       else
1296         Visit(E->getSubExpr());
1297     }
1298 
VisitConditionalOperator(ConditionalOperator * E)1299     void VisitConditionalOperator(ConditionalOperator *E) {
1300       Visit(E->getCond());
1301       Visit(E->getTrueExpr());
1302       Visit(E->getFalseExpr());
1303     }
1304 
VisitParenExpr(ParenExpr * E)1305     void VisitParenExpr(ParenExpr *E) {
1306       Visit(E->getSubExpr());
1307     }
1308 
VisitBinaryConditionalOperator(BinaryConditionalOperator * E)1309     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1310       Visit(E->getOpaqueValue()->getSourceExpr());
1311       Visit(E->getFalseExpr());
1312     }
1313 
VisitIntegerLiteral(IntegerLiteral * E)1314     void VisitIntegerLiteral(IntegerLiteral *E) { }
VisitFloatingLiteral(FloatingLiteral * E)1315     void VisitFloatingLiteral(FloatingLiteral *E) { }
VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr * E)1316     void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
VisitCharacterLiteral(CharacterLiteral * E)1317     void VisitCharacterLiteral(CharacterLiteral *E) { }
VisitGNUNullExpr(GNUNullExpr * E)1318     void VisitGNUNullExpr(GNUNullExpr *E) { }
VisitImaginaryLiteral(ImaginaryLiteral * E)1319     void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1320 
VisitDeclRefExpr(DeclRefExpr * E)1321     void VisitDeclRefExpr(DeclRefExpr *E) {
1322       VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1323       if (!VD) return;
1324 
1325       Ranges.push_back(E->getSourceRange());
1326 
1327       Decls.insert(VD);
1328     }
1329 
1330   }; // end class DeclExtractor
1331 
1332   // DeclMatcher checks to see if the decls are used in a non-evauluated
1333   // context.
1334   class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1335     llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1336     bool FoundDecl;
1337 
1338   public:
1339     typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1340 
DeclMatcher(Sema & S,llvm::SmallPtrSet<VarDecl *,8> & Decls,Stmt * Statement)1341     DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1342                 Stmt *Statement) :
1343         Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1344       if (!Statement) return;
1345 
1346       Visit(Statement);
1347     }
1348 
VisitReturnStmt(ReturnStmt * S)1349     void VisitReturnStmt(ReturnStmt *S) {
1350       FoundDecl = true;
1351     }
1352 
VisitBreakStmt(BreakStmt * S)1353     void VisitBreakStmt(BreakStmt *S) {
1354       FoundDecl = true;
1355     }
1356 
VisitGotoStmt(GotoStmt * S)1357     void VisitGotoStmt(GotoStmt *S) {
1358       FoundDecl = true;
1359     }
1360 
VisitCastExpr(CastExpr * E)1361     void VisitCastExpr(CastExpr *E) {
1362       if (E->getCastKind() == CK_LValueToRValue)
1363         CheckLValueToRValueCast(E->getSubExpr());
1364       else
1365         Visit(E->getSubExpr());
1366     }
1367 
CheckLValueToRValueCast(Expr * E)1368     void CheckLValueToRValueCast(Expr *E) {
1369       E = E->IgnoreParenImpCasts();
1370 
1371       if (isa<DeclRefExpr>(E)) {
1372         return;
1373       }
1374 
1375       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1376         Visit(CO->getCond());
1377         CheckLValueToRValueCast(CO->getTrueExpr());
1378         CheckLValueToRValueCast(CO->getFalseExpr());
1379         return;
1380       }
1381 
1382       if (BinaryConditionalOperator *BCO =
1383               dyn_cast<BinaryConditionalOperator>(E)) {
1384         CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1385         CheckLValueToRValueCast(BCO->getFalseExpr());
1386         return;
1387       }
1388 
1389       Visit(E);
1390     }
1391 
VisitDeclRefExpr(DeclRefExpr * E)1392     void VisitDeclRefExpr(DeclRefExpr *E) {
1393       if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1394         if (Decls.count(VD))
1395           FoundDecl = true;
1396     }
1397 
FoundDeclInUse()1398     bool FoundDeclInUse() { return FoundDecl; }
1399 
1400   };  // end class DeclMatcher
1401 
CheckForLoopConditionalStatement(Sema & S,Expr * Second,Expr * Third,Stmt * Body)1402   void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1403                                         Expr *Third, Stmt *Body) {
1404     // Condition is empty
1405     if (!Second) return;
1406 
1407     if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body,
1408                           Second->getLocStart()))
1409       return;
1410 
1411     PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1412     llvm::SmallPtrSet<VarDecl*, 8> Decls;
1413     SmallVector<SourceRange, 10> Ranges;
1414     DeclExtractor DE(S, Decls, Ranges);
1415     DE.Visit(Second);
1416 
1417     // Don't analyze complex conditionals.
1418     if (!DE.isSimple()) return;
1419 
1420     // No decls found.
1421     if (Decls.size() == 0) return;
1422 
1423     // Don't warn on volatile, static, or global variables.
1424     for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1425                                                   E = Decls.end();
1426          I != E; ++I)
1427       if ((*I)->getType().isVolatileQualified() ||
1428           (*I)->hasGlobalStorage()) return;
1429 
1430     if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1431         DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1432         DeclMatcher(S, Decls, Body).FoundDeclInUse())
1433       return;
1434 
1435     // Load decl names into diagnostic.
1436     if (Decls.size() > 4)
1437       PDiag << 0;
1438     else {
1439       PDiag << Decls.size();
1440       for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1441                                                     E = Decls.end();
1442            I != E; ++I)
1443         PDiag << (*I)->getDeclName();
1444     }
1445 
1446     // Load SourceRanges into diagnostic if there is room.
1447     // Otherwise, load the SourceRange of the conditional expression.
1448     if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1449       for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(),
1450                                                   E = Ranges.end();
1451            I != E; ++I)
1452         PDiag << *I;
1453     else
1454       PDiag << Second->getSourceRange();
1455 
1456     S.Diag(Ranges.begin()->getBegin(), PDiag);
1457   }
1458 
1459   // If Statement is an incemement or decrement, return true and sets the
1460   // variables Increment and DRE.
ProcessIterationStmt(Sema & S,Stmt * Statement,bool & Increment,DeclRefExpr * & DRE)1461   bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment,
1462                             DeclRefExpr *&DRE) {
1463     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) {
1464       switch (UO->getOpcode()) {
1465         default: return false;
1466         case UO_PostInc:
1467         case UO_PreInc:
1468           Increment = true;
1469           break;
1470         case UO_PostDec:
1471         case UO_PreDec:
1472           Increment = false;
1473           break;
1474       }
1475       DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr());
1476       return DRE;
1477     }
1478 
1479     if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) {
1480       FunctionDecl *FD = Call->getDirectCallee();
1481       if (!FD || !FD->isOverloadedOperator()) return false;
1482       switch (FD->getOverloadedOperator()) {
1483         default: return false;
1484         case OO_PlusPlus:
1485           Increment = true;
1486           break;
1487         case OO_MinusMinus:
1488           Increment = false;
1489           break;
1490       }
1491       DRE = dyn_cast<DeclRefExpr>(Call->getArg(0));
1492       return DRE;
1493     }
1494 
1495     return false;
1496   }
1497 
1498   // A visitor to determine if a continue or break statement is a
1499   // subexpression.
1500   class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> {
1501     SourceLocation BreakLoc;
1502     SourceLocation ContinueLoc;
1503   public:
BreakContinueFinder(Sema & S,Stmt * Body)1504     BreakContinueFinder(Sema &S, Stmt* Body) :
1505         Inherited(S.Context) {
1506       Visit(Body);
1507     }
1508 
1509     typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited;
1510 
VisitContinueStmt(ContinueStmt * E)1511     void VisitContinueStmt(ContinueStmt* E) {
1512       ContinueLoc = E->getContinueLoc();
1513     }
1514 
VisitBreakStmt(BreakStmt * E)1515     void VisitBreakStmt(BreakStmt* E) {
1516       BreakLoc = E->getBreakLoc();
1517     }
1518 
ContinueFound()1519     bool ContinueFound() { return ContinueLoc.isValid(); }
BreakFound()1520     bool BreakFound() { return BreakLoc.isValid(); }
GetContinueLoc()1521     SourceLocation GetContinueLoc() { return ContinueLoc; }
GetBreakLoc()1522     SourceLocation GetBreakLoc() { return BreakLoc; }
1523 
1524   };  // end class BreakContinueFinder
1525 
1526   // Emit a warning when a loop increment/decrement appears twice per loop
1527   // iteration.  The conditions which trigger this warning are:
1528   // 1) The last statement in the loop body and the third expression in the
1529   //    for loop are both increment or both decrement of the same variable
1530   // 2) No continue statements in the loop body.
CheckForRedundantIteration(Sema & S,Expr * Third,Stmt * Body)1531   void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) {
1532     // Return when there is nothing to check.
1533     if (!Body || !Third) return;
1534 
1535     if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration,
1536                           Third->getLocStart()))
1537       return;
1538 
1539     // Get the last statement from the loop body.
1540     CompoundStmt *CS = dyn_cast<CompoundStmt>(Body);
1541     if (!CS || CS->body_empty()) return;
1542     Stmt *LastStmt = CS->body_back();
1543     if (!LastStmt) return;
1544 
1545     bool LoopIncrement, LastIncrement;
1546     DeclRefExpr *LoopDRE, *LastDRE;
1547 
1548     if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return;
1549     if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return;
1550 
1551     // Check that the two statements are both increments or both decrements
1552     // on the same variable.
1553     if (LoopIncrement != LastIncrement ||
1554         LoopDRE->getDecl() != LastDRE->getDecl()) return;
1555 
1556     if (BreakContinueFinder(S, Body).ContinueFound()) return;
1557 
1558     S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration)
1559          << LastDRE->getDecl() << LastIncrement;
1560     S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here)
1561          << LoopIncrement;
1562   }
1563 
1564 } // end namespace
1565 
1566 
CheckBreakContinueBinding(Expr * E)1567 void Sema::CheckBreakContinueBinding(Expr *E) {
1568   if (!E || getLangOpts().CPlusPlus)
1569     return;
1570   BreakContinueFinder BCFinder(*this, E);
1571   Scope *BreakParent = CurScope->getBreakParent();
1572   if (BCFinder.BreakFound() && BreakParent) {
1573     if (BreakParent->getFlags() & Scope::SwitchScope) {
1574       Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch);
1575     } else {
1576       Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner)
1577           << "break";
1578     }
1579   } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) {
1580     Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner)
1581         << "continue";
1582   }
1583 }
1584 
1585 StmtResult
ActOnForStmt(SourceLocation ForLoc,SourceLocation LParenLoc,Stmt * First,FullExprArg second,Decl * secondVar,FullExprArg third,SourceLocation RParenLoc,Stmt * Body)1586 Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1587                    Stmt *First, FullExprArg second, Decl *secondVar,
1588                    FullExprArg third,
1589                    SourceLocation RParenLoc, Stmt *Body) {
1590   if (!getLangOpts().CPlusPlus) {
1591     if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1592       // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1593       // declare identifiers for objects having storage class 'auto' or
1594       // 'register'.
1595       for (auto *DI : DS->decls()) {
1596         VarDecl *VD = dyn_cast<VarDecl>(DI);
1597         if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
1598           VD = nullptr;
1599         if (!VD) {
1600           Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for);
1601           DI->setInvalidDecl();
1602         }
1603       }
1604     }
1605   }
1606 
1607   CheckBreakContinueBinding(second.get());
1608   CheckBreakContinueBinding(third.get());
1609 
1610   CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1611   CheckForRedundantIteration(*this, third.get(), Body);
1612 
1613   ExprResult SecondResult(second.release());
1614   VarDecl *ConditionVar = nullptr;
1615   if (secondVar) {
1616     ConditionVar = cast<VarDecl>(secondVar);
1617     SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
1618     if (SecondResult.isInvalid())
1619       return StmtError();
1620   }
1621 
1622   Expr *Third  = third.release().getAs<Expr>();
1623 
1624   DiagnoseUnusedExprResult(First);
1625   DiagnoseUnusedExprResult(Third);
1626   DiagnoseUnusedExprResult(Body);
1627 
1628   if (isa<NullStmt>(Body))
1629     getCurCompoundScope().setHasEmptyLoopBodies();
1630 
1631   return new (Context) ForStmt(Context, First, SecondResult.get(), ConditionVar,
1632                                Third, Body, ForLoc, LParenLoc, RParenLoc);
1633 }
1634 
1635 /// In an Objective C collection iteration statement:
1636 ///   for (x in y)
1637 /// x can be an arbitrary l-value expression.  Bind it up as a
1638 /// full-expression.
ActOnForEachLValueExpr(Expr * E)1639 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1640   // Reduce placeholder expressions here.  Note that this rejects the
1641   // use of pseudo-object l-values in this position.
1642   ExprResult result = CheckPlaceholderExpr(E);
1643   if (result.isInvalid()) return StmtError();
1644   E = result.get();
1645 
1646   ExprResult FullExpr = ActOnFinishFullExpr(E);
1647   if (FullExpr.isInvalid())
1648     return StmtError();
1649   return StmtResult(static_cast<Stmt*>(FullExpr.get()));
1650 }
1651 
1652 ExprResult
CheckObjCForCollectionOperand(SourceLocation forLoc,Expr * collection)1653 Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1654   if (!collection)
1655     return ExprError();
1656 
1657   // Bail out early if we've got a type-dependent expression.
1658   if (collection->isTypeDependent()) return collection;
1659 
1660   // Perform normal l-value conversion.
1661   ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1662   if (result.isInvalid())
1663     return ExprError();
1664   collection = result.get();
1665 
1666   // The operand needs to have object-pointer type.
1667   // TODO: should we do a contextual conversion?
1668   const ObjCObjectPointerType *pointerType =
1669     collection->getType()->getAs<ObjCObjectPointerType>();
1670   if (!pointerType)
1671     return Diag(forLoc, diag::err_collection_expr_type)
1672              << collection->getType() << collection->getSourceRange();
1673 
1674   // Check that the operand provides
1675   //   - countByEnumeratingWithState:objects:count:
1676   const ObjCObjectType *objectType = pointerType->getObjectType();
1677   ObjCInterfaceDecl *iface = objectType->getInterface();
1678 
1679   // If we have a forward-declared type, we can't do this check.
1680   // Under ARC, it is an error not to have a forward-declared class.
1681   if (iface &&
1682       RequireCompleteType(forLoc, QualType(objectType, 0),
1683                           getLangOpts().ObjCAutoRefCount
1684                             ? diag::err_arc_collection_forward
1685                             : 0,
1686                           collection)) {
1687     // Otherwise, if we have any useful type information, check that
1688     // the type declares the appropriate method.
1689   } else if (iface || !objectType->qual_empty()) {
1690     IdentifierInfo *selectorIdents[] = {
1691       &Context.Idents.get("countByEnumeratingWithState"),
1692       &Context.Idents.get("objects"),
1693       &Context.Idents.get("count")
1694     };
1695     Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1696 
1697     ObjCMethodDecl *method = nullptr;
1698 
1699     // If there's an interface, look in both the public and private APIs.
1700     if (iface) {
1701       method = iface->lookupInstanceMethod(selector);
1702       if (!method) method = iface->lookupPrivateMethod(selector);
1703     }
1704 
1705     // Also check protocol qualifiers.
1706     if (!method)
1707       method = LookupMethodInQualifiedType(selector, pointerType,
1708                                            /*instance*/ true);
1709 
1710     // If we didn't find it anywhere, give up.
1711     if (!method) {
1712       Diag(forLoc, diag::warn_collection_expr_type)
1713         << collection->getType() << selector << collection->getSourceRange();
1714     }
1715 
1716     // TODO: check for an incompatible signature?
1717   }
1718 
1719   // Wrap up any cleanups in the expression.
1720   return collection;
1721 }
1722 
1723 StmtResult
ActOnObjCForCollectionStmt(SourceLocation ForLoc,Stmt * First,Expr * collection,SourceLocation RParenLoc)1724 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1725                                  Stmt *First, Expr *collection,
1726                                  SourceLocation RParenLoc) {
1727 
1728   ExprResult CollectionExprResult =
1729     CheckObjCForCollectionOperand(ForLoc, collection);
1730 
1731   if (First) {
1732     QualType FirstType;
1733     if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1734       if (!DS->isSingleDecl())
1735         return StmtError(Diag((*DS->decl_begin())->getLocation(),
1736                          diag::err_toomany_element_decls));
1737 
1738       VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl());
1739       if (!D || D->isInvalidDecl())
1740         return StmtError();
1741 
1742       FirstType = D->getType();
1743       // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1744       // declare identifiers for objects having storage class 'auto' or
1745       // 'register'.
1746       if (!D->hasLocalStorage())
1747         return StmtError(Diag(D->getLocation(),
1748                               diag::err_non_local_variable_decl_in_for));
1749 
1750       // If the type contained 'auto', deduce the 'auto' to 'id'.
1751       if (FirstType->getContainedAutoType()) {
1752         OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(),
1753                                  VK_RValue);
1754         Expr *DeducedInit = &OpaqueId;
1755         if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) ==
1756                 DAR_Failed)
1757           DiagnoseAutoDeductionFailure(D, DeducedInit);
1758         if (FirstType.isNull()) {
1759           D->setInvalidDecl();
1760           return StmtError();
1761         }
1762 
1763         D->setType(FirstType);
1764 
1765         if (ActiveTemplateInstantiations.empty()) {
1766           SourceLocation Loc =
1767               D->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
1768           Diag(Loc, diag::warn_auto_var_is_id)
1769             << D->getDeclName();
1770         }
1771       }
1772 
1773     } else {
1774       Expr *FirstE = cast<Expr>(First);
1775       if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1776         return StmtError(Diag(First->getLocStart(),
1777                    diag::err_selector_element_not_lvalue)
1778           << First->getSourceRange());
1779 
1780       FirstType = static_cast<Expr*>(First)->getType();
1781       if (FirstType.isConstQualified())
1782         Diag(ForLoc, diag::err_selector_element_const_type)
1783           << FirstType << First->getSourceRange();
1784     }
1785     if (!FirstType->isDependentType() &&
1786         !FirstType->isObjCObjectPointerType() &&
1787         !FirstType->isBlockPointerType())
1788         return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1789                            << FirstType << First->getSourceRange());
1790   }
1791 
1792   if (CollectionExprResult.isInvalid())
1793     return StmtError();
1794 
1795   CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get());
1796   if (CollectionExprResult.isInvalid())
1797     return StmtError();
1798 
1799   return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(),
1800                                              nullptr, ForLoc, RParenLoc);
1801 }
1802 
1803 /// Finish building a variable declaration for a for-range statement.
1804 /// \return true if an error occurs.
FinishForRangeVarDecl(Sema & SemaRef,VarDecl * Decl,Expr * Init,SourceLocation Loc,int DiagID)1805 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1806                                   SourceLocation Loc, int DiagID) {
1807   // Deduce the type for the iterator variable now rather than leaving it to
1808   // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1809   QualType InitType;
1810   if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
1811       SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) ==
1812           Sema::DAR_Failed)
1813     SemaRef.Diag(Loc, DiagID) << Init->getType();
1814   if (InitType.isNull()) {
1815     Decl->setInvalidDecl();
1816     return true;
1817   }
1818   Decl->setType(InitType);
1819 
1820   // In ARC, infer lifetime.
1821   // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1822   // we're doing the equivalent of fast iteration.
1823   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1824       SemaRef.inferObjCARCLifetime(Decl))
1825     Decl->setInvalidDecl();
1826 
1827   SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1828                                /*TypeMayContainAuto=*/false);
1829   SemaRef.FinalizeDeclaration(Decl);
1830   SemaRef.CurContext->addHiddenDecl(Decl);
1831   return false;
1832 }
1833 
1834 namespace {
1835 
1836 /// Produce a note indicating which begin/end function was implicitly called
1837 /// by a C++11 for-range statement. This is often not obvious from the code,
1838 /// nor from the diagnostics produced when analysing the implicit expressions
1839 /// required in a for-range statement.
NoteForRangeBeginEndFunction(Sema & SemaRef,Expr * E,Sema::BeginEndFunction BEF)1840 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1841                                   Sema::BeginEndFunction BEF) {
1842   CallExpr *CE = dyn_cast<CallExpr>(E);
1843   if (!CE)
1844     return;
1845   FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1846   if (!D)
1847     return;
1848   SourceLocation Loc = D->getLocation();
1849 
1850   std::string Description;
1851   bool IsTemplate = false;
1852   if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1853     Description = SemaRef.getTemplateArgumentBindingsText(
1854       FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1855     IsTemplate = true;
1856   }
1857 
1858   SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1859     << BEF << IsTemplate << Description << E->getType();
1860 }
1861 
1862 /// Build a variable declaration for a for-range statement.
BuildForRangeVarDecl(Sema & SemaRef,SourceLocation Loc,QualType Type,const char * Name)1863 VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1864                               QualType Type, const char *Name) {
1865   DeclContext *DC = SemaRef.CurContext;
1866   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1867   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1868   VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1869                                   TInfo, SC_None);
1870   Decl->setImplicit();
1871   return Decl;
1872 }
1873 
1874 }
1875 
ObjCEnumerationCollection(Expr * Collection)1876 static bool ObjCEnumerationCollection(Expr *Collection) {
1877   return !Collection->isTypeDependent()
1878           && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr;
1879 }
1880 
1881 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
1882 ///
1883 /// C++11 [stmt.ranged]:
1884 ///   A range-based for statement is equivalent to
1885 ///
1886 ///   {
1887 ///     auto && __range = range-init;
1888 ///     for ( auto __begin = begin-expr,
1889 ///           __end = end-expr;
1890 ///           __begin != __end;
1891 ///           ++__begin ) {
1892 ///       for-range-declaration = *__begin;
1893 ///       statement
1894 ///     }
1895 ///   }
1896 ///
1897 /// The body of the loop is not available yet, since it cannot be analysed until
1898 /// we have determined the type of the for-range-declaration.
1899 StmtResult
ActOnCXXForRangeStmt(SourceLocation ForLoc,Stmt * First,SourceLocation ColonLoc,Expr * Range,SourceLocation RParenLoc,BuildForRangeKind Kind)1900 Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
1901                            Stmt *First, SourceLocation ColonLoc, Expr *Range,
1902                            SourceLocation RParenLoc, BuildForRangeKind Kind) {
1903   if (!First)
1904     return StmtError();
1905 
1906   if (Range && ObjCEnumerationCollection(Range))
1907     return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
1908 
1909   DeclStmt *DS = dyn_cast<DeclStmt>(First);
1910   assert(DS && "first part of for range not a decl stmt");
1911 
1912   if (!DS->isSingleDecl()) {
1913     Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1914     return StmtError();
1915   }
1916 
1917   Decl *LoopVar = DS->getSingleDecl();
1918   if (LoopVar->isInvalidDecl() || !Range ||
1919       DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) {
1920     LoopVar->setInvalidDecl();
1921     return StmtError();
1922   }
1923 
1924   // Build  auto && __range = range-init
1925   SourceLocation RangeLoc = Range->getLocStart();
1926   VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1927                                            Context.getAutoRRefDeductType(),
1928                                            "__range");
1929   if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1930                             diag::err_for_range_deduction_failure)) {
1931     LoopVar->setInvalidDecl();
1932     return StmtError();
1933   }
1934 
1935   // Claim the type doesn't contain auto: we've already done the checking.
1936   DeclGroupPtrTy RangeGroup =
1937       BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1),
1938                            /*TypeMayContainAuto=*/ false);
1939   StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1940   if (RangeDecl.isInvalid()) {
1941     LoopVar->setInvalidDecl();
1942     return StmtError();
1943   }
1944 
1945   return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1946                               /*BeginEndDecl=*/nullptr, /*Cond=*/nullptr,
1947                               /*Inc=*/nullptr, DS, RParenLoc, Kind);
1948 }
1949 
1950 /// \brief Create the initialization, compare, and increment steps for
1951 /// the range-based for loop expression.
1952 /// This function does not handle array-based for loops,
1953 /// which are created in Sema::BuildCXXForRangeStmt.
1954 ///
1955 /// \returns a ForRangeStatus indicating success or what kind of error occurred.
1956 /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1957 /// CandidateSet and BEF are set and some non-success value is returned on
1958 /// failure.
BuildNonArrayForRange(Sema & SemaRef,Scope * S,Expr * BeginRange,Expr * EndRange,QualType RangeType,VarDecl * BeginVar,VarDecl * EndVar,SourceLocation ColonLoc,OverloadCandidateSet * CandidateSet,ExprResult * BeginExpr,ExprResult * EndExpr,Sema::BeginEndFunction * BEF)1959 static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1960                                             Expr *BeginRange, Expr *EndRange,
1961                                             QualType RangeType,
1962                                             VarDecl *BeginVar,
1963                                             VarDecl *EndVar,
1964                                             SourceLocation ColonLoc,
1965                                             OverloadCandidateSet *CandidateSet,
1966                                             ExprResult *BeginExpr,
1967                                             ExprResult *EndExpr,
1968                                             Sema::BeginEndFunction *BEF) {
1969   DeclarationNameInfo BeginNameInfo(
1970       &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1971   DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1972                                   ColonLoc);
1973 
1974   LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1975                                  Sema::LookupMemberName);
1976   LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1977 
1978   if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1979     // - if _RangeT is a class type, the unqualified-ids begin and end are
1980     //   looked up in the scope of class _RangeT as if by class member access
1981     //   lookup (3.4.5), and if either (or both) finds at least one
1982     //   declaration, begin-expr and end-expr are __range.begin() and
1983     //   __range.end(), respectively;
1984     SemaRef.LookupQualifiedName(BeginMemberLookup, D);
1985     SemaRef.LookupQualifiedName(EndMemberLookup, D);
1986 
1987     if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1988       SourceLocation RangeLoc = BeginVar->getLocation();
1989       *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
1990 
1991       SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
1992           << RangeLoc << BeginRange->getType() << *BEF;
1993       return Sema::FRS_DiagnosticIssued;
1994     }
1995   } else {
1996     // - otherwise, begin-expr and end-expr are begin(__range) and
1997     //   end(__range), respectively, where begin and end are looked up with
1998     //   argument-dependent lookup (3.4.2). For the purposes of this name
1999     //   lookup, namespace std is an associated namespace.
2000 
2001   }
2002 
2003   *BEF = Sema::BEF_begin;
2004   Sema::ForRangeStatus RangeStatus =
2005       SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
2006                                         Sema::BEF_begin, BeginNameInfo,
2007                                         BeginMemberLookup, CandidateSet,
2008                                         BeginRange, BeginExpr);
2009 
2010   if (RangeStatus != Sema::FRS_Success)
2011     return RangeStatus;
2012   if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
2013                             diag::err_for_range_iter_deduction_failure)) {
2014     NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
2015     return Sema::FRS_DiagnosticIssued;
2016   }
2017 
2018   *BEF = Sema::BEF_end;
2019   RangeStatus =
2020       SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
2021                                         Sema::BEF_end, EndNameInfo,
2022                                         EndMemberLookup, CandidateSet,
2023                                         EndRange, EndExpr);
2024   if (RangeStatus != Sema::FRS_Success)
2025     return RangeStatus;
2026   if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
2027                             diag::err_for_range_iter_deduction_failure)) {
2028     NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
2029     return Sema::FRS_DiagnosticIssued;
2030   }
2031   return Sema::FRS_Success;
2032 }
2033 
2034 /// Speculatively attempt to dereference an invalid range expression.
2035 /// If the attempt fails, this function will return a valid, null StmtResult
2036 /// and emit no diagnostics.
RebuildForRangeWithDereference(Sema & SemaRef,Scope * S,SourceLocation ForLoc,Stmt * LoopVarDecl,SourceLocation ColonLoc,Expr * Range,SourceLocation RangeLoc,SourceLocation RParenLoc)2037 static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
2038                                                  SourceLocation ForLoc,
2039                                                  Stmt *LoopVarDecl,
2040                                                  SourceLocation ColonLoc,
2041                                                  Expr *Range,
2042                                                  SourceLocation RangeLoc,
2043                                                  SourceLocation RParenLoc) {
2044   // Determine whether we can rebuild the for-range statement with a
2045   // dereferenced range expression.
2046   ExprResult AdjustedRange;
2047   {
2048     Sema::SFINAETrap Trap(SemaRef);
2049 
2050     AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
2051     if (AdjustedRange.isInvalid())
2052       return StmtResult();
2053 
2054     StmtResult SR =
2055       SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2056                                    AdjustedRange.get(), RParenLoc,
2057                                    Sema::BFRK_Check);
2058     if (SR.isInvalid())
2059       return StmtResult();
2060   }
2061 
2062   // The attempt to dereference worked well enough that it could produce a valid
2063   // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
2064   // case there are any other (non-fatal) problems with it.
2065   SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
2066     << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
2067   return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
2068                                       AdjustedRange.get(), RParenLoc,
2069                                       Sema::BFRK_Rebuild);
2070 }
2071 
2072 namespace {
2073 /// RAII object to automatically invalidate a declaration if an error occurs.
2074 struct InvalidateOnErrorScope {
InvalidateOnErrorScope__anon199a60c30411::InvalidateOnErrorScope2075   InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled)
2076       : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {}
~InvalidateOnErrorScope__anon199a60c30411::InvalidateOnErrorScope2077   ~InvalidateOnErrorScope() {
2078     if (Enabled && Trap.hasErrorOccurred())
2079       D->setInvalidDecl();
2080   }
2081 
2082   DiagnosticErrorTrap Trap;
2083   Decl *D;
2084   bool Enabled;
2085 };
2086 }
2087 
2088 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
2089 StmtResult
BuildCXXForRangeStmt(SourceLocation ForLoc,SourceLocation ColonLoc,Stmt * RangeDecl,Stmt * BeginEnd,Expr * Cond,Expr * Inc,Stmt * LoopVarDecl,SourceLocation RParenLoc,BuildForRangeKind Kind)2090 Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
2091                            Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
2092                            Expr *Inc, Stmt *LoopVarDecl,
2093                            SourceLocation RParenLoc, BuildForRangeKind Kind) {
2094   Scope *S = getCurScope();
2095 
2096   DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
2097   VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
2098   QualType RangeVarType = RangeVar->getType();
2099 
2100   DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
2101   VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
2102 
2103   // If we hit any errors, mark the loop variable as invalid if its type
2104   // contains 'auto'.
2105   InvalidateOnErrorScope Invalidate(*this, LoopVar,
2106                                     LoopVar->getType()->isUndeducedType());
2107 
2108   StmtResult BeginEndDecl = BeginEnd;
2109   ExprResult NotEqExpr = Cond, IncrExpr = Inc;
2110 
2111   if (RangeVarType->isDependentType()) {
2112     // The range is implicitly used as a placeholder when it is dependent.
2113     RangeVar->markUsed(Context);
2114 
2115     // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill
2116     // them in properly when we instantiate the loop.
2117     if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check)
2118       LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy));
2119   } else if (!BeginEndDecl.get()) {
2120     SourceLocation RangeLoc = RangeVar->getLocation();
2121 
2122     const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
2123 
2124     ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2125                                                 VK_LValue, ColonLoc);
2126     if (BeginRangeRef.isInvalid())
2127       return StmtError();
2128 
2129     ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
2130                                               VK_LValue, ColonLoc);
2131     if (EndRangeRef.isInvalid())
2132       return StmtError();
2133 
2134     QualType AutoType = Context.getAutoDeductType();
2135     Expr *Range = RangeVar->getInit();
2136     if (!Range)
2137       return StmtError();
2138     QualType RangeType = Range->getType();
2139 
2140     if (RequireCompleteType(RangeLoc, RangeType,
2141                             diag::err_for_range_incomplete_type))
2142       return StmtError();
2143 
2144     // Build auto __begin = begin-expr, __end = end-expr.
2145     VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2146                                              "__begin");
2147     VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
2148                                            "__end");
2149 
2150     // Build begin-expr and end-expr and attach to __begin and __end variables.
2151     ExprResult BeginExpr, EndExpr;
2152     if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
2153       // - if _RangeT is an array type, begin-expr and end-expr are __range and
2154       //   __range + __bound, respectively, where __bound is the array bound. If
2155       //   _RangeT is an array of unknown size or an array of incomplete type,
2156       //   the program is ill-formed;
2157 
2158       // begin-expr is __range.
2159       BeginExpr = BeginRangeRef;
2160       if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
2161                                 diag::err_for_range_iter_deduction_failure)) {
2162         NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2163         return StmtError();
2164       }
2165 
2166       // Find the array bound.
2167       ExprResult BoundExpr;
2168       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
2169         BoundExpr = IntegerLiteral::Create(
2170             Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc);
2171       else if (const VariableArrayType *VAT =
2172                dyn_cast<VariableArrayType>(UnqAT))
2173         BoundExpr = VAT->getSizeExpr();
2174       else {
2175         // Can't be a DependentSizedArrayType or an IncompleteArrayType since
2176         // UnqAT is not incomplete and Range is not type-dependent.
2177         llvm_unreachable("Unexpected array type in for-range");
2178       }
2179 
2180       // end-expr is __range + __bound.
2181       EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
2182                            BoundExpr.get());
2183       if (EndExpr.isInvalid())
2184         return StmtError();
2185       if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
2186                                 diag::err_for_range_iter_deduction_failure)) {
2187         NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2188         return StmtError();
2189       }
2190     } else {
2191       OverloadCandidateSet CandidateSet(RangeLoc,
2192                                         OverloadCandidateSet::CSK_Normal);
2193       Sema::BeginEndFunction BEFFailure;
2194       ForRangeStatus RangeStatus =
2195           BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
2196                                 EndRangeRef.get(), RangeType,
2197                                 BeginVar, EndVar, ColonLoc, &CandidateSet,
2198                                 &BeginExpr, &EndExpr, &BEFFailure);
2199 
2200       if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
2201           BEFFailure == BEF_begin) {
2202         // If the range is being built from an array parameter, emit a
2203         // a diagnostic that it is being treated as a pointer.
2204         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) {
2205           if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
2206             QualType ArrayTy = PVD->getOriginalType();
2207             QualType PointerTy = PVD->getType();
2208             if (PointerTy->isPointerType() && ArrayTy->isArrayType()) {
2209               Diag(Range->getLocStart(), diag::err_range_on_array_parameter)
2210                 << RangeLoc << PVD << ArrayTy << PointerTy;
2211               Diag(PVD->getLocation(), diag::note_declared_at);
2212               return StmtError();
2213             }
2214           }
2215         }
2216 
2217         // If building the range failed, try dereferencing the range expression
2218         // unless a diagnostic was issued or the end function is problematic.
2219         StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
2220                                                        LoopVarDecl, ColonLoc,
2221                                                        Range, RangeLoc,
2222                                                        RParenLoc);
2223         if (SR.isInvalid() || SR.isUsable())
2224           return SR;
2225       }
2226 
2227       // Otherwise, emit diagnostics if we haven't already.
2228       if (RangeStatus == FRS_NoViableFunction) {
2229         Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
2230         Diag(Range->getLocStart(), diag::err_for_range_invalid)
2231             << RangeLoc << Range->getType() << BEFFailure;
2232         CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range);
2233       }
2234       // Return an error if no fix was discovered.
2235       if (RangeStatus != FRS_Success)
2236         return StmtError();
2237     }
2238 
2239     assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
2240            "invalid range expression in for loop");
2241 
2242     // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
2243     QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
2244     if (!Context.hasSameType(BeginType, EndType)) {
2245       Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
2246         << BeginType << EndType;
2247       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2248       NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2249     }
2250 
2251     Decl *BeginEndDecls[] = { BeginVar, EndVar };
2252     // Claim the type doesn't contain auto: we've already done the checking.
2253     DeclGroupPtrTy BeginEndGroup =
2254         BuildDeclaratorGroup(MutableArrayRef<Decl *>(BeginEndDecls, 2),
2255                              /*TypeMayContainAuto=*/ false);
2256     BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
2257 
2258     const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
2259     ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2260                                            VK_LValue, ColonLoc);
2261     if (BeginRef.isInvalid())
2262       return StmtError();
2263 
2264     ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
2265                                          VK_LValue, ColonLoc);
2266     if (EndRef.isInvalid())
2267       return StmtError();
2268 
2269     // Build and check __begin != __end expression.
2270     NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
2271                            BeginRef.get(), EndRef.get());
2272     NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
2273     NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
2274     if (NotEqExpr.isInvalid()) {
2275       Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2276         << RangeLoc << 0 << BeginRangeRef.get()->getType();
2277       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2278       if (!Context.hasSameType(BeginType, EndType))
2279         NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
2280       return StmtError();
2281     }
2282 
2283     // Build and check ++__begin expression.
2284     BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2285                                 VK_LValue, ColonLoc);
2286     if (BeginRef.isInvalid())
2287       return StmtError();
2288 
2289     IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
2290     IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
2291     if (IncrExpr.isInvalid()) {
2292       Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2293         << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
2294       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2295       return StmtError();
2296     }
2297 
2298     // Build and check *__begin  expression.
2299     BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2300                                 VK_LValue, ColonLoc);
2301     if (BeginRef.isInvalid())
2302       return StmtError();
2303 
2304     ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2305     if (DerefExpr.isInvalid()) {
2306       Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2307         << RangeLoc << 1 << BeginRangeRef.get()->getType();
2308       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2309       return StmtError();
2310     }
2311 
2312     // Attach  *__begin  as initializer for VD. Don't touch it if we're just
2313     // trying to determine whether this would be a valid range.
2314     if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2315       AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2316                            /*TypeMayContainAuto=*/true);
2317       if (LoopVar->isInvalidDecl())
2318         NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2319     }
2320   }
2321 
2322   // Don't bother to actually allocate the result if we're just trying to
2323   // determine whether it would be valid.
2324   if (Kind == BFRK_Check)
2325     return StmtResult();
2326 
2327   return new (Context) CXXForRangeStmt(
2328       RangeDS, cast_or_null<DeclStmt>(BeginEndDecl.get()), NotEqExpr.get(),
2329       IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, ColonLoc, RParenLoc);
2330 }
2331 
2332 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
2333 /// statement.
FinishObjCForCollectionStmt(Stmt * S,Stmt * B)2334 StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2335   if (!S || !B)
2336     return StmtError();
2337   ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
2338 
2339   ForStmt->setBody(B);
2340   return S;
2341 }
2342 
2343 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2344 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2345 /// body cannot be performed until after the type of the range variable is
2346 /// determined.
FinishCXXForRangeStmt(Stmt * S,Stmt * B)2347 StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2348   if (!S || !B)
2349     return StmtError();
2350 
2351   if (isa<ObjCForCollectionStmt>(S))
2352     return FinishObjCForCollectionStmt(S, B);
2353 
2354   CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2355   ForStmt->setBody(B);
2356 
2357   DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2358                         diag::warn_empty_range_based_for_body);
2359 
2360   return S;
2361 }
2362 
ActOnGotoStmt(SourceLocation GotoLoc,SourceLocation LabelLoc,LabelDecl * TheDecl)2363 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2364                                SourceLocation LabelLoc,
2365                                LabelDecl *TheDecl) {
2366   getCurFunction()->setHasBranchIntoScope();
2367   TheDecl->markUsed(Context);
2368   return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc);
2369 }
2370 
2371 StmtResult
ActOnIndirectGotoStmt(SourceLocation GotoLoc,SourceLocation StarLoc,Expr * E)2372 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
2373                             Expr *E) {
2374   // Convert operand to void*
2375   if (!E->isTypeDependent()) {
2376     QualType ETy = E->getType();
2377     QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
2378     ExprResult ExprRes = E;
2379     AssignConvertType ConvTy =
2380       CheckSingleAssignmentConstraints(DestTy, ExprRes);
2381     if (ExprRes.isInvalid())
2382       return StmtError();
2383     E = ExprRes.get();
2384     if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
2385       return StmtError();
2386   }
2387 
2388   ExprResult ExprRes = ActOnFinishFullExpr(E);
2389   if (ExprRes.isInvalid())
2390     return StmtError();
2391   E = ExprRes.get();
2392 
2393   getCurFunction()->setHasIndirectGoto();
2394 
2395   return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E);
2396 }
2397 
2398 StmtResult
ActOnContinueStmt(SourceLocation ContinueLoc,Scope * CurScope)2399 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
2400   Scope *S = CurScope->getContinueParent();
2401   if (!S) {
2402     // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
2403     return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
2404   }
2405 
2406   return new (Context) ContinueStmt(ContinueLoc);
2407 }
2408 
2409 StmtResult
ActOnBreakStmt(SourceLocation BreakLoc,Scope * CurScope)2410 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
2411   Scope *S = CurScope->getBreakParent();
2412   if (!S) {
2413     // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
2414     return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
2415   }
2416   if (S->isOpenMPLoopScope())
2417     return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt)
2418                      << "break");
2419 
2420   return new (Context) BreakStmt(BreakLoc);
2421 }
2422 
2423 /// \brief Determine whether the given expression is a candidate for
2424 /// copy elision in either a return statement or a throw expression.
2425 ///
2426 /// \param ReturnType If we're determining the copy elision candidate for
2427 /// a return statement, this is the return type of the function. If we're
2428 /// determining the copy elision candidate for a throw expression, this will
2429 /// be a NULL type.
2430 ///
2431 /// \param E The expression being returned from the function or block, or
2432 /// being thrown.
2433 ///
2434 /// \param AllowFunctionParameter Whether we allow function parameters to
2435 /// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2436 /// we re-use this logic to determine whether we should try to move as part of
2437 /// a return or throw (which does allow function parameters).
2438 ///
2439 /// \returns The NRVO candidate variable, if the return statement may use the
2440 /// NRVO, or NULL if there is no such candidate.
getCopyElisionCandidate(QualType ReturnType,Expr * E,bool AllowFunctionParameter)2441 VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2442                                        Expr *E,
2443                                        bool AllowFunctionParameter) {
2444   if (!getLangOpts().CPlusPlus)
2445     return nullptr;
2446 
2447   // - in a return statement in a function [where] ...
2448   // ... the expression is the name of a non-volatile automatic object ...
2449   DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2450   if (!DR || DR->refersToEnclosingLocal())
2451     return nullptr;
2452   VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2453   if (!VD)
2454     return nullptr;
2455 
2456   if (isCopyElisionCandidate(ReturnType, VD, AllowFunctionParameter))
2457     return VD;
2458   return nullptr;
2459 }
2460 
isCopyElisionCandidate(QualType ReturnType,const VarDecl * VD,bool AllowFunctionParameter)2461 bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
2462                                   bool AllowFunctionParameter) {
2463   QualType VDType = VD->getType();
2464   // - in a return statement in a function with ...
2465   // ... a class return type ...
2466   if (!ReturnType.isNull() && !ReturnType->isDependentType()) {
2467     if (!ReturnType->isRecordType())
2468       return false;
2469     // ... the same cv-unqualified type as the function return type ...
2470     if (!VDType->isDependentType() &&
2471         !Context.hasSameUnqualifiedType(ReturnType, VDType))
2472       return false;
2473   }
2474 
2475   // ...object (other than a function or catch-clause parameter)...
2476   if (VD->getKind() != Decl::Var &&
2477       !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2478     return false;
2479   if (VD->isExceptionVariable()) return false;
2480 
2481   // ...automatic...
2482   if (!VD->hasLocalStorage()) return false;
2483 
2484   // ...non-volatile...
2485   if (VD->getType().isVolatileQualified()) return false;
2486 
2487   // __block variables can't be allocated in a way that permits NRVO.
2488   if (VD->hasAttr<BlocksAttr>()) return false;
2489 
2490   // Variables with higher required alignment than their type's ABI
2491   // alignment cannot use NRVO.
2492   if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() &&
2493       Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2494     return false;
2495 
2496   return true;
2497 }
2498 
2499 /// \brief Perform the initialization of a potentially-movable value, which
2500 /// is the result of return value.
2501 ///
2502 /// This routine implements C++0x [class.copy]p33, which attempts to treat
2503 /// returned lvalues as rvalues in certain cases (to prefer move construction),
2504 /// then falls back to treating them as lvalues if that failed.
2505 ExprResult
PerformMoveOrCopyInitialization(const InitializedEntity & Entity,const VarDecl * NRVOCandidate,QualType ResultType,Expr * Value,bool AllowNRVO)2506 Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2507                                       const VarDecl *NRVOCandidate,
2508                                       QualType ResultType,
2509                                       Expr *Value,
2510                                       bool AllowNRVO) {
2511   // C++0x [class.copy]p33:
2512   //   When the criteria for elision of a copy operation are met or would
2513   //   be met save for the fact that the source object is a function
2514   //   parameter, and the object to be copied is designated by an lvalue,
2515   //   overload resolution to select the constructor for the copy is first
2516   //   performed as if the object were designated by an rvalue.
2517   ExprResult Res = ExprError();
2518   if (AllowNRVO &&
2519       (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
2520     ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
2521                               Value->getType(), CK_NoOp, Value, VK_XValue);
2522 
2523     Expr *InitExpr = &AsRvalue;
2524     InitializationKind Kind
2525       = InitializationKind::CreateCopy(Value->getLocStart(),
2526                                        Value->getLocStart());
2527     InitializationSequence Seq(*this, Entity, Kind, InitExpr);
2528 
2529     //   [...] If overload resolution fails, or if the type of the first
2530     //   parameter of the selected constructor is not an rvalue reference
2531     //   to the object's type (possibly cv-qualified), overload resolution
2532     //   is performed again, considering the object as an lvalue.
2533     if (Seq) {
2534       for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2535            StepEnd = Seq.step_end();
2536            Step != StepEnd; ++Step) {
2537         if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
2538           continue;
2539 
2540         CXXConstructorDecl *Constructor
2541         = cast<CXXConstructorDecl>(Step->Function.Function);
2542 
2543         const RValueReferenceType *RRefType
2544           = Constructor->getParamDecl(0)->getType()
2545                                                  ->getAs<RValueReferenceType>();
2546 
2547         // If we don't meet the criteria, break out now.
2548         if (!RRefType ||
2549             !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2550                             Context.getTypeDeclType(Constructor->getParent())))
2551           break;
2552 
2553         // Promote "AsRvalue" to the heap, since we now need this
2554         // expression node to persist.
2555         Value = ImplicitCastExpr::Create(Context, Value->getType(),
2556                                          CK_NoOp, Value, nullptr, VK_XValue);
2557 
2558         // Complete type-checking the initialization of the return type
2559         // using the constructor we found.
2560         Res = Seq.Perform(*this, Entity, Kind, Value);
2561       }
2562     }
2563   }
2564 
2565   // Either we didn't meet the criteria for treating an lvalue as an rvalue,
2566   // above, or overload resolution failed. Either way, we need to try
2567   // (again) now with the return value expression as written.
2568   if (Res.isInvalid())
2569     Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
2570 
2571   return Res;
2572 }
2573 
2574 /// \brief Determine whether the declared return type of the specified function
2575 /// contains 'auto'.
hasDeducedReturnType(FunctionDecl * FD)2576 static bool hasDeducedReturnType(FunctionDecl *FD) {
2577   const FunctionProtoType *FPT =
2578       FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
2579   return FPT->getReturnType()->isUndeducedType();
2580 }
2581 
2582 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2583 /// for capturing scopes.
2584 ///
2585 StmtResult
ActOnCapScopeReturnStmt(SourceLocation ReturnLoc,Expr * RetValExp)2586 Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2587   // If this is the first return we've seen, infer the return type.
2588   // [expr.prim.lambda]p4 in C++11; block literals follow the same rules.
2589   CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
2590   QualType FnRetType = CurCap->ReturnType;
2591   LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap);
2592 
2593   if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) {
2594     // In C++1y, the return type may involve 'auto'.
2595     // FIXME: Blocks might have a return type of 'auto' explicitly specified.
2596     FunctionDecl *FD = CurLambda->CallOperator;
2597     if (CurCap->ReturnType.isNull())
2598       CurCap->ReturnType = FD->getReturnType();
2599 
2600     AutoType *AT = CurCap->ReturnType->getContainedAutoType();
2601     assert(AT && "lost auto type from lambda return type");
2602     if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2603       FD->setInvalidDecl();
2604       return StmtError();
2605     }
2606     CurCap->ReturnType = FnRetType = FD->getReturnType();
2607   } else if (CurCap->HasImplicitReturnType) {
2608     // For blocks/lambdas with implicit return types, we check each return
2609     // statement individually, and deduce the common return type when the block
2610     // or lambda is completed.
2611     // FIXME: Fold this into the 'auto' codepath above.
2612     if (RetValExp && !isa<InitListExpr>(RetValExp)) {
2613       ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2614       if (Result.isInvalid())
2615         return StmtError();
2616       RetValExp = Result.get();
2617 
2618       if (!CurContext->isDependentContext())
2619         FnRetType = RetValExp->getType();
2620       else
2621         FnRetType = CurCap->ReturnType = Context.DependentTy;
2622     } else {
2623       if (RetValExp) {
2624         // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2625         // initializer list, because it is not an expression (even
2626         // though we represent it as one). We still deduce 'void'.
2627         Diag(ReturnLoc, diag::err_lambda_return_init_list)
2628           << RetValExp->getSourceRange();
2629       }
2630 
2631       FnRetType = Context.VoidTy;
2632     }
2633 
2634     // Although we'll properly infer the type of the block once it's completed,
2635     // make sure we provide a return type now for better error recovery.
2636     if (CurCap->ReturnType.isNull())
2637       CurCap->ReturnType = FnRetType;
2638   }
2639   assert(!FnRetType.isNull());
2640 
2641   if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
2642     if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2643       Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2644       return StmtError();
2645     }
2646   } else if (CapturedRegionScopeInfo *CurRegion =
2647                  dyn_cast<CapturedRegionScopeInfo>(CurCap)) {
2648     Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName();
2649     return StmtError();
2650   } else {
2651     assert(CurLambda && "unknown kind of captured scope");
2652     if (CurLambda->CallOperator->getType()->getAs<FunctionType>()
2653             ->getNoReturnAttr()) {
2654       Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2655       return StmtError();
2656     }
2657   }
2658 
2659   // Otherwise, verify that this result type matches the previous one.  We are
2660   // pickier with blocks than for normal functions because we don't have GCC
2661   // compatibility to worry about here.
2662   const VarDecl *NRVOCandidate = nullptr;
2663   if (FnRetType->isDependentType()) {
2664     // Delay processing for now.  TODO: there are lots of dependent
2665     // types we can conclusively prove aren't void.
2666   } else if (FnRetType->isVoidType()) {
2667     if (RetValExp && !isa<InitListExpr>(RetValExp) &&
2668         !(getLangOpts().CPlusPlus &&
2669           (RetValExp->isTypeDependent() ||
2670            RetValExp->getType()->isVoidType()))) {
2671       if (!getLangOpts().CPlusPlus &&
2672           RetValExp->getType()->isVoidType())
2673         Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
2674       else {
2675         Diag(ReturnLoc, diag::err_return_block_has_expr);
2676         RetValExp = nullptr;
2677       }
2678     }
2679   } else if (!RetValExp) {
2680     return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2681   } else if (!RetValExp->isTypeDependent()) {
2682     // we have a non-void block with an expression, continue checking
2683 
2684     // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2685     // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2686     // function return.
2687 
2688     // In C++ the return statement is handled via a copy initialization.
2689     // the C version of which boils down to CheckSingleAssignmentConstraints.
2690     NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2691     InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2692                                                                    FnRetType,
2693                                                       NRVOCandidate != nullptr);
2694     ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2695                                                      FnRetType, RetValExp);
2696     if (Res.isInvalid()) {
2697       // FIXME: Cleanup temporaries here, anyway?
2698       return StmtError();
2699     }
2700     RetValExp = Res.get();
2701     CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc);
2702   } else {
2703     NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2704   }
2705 
2706   if (RetValExp) {
2707     ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2708     if (ER.isInvalid())
2709       return StmtError();
2710     RetValExp = ER.get();
2711   }
2712   ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2713                                                 NRVOCandidate);
2714 
2715   // If we need to check for the named return value optimization,
2716   // or if we need to infer the return type,
2717   // save the return statement in our scope for later processing.
2718   if (CurCap->HasImplicitReturnType || NRVOCandidate)
2719     FunctionScopes.back()->Returns.push_back(Result);
2720 
2721   return Result;
2722 }
2723 
2724 /// Deduce the return type for a function from a returned expression, per
2725 /// C++1y [dcl.spec.auto]p6.
DeduceFunctionTypeFromReturnExpr(FunctionDecl * FD,SourceLocation ReturnLoc,Expr * & RetExpr,AutoType * AT)2726 bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
2727                                             SourceLocation ReturnLoc,
2728                                             Expr *&RetExpr,
2729                                             AutoType *AT) {
2730   TypeLoc OrigResultType = FD->getTypeSourceInfo()->getTypeLoc().
2731     IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc();
2732   QualType Deduced;
2733 
2734   if (RetExpr && isa<InitListExpr>(RetExpr)) {
2735     //  If the deduction is for a return statement and the initializer is
2736     //  a braced-init-list, the program is ill-formed.
2737     Diag(RetExpr->getExprLoc(),
2738          getCurLambda() ? diag::err_lambda_return_init_list
2739                         : diag::err_auto_fn_return_init_list)
2740         << RetExpr->getSourceRange();
2741     return true;
2742   }
2743 
2744   if (FD->isDependentContext()) {
2745     // C++1y [dcl.spec.auto]p12:
2746     //   Return type deduction [...] occurs when the definition is
2747     //   instantiated even if the function body contains a return
2748     //   statement with a non-type-dependent operand.
2749     assert(AT->isDeduced() && "should have deduced to dependent type");
2750     return false;
2751   } else if (RetExpr) {
2752     //  If the deduction is for a return statement and the initializer is
2753     //  a braced-init-list, the program is ill-formed.
2754     if (isa<InitListExpr>(RetExpr)) {
2755       Diag(RetExpr->getExprLoc(), diag::err_auto_fn_return_init_list);
2756       return true;
2757     }
2758 
2759     //  Otherwise, [...] deduce a value for U using the rules of template
2760     //  argument deduction.
2761     DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced);
2762 
2763     if (DAR == DAR_Failed && !FD->isInvalidDecl())
2764       Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure)
2765         << OrigResultType.getType() << RetExpr->getType();
2766 
2767     if (DAR != DAR_Succeeded)
2768       return true;
2769   } else {
2770     //  In the case of a return with no operand, the initializer is considered
2771     //  to be void().
2772     //
2773     // Deduction here can only succeed if the return type is exactly 'cv auto'
2774     // or 'decltype(auto)', so just check for that case directly.
2775     if (!OrigResultType.getType()->getAs<AutoType>()) {
2776       Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto)
2777         << OrigResultType.getType();
2778       return true;
2779     }
2780     // We always deduce U = void in this case.
2781     Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy);
2782     if (Deduced.isNull())
2783       return true;
2784   }
2785 
2786   //  If a function with a declared return type that contains a placeholder type
2787   //  has multiple return statements, the return type is deduced for each return
2788   //  statement. [...] if the type deduced is not the same in each deduction,
2789   //  the program is ill-formed.
2790   if (AT->isDeduced() && !FD->isInvalidDecl()) {
2791     AutoType *NewAT = Deduced->getContainedAutoType();
2792     if (!FD->isDependentContext() &&
2793         !Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) {
2794       const LambdaScopeInfo *LambdaSI = getCurLambda();
2795       if (LambdaSI && LambdaSI->HasImplicitReturnType) {
2796         Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
2797           << NewAT->getDeducedType() << AT->getDeducedType()
2798           << true /*IsLambda*/;
2799       } else {
2800         Diag(ReturnLoc, diag::err_auto_fn_different_deductions)
2801           << (AT->isDecltypeAuto() ? 1 : 0)
2802           << NewAT->getDeducedType() << AT->getDeducedType();
2803       }
2804       return true;
2805     }
2806   } else if (!FD->isInvalidDecl()) {
2807     // Update all declarations of the function to have the deduced return type.
2808     Context.adjustDeducedFunctionResultType(FD, Deduced);
2809   }
2810 
2811   return false;
2812 }
2813 
2814 StmtResult
ActOnReturnStmt(SourceLocation ReturnLoc,Expr * RetValExp,Scope * CurScope)2815 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
2816                       Scope *CurScope) {
2817   StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp);
2818   if (R.isInvalid()) {
2819     return R;
2820   }
2821 
2822   if (VarDecl *VD =
2823       const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) {
2824     CurScope->addNRVOCandidate(VD);
2825   } else {
2826     CurScope->setNoNRVO();
2827   }
2828 
2829   return R;
2830 }
2831 
BuildReturnStmt(SourceLocation ReturnLoc,Expr * RetValExp)2832 StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2833   // Check for unexpanded parameter packs.
2834   if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2835     return StmtError();
2836 
2837   if (isa<CapturingScopeInfo>(getCurFunction()))
2838     return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
2839 
2840   QualType FnRetType;
2841   QualType RelatedRetType;
2842   const AttrVec *Attrs = nullptr;
2843   bool isObjCMethod = false;
2844 
2845   if (const FunctionDecl *FD = getCurFunctionDecl()) {
2846     FnRetType = FD->getReturnType();
2847     if (FD->hasAttrs())
2848       Attrs = &FD->getAttrs();
2849     if (FD->isNoReturn())
2850       Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
2851         << FD->getDeclName();
2852   } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2853     FnRetType = MD->getReturnType();
2854     isObjCMethod = true;
2855     if (MD->hasAttrs())
2856       Attrs = &MD->getAttrs();
2857     if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2858       // In the implementation of a method with a related return type, the
2859       // type used to type-check the validity of return statements within the
2860       // method body is a pointer to the type of the class being implemented.
2861       RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2862       RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
2863     }
2864   } else // If we don't have a function/method context, bail.
2865     return StmtError();
2866 
2867   // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing
2868   // deduction.
2869   if (getLangOpts().CPlusPlus1y) {
2870     if (AutoType *AT = FnRetType->getContainedAutoType()) {
2871       FunctionDecl *FD = cast<FunctionDecl>(CurContext);
2872       if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) {
2873         FD->setInvalidDecl();
2874         return StmtError();
2875       } else {
2876         FnRetType = FD->getReturnType();
2877       }
2878     }
2879   }
2880 
2881   bool HasDependentReturnType = FnRetType->isDependentType();
2882 
2883   ReturnStmt *Result = nullptr;
2884   if (FnRetType->isVoidType()) {
2885     if (RetValExp) {
2886       if (isa<InitListExpr>(RetValExp)) {
2887         // We simply never allow init lists as the return value of void
2888         // functions. This is compatible because this was never allowed before,
2889         // so there's no legacy code to deal with.
2890         NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2891         int FunctionKind = 0;
2892         if (isa<ObjCMethodDecl>(CurDecl))
2893           FunctionKind = 1;
2894         else if (isa<CXXConstructorDecl>(CurDecl))
2895           FunctionKind = 2;
2896         else if (isa<CXXDestructorDecl>(CurDecl))
2897           FunctionKind = 3;
2898 
2899         Diag(ReturnLoc, diag::err_return_init_list)
2900           << CurDecl->getDeclName() << FunctionKind
2901           << RetValExp->getSourceRange();
2902 
2903         // Drop the expression.
2904         RetValExp = nullptr;
2905       } else if (!RetValExp->isTypeDependent()) {
2906         // C99 6.8.6.4p1 (ext_ since GCC warns)
2907         unsigned D = diag::ext_return_has_expr;
2908         if (RetValExp->getType()->isVoidType()) {
2909           NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2910           if (isa<CXXConstructorDecl>(CurDecl) ||
2911               isa<CXXDestructorDecl>(CurDecl))
2912             D = diag::err_ctor_dtor_returns_void;
2913           else
2914             D = diag::ext_return_has_void_expr;
2915         }
2916         else {
2917           ExprResult Result = RetValExp;
2918           Result = IgnoredValueConversions(Result.get());
2919           if (Result.isInvalid())
2920             return StmtError();
2921           RetValExp = Result.get();
2922           RetValExp = ImpCastExprToType(RetValExp,
2923                                         Context.VoidTy, CK_ToVoid).get();
2924         }
2925         // return of void in constructor/destructor is illegal in C++.
2926         if (D == diag::err_ctor_dtor_returns_void) {
2927           NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2928           Diag(ReturnLoc, D)
2929             << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl)
2930             << RetValExp->getSourceRange();
2931         }
2932         // return (some void expression); is legal in C++.
2933         else if (D != diag::ext_return_has_void_expr ||
2934             !getLangOpts().CPlusPlus) {
2935           NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2936 
2937           int FunctionKind = 0;
2938           if (isa<ObjCMethodDecl>(CurDecl))
2939             FunctionKind = 1;
2940           else if (isa<CXXConstructorDecl>(CurDecl))
2941             FunctionKind = 2;
2942           else if (isa<CXXDestructorDecl>(CurDecl))
2943             FunctionKind = 3;
2944 
2945           Diag(ReturnLoc, D)
2946             << CurDecl->getDeclName() << FunctionKind
2947             << RetValExp->getSourceRange();
2948         }
2949       }
2950 
2951       if (RetValExp) {
2952         ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
2953         if (ER.isInvalid())
2954           return StmtError();
2955         RetValExp = ER.get();
2956       }
2957     }
2958 
2959     Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr);
2960   } else if (!RetValExp && !HasDependentReturnType) {
2961     unsigned DiagID = diag::warn_return_missing_expr;  // C90 6.6.6.4p4
2962     // C99 6.8.6.4p1 (ext_ since GCC warns)
2963     if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
2964 
2965     if (FunctionDecl *FD = getCurFunctionDecl())
2966       Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
2967     else
2968       Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
2969     Result = new (Context) ReturnStmt(ReturnLoc);
2970   } else {
2971     assert(RetValExp || HasDependentReturnType);
2972     const VarDecl *NRVOCandidate = nullptr;
2973 
2974     QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType;
2975 
2976     // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2977     // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2978     // function return.
2979 
2980     // In C++ the return statement is handled via a copy initialization,
2981     // the C version of which boils down to CheckSingleAssignmentConstraints.
2982     if (RetValExp)
2983       NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2984     if (!HasDependentReturnType && !RetValExp->isTypeDependent()) {
2985       // we have a non-void function with an expression, continue checking
2986       InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2987                                                                      RetType,
2988                                                       NRVOCandidate != nullptr);
2989       ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2990                                                        RetType, RetValExp);
2991       if (Res.isInvalid()) {
2992         // FIXME: Clean up temporaries here anyway?
2993         return StmtError();
2994       }
2995       RetValExp = Res.getAs<Expr>();
2996 
2997       // If we have a related result type, we need to implicitly
2998       // convert back to the formal result type.  We can't pretend to
2999       // initialize the result again --- we might end double-retaining
3000       // --- so instead we initialize a notional temporary.
3001       if (!RelatedRetType.isNull()) {
3002         Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(),
3003                                                             FnRetType);
3004         Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp);
3005         if (Res.isInvalid()) {
3006           // FIXME: Clean up temporaries here anyway?
3007           return StmtError();
3008         }
3009         RetValExp = Res.getAs<Expr>();
3010       }
3011 
3012       CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs,
3013                          getCurFunctionDecl());
3014     }
3015 
3016     if (RetValExp) {
3017       ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc);
3018       if (ER.isInvalid())
3019         return StmtError();
3020       RetValExp = ER.get();
3021     }
3022     Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
3023   }
3024 
3025   // If we need to check for the named return value optimization, save the
3026   // return statement in our scope for later processing.
3027   if (Result->getNRVOCandidate())
3028     FunctionScopes.back()->Returns.push_back(Result);
3029 
3030   return Result;
3031 }
3032 
3033 StmtResult
ActOnObjCAtCatchStmt(SourceLocation AtLoc,SourceLocation RParen,Decl * Parm,Stmt * Body)3034 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
3035                            SourceLocation RParen, Decl *Parm,
3036                            Stmt *Body) {
3037   VarDecl *Var = cast_or_null<VarDecl>(Parm);
3038   if (Var && Var->isInvalidDecl())
3039     return StmtError();
3040 
3041   return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body);
3042 }
3043 
3044 StmtResult
ActOnObjCAtFinallyStmt(SourceLocation AtLoc,Stmt * Body)3045 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
3046   return new (Context) ObjCAtFinallyStmt(AtLoc, Body);
3047 }
3048 
3049 StmtResult
ActOnObjCAtTryStmt(SourceLocation AtLoc,Stmt * Try,MultiStmtArg CatchStmts,Stmt * Finally)3050 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
3051                          MultiStmtArg CatchStmts, Stmt *Finally) {
3052   if (!getLangOpts().ObjCExceptions)
3053     Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
3054 
3055   getCurFunction()->setHasBranchProtectedScope();
3056   unsigned NumCatchStmts = CatchStmts.size();
3057   return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(),
3058                                NumCatchStmts, Finally);
3059 }
3060 
BuildObjCAtThrowStmt(SourceLocation AtLoc,Expr * Throw)3061 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
3062   if (Throw) {
3063     ExprResult Result = DefaultLvalueConversion(Throw);
3064     if (Result.isInvalid())
3065       return StmtError();
3066 
3067     Result = ActOnFinishFullExpr(Result.get());
3068     if (Result.isInvalid())
3069       return StmtError();
3070     Throw = Result.get();
3071 
3072     QualType ThrowType = Throw->getType();
3073     // Make sure the expression type is an ObjC pointer or "void *".
3074     if (!ThrowType->isDependentType() &&
3075         !ThrowType->isObjCObjectPointerType()) {
3076       const PointerType *PT = ThrowType->getAs<PointerType>();
3077       if (!PT || !PT->getPointeeType()->isVoidType())
3078         return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
3079                          << Throw->getType() << Throw->getSourceRange());
3080     }
3081   }
3082 
3083   return new (Context) ObjCAtThrowStmt(AtLoc, Throw);
3084 }
3085 
3086 StmtResult
ActOnObjCAtThrowStmt(SourceLocation AtLoc,Expr * Throw,Scope * CurScope)3087 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
3088                            Scope *CurScope) {
3089   if (!getLangOpts().ObjCExceptions)
3090     Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
3091 
3092   if (!Throw) {
3093     // @throw without an expression designates a rethrow (which much occur
3094     // in the context of an @catch clause).
3095     Scope *AtCatchParent = CurScope;
3096     while (AtCatchParent && !AtCatchParent->isAtCatchScope())
3097       AtCatchParent = AtCatchParent->getParent();
3098     if (!AtCatchParent)
3099       return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
3100   }
3101   return BuildObjCAtThrowStmt(AtLoc, Throw);
3102 }
3103 
3104 ExprResult
ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,Expr * operand)3105 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
3106   ExprResult result = DefaultLvalueConversion(operand);
3107   if (result.isInvalid())
3108     return ExprError();
3109   operand = result.get();
3110 
3111   // Make sure the expression type is an ObjC pointer or "void *".
3112   QualType type = operand->getType();
3113   if (!type->isDependentType() &&
3114       !type->isObjCObjectPointerType()) {
3115     const PointerType *pointerType = type->getAs<PointerType>();
3116     if (!pointerType || !pointerType->getPointeeType()->isVoidType())
3117       return Diag(atLoc, diag::error_objc_synchronized_expects_object)
3118                << type << operand->getSourceRange();
3119   }
3120 
3121   // The operand to @synchronized is a full-expression.
3122   return ActOnFinishFullExpr(operand);
3123 }
3124 
3125 StmtResult
ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,Expr * SyncExpr,Stmt * SyncBody)3126 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
3127                                   Stmt *SyncBody) {
3128   // We can't jump into or indirect-jump out of a @synchronized block.
3129   getCurFunction()->setHasBranchProtectedScope();
3130   return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody);
3131 }
3132 
3133 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
3134 /// and creates a proper catch handler from them.
3135 StmtResult
ActOnCXXCatchBlock(SourceLocation CatchLoc,Decl * ExDecl,Stmt * HandlerBlock)3136 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
3137                          Stmt *HandlerBlock) {
3138   // There's nothing to test that ActOnExceptionDecl didn't already test.
3139   return new (Context)
3140       CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock);
3141 }
3142 
3143 StmtResult
ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc,Stmt * Body)3144 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
3145   getCurFunction()->setHasBranchProtectedScope();
3146   return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body);
3147 }
3148 
3149 namespace {
3150 
3151 class TypeWithHandler {
3152   QualType t;
3153   CXXCatchStmt *stmt;
3154 public:
TypeWithHandler(const QualType & type,CXXCatchStmt * statement)3155   TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
3156   : t(type), stmt(statement) {}
3157 
3158   // An arbitrary order is fine as long as it places identical
3159   // types next to each other.
operator <(const TypeWithHandler & y) const3160   bool operator<(const TypeWithHandler &y) const {
3161     if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
3162       return true;
3163     if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
3164       return false;
3165     else
3166       return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
3167   }
3168 
operator ==(const TypeWithHandler & other) const3169   bool operator==(const TypeWithHandler& other) const {
3170     return t == other.t;
3171   }
3172 
getCatchStmt() const3173   CXXCatchStmt *getCatchStmt() const { return stmt; }
getTypeSpecStartLoc() const3174   SourceLocation getTypeSpecStartLoc() const {
3175     return stmt->getExceptionDecl()->getTypeSpecStartLoc();
3176   }
3177 };
3178 
3179 }
3180 
3181 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
3182 /// handlers and creates a try statement from them.
ActOnCXXTryBlock(SourceLocation TryLoc,Stmt * TryBlock,ArrayRef<Stmt * > Handlers)3183 StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
3184                                   ArrayRef<Stmt *> Handlers) {
3185   // Don't report an error if 'try' is used in system headers.
3186   if (!getLangOpts().CXXExceptions &&
3187       !getSourceManager().isInSystemHeader(TryLoc))
3188       Diag(TryLoc, diag::err_exceptions_disabled) << "try";
3189 
3190   if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
3191     Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try";
3192 
3193   const unsigned NumHandlers = Handlers.size();
3194   assert(NumHandlers > 0 &&
3195          "The parser shouldn't call this if there are no handlers.");
3196 
3197   SmallVector<TypeWithHandler, 8> TypesWithHandlers;
3198 
3199   for (unsigned i = 0; i < NumHandlers; ++i) {
3200     CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
3201     if (!Handler->getExceptionDecl()) {
3202       if (i < NumHandlers - 1)
3203         return StmtError(Diag(Handler->getLocStart(),
3204                               diag::err_early_catch_all));
3205 
3206       continue;
3207     }
3208 
3209     const QualType CaughtType = Handler->getCaughtType();
3210     const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
3211     TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
3212   }
3213 
3214   // Detect handlers for the same type as an earlier one.
3215   if (NumHandlers > 1) {
3216     llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
3217 
3218     TypeWithHandler prev = TypesWithHandlers[0];
3219     for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
3220       TypeWithHandler curr = TypesWithHandlers[i];
3221 
3222       if (curr == prev) {
3223         Diag(curr.getTypeSpecStartLoc(),
3224              diag::warn_exception_caught_by_earlier_handler)
3225           << curr.getCatchStmt()->getCaughtType().getAsString();
3226         Diag(prev.getTypeSpecStartLoc(),
3227              diag::note_previous_exception_handler)
3228           << prev.getCatchStmt()->getCaughtType().getAsString();
3229       }
3230 
3231       prev = curr;
3232     }
3233   }
3234 
3235   getCurFunction()->setHasBranchProtectedScope();
3236 
3237   // FIXME: We should detect handlers that cannot catch anything because an
3238   // earlier handler catches a superclass. Need to find a method that is not
3239   // quadratic for this.
3240   // Neither of these are explicitly forbidden, but every compiler detects them
3241   // and warns.
3242 
3243   return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers);
3244 }
3245 
3246 StmtResult
ActOnSEHTryBlock(bool IsCXXTry,SourceLocation TryLoc,Stmt * TryBlock,Stmt * Handler)3247 Sema::ActOnSEHTryBlock(bool IsCXXTry,
3248                        SourceLocation TryLoc,
3249                        Stmt *TryBlock,
3250                        Stmt *Handler) {
3251   assert(TryBlock && Handler);
3252 
3253   getCurFunction()->setHasBranchProtectedScope();
3254 
3255   return SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler);
3256 }
3257 
3258 StmtResult
ActOnSEHExceptBlock(SourceLocation Loc,Expr * FilterExpr,Stmt * Block)3259 Sema::ActOnSEHExceptBlock(SourceLocation Loc,
3260                           Expr *FilterExpr,
3261                           Stmt *Block) {
3262   assert(FilterExpr && Block);
3263 
3264   if(!FilterExpr->getType()->isIntegerType()) {
3265     return StmtError(Diag(FilterExpr->getExprLoc(),
3266                      diag::err_filter_expression_integral)
3267                      << FilterExpr->getType());
3268   }
3269 
3270   return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block);
3271 }
3272 
3273 StmtResult
ActOnSEHFinallyBlock(SourceLocation Loc,Stmt * Block)3274 Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
3275                            Stmt *Block) {
3276   assert(Block);
3277   return SEHFinallyStmt::Create(Context,Loc,Block);
3278 }
3279 
3280 StmtResult
ActOnSEHLeaveStmt(SourceLocation Loc,Scope * CurScope)3281 Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) {
3282   Scope *SEHTryParent = CurScope;
3283   while (SEHTryParent && !SEHTryParent->isSEHTryScope())
3284     SEHTryParent = SEHTryParent->getParent();
3285   if (!SEHTryParent)
3286     return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try));
3287 
3288   return new (Context) SEHLeaveStmt(Loc);
3289 }
3290 
BuildMSDependentExistsStmt(SourceLocation KeywordLoc,bool IsIfExists,NestedNameSpecifierLoc QualifierLoc,DeclarationNameInfo NameInfo,Stmt * Nested)3291 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
3292                                             bool IsIfExists,
3293                                             NestedNameSpecifierLoc QualifierLoc,
3294                                             DeclarationNameInfo NameInfo,
3295                                             Stmt *Nested)
3296 {
3297   return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
3298                                              QualifierLoc, NameInfo,
3299                                              cast<CompoundStmt>(Nested));
3300 }
3301 
3302 
ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,bool IsIfExists,CXXScopeSpec & SS,UnqualifiedId & Name,Stmt * Nested)3303 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
3304                                             bool IsIfExists,
3305                                             CXXScopeSpec &SS,
3306                                             UnqualifiedId &Name,
3307                                             Stmt *Nested) {
3308   return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
3309                                     SS.getWithLocInContext(Context),
3310                                     GetNameFromUnqualifiedId(Name),
3311                                     Nested);
3312 }
3313 
3314 RecordDecl*
CreateCapturedStmtRecordDecl(CapturedDecl * & CD,SourceLocation Loc,unsigned NumParams)3315 Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc,
3316                                    unsigned NumParams) {
3317   DeclContext *DC = CurContext;
3318   while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
3319     DC = DC->getParent();
3320 
3321   RecordDecl *RD = nullptr;
3322   if (getLangOpts().CPlusPlus)
3323     RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc,
3324                                /*Id=*/nullptr);
3325   else
3326     RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr);
3327 
3328   DC->addDecl(RD);
3329   RD->setImplicit();
3330   RD->startDefinition();
3331 
3332   assert(NumParams > 0 && "CapturedStmt requires context parameter");
3333   CD = CapturedDecl::Create(Context, CurContext, NumParams);
3334   DC->addDecl(CD);
3335   return RD;
3336 }
3337 
buildCapturedStmtCaptureList(SmallVectorImpl<CapturedStmt::Capture> & Captures,SmallVectorImpl<Expr * > & CaptureInits,ArrayRef<CapturingScopeInfo::Capture> Candidates)3338 static void buildCapturedStmtCaptureList(
3339     SmallVectorImpl<CapturedStmt::Capture> &Captures,
3340     SmallVectorImpl<Expr *> &CaptureInits,
3341     ArrayRef<CapturingScopeInfo::Capture> Candidates) {
3342 
3343   typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter;
3344   for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) {
3345 
3346     if (Cap->isThisCapture()) {
3347       Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3348                                                CapturedStmt::VCK_This));
3349       CaptureInits.push_back(Cap->getInitExpr());
3350       continue;
3351     }
3352 
3353     assert(Cap->isReferenceCapture() &&
3354            "non-reference capture not yet implemented");
3355 
3356     Captures.push_back(CapturedStmt::Capture(Cap->getLocation(),
3357                                              CapturedStmt::VCK_ByRef,
3358                                              Cap->getVariable()));
3359     CaptureInits.push_back(Cap->getInitExpr());
3360   }
3361 }
3362 
ActOnCapturedRegionStart(SourceLocation Loc,Scope * CurScope,CapturedRegionKind Kind,unsigned NumParams)3363 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3364                                     CapturedRegionKind Kind,
3365                                     unsigned NumParams) {
3366   CapturedDecl *CD = nullptr;
3367   RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams);
3368 
3369   // Build the context parameter
3370   DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3371   IdentifierInfo *ParamName = &Context.Idents.get("__context");
3372   QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3373   ImplicitParamDecl *Param
3374     = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3375   DC->addDecl(Param);
3376 
3377   CD->setContextParam(0, Param);
3378 
3379   // Enter the capturing scope for this captured region.
3380   PushCapturedRegionScope(CurScope, CD, RD, Kind);
3381 
3382   if (CurScope)
3383     PushDeclContext(CurScope, CD);
3384   else
3385     CurContext = CD;
3386 
3387   PushExpressionEvaluationContext(PotentiallyEvaluated);
3388 }
3389 
ActOnCapturedRegionStart(SourceLocation Loc,Scope * CurScope,CapturedRegionKind Kind,ArrayRef<CapturedParamNameType> Params)3390 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
3391                                     CapturedRegionKind Kind,
3392                                     ArrayRef<CapturedParamNameType> Params) {
3393   CapturedDecl *CD = nullptr;
3394   RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size());
3395 
3396   // Build the context parameter
3397   DeclContext *DC = CapturedDecl::castToDeclContext(CD);
3398   bool ContextIsFound = false;
3399   unsigned ParamNum = 0;
3400   for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(),
3401                                                  E = Params.end();
3402        I != E; ++I, ++ParamNum) {
3403     if (I->second.isNull()) {
3404       assert(!ContextIsFound &&
3405              "null type has been found already for '__context' parameter");
3406       IdentifierInfo *ParamName = &Context.Idents.get("__context");
3407       QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3408       ImplicitParamDecl *Param
3409         = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3410       DC->addDecl(Param);
3411       CD->setContextParam(ParamNum, Param);
3412       ContextIsFound = true;
3413     } else {
3414       IdentifierInfo *ParamName = &Context.Idents.get(I->first);
3415       ImplicitParamDecl *Param
3416         = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second);
3417       DC->addDecl(Param);
3418       CD->setParam(ParamNum, Param);
3419     }
3420   }
3421   assert(ContextIsFound && "no null type for '__context' parameter");
3422   if (!ContextIsFound) {
3423     // Add __context implicitly if it is not specified.
3424     IdentifierInfo *ParamName = &Context.Idents.get("__context");
3425     QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD));
3426     ImplicitParamDecl *Param =
3427         ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType);
3428     DC->addDecl(Param);
3429     CD->setContextParam(ParamNum, Param);
3430   }
3431   // Enter the capturing scope for this captured region.
3432   PushCapturedRegionScope(CurScope, CD, RD, Kind);
3433 
3434   if (CurScope)
3435     PushDeclContext(CurScope, CD);
3436   else
3437     CurContext = CD;
3438 
3439   PushExpressionEvaluationContext(PotentiallyEvaluated);
3440 }
3441 
ActOnCapturedRegionError()3442 void Sema::ActOnCapturedRegionError() {
3443   DiscardCleanupsInEvaluationContext();
3444   PopExpressionEvaluationContext();
3445 
3446   CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3447   RecordDecl *Record = RSI->TheRecordDecl;
3448   Record->setInvalidDecl();
3449 
3450   SmallVector<Decl*, 4> Fields(Record->fields());
3451   ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields,
3452               SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr);
3453 
3454   PopDeclContext();
3455   PopFunctionScopeInfo();
3456 }
3457 
ActOnCapturedRegionEnd(Stmt * S)3458 StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) {
3459   CapturedRegionScopeInfo *RSI = getCurCapturedRegion();
3460 
3461   SmallVector<CapturedStmt::Capture, 4> Captures;
3462   SmallVector<Expr *, 4> CaptureInits;
3463   buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures);
3464 
3465   CapturedDecl *CD = RSI->TheCapturedDecl;
3466   RecordDecl *RD = RSI->TheRecordDecl;
3467 
3468   CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S,
3469                                            RSI->CapRegionKind, Captures,
3470                                            CaptureInits, CD, RD);
3471 
3472   CD->setBody(Res->getCapturedStmt());
3473   RD->completeDefinition();
3474 
3475   DiscardCleanupsInEvaluationContext();
3476   PopExpressionEvaluationContext();
3477 
3478   PopDeclContext();
3479   PopFunctionScopeInfo();
3480 
3481   return Res;
3482 }
3483