1 //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for statements.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Scope.h"
16 #include "clang/Sema/ScopeInfo.h"
17 #include "clang/Sema/Initialization.h"
18 #include "clang/Sema/Lookup.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Basic/TargetInfo.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;
38 StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
40 if (!E) // FIXME: FullExprArg has no error state?
43 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
44 // void expression for its side effects. Conversion to void allows any
45 // operand, even incomplete types.
47 // Same thing in for stmt first clause (when expr) and third clause.
48 return Owned(static_cast<Stmt*>(E));
52 StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
53 bool HasLeadingEmptyMacro) {
54 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
57 StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
58 SourceLocation EndLoc) {
59 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
61 // If we have an invalid decl, just return an error.
62 if (DG.isNull()) return StmtError();
64 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
67 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
68 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
70 // If we have an invalid decl, just return.
71 if (DG.isNull() || !DG.isSingleDecl()) return;
72 VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
74 // suppress any potential 'unused variable' warning.
77 // foreach variables are never actually initialized in the way that
78 // the parser came up with.
81 // In ARC, we don't need to retain the iteration variable of a fast
82 // enumeration loop. Rather than actually trying to catch that
83 // during declaration processing, we remove the consequences here.
84 if (getLangOpts().ObjCAutoRefCount) {
85 QualType type = var->getType();
87 // Only do this if we inferred the lifetime. Inferred lifetime
88 // will show up as a local qualifier because explicit lifetime
89 // should have shown up as an AttributedType instead.
90 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
91 // Add 'const' and mark the variable as pseudo-strong.
92 var->setType(type.withConst());
93 var->setARCPseudoStrong(true);
98 /// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
100 /// Adding a cast to void (or other expression wrappers) will prevent the
101 /// warning from firing.
102 static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
104 bool IsNotEqual, CanAssign;
106 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
107 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
110 Loc = Op->getOperatorLoc();
111 IsNotEqual = Op->getOpcode() == BO_NE;
112 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
113 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
114 if (Op->getOperator() != OO_EqualEqual &&
115 Op->getOperator() != OO_ExclaimEqual)
118 Loc = Op->getOperatorLoc();
119 IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
120 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
122 // Not a typo-prone comparison.
126 // Suppress warnings when the operator, suspicious as it may be, comes from
127 // a macro expansion.
131 S.Diag(Loc, diag::warn_unused_comparison)
132 << (unsigned)IsNotEqual << E->getSourceRange();
134 // If the LHS is a plausible entity to assign to, provide a fixit hint to
135 // correct common typos.
138 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
139 << FixItHint::CreateReplacement(Loc, "|=");
141 S.Diag(Loc, diag::note_equality_comparison_to_assign)
142 << FixItHint::CreateReplacement(Loc, "=");
148 void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
149 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
150 return DiagnoseUnusedExprResult(Label->getSubStmt());
152 const Expr *E = dyn_cast_or_null<Expr>(S);
156 const Expr *WarnExpr;
159 if (SourceMgr.isInSystemMacro(E->getExprLoc()) ||
160 !E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
163 // If this is a GNU statement expression expanded from a macro, it is probably
164 // unused because it is a function-like macro that can be used as either an
165 // expression or statement. Don't warn, because it is almost certainly a
167 if (isa<StmtExpr>(E) && Loc.isMacroID())
170 // Okay, we have an unused result. Depending on what the base expression is,
171 // we might want to make a more specific diagnostic. Check for one of these
173 unsigned DiagID = diag::warn_unused_expr;
174 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
175 E = Temps->getSubExpr();
176 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
177 E = TempExpr->getSubExpr();
179 if (DiagnoseUnusedComparison(*this, E))
183 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
184 if (E->getType()->isVoidType())
187 // If the callee has attribute pure, const, or warn_unused_result, warn with
188 // a more specific message to make it clear what is happening.
189 if (const Decl *FD = CE->getCalleeDecl()) {
190 if (FD->getAttr<WarnUnusedResultAttr>()) {
191 Diag(Loc, diag::warn_unused_result) << R1 << R2;
194 if (FD->getAttr<PureAttr>()) {
195 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
198 if (FD->getAttr<ConstAttr>()) {
199 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
203 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
204 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
205 Diag(Loc, diag::err_arc_unused_init_message) << R1;
208 const ObjCMethodDecl *MD = ME->getMethodDecl();
209 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
210 Diag(Loc, diag::warn_unused_result) << R1 << R2;
213 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
214 const Expr *Source = POE->getSyntacticForm();
215 if (isa<ObjCSubscriptRefExpr>(Source))
216 DiagID = diag::warn_unused_container_subscript_expr;
218 DiagID = diag::warn_unused_property_expr;
219 } else if (const CXXFunctionalCastExpr *FC
220 = dyn_cast<CXXFunctionalCastExpr>(E)) {
221 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
222 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
225 // Diagnose "(void*) blah" as a typo for "(void) blah".
226 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
227 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
228 QualType T = TI->getType();
230 // We really do want to use the non-canonical type here.
231 if (T == Context.VoidPtrTy) {
232 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
234 Diag(Loc, diag::warn_unused_voidptr)
235 << FixItHint::CreateRemoval(TL.getStarLoc());
240 if (E->isGLValue() && E->getType().isVolatileQualified()) {
241 Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
245 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
248 void Sema::ActOnStartOfCompoundStmt() {
252 void Sema::ActOnFinishOfCompoundStmt() {
256 sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
257 return getCurFunction()->CompoundScopes.back();
261 Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
262 MultiStmtArg elts, bool isStmtExpr) {
263 unsigned NumElts = elts.size();
264 Stmt **Elts = elts.data();
265 // If we're in C89 mode, check that we don't have any decls after stmts. If
266 // so, emit an extension diagnostic.
267 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
268 // Note that __extension__ can be around a decl.
270 // Skip over all declarations.
271 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
274 // We found the end of the list or a statement. Scan for another declstmt.
275 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
279 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
280 Diag(D->getLocation(), diag::ext_mixed_decls_code);
283 // Warn about unused expressions in statements.
284 for (unsigned i = 0; i != NumElts; ++i) {
285 // Ignore statements that are last in a statement expression.
286 if (isStmtExpr && i == NumElts - 1)
289 DiagnoseUnusedExprResult(Elts[i]);
292 // Check for suspicious empty body (null statement) in `for' and `while'
293 // statements. Don't do anything for template instantiations, this just adds
295 if (NumElts != 0 && !CurrentInstantiationScope &&
296 getCurCompoundScope().HasEmptyLoopBodies) {
297 for (unsigned i = 0; i != NumElts - 1; ++i)
298 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
301 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
305 Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
306 SourceLocation DotDotDotLoc, Expr *RHSVal,
307 SourceLocation ColonLoc) {
308 assert((LHSVal != 0) && "missing expression in case statement");
310 if (getCurFunction()->SwitchStack.empty()) {
311 Diag(CaseLoc, diag::err_case_not_in_switch);
315 if (!getLangOpts().CPlusPlus0x) {
316 // C99 6.8.4.2p3: The expression shall be an integer constant.
317 // However, GCC allows any evaluatable integer expression.
318 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
319 LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
324 // GCC extension: The expression shall be an integer constant.
326 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
327 RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
328 // Recover from an error by just forgetting about it.
332 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
334 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
338 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
339 void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
340 DiagnoseUnusedExprResult(SubStmt);
342 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
343 CS->setSubStmt(SubStmt);
347 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
348 Stmt *SubStmt, Scope *CurScope) {
349 DiagnoseUnusedExprResult(SubStmt);
351 if (getCurFunction()->SwitchStack.empty()) {
352 Diag(DefaultLoc, diag::err_default_not_in_switch);
353 return Owned(SubStmt);
356 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
357 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
362 Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
363 SourceLocation ColonLoc, Stmt *SubStmt) {
364 // If the label was multiply defined, reject it now.
365 if (TheDecl->getStmt()) {
366 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
367 Diag(TheDecl->getLocation(), diag::note_previous_definition);
368 return Owned(SubStmt);
371 // Otherwise, things are good. Fill in the declaration and return it.
372 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
373 TheDecl->setStmt(LS);
374 if (!TheDecl->isGnuLocal()) {
375 TheDecl->setLocStart(IdentLoc);
376 TheDecl->setLocation(IdentLoc);
381 StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
382 ArrayRef<const Attr*> Attrs,
384 // Fill in the declaration and return it.
385 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt);
390 Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
391 Stmt *thenStmt, SourceLocation ElseLoc,
393 ExprResult CondResult(CondVal.release());
395 VarDecl *ConditionVar = 0;
397 ConditionVar = cast<VarDecl>(CondVar);
398 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
399 if (CondResult.isInvalid())
402 Expr *ConditionExpr = CondResult.takeAs<Expr>();
406 DiagnoseUnusedExprResult(thenStmt);
409 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
410 diag::warn_empty_if_body);
413 DiagnoseUnusedExprResult(elseStmt);
415 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
416 thenStmt, ElseLoc, elseStmt));
419 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
420 /// the specified width and sign. If an overflow occurs, detect it and emit
421 /// the specified diagnostic.
422 void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
423 unsigned NewWidth, bool NewSign,
426 // Perform a conversion to the promoted condition type if needed.
427 if (NewWidth > Val.getBitWidth()) {
428 // If this is an extension, just do it.
429 Val = Val.extend(NewWidth);
430 Val.setIsSigned(NewSign);
432 // If the input was signed and negative and the output is
433 // unsigned, don't bother to warn: this is implementation-defined
435 // FIXME: Introduce a second, default-ignored warning for this case?
436 } else if (NewWidth < Val.getBitWidth()) {
437 // If this is a truncation, check for overflow.
438 llvm::APSInt ConvVal(Val);
439 ConvVal = ConvVal.trunc(NewWidth);
440 ConvVal.setIsSigned(NewSign);
441 ConvVal = ConvVal.extend(Val.getBitWidth());
442 ConvVal.setIsSigned(Val.isSigned());
444 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
446 // Regardless of whether a diagnostic was emitted, really do the
448 Val = Val.trunc(NewWidth);
449 Val.setIsSigned(NewSign);
450 } else if (NewSign != Val.isSigned()) {
451 // Convert the sign to match the sign of the condition. This can cause
452 // overflow as well: unsigned(INTMIN)
453 // We don't diagnose this overflow, because it is implementation-defined
455 // FIXME: Introduce a second, default-ignored warning for this case?
456 llvm::APSInt OldVal(Val);
457 Val.setIsSigned(NewSign);
462 struct CaseCompareFunctor {
463 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
464 const llvm::APSInt &RHS) {
465 return LHS.first < RHS;
467 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
468 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
469 return LHS.first < RHS.first;
471 bool operator()(const llvm::APSInt &LHS,
472 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
473 return LHS < RHS.first;
478 /// CmpCaseVals - Comparison predicate for sorting case values.
480 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
481 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
482 if (lhs.first < rhs.first)
485 if (lhs.first == rhs.first &&
486 lhs.second->getCaseLoc().getRawEncoding()
487 < rhs.second->getCaseLoc().getRawEncoding())
492 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
494 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
495 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
497 return lhs.first < rhs.first;
500 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
502 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
503 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
505 return lhs.first == rhs.first;
508 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
509 /// potentially integral-promoted expression @p expr.
510 static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
511 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
512 expr = cleanups->getSubExpr();
513 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
514 if (impcast->getCastKind() != CK_IntegralCast) break;
515 expr = impcast->getSubExpr();
517 return expr->getType();
521 Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
523 ExprResult CondResult;
525 VarDecl *ConditionVar = 0;
527 ConditionVar = cast<VarDecl>(CondVar);
528 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
529 if (CondResult.isInvalid())
532 Cond = CondResult.release();
538 class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
542 SwitchConvertDiagnoser(Expr *Cond)
543 : ICEConvertDiagnoser(false, true), Cond(Cond) { }
545 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
547 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
550 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
552 return S.Diag(Loc, diag::err_switch_incomplete_class_type)
553 << T << Cond->getSourceRange();
556 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
559 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
562 virtual DiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
564 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
565 << ConvTy->isEnumeralType() << ConvTy;
568 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
570 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
573 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
575 return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
576 << ConvTy->isEnumeralType() << ConvTy;
579 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
582 return DiagnosticBuilder::getEmpty();
584 } SwitchDiagnoser(Cond);
587 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, SwitchDiagnoser,
588 /*AllowScopedEnumerations*/ true);
589 if (CondResult.isInvalid()) return StmtError();
590 Cond = CondResult.take();
592 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
593 CondResult = UsualUnaryConversions(Cond);
594 if (CondResult.isInvalid()) return StmtError();
595 Cond = CondResult.take();
598 CheckImplicitConversions(Cond, SwitchLoc);
599 CondResult = MaybeCreateExprWithCleanups(Cond);
600 if (CondResult.isInvalid())
602 Cond = CondResult.take();
605 getCurFunction()->setHasBranchIntoScope();
607 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
608 getCurFunction()->SwitchStack.push_back(SS);
612 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
613 if (Val.getBitWidth() < BitWidth)
614 Val = Val.extend(BitWidth);
615 else if (Val.getBitWidth() > BitWidth)
616 Val = Val.trunc(BitWidth);
617 Val.setIsSigned(IsSigned);
621 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
623 SwitchStmt *SS = cast<SwitchStmt>(Switch);
624 assert(SS == getCurFunction()->SwitchStack.back() &&
625 "switch stack missing push/pop!");
627 SS->setBody(BodyStmt, SwitchLoc);
628 getCurFunction()->SwitchStack.pop_back();
630 Expr *CondExpr = SS->getCond();
631 if (!CondExpr) return StmtError();
633 QualType CondType = CondExpr->getType();
635 Expr *CondExprBeforePromotion = CondExpr;
636 QualType CondTypeBeforePromotion =
637 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
640 // Integral promotions are performed (on the switch condition).
642 // A case value unrepresentable by the original switch condition
643 // type (before the promotion) doesn't make sense, even when it can
644 // be represented by the promoted type. Therefore we need to find
645 // the pre-promotion type of the switch condition.
646 if (!CondExpr->isTypeDependent()) {
647 // We have already converted the expression to an integral or enumeration
648 // type, when we started the switch statement. If we don't have an
649 // appropriate type now, just return an error.
650 if (!CondType->isIntegralOrEnumerationType())
653 if (CondExpr->isKnownToHaveBooleanValue()) {
654 // switch(bool_expr) {...} is often a programmer error, e.g.
655 // switch(n && mask) { ... } // Doh - should be "n & mask".
656 // One can always use an if statement instead of switch(bool_expr).
657 Diag(SwitchLoc, diag::warn_bool_switch_condition)
658 << CondExpr->getSourceRange();
662 // Get the bitwidth of the switched-on value before promotions. We must
663 // convert the integer case values to this width before comparison.
664 bool HasDependentValue
665 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
667 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
669 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
671 // Accumulate all of the case values in a vector so that we can sort them
672 // and detect duplicates. This vector contains the APInt for the case after
673 // it has been converted to the condition type.
674 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
677 // Keep track of any GNU case ranges we see. The APSInt is the low value.
678 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
679 CaseRangesTy CaseRanges;
681 DefaultStmt *TheDefaultStmt = 0;
683 bool CaseListIsErroneous = false;
685 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
686 SC = SC->getNextSwitchCase()) {
688 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
689 if (TheDefaultStmt) {
690 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
691 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
693 // FIXME: Remove the default statement from the switch block so that
694 // we'll return a valid AST. This requires recursing down the AST and
695 // finding it, not something we are set up to do right now. For now,
696 // just lop the entire switch stmt out of the AST.
697 CaseListIsErroneous = true;
702 CaseStmt *CS = cast<CaseStmt>(SC);
704 Expr *Lo = CS->getLHS();
706 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
707 HasDependentValue = true;
713 if (getLangOpts().CPlusPlus0x) {
714 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
715 // constant expression of the promoted type of the switch condition.
717 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
718 if (ConvLo.isInvalid()) {
719 CaseListIsErroneous = true;
724 // We already verified that the expression has a i-c-e value (C99
725 // 6.8.4.2p3) - get that value now.
726 LoVal = Lo->EvaluateKnownConstInt(Context);
728 // If the LHS is not the same type as the condition, insert an implicit
730 Lo = DefaultLvalueConversion(Lo).take();
731 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
734 // Convert the value to the same width/sign as the condition had prior to
735 // integral promotions.
737 // FIXME: This causes us to reject valid code:
738 // switch ((char)c) { case 256: case 0: return 0; }
739 // Here we claim there is a duplicated condition value, but there is not.
740 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
742 diag::warn_case_value_overflow);
746 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
748 if (CS->getRHS()->isTypeDependent() ||
749 CS->getRHS()->isValueDependent()) {
750 HasDependentValue = true;
753 CaseRanges.push_back(std::make_pair(LoVal, CS));
755 CaseVals.push_back(std::make_pair(LoVal, CS));
759 if (!HasDependentValue) {
760 // If we don't have a default statement, check whether the
761 // condition is constant.
762 llvm::APSInt ConstantCondValue;
763 bool HasConstantCond = false;
764 if (!HasDependentValue && !TheDefaultStmt) {
766 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
767 Expr::SE_AllowSideEffects);
768 assert(!HasConstantCond ||
769 (ConstantCondValue.getBitWidth() == CondWidth &&
770 ConstantCondValue.isSigned() == CondIsSigned));
772 bool ShouldCheckConstantCond = HasConstantCond;
774 // Sort all the scalar case values so we can easily detect duplicates.
775 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
777 if (!CaseVals.empty()) {
778 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
779 if (ShouldCheckConstantCond &&
780 CaseVals[i].first == ConstantCondValue)
781 ShouldCheckConstantCond = false;
783 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
784 // If we have a duplicate, report it.
785 // First, determine if either case value has a name
786 StringRef PrevString, CurrString;
787 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
788 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
789 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
790 PrevString = DeclRef->getDecl()->getName();
792 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
793 CurrString = DeclRef->getDecl()->getName();
795 llvm::SmallString<16> CaseValStr;
796 CaseVals[i-1].first.toString(CaseValStr);
798 if (PrevString == CurrString)
799 Diag(CaseVals[i].second->getLHS()->getLocStart(),
800 diag::err_duplicate_case) <<
801 (PrevString.empty() ? CaseValStr.str() : PrevString);
803 Diag(CaseVals[i].second->getLHS()->getLocStart(),
804 diag::err_duplicate_case_differing_expr) <<
805 (PrevString.empty() ? CaseValStr.str() : PrevString) <<
806 (CurrString.empty() ? CaseValStr.str() : CurrString) <<
809 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
810 diag::note_duplicate_case_prev);
811 // FIXME: We really want to remove the bogus case stmt from the
812 // substmt, but we have no way to do this right now.
813 CaseListIsErroneous = true;
818 // Detect duplicate case ranges, which usually don't exist at all in
820 if (!CaseRanges.empty()) {
821 // Sort all the case ranges by their low value so we can easily detect
822 // overlaps between ranges.
823 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
825 // Scan the ranges, computing the high values and removing empty ranges.
826 std::vector<llvm::APSInt> HiVals;
827 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
828 llvm::APSInt &LoVal = CaseRanges[i].first;
829 CaseStmt *CR = CaseRanges[i].second;
830 Expr *Hi = CR->getRHS();
833 if (getLangOpts().CPlusPlus0x) {
834 // C++11 [stmt.switch]p2: the constant-expression shall be a converted
835 // constant expression of the promoted type of the switch condition.
837 CheckConvertedConstantExpression(Hi, CondType, HiVal,
839 if (ConvHi.isInvalid()) {
840 CaseListIsErroneous = true;
845 HiVal = Hi->EvaluateKnownConstInt(Context);
847 // If the RHS is not the same type as the condition, insert an
849 Hi = DefaultLvalueConversion(Hi).take();
850 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
853 // Convert the value to the same width/sign as the condition.
854 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
856 diag::warn_case_value_overflow);
860 // If the low value is bigger than the high value, the case is empty.
862 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
863 << SourceRange(CR->getLHS()->getLocStart(),
865 CaseRanges.erase(CaseRanges.begin()+i);
870 if (ShouldCheckConstantCond &&
871 LoVal <= ConstantCondValue &&
872 ConstantCondValue <= HiVal)
873 ShouldCheckConstantCond = false;
875 HiVals.push_back(HiVal);
878 // Rescan the ranges, looking for overlap with singleton values and other
879 // ranges. Since the range list is sorted, we only need to compare case
880 // ranges with their neighbors.
881 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
882 llvm::APSInt &CRLo = CaseRanges[i].first;
883 llvm::APSInt &CRHi = HiVals[i];
884 CaseStmt *CR = CaseRanges[i].second;
886 // Check to see whether the case range overlaps with any
888 CaseStmt *OverlapStmt = 0;
889 llvm::APSInt OverlapVal(32);
891 // Find the smallest value >= the lower bound. If I is in the
892 // case range, then we have overlap.
893 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
894 CaseVals.end(), CRLo,
895 CaseCompareFunctor());
896 if (I != CaseVals.end() && I->first < CRHi) {
897 OverlapVal = I->first; // Found overlap with scalar.
898 OverlapStmt = I->second;
901 // Find the smallest value bigger than the upper bound.
902 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
903 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
904 OverlapVal = (I-1)->first; // Found overlap with scalar.
905 OverlapStmt = (I-1)->second;
908 // Check to see if this case stmt overlaps with the subsequent
910 if (i && CRLo <= HiVals[i-1]) {
911 OverlapVal = HiVals[i-1]; // Found overlap with range.
912 OverlapStmt = CaseRanges[i-1].second;
916 // If we have a duplicate, report it.
917 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
918 << OverlapVal.toString(10);
919 Diag(OverlapStmt->getLHS()->getLocStart(),
920 diag::note_duplicate_case_prev);
921 // FIXME: We really want to remove the bogus case stmt from the
922 // substmt, but we have no way to do this right now.
923 CaseListIsErroneous = true;
928 // Complain if we have a constant condition and we didn't find a match.
929 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
930 // TODO: it would be nice if we printed enums as enums, chars as
932 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
933 << ConstantCondValue.toString(10)
934 << CondExpr->getSourceRange();
937 // Check to see if switch is over an Enum and handles all of its
938 // values. We only issue a warning if there is not 'default:', but
939 // we still do the analysis to preserve this information in the AST
940 // (which can be used by flow-based analyes).
942 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
944 // If switch has default case, then ignore it.
945 if (!CaseListIsErroneous && !HasConstantCond && ET) {
946 const EnumDecl *ED = ET->getDecl();
947 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
951 // Gather all enum values, set their type and sort them,
952 // allowing easier comparison with CaseVals.
953 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
954 EDI != ED->enumerator_end(); ++EDI) {
955 llvm::APSInt Val = EDI->getInitVal();
956 AdjustAPSInt(Val, CondWidth, CondIsSigned);
957 EnumVals.push_back(std::make_pair(Val, *EDI));
959 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
960 EnumValsTy::iterator EIend =
961 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
963 // See which case values aren't in enum.
964 EnumValsTy::const_iterator EI = EnumVals.begin();
965 for (CaseValsTy::const_iterator CI = CaseVals.begin();
966 CI != CaseVals.end(); CI++) {
967 while (EI != EIend && EI->first < CI->first)
969 if (EI == EIend || EI->first > CI->first)
970 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
971 << CondTypeBeforePromotion;
973 // See which of case ranges aren't in enum
974 EI = EnumVals.begin();
975 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
976 RI != CaseRanges.end() && EI != EIend; RI++) {
977 while (EI != EIend && EI->first < RI->first)
980 if (EI == EIend || EI->first != RI->first) {
981 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
982 << CondTypeBeforePromotion;
986 RI->second->getRHS()->EvaluateKnownConstInt(Context);
987 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
988 while (EI != EIend && EI->first < Hi)
990 if (EI == EIend || EI->first != Hi)
991 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
992 << CondTypeBeforePromotion;
995 // Check which enum vals aren't in switch
996 CaseValsTy::const_iterator CI = CaseVals.begin();
997 CaseRangesTy::const_iterator RI = CaseRanges.begin();
998 bool hasCasesNotInSwitch = false;
1000 SmallVector<DeclarationName,8> UnhandledNames;
1002 for (EI = EnumVals.begin(); EI != EIend; EI++){
1003 // Drop unneeded case values
1005 while (CI != CaseVals.end() && CI->first < EI->first)
1008 if (CI != CaseVals.end() && CI->first == EI->first)
1011 // Drop unneeded case ranges
1012 for (; RI != CaseRanges.end(); RI++) {
1014 RI->second->getRHS()->EvaluateKnownConstInt(Context);
1015 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1016 if (EI->first <= Hi)
1020 if (RI == CaseRanges.end() || EI->first < RI->first) {
1021 hasCasesNotInSwitch = true;
1022 UnhandledNames.push_back(EI->second->getDeclName());
1026 if (TheDefaultStmt && UnhandledNames.empty())
1027 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1029 // Produce a nice diagnostic if multiple values aren't handled.
1030 switch (UnhandledNames.size()) {
1033 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1034 ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
1035 << UnhandledNames[0];
1038 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1039 ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
1040 << UnhandledNames[0] << UnhandledNames[1];
1043 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1044 ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
1045 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1048 Diag(CondExpr->getExprLoc(), TheDefaultStmt
1049 ? diag::warn_def_missing_cases : diag::warn_missing_cases)
1050 << (unsigned)UnhandledNames.size()
1051 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1055 if (!hasCasesNotInSwitch)
1056 SS->setAllEnumCasesCovered();
1060 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1061 diag::warn_empty_switch_body);
1063 // FIXME: If the case list was broken is some way, we don't have a good system
1064 // to patch it up. Instead, just return the whole substmt as broken.
1065 if (CaseListIsErroneous)
1072 Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
1074 unsigned DIAG = diag::warn_not_in_enum_assignement;
1075 if (Diags.getDiagnosticLevel(DIAG, SrcExpr->getExprLoc())
1076 == DiagnosticsEngine::Ignored)
1079 if (const EnumType *ET = DstType->getAs<EnumType>())
1080 if (!Context.hasSameType(SrcType, DstType) &&
1081 SrcType->isIntegerType()) {
1082 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() &&
1083 SrcExpr->isIntegerConstantExpr(Context)) {
1084 // Get the bitwidth of the enum value before promotions.
1085 unsigned DstWith = Context.getIntWidth(DstType);
1086 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType();
1088 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context);
1089 const EnumDecl *ED = ET->getDecl();
1090 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
1092 EnumValsTy EnumVals;
1094 // Gather all enum values, set their type and sort them,
1095 // allowing easier comparison with rhs constant.
1096 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
1097 EDI != ED->enumerator_end(); ++EDI) {
1098 llvm::APSInt Val = EDI->getInitVal();
1099 AdjustAPSInt(Val, DstWith, DstIsSigned);
1100 EnumVals.push_back(std::make_pair(Val, *EDI));
1102 if (EnumVals.empty())
1104 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
1105 EnumValsTy::iterator EIend =
1106 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
1108 // See which case values aren't in enum.
1109 EnumValsTy::const_iterator EI = EnumVals.begin();
1110 while (EI != EIend && EI->first < RhsVal)
1112 if (EI == EIend || EI->first != RhsVal) {
1113 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignement)
1121 Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
1122 Decl *CondVar, Stmt *Body) {
1123 ExprResult CondResult(Cond.release());
1125 VarDecl *ConditionVar = 0;
1127 ConditionVar = cast<VarDecl>(CondVar);
1128 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
1129 if (CondResult.isInvalid())
1132 Expr *ConditionExpr = CondResult.take();
1136 DiagnoseUnusedExprResult(Body);
1138 if (isa<NullStmt>(Body))
1139 getCurCompoundScope().setHasEmptyLoopBodies();
1141 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
1146 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1147 SourceLocation WhileLoc, SourceLocation CondLParen,
1148 Expr *Cond, SourceLocation CondRParen) {
1149 assert(Cond && "ActOnDoStmt(): missing expression");
1151 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
1152 if (CondResult.isInvalid() || CondResult.isInvalid())
1154 Cond = CondResult.take();
1156 CheckImplicitConversions(Cond, DoLoc);
1157 CondResult = MaybeCreateExprWithCleanups(Cond);
1158 if (CondResult.isInvalid())
1160 Cond = CondResult.take();
1162 DiagnoseUnusedExprResult(Body);
1164 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
1168 // This visitor will traverse a conditional statement and store all
1169 // the evaluated decls into a vector. Simple is set to true if none
1170 // of the excluded constructs are used.
1171 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1172 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1173 llvm::SmallVector<SourceRange, 10> &Ranges;
1176 typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1178 DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1179 llvm::SmallVector<SourceRange, 10> &Ranges) :
1180 Inherited(S.Context),
1185 bool isSimple() { return Simple; }
1187 // Replaces the method in EvaluatedExprVisitor.
1188 void VisitMemberExpr(MemberExpr* E) {
1192 // Any Stmt not whitelisted will cause the condition to be marked complex.
1193 void VisitStmt(Stmt *S) {
1197 void VisitBinaryOperator(BinaryOperator *E) {
1202 void VisitCastExpr(CastExpr *E) {
1203 Visit(E->getSubExpr());
1206 void VisitUnaryOperator(UnaryOperator *E) {
1207 // Skip checking conditionals with derefernces.
1208 if (E->getOpcode() == UO_Deref)
1211 Visit(E->getSubExpr());
1214 void VisitConditionalOperator(ConditionalOperator *E) {
1215 Visit(E->getCond());
1216 Visit(E->getTrueExpr());
1217 Visit(E->getFalseExpr());
1220 void VisitParenExpr(ParenExpr *E) {
1221 Visit(E->getSubExpr());
1224 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1225 Visit(E->getOpaqueValue()->getSourceExpr());
1226 Visit(E->getFalseExpr());
1229 void VisitIntegerLiteral(IntegerLiteral *E) { }
1230 void VisitFloatingLiteral(FloatingLiteral *E) { }
1231 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1232 void VisitCharacterLiteral(CharacterLiteral *E) { }
1233 void VisitGNUNullExpr(GNUNullExpr *E) { }
1234 void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1236 void VisitDeclRefExpr(DeclRefExpr *E) {
1237 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1240 Ranges.push_back(E->getSourceRange());
1245 }; // end class DeclExtractor
1247 // DeclMatcher checks to see if the decls are used in a non-evauluated
1249 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1250 llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1254 typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1256 DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
1257 Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1258 if (!Statement) return;
1263 void VisitReturnStmt(ReturnStmt *S) {
1267 void VisitBreakStmt(BreakStmt *S) {
1271 void VisitGotoStmt(GotoStmt *S) {
1275 void VisitCastExpr(CastExpr *E) {
1276 if (E->getCastKind() == CK_LValueToRValue)
1277 CheckLValueToRValueCast(E->getSubExpr());
1279 Visit(E->getSubExpr());
1282 void CheckLValueToRValueCast(Expr *E) {
1283 E = E->IgnoreParenImpCasts();
1285 if (isa<DeclRefExpr>(E)) {
1289 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1290 Visit(CO->getCond());
1291 CheckLValueToRValueCast(CO->getTrueExpr());
1292 CheckLValueToRValueCast(CO->getFalseExpr());
1296 if (BinaryConditionalOperator *BCO =
1297 dyn_cast<BinaryConditionalOperator>(E)) {
1298 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1299 CheckLValueToRValueCast(BCO->getFalseExpr());
1306 void VisitDeclRefExpr(DeclRefExpr *E) {
1307 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1308 if (Decls.count(VD))
1312 bool FoundDeclInUse() { return FoundDecl; }
1314 }; // end class DeclMatcher
1316 void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1317 Expr *Third, Stmt *Body) {
1318 // Condition is empty
1319 if (!Second) return;
1321 if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1322 Second->getLocStart())
1323 == DiagnosticsEngine::Ignored)
1326 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1327 llvm::SmallPtrSet<VarDecl*, 8> Decls;
1328 llvm::SmallVector<SourceRange, 10> Ranges;
1329 DeclExtractor DE(S, Decls, Ranges);
1332 // Don't analyze complex conditionals.
1333 if (!DE.isSimple()) return;
1336 if (Decls.size() == 0) return;
1338 // Don't warn on volatile, static, or global variables.
1339 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1342 if ((*I)->getType().isVolatileQualified() ||
1343 (*I)->hasGlobalStorage()) return;
1345 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1346 DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1347 DeclMatcher(S, Decls, Body).FoundDeclInUse())
1350 // Load decl names into diagnostic.
1351 if (Decls.size() > 4)
1354 PDiag << Decls.size();
1355 for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1358 PDiag << (*I)->getDeclName();
1361 // Load SourceRanges into diagnostic if there is room.
1362 // Otherwise, load the SourceRange of the conditional expression.
1363 if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1364 for (llvm::SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1369 PDiag << Second->getSourceRange();
1371 S.Diag(Ranges.begin()->getBegin(), PDiag);
1377 Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1378 Stmt *First, FullExprArg second, Decl *secondVar,
1380 SourceLocation RParenLoc, Stmt *Body) {
1381 if (!getLangOpts().CPlusPlus) {
1382 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1383 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1384 // declare identifiers for objects having storage class 'auto' or
1386 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1388 VarDecl *VD = dyn_cast<VarDecl>(*DI);
1389 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
1392 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
1393 // FIXME: mark decl erroneous!
1398 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1400 ExprResult SecondResult(second.release());
1401 VarDecl *ConditionVar = 0;
1403 ConditionVar = cast<VarDecl>(secondVar);
1404 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
1405 if (SecondResult.isInvalid())
1409 Expr *Third = third.release().takeAs<Expr>();
1411 DiagnoseUnusedExprResult(First);
1412 DiagnoseUnusedExprResult(Third);
1413 DiagnoseUnusedExprResult(Body);
1415 if (isa<NullStmt>(Body))
1416 getCurCompoundScope().setHasEmptyLoopBodies();
1418 return Owned(new (Context) ForStmt(Context, First,
1419 SecondResult.take(), ConditionVar,
1420 Third, Body, ForLoc, LParenLoc,
1424 /// In an Objective C collection iteration statement:
1426 /// x can be an arbitrary l-value expression. Bind it up as a
1427 /// full-expression.
1428 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1429 // Reduce placeholder expressions here. Note that this rejects the
1430 // use of pseudo-object l-values in this position.
1431 ExprResult result = CheckPlaceholderExpr(E);
1432 if (result.isInvalid()) return StmtError();
1435 CheckImplicitConversions(E);
1437 result = MaybeCreateExprWithCleanups(E);
1438 if (result.isInvalid()) return StmtError();
1440 return Owned(static_cast<Stmt*>(result.take()));
1444 Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1448 // Bail out early if we've got a type-dependent expression.
1449 if (collection->isTypeDependent()) return Owned(collection);
1451 // Perform normal l-value conversion.
1452 ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1453 if (result.isInvalid())
1455 collection = result.take();
1457 // The operand needs to have object-pointer type.
1458 // TODO: should we do a contextual conversion?
1459 const ObjCObjectPointerType *pointerType =
1460 collection->getType()->getAs<ObjCObjectPointerType>();
1462 return Diag(forLoc, diag::err_collection_expr_type)
1463 << collection->getType() << collection->getSourceRange();
1465 // Check that the operand provides
1466 // - countByEnumeratingWithState:objects:count:
1467 const ObjCObjectType *objectType = pointerType->getObjectType();
1468 ObjCInterfaceDecl *iface = objectType->getInterface();
1470 // If we have a forward-declared type, we can't do this check.
1471 // Under ARC, it is an error not to have a forward-declared class.
1473 RequireCompleteType(forLoc, QualType(objectType, 0),
1474 getLangOpts().ObjCAutoRefCount
1475 ? diag::err_arc_collection_forward
1478 // Otherwise, if we have any useful type information, check that
1479 // the type declares the appropriate method.
1480 } else if (iface || !objectType->qual_empty()) {
1481 IdentifierInfo *selectorIdents[] = {
1482 &Context.Idents.get("countByEnumeratingWithState"),
1483 &Context.Idents.get("objects"),
1484 &Context.Idents.get("count")
1486 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1488 ObjCMethodDecl *method = 0;
1490 // If there's an interface, look in both the public and private APIs.
1492 method = iface->lookupInstanceMethod(selector);
1493 if (!method) method = iface->lookupPrivateMethod(selector);
1496 // Also check protocol qualifiers.
1498 method = LookupMethodInQualifiedType(selector, pointerType,
1501 // If we didn't find it anywhere, give up.
1503 Diag(forLoc, diag::warn_collection_expr_type)
1504 << collection->getType() << selector << collection->getSourceRange();
1507 // TODO: check for an incompatible signature?
1510 // Wrap up any cleanups in the expression.
1511 return Owned(MaybeCreateExprWithCleanups(collection));
1515 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1516 Stmt *First, Expr *collection,
1517 SourceLocation RParenLoc) {
1519 ExprResult CollectionExprResult =
1520 CheckObjCForCollectionOperand(ForLoc, collection);
1524 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1525 if (!DS->isSingleDecl())
1526 return StmtError(Diag((*DS->decl_begin())->getLocation(),
1527 diag::err_toomany_element_decls));
1529 VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1530 FirstType = D->getType();
1531 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1532 // declare identifiers for objects having storage class 'auto' or
1534 if (!D->hasLocalStorage())
1535 return StmtError(Diag(D->getLocation(),
1536 diag::err_non_variable_decl_in_for));
1538 Expr *FirstE = cast<Expr>(First);
1539 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1540 return StmtError(Diag(First->getLocStart(),
1541 diag::err_selector_element_not_lvalue)
1542 << First->getSourceRange());
1544 FirstType = static_cast<Expr*>(First)->getType();
1546 if (!FirstType->isDependentType() &&
1547 !FirstType->isObjCObjectPointerType() &&
1548 !FirstType->isBlockPointerType())
1549 return StmtError(Diag(ForLoc, diag::err_selector_element_type)
1550 << FirstType << First->getSourceRange());
1553 if (CollectionExprResult.isInvalid())
1556 return Owned(new (Context) ObjCForCollectionStmt(First,
1557 CollectionExprResult.take(), 0,
1558 ForLoc, RParenLoc));
1561 /// Finish building a variable declaration for a for-range statement.
1562 /// \return true if an error occurs.
1563 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1564 SourceLocation Loc, int diag) {
1565 // Deduce the type for the iterator variable now rather than leaving it to
1566 // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1567 TypeSourceInfo *InitTSI = 0;
1568 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
1569 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
1571 SemaRef.Diag(Loc, diag) << Init->getType();
1573 Decl->setInvalidDecl();
1576 Decl->setTypeSourceInfo(InitTSI);
1577 Decl->setType(InitTSI->getType());
1579 // In ARC, infer lifetime.
1580 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1581 // we're doing the equivalent of fast iteration.
1582 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1583 SemaRef.inferObjCARCLifetime(Decl))
1584 Decl->setInvalidDecl();
1586 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1587 /*TypeMayContainAuto=*/false);
1588 SemaRef.FinalizeDeclaration(Decl);
1589 SemaRef.CurContext->addHiddenDecl(Decl);
1595 /// Produce a note indicating which begin/end function was implicitly called
1596 /// by a C++11 for-range statement. This is often not obvious from the code,
1597 /// nor from the diagnostics produced when analysing the implicit expressions
1598 /// required in a for-range statement.
1599 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1600 Sema::BeginEndFunction BEF) {
1601 CallExpr *CE = dyn_cast<CallExpr>(E);
1604 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1607 SourceLocation Loc = D->getLocation();
1609 std::string Description;
1610 bool IsTemplate = false;
1611 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1612 Description = SemaRef.getTemplateArgumentBindingsText(
1613 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1617 SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1618 << BEF << IsTemplate << Description << E->getType();
1621 /// Build a variable declaration for a for-range statement.
1622 VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1623 QualType Type, const char *Name) {
1624 DeclContext *DC = SemaRef.CurContext;
1625 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1626 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1627 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1628 TInfo, SC_Auto, SC_None);
1629 Decl->setImplicit();
1635 static bool ObjCEnumerationCollection(Expr *Collection) {
1636 return !Collection->isTypeDependent()
1637 && Collection->getType()->getAs<ObjCObjectPointerType>() != 0;
1640 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement.
1642 /// C++11 [stmt.ranged]:
1643 /// A range-based for statement is equivalent to
1646 /// auto && __range = range-init;
1647 /// for ( auto __begin = begin-expr,
1648 /// __end = end-expr;
1649 /// __begin != __end;
1651 /// for-range-declaration = *__begin;
1656 /// The body of the loop is not available yet, since it cannot be analysed until
1657 /// we have determined the type of the for-range-declaration.
1659 Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc,
1660 Stmt *First, SourceLocation ColonLoc, Expr *Range,
1661 SourceLocation RParenLoc, BuildForRangeKind Kind) {
1662 if (!First || !Range)
1665 if (ObjCEnumerationCollection(Range))
1666 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc);
1668 DeclStmt *DS = dyn_cast<DeclStmt>(First);
1669 assert(DS && "first part of for range not a decl stmt");
1671 if (!DS->isSingleDecl()) {
1672 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1675 if (DS->getSingleDecl()->isInvalidDecl())
1678 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1681 // Build auto && __range = range-init
1682 SourceLocation RangeLoc = Range->getLocStart();
1683 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1684 Context.getAutoRRefDeductType(),
1686 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1687 diag::err_for_range_deduction_failure))
1690 // Claim the type doesn't contain auto: we've already done the checking.
1691 DeclGroupPtrTy RangeGroup =
1692 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1693 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1694 if (RangeDecl.isInvalid())
1697 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1698 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
1702 /// \brief Create the initialization, compare, and increment steps for
1703 /// the range-based for loop expression.
1704 /// This function does not handle array-based for loops,
1705 /// which are created in Sema::BuildCXXForRangeStmt.
1707 /// \returns a ForRangeStatus indicating success or what kind of error occurred.
1708 /// BeginExpr and EndExpr are set and FRS_Success is returned on success;
1709 /// CandidateSet and BEF are set and some non-success value is returned on
1711 static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S,
1712 Expr *BeginRange, Expr *EndRange,
1716 SourceLocation ColonLoc,
1717 OverloadCandidateSet *CandidateSet,
1718 ExprResult *BeginExpr,
1719 ExprResult *EndExpr,
1720 Sema::BeginEndFunction *BEF) {
1721 DeclarationNameInfo BeginNameInfo(
1722 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc);
1723 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"),
1726 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo,
1727 Sema::LookupMemberName);
1728 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName);
1730 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1731 // - if _RangeT is a class type, the unqualified-ids begin and end are
1732 // looked up in the scope of class _RangeT as if by class member access
1733 // lookup (3.4.5), and if either (or both) finds at least one
1734 // declaration, begin-expr and end-expr are __range.begin() and
1735 // __range.end(), respectively;
1736 SemaRef.LookupQualifiedName(BeginMemberLookup, D);
1737 SemaRef.LookupQualifiedName(EndMemberLookup, D);
1739 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1740 SourceLocation RangeLoc = BeginVar->getLocation();
1741 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin;
1743 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch)
1744 << RangeLoc << BeginRange->getType() << *BEF;
1745 return Sema::FRS_DiagnosticIssued;
1748 // - otherwise, begin-expr and end-expr are begin(__range) and
1749 // end(__range), respectively, where begin and end are looked up with
1750 // argument-dependent lookup (3.4.2). For the purposes of this name
1751 // lookup, namespace std is an associated namespace.
1755 *BEF = Sema::BEF_begin;
1756 Sema::ForRangeStatus RangeStatus =
1757 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar,
1758 Sema::BEF_begin, BeginNameInfo,
1759 BeginMemberLookup, CandidateSet,
1760 BeginRange, BeginExpr);
1762 if (RangeStatus != Sema::FRS_Success)
1764 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc,
1765 diag::err_for_range_iter_deduction_failure)) {
1766 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF);
1767 return Sema::FRS_DiagnosticIssued;
1770 *BEF = Sema::BEF_end;
1772 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar,
1773 Sema::BEF_end, EndNameInfo,
1774 EndMemberLookup, CandidateSet,
1776 if (RangeStatus != Sema::FRS_Success)
1778 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc,
1779 diag::err_for_range_iter_deduction_failure)) {
1780 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF);
1781 return Sema::FRS_DiagnosticIssued;
1783 return Sema::FRS_Success;
1786 /// Speculatively attempt to dereference an invalid range expression.
1787 /// If the attempt fails, this function will return a valid, null StmtResult
1788 /// and emit no diagnostics.
1789 static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S,
1790 SourceLocation ForLoc,
1792 SourceLocation ColonLoc,
1794 SourceLocation RangeLoc,
1795 SourceLocation RParenLoc) {
1796 // Determine whether we can rebuild the for-range statement with a
1797 // dereferenced range expression.
1798 ExprResult AdjustedRange;
1800 Sema::SFINAETrap Trap(SemaRef);
1802 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range);
1803 if (AdjustedRange.isInvalid())
1804 return StmtResult();
1807 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1808 AdjustedRange.get(), RParenLoc,
1811 return StmtResult();
1814 // The attempt to dereference worked well enough that it could produce a valid
1815 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in
1816 // case there are any other (non-fatal) problems with it.
1817 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference)
1818 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*");
1819 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc,
1820 AdjustedRange.get(), RParenLoc,
1821 Sema::BFRK_Rebuild);
1824 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement.
1826 Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1827 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1828 Expr *Inc, Stmt *LoopVarDecl,
1829 SourceLocation RParenLoc, BuildForRangeKind Kind) {
1830 Scope *S = getCurScope();
1832 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1833 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1834 QualType RangeVarType = RangeVar->getType();
1836 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1837 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1839 StmtResult BeginEndDecl = BeginEnd;
1840 ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1842 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1843 SourceLocation RangeLoc = RangeVar->getLocation();
1845 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1847 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1848 VK_LValue, ColonLoc);
1849 if (BeginRangeRef.isInvalid())
1852 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1853 VK_LValue, ColonLoc);
1854 if (EndRangeRef.isInvalid())
1857 QualType AutoType = Context.getAutoDeductType();
1858 Expr *Range = RangeVar->getInit();
1861 QualType RangeType = Range->getType();
1863 if (RequireCompleteType(RangeLoc, RangeType,
1864 diag::err_for_range_incomplete_type))
1867 // Build auto __begin = begin-expr, __end = end-expr.
1868 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1870 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1873 // Build begin-expr and end-expr and attach to __begin and __end variables.
1874 ExprResult BeginExpr, EndExpr;
1875 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1876 // - if _RangeT is an array type, begin-expr and end-expr are __range and
1877 // __range + __bound, respectively, where __bound is the array bound. If
1878 // _RangeT is an array of unknown size or an array of incomplete type,
1879 // the program is ill-formed;
1881 // begin-expr is __range.
1882 BeginExpr = BeginRangeRef;
1883 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
1884 diag::err_for_range_iter_deduction_failure)) {
1885 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1889 // Find the array bound.
1890 ExprResult BoundExpr;
1891 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1892 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
1893 Context.getPointerDiffType(),
1895 else if (const VariableArrayType *VAT =
1896 dyn_cast<VariableArrayType>(UnqAT))
1897 BoundExpr = VAT->getSizeExpr();
1899 // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1900 // UnqAT is not incomplete and Range is not type-dependent.
1901 llvm_unreachable("Unexpected array type in for-range");
1904 // end-expr is __range + __bound.
1905 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
1907 if (EndExpr.isInvalid())
1909 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1910 diag::err_for_range_iter_deduction_failure)) {
1911 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1915 OverloadCandidateSet CandidateSet(RangeLoc);
1916 Sema::BeginEndFunction BEFFailure;
1917 ForRangeStatus RangeStatus =
1918 BuildNonArrayForRange(*this, S, BeginRangeRef.get(),
1919 EndRangeRef.get(), RangeType,
1920 BeginVar, EndVar, ColonLoc, &CandidateSet,
1921 &BeginExpr, &EndExpr, &BEFFailure);
1923 // If building the range failed, try dereferencing the range expression
1924 // unless a diagnostic was issued or the end function is problematic.
1925 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction &&
1926 BEFFailure == BEF_begin) {
1927 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc,
1928 LoopVarDecl, ColonLoc,
1931 if (SR.isInvalid() || SR.isUsable())
1935 // Otherwise, emit diagnostics if we haven't already.
1936 if (RangeStatus == FRS_NoViableFunction) {
1937 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get();
1938 Diag(Range->getLocStart(), diag::err_for_range_invalid)
1939 << RangeLoc << Range->getType() << BEFFailure;
1940 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
1941 llvm::makeArrayRef(&Range, /*NumArgs=*/1));
1943 // Return an error if no fix was discovered.
1944 if (RangeStatus != FRS_Success)
1948 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() &&
1949 "invalid range expression in for loop");
1951 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same.
1952 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1953 if (!Context.hasSameType(BeginType, EndType)) {
1954 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1955 << BeginType << EndType;
1956 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1957 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1960 Decl *BeginEndDecls[] = { BeginVar, EndVar };
1961 // Claim the type doesn't contain auto: we've already done the checking.
1962 DeclGroupPtrTy BeginEndGroup =
1963 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1964 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1966 const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
1967 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1968 VK_LValue, ColonLoc);
1969 if (BeginRef.isInvalid())
1972 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1973 VK_LValue, ColonLoc);
1974 if (EndRef.isInvalid())
1977 // Build and check __begin != __end expression.
1978 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1979 BeginRef.get(), EndRef.get());
1980 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1981 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1982 if (NotEqExpr.isInvalid()) {
1983 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
1984 << RangeLoc << 0 << BeginRangeRef.get()->getType();
1985 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1986 if (!Context.hasSameType(BeginType, EndType))
1987 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1991 // Build and check ++__begin expression.
1992 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1993 VK_LValue, ColonLoc);
1994 if (BeginRef.isInvalid())
1997 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
1998 IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
1999 if (IncrExpr.isInvalid()) {
2000 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2001 << RangeLoc << 2 << BeginRangeRef.get()->getType() ;
2002 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2006 // Build and check *__begin expression.
2007 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
2008 VK_LValue, ColonLoc);
2009 if (BeginRef.isInvalid())
2012 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
2013 if (DerefExpr.isInvalid()) {
2014 Diag(RangeLoc, diag::note_for_range_invalid_iterator)
2015 << RangeLoc << 1 << BeginRangeRef.get()->getType();
2016 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2020 // Attach *__begin as initializer for VD. Don't touch it if we're just
2021 // trying to determine whether this would be a valid range.
2022 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) {
2023 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
2024 /*TypeMayContainAuto=*/true);
2025 if (LoopVar->isInvalidDecl())
2026 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
2029 // The range is implicitly used as a placeholder when it is dependent.
2030 RangeVar->setUsed();
2033 // Don't bother to actually allocate the result if we're just trying to
2034 // determine whether it would be valid.
2035 if (Kind == BFRK_Check)
2036 return StmtResult();
2038 return Owned(new (Context) CXXForRangeStmt(RangeDS,
2039 cast_or_null<DeclStmt>(BeginEndDecl.get()),
2040 NotEqExpr.take(), IncrExpr.take(),
2041 LoopVarDS, /*Body=*/0, ForLoc,
2042 ColonLoc, RParenLoc));
2045 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach
2047 StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) {
2050 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S);
2052 ForStmt->setBody(B);
2056 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
2057 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
2058 /// body cannot be performed until after the type of the range variable is
2060 StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
2064 if (isa<ObjCForCollectionStmt>(S))
2065 return FinishObjCForCollectionStmt(S, B);
2067 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
2068 ForStmt->setBody(B);
2070 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
2071 diag::warn_empty_range_based_for_body);
2076 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
2077 SourceLocation LabelLoc,
2078 LabelDecl *TheDecl) {
2079 getCurFunction()->setHasBranchIntoScope();
2081 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
2085 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
2087 // Convert operand to void*
2088 if (!E->isTypeDependent()) {
2089 QualType ETy = E->getType();
2090 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
2091 ExprResult ExprRes = Owned(E);
2092 AssignConvertType ConvTy =
2093 CheckSingleAssignmentConstraints(DestTy, ExprRes);
2094 if (ExprRes.isInvalid())
2097 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
2099 E = MaybeCreateExprWithCleanups(E);
2102 getCurFunction()->setHasIndirectGoto();
2104 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
2108 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
2109 Scope *S = CurScope->getContinueParent();
2111 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
2112 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
2115 return Owned(new (Context) ContinueStmt(ContinueLoc));
2119 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
2120 Scope *S = CurScope->getBreakParent();
2122 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
2123 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
2126 return Owned(new (Context) BreakStmt(BreakLoc));
2129 /// \brief Determine whether the given expression is a candidate for
2130 /// copy elision in either a return statement or a throw expression.
2132 /// \param ReturnType If we're determining the copy elision candidate for
2133 /// a return statement, this is the return type of the function. If we're
2134 /// determining the copy elision candidate for a throw expression, this will
2137 /// \param E The expression being returned from the function or block, or
2140 /// \param AllowFunctionParameter Whether we allow function parameters to
2141 /// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
2142 /// we re-use this logic to determine whether we should try to move as part of
2143 /// a return or throw (which does allow function parameters).
2145 /// \returns The NRVO candidate variable, if the return statement may use the
2146 /// NRVO, or NULL if there is no such candidate.
2147 const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
2149 bool AllowFunctionParameter) {
2150 QualType ExprType = E->getType();
2151 // - in a return statement in a function with ...
2152 // ... a class return type ...
2153 if (!ReturnType.isNull()) {
2154 if (!ReturnType->isRecordType())
2156 // ... the same cv-unqualified type as the function return type ...
2157 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2161 // ... the expression is the name of a non-volatile automatic object
2162 // (other than a function or catch-clause parameter)) ...
2163 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2164 if (!DR || DR->refersToEnclosingLocal())
2166 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2170 // ...object (other than a function or catch-clause parameter)...
2171 if (VD->getKind() != Decl::Var &&
2172 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2174 if (VD->isExceptionVariable()) return 0;
2177 if (!VD->hasLocalStorage()) return 0;
2179 // ...non-volatile...
2180 if (VD->getType().isVolatileQualified()) return 0;
2181 if (VD->getType()->isReferenceType()) return 0;
2183 // __block variables can't be allocated in a way that permits NRVO.
2184 if (VD->hasAttr<BlocksAttr>()) return 0;
2186 // Variables with higher required alignment than their type's ABI
2187 // alignment cannot use NRVO.
2188 if (VD->hasAttr<AlignedAttr>() &&
2189 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2195 /// \brief Perform the initialization of a potentially-movable value, which
2196 /// is the result of return value.
2198 /// This routine implements C++0x [class.copy]p33, which attempts to treat
2199 /// returned lvalues as rvalues in certain cases (to prefer move construction),
2200 /// then falls back to treating them as lvalues if that failed.
2202 Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2203 const VarDecl *NRVOCandidate,
2204 QualType ResultType,
2207 // C++0x [class.copy]p33:
2208 // When the criteria for elision of a copy operation are met or would
2209 // be met save for the fact that the source object is a function
2210 // parameter, and the object to be copied is designated by an lvalue,
2211 // overload resolution to select the constructor for the copy is first
2212 // performed as if the object were designated by an rvalue.
2213 ExprResult Res = ExprError();
2215 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
2216 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
2217 Value->getType(), CK_NoOp, Value, VK_XValue);
2219 Expr *InitExpr = &AsRvalue;
2220 InitializationKind Kind
2221 = InitializationKind::CreateCopy(Value->getLocStart(),
2222 Value->getLocStart());
2223 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
2225 // [...] If overload resolution fails, or if the type of the first
2226 // parameter of the selected constructor is not an rvalue reference
2227 // to the object's type (possibly cv-qualified), overload resolution
2228 // is performed again, considering the object as an lvalue.
2230 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2231 StepEnd = Seq.step_end();
2232 Step != StepEnd; ++Step) {
2233 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
2236 CXXConstructorDecl *Constructor
2237 = cast<CXXConstructorDecl>(Step->Function.Function);
2239 const RValueReferenceType *RRefType
2240 = Constructor->getParamDecl(0)->getType()
2241 ->getAs<RValueReferenceType>();
2243 // If we don't meet the criteria, break out now.
2245 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2246 Context.getTypeDeclType(Constructor->getParent())))
2249 // Promote "AsRvalue" to the heap, since we now need this
2250 // expression node to persist.
2251 Value = ImplicitCastExpr::Create(Context, Value->getType(),
2252 CK_NoOp, Value, 0, VK_XValue);
2254 // Complete type-checking the initialization of the return type
2255 // using the constructor we found.
2256 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
2261 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
2262 // above, or overload resolution failed. Either way, we need to try
2263 // (again) now with the return value expression as written.
2264 if (Res.isInvalid())
2265 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
2270 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2271 /// for capturing scopes.
2274 Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2275 // If this is the first return we've seen, infer the return type.
2276 // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
2277 // rules which allows multiple return statements.
2278 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
2279 QualType FnRetType = CurCap->ReturnType;
2281 // For blocks/lambdas with implicit return types, we check each return
2282 // statement individually, and deduce the common return type when the block
2283 // or lambda is completed.
2284 if (CurCap->HasImplicitReturnType) {
2285 if (RetValExp && !isa<InitListExpr>(RetValExp)) {
2286 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2287 if (Result.isInvalid())
2289 RetValExp = Result.take();
2291 if (!RetValExp->isTypeDependent())
2292 FnRetType = RetValExp->getType();
2294 FnRetType = CurCap->ReturnType = Context.DependentTy;
2297 // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2298 // initializer list, because it is not an expression (even
2299 // though we represent it as one). We still deduce 'void'.
2300 Diag(ReturnLoc, diag::err_lambda_return_init_list)
2301 << RetValExp->getSourceRange();
2304 FnRetType = Context.VoidTy;
2307 // Although we'll properly infer the type of the block once it's completed,
2308 // make sure we provide a return type now for better error recovery.
2309 if (CurCap->ReturnType.isNull())
2310 CurCap->ReturnType = FnRetType;
2312 assert(!FnRetType.isNull());
2314 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
2315 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2316 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2320 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2321 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2322 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2327 // Otherwise, verify that this result type matches the previous one. We are
2328 // pickier with blocks than for normal functions because we don't have GCC
2329 // compatibility to worry about here.
2330 const VarDecl *NRVOCandidate = 0;
2331 if (FnRetType->isDependentType()) {
2332 // Delay processing for now. TODO: there are lots of dependent
2333 // types we can conclusively prove aren't void.
2334 } else if (FnRetType->isVoidType()) {
2335 if (RetValExp && !isa<InitListExpr>(RetValExp) &&
2336 !(getLangOpts().CPlusPlus &&
2337 (RetValExp->isTypeDependent() ||
2338 RetValExp->getType()->isVoidType()))) {
2339 if (!getLangOpts().CPlusPlus &&
2340 RetValExp->getType()->isVoidType())
2341 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
2343 Diag(ReturnLoc, diag::err_return_block_has_expr);
2347 } else if (!RetValExp) {
2348 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2349 } else if (!RetValExp->isTypeDependent()) {
2350 // we have a non-void block with an expression, continue checking
2352 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2353 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2356 // In C++ the return statement is handled via a copy initialization.
2357 // the C version of which boils down to CheckSingleAssignmentConstraints.
2358 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2359 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2361 NRVOCandidate != 0);
2362 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2363 FnRetType, RetValExp);
2364 if (Res.isInvalid()) {
2365 // FIXME: Cleanup temporaries here, anyway?
2368 RetValExp = Res.take();
2369 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
2373 CheckImplicitConversions(RetValExp, ReturnLoc);
2374 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2376 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2379 // If we need to check for the named return value optimization,
2380 // or if we need to infer the return type,
2381 // save the return statement in our scope for later processing.
2382 if (CurCap->HasImplicitReturnType ||
2383 (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2384 !CurContext->isDependentContext()))
2385 FunctionScopes.back()->Returns.push_back(Result);
2387 return Owned(Result);
2391 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2392 // Check for unexpanded parameter packs.
2393 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2396 if (isa<CapturingScopeInfo>(getCurFunction()))
2397 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
2400 QualType RelatedRetType;
2401 if (const FunctionDecl *FD = getCurFunctionDecl()) {
2402 FnRetType = FD->getResultType();
2403 if (FD->hasAttr<NoReturnAttr>() ||
2404 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
2405 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
2406 << FD->getDeclName();
2407 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2408 FnRetType = MD->getResultType();
2409 if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2410 // In the implementation of a method with a related return type, the
2411 // type used to type-check the validity of return statements within the
2412 // method body is a pointer to the type of the class being implemented.
2413 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2414 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
2416 } else // If we don't have a function/method context, bail.
2419 ReturnStmt *Result = 0;
2420 if (FnRetType->isVoidType()) {
2422 if (isa<InitListExpr>(RetValExp)) {
2423 // We simply never allow init lists as the return value of void
2424 // functions. This is compatible because this was never allowed before,
2425 // so there's no legacy code to deal with.
2426 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2427 int FunctionKind = 0;
2428 if (isa<ObjCMethodDecl>(CurDecl))
2430 else if (isa<CXXConstructorDecl>(CurDecl))
2432 else if (isa<CXXDestructorDecl>(CurDecl))
2435 Diag(ReturnLoc, diag::err_return_init_list)
2436 << CurDecl->getDeclName() << FunctionKind
2437 << RetValExp->getSourceRange();
2439 // Drop the expression.
2441 } else if (!RetValExp->isTypeDependent()) {
2442 // C99 6.8.6.4p1 (ext_ since GCC warns)
2443 unsigned D = diag::ext_return_has_expr;
2444 if (RetValExp->getType()->isVoidType())
2445 D = diag::ext_return_has_void_expr;
2447 ExprResult Result = Owned(RetValExp);
2448 Result = IgnoredValueConversions(Result.take());
2449 if (Result.isInvalid())
2451 RetValExp = Result.take();
2452 RetValExp = ImpCastExprToType(RetValExp,
2453 Context.VoidTy, CK_ToVoid).take();
2456 // return (some void expression); is legal in C++.
2457 if (D != diag::ext_return_has_void_expr ||
2458 !getLangOpts().CPlusPlus) {
2459 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2461 int FunctionKind = 0;
2462 if (isa<ObjCMethodDecl>(CurDecl))
2464 else if (isa<CXXConstructorDecl>(CurDecl))
2466 else if (isa<CXXDestructorDecl>(CurDecl))
2470 << CurDecl->getDeclName() << FunctionKind
2471 << RetValExp->getSourceRange();
2476 CheckImplicitConversions(RetValExp, ReturnLoc);
2477 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2481 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
2482 } else if (!RetValExp && !FnRetType->isDependentType()) {
2483 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
2484 // C99 6.8.6.4p1 (ext_ since GCC warns)
2485 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
2487 if (FunctionDecl *FD = getCurFunctionDecl())
2488 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
2490 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
2491 Result = new (Context) ReturnStmt(ReturnLoc);
2493 const VarDecl *NRVOCandidate = 0;
2494 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
2495 // we have a non-void function with an expression, continue checking
2497 if (!RelatedRetType.isNull()) {
2498 // If we have a related result type, perform an extra conversion here.
2499 // FIXME: The diagnostics here don't really describe what is happening.
2500 InitializedEntity Entity =
2501 InitializedEntity::InitializeTemporary(RelatedRetType);
2503 ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(),
2505 if (Res.isInvalid()) {
2506 // FIXME: Cleanup temporaries here, anyway?
2509 RetValExp = Res.takeAs<Expr>();
2512 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2513 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2516 // In C++ the return statement is handled via a copy initialization,
2517 // the C version of which boils down to CheckSingleAssignmentConstraints.
2518 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2519 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2521 NRVOCandidate != 0);
2522 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2523 FnRetType, RetValExp);
2524 if (Res.isInvalid()) {
2525 // FIXME: Cleanup temporaries here, anyway?
2529 RetValExp = Res.takeAs<Expr>();
2531 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
2535 CheckImplicitConversions(RetValExp, ReturnLoc);
2536 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2538 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
2541 // If we need to check for the named return value optimization, save the
2542 // return statement in our scope for later processing.
2543 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2544 !CurContext->isDependentContext())
2545 FunctionScopes.back()->Returns.push_back(Result);
2547 return Owned(Result);
2551 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
2552 SourceLocation RParen, Decl *Parm,
2554 VarDecl *Var = cast_or_null<VarDecl>(Parm);
2555 if (Var && Var->isInvalidDecl())
2558 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
2562 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2563 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
2567 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
2568 MultiStmtArg CatchStmts, Stmt *Finally) {
2569 if (!getLangOpts().ObjCExceptions)
2570 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2572 getCurFunction()->setHasBranchProtectedScope();
2573 unsigned NumCatchStmts = CatchStmts.size();
2574 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
2580 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
2582 ExprResult Result = DefaultLvalueConversion(Throw);
2583 if (Result.isInvalid())
2586 Throw = MaybeCreateExprWithCleanups(Result.take());
2587 QualType ThrowType = Throw->getType();
2588 // Make sure the expression type is an ObjC pointer or "void *".
2589 if (!ThrowType->isDependentType() &&
2590 !ThrowType->isObjCObjectPointerType()) {
2591 const PointerType *PT = ThrowType->getAs<PointerType>();
2592 if (!PT || !PT->getPointeeType()->isVoidType())
2593 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2594 << Throw->getType() << Throw->getSourceRange());
2598 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
2602 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
2604 if (!getLangOpts().ObjCExceptions)
2605 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2608 // @throw without an expression designates a rethrow (which much occur
2609 // in the context of an @catch clause).
2610 Scope *AtCatchParent = CurScope;
2611 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2612 AtCatchParent = AtCatchParent->getParent();
2614 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
2616 return BuildObjCAtThrowStmt(AtLoc, Throw);
2620 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2621 ExprResult result = DefaultLvalueConversion(operand);
2622 if (result.isInvalid())
2624 operand = result.take();
2626 // Make sure the expression type is an ObjC pointer or "void *".
2627 QualType type = operand->getType();
2628 if (!type->isDependentType() &&
2629 !type->isObjCObjectPointerType()) {
2630 const PointerType *pointerType = type->getAs<PointerType>();
2631 if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2632 return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2633 << type << operand->getSourceRange();
2636 // The operand to @synchronized is a full-expression.
2637 return MaybeCreateExprWithCleanups(operand);
2641 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2643 // We can't jump into or indirect-jump out of a @synchronized block.
2644 getCurFunction()->setHasBranchProtectedScope();
2645 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
2648 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2649 /// and creates a proper catch handler from them.
2651 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
2652 Stmt *HandlerBlock) {
2653 // There's nothing to test that ActOnExceptionDecl didn't already test.
2654 return Owned(new (Context) CXXCatchStmt(CatchLoc,
2655 cast_or_null<VarDecl>(ExDecl),
2660 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2661 getCurFunction()->setHasBranchProtectedScope();
2662 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2667 class TypeWithHandler {
2671 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2672 : t(type), stmt(statement) {}
2674 // An arbitrary order is fine as long as it places identical
2675 // types next to each other.
2676 bool operator<(const TypeWithHandler &y) const {
2677 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
2679 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
2682 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2685 bool operator==(const TypeWithHandler& other) const {
2686 return t == other.t;
2689 CXXCatchStmt *getCatchStmt() const { return stmt; }
2690 SourceLocation getTypeSpecStartLoc() const {
2691 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2697 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2698 /// handlers and creates a try statement from them.
2700 Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
2701 MultiStmtArg RawHandlers) {
2702 // Don't report an error if 'try' is used in system headers.
2703 if (!getLangOpts().CXXExceptions &&
2704 !getSourceManager().isInSystemHeader(TryLoc))
2705 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
2707 unsigned NumHandlers = RawHandlers.size();
2708 assert(NumHandlers > 0 &&
2709 "The parser shouldn't call this if there are no handlers.");
2710 Stmt **Handlers = RawHandlers.data();
2712 SmallVector<TypeWithHandler, 8> TypesWithHandlers;
2714 for (unsigned i = 0; i < NumHandlers; ++i) {
2715 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
2716 if (!Handler->getExceptionDecl()) {
2717 if (i < NumHandlers - 1)
2718 return StmtError(Diag(Handler->getLocStart(),
2719 diag::err_early_catch_all));
2724 const QualType CaughtType = Handler->getCaughtType();
2725 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2726 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
2729 // Detect handlers for the same type as an earlier one.
2730 if (NumHandlers > 1) {
2731 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
2733 TypeWithHandler prev = TypesWithHandlers[0];
2734 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2735 TypeWithHandler curr = TypesWithHandlers[i];
2738 Diag(curr.getTypeSpecStartLoc(),
2739 diag::warn_exception_caught_by_earlier_handler)
2740 << curr.getCatchStmt()->getCaughtType().getAsString();
2741 Diag(prev.getTypeSpecStartLoc(),
2742 diag::note_previous_exception_handler)
2743 << prev.getCatchStmt()->getCaughtType().getAsString();
2750 getCurFunction()->setHasBranchProtectedScope();
2752 // FIXME: We should detect handlers that cannot catch anything because an
2753 // earlier handler catches a superclass. Need to find a method that is not
2754 // quadratic for this.
2755 // Neither of these are explicitly forbidden, but every compiler detects them
2758 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
2759 Handlers, NumHandlers));
2763 Sema::ActOnSEHTryBlock(bool IsCXXTry,
2764 SourceLocation TryLoc,
2767 assert(TryBlock && Handler);
2769 getCurFunction()->setHasBranchProtectedScope();
2771 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2775 Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2778 assert(FilterExpr && Block);
2780 if(!FilterExpr->getType()->isIntegerType()) {
2781 return StmtError(Diag(FilterExpr->getExprLoc(),
2782 diag::err_filter_expression_integral)
2783 << FilterExpr->getType());
2786 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2790 Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2793 return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2796 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2798 NestedNameSpecifierLoc QualifierLoc,
2799 DeclarationNameInfo NameInfo,
2802 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
2803 QualifierLoc, NameInfo,
2804 cast<CompoundStmt>(Nested));
2808 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
2811 UnqualifiedId &Name,
2813 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2814 SS.getWithLocInContext(Context),
2815 GetNameFromUnqualifiedId(Name),