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/AST/APValue.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/StmtObjC.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/Lex/Preprocessor.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "llvm/ADT/ArrayRef.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include "llvm/ADT/SmallVector.h"
31 using namespace clang;
34 StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
36 if (!E) // FIXME: FullExprArg has no error state?
39 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
40 // void expression for its side effects. Conversion to void allows any
41 // operand, even incomplete types.
43 // Same thing in for stmt first clause (when expr) and third clause.
44 return Owned(static_cast<Stmt*>(E));
48 StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc, bool LeadingEmptyMacro) {
49 return Owned(new (Context) NullStmt(SemiLoc, LeadingEmptyMacro));
52 StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
53 SourceLocation EndLoc) {
54 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
56 // If we have an invalid decl, just return an error.
57 if (DG.isNull()) return StmtError();
59 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
62 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
63 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
65 // If we have an invalid decl, just return.
66 if (DG.isNull() || !DG.isSingleDecl()) return;
67 // suppress any potential 'unused variable' warning.
68 DG.getSingleDecl()->setUsed();
71 void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
72 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
73 return DiagnoseUnusedExprResult(Label->getSubStmt());
75 const Expr *E = dyn_cast_or_null<Expr>(S);
79 if (E->isBoundMemberFunction(Context)) {
80 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
81 << E->getSourceRange();
87 if (!E->isUnusedResultAWarning(Loc, R1, R2, Context))
90 // Okay, we have an unused result. Depending on what the base expression is,
91 // we might want to make a more specific diagnostic. Check for one of these
93 unsigned DiagID = diag::warn_unused_expr;
94 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
95 E = Temps->getSubExpr();
96 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
97 E = TempExpr->getSubExpr();
99 E = E->IgnoreParenImpCasts();
100 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
101 if (E->getType()->isVoidType())
104 // If the callee has attribute pure, const, or warn_unused_result, warn with
105 // a more specific message to make it clear what is happening.
106 if (const Decl *FD = CE->getCalleeDecl()) {
107 if (FD->getAttr<WarnUnusedResultAttr>()) {
108 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
111 if (FD->getAttr<PureAttr>()) {
112 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
115 if (FD->getAttr<ConstAttr>()) {
116 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
120 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
121 const ObjCMethodDecl *MD = ME->getMethodDecl();
122 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
123 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
126 } else if (isa<ObjCPropertyRefExpr>(E)) {
127 DiagID = diag::warn_unused_property_expr;
128 } else if (const CXXFunctionalCastExpr *FC
129 = dyn_cast<CXXFunctionalCastExpr>(E)) {
130 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
131 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
134 // Diagnose "(void*) blah" as a typo for "(void) blah".
135 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
136 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
137 QualType T = TI->getType();
139 // We really do want to use the non-canonical type here.
140 if (T == Context.VoidPtrTy) {
141 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
143 Diag(Loc, diag::warn_unused_voidptr)
144 << FixItHint::CreateRemoval(TL.getStarLoc());
149 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
153 Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
154 MultiStmtArg elts, bool isStmtExpr) {
155 unsigned NumElts = elts.size();
156 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
157 // If we're in C89 mode, check that we don't have any decls after stmts. If
158 // so, emit an extension diagnostic.
159 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
160 // Note that __extension__ can be around a decl.
162 // Skip over all declarations.
163 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
166 // We found the end of the list or a statement. Scan for another declstmt.
167 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
171 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
172 Diag(D->getLocation(), diag::ext_mixed_decls_code);
175 // Warn about unused expressions in statements.
176 for (unsigned i = 0; i != NumElts; ++i) {
177 // Ignore statements that are last in a statement expression.
178 if (isStmtExpr && i == NumElts - 1)
181 DiagnoseUnusedExprResult(Elts[i]);
184 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
188 Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
189 SourceLocation DotDotDotLoc, Expr *RHSVal,
190 SourceLocation ColonLoc) {
191 assert((LHSVal != 0) && "missing expression in case statement");
193 // C99 6.8.4.2p3: The expression shall be an integer constant.
194 // However, GCC allows any evaluatable integer expression.
195 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() &&
196 VerifyIntegerConstantExpression(LHSVal))
199 // GCC extension: The expression shall be an integer constant.
201 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() &&
202 VerifyIntegerConstantExpression(RHSVal)) {
203 RHSVal = 0; // Recover by just forgetting about it.
206 if (getCurFunction()->SwitchStack.empty()) {
207 Diag(CaseLoc, diag::err_case_not_in_switch);
211 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
213 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
217 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
218 void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
219 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
220 CS->setSubStmt(SubStmt);
224 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
225 Stmt *SubStmt, Scope *CurScope) {
226 if (getCurFunction()->SwitchStack.empty()) {
227 Diag(DefaultLoc, diag::err_default_not_in_switch);
228 return Owned(SubStmt);
231 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
232 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
237 Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
238 SourceLocation ColonLoc, Stmt *SubStmt) {
240 // If the label was multiply defined, reject it now.
241 if (TheDecl->getStmt()) {
242 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
243 Diag(TheDecl->getLocation(), diag::note_previous_definition);
244 return Owned(SubStmt);
247 // Otherwise, things are good. Fill in the declaration and return it.
248 TheDecl->setLocation(IdentLoc);
250 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
251 TheDecl->setStmt(LS);
252 TheDecl->setLocation(IdentLoc);
257 Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
258 Stmt *thenStmt, SourceLocation ElseLoc,
260 ExprResult CondResult(CondVal.release());
262 VarDecl *ConditionVar = 0;
264 ConditionVar = cast<VarDecl>(CondVar);
265 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
266 if (CondResult.isInvalid())
269 Expr *ConditionExpr = CondResult.takeAs<Expr>();
273 DiagnoseUnusedExprResult(thenStmt);
275 // Warn if the if block has a null body without an else value.
276 // this helps prevent bugs due to typos, such as
281 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
282 // But do not warn if the body is a macro that expands to nothing, e.g:
288 if (!stmt->hasLeadingEmptyMacro())
289 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
292 DiagnoseUnusedExprResult(elseStmt);
294 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
295 thenStmt, ElseLoc, elseStmt));
298 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
299 /// the specified width and sign. If an overflow occurs, detect it and emit
300 /// the specified diagnostic.
301 void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
302 unsigned NewWidth, bool NewSign,
305 // Perform a conversion to the promoted condition type if needed.
306 if (NewWidth > Val.getBitWidth()) {
307 // If this is an extension, just do it.
308 Val = Val.extend(NewWidth);
309 Val.setIsSigned(NewSign);
311 // If the input was signed and negative and the output is
312 // unsigned, don't bother to warn: this is implementation-defined
314 // FIXME: Introduce a second, default-ignored warning for this case?
315 } else if (NewWidth < Val.getBitWidth()) {
316 // If this is a truncation, check for overflow.
317 llvm::APSInt ConvVal(Val);
318 ConvVal = ConvVal.trunc(NewWidth);
319 ConvVal.setIsSigned(NewSign);
320 ConvVal = ConvVal.extend(Val.getBitWidth());
321 ConvVal.setIsSigned(Val.isSigned());
323 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
325 // Regardless of whether a diagnostic was emitted, really do the
327 Val = Val.trunc(NewWidth);
328 Val.setIsSigned(NewSign);
329 } else if (NewSign != Val.isSigned()) {
330 // Convert the sign to match the sign of the condition. This can cause
331 // overflow as well: unsigned(INTMIN)
332 // We don't diagnose this overflow, because it is implementation-defined
334 // FIXME: Introduce a second, default-ignored warning for this case?
335 llvm::APSInt OldVal(Val);
336 Val.setIsSigned(NewSign);
341 struct CaseCompareFunctor {
342 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
343 const llvm::APSInt &RHS) {
344 return LHS.first < RHS;
346 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
347 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
348 return LHS.first < RHS.first;
350 bool operator()(const llvm::APSInt &LHS,
351 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
352 return LHS < RHS.first;
357 /// CmpCaseVals - Comparison predicate for sorting case values.
359 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
360 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
361 if (lhs.first < rhs.first)
364 if (lhs.first == rhs.first &&
365 lhs.second->getCaseLoc().getRawEncoding()
366 < rhs.second->getCaseLoc().getRawEncoding())
371 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
373 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
374 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
376 return lhs.first < rhs.first;
379 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
381 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
382 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
384 return lhs.first == rhs.first;
387 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
388 /// potentially integral-promoted expression @p expr.
389 static QualType GetTypeBeforeIntegralPromotion(const Expr* expr) {
390 if (const CastExpr *ImplicitCast = dyn_cast<ImplicitCastExpr>(expr)) {
391 const Expr *ExprBeforePromotion = ImplicitCast->getSubExpr();
392 QualType TypeBeforePromotion = ExprBeforePromotion->getType();
393 if (TypeBeforePromotion->isIntegralOrEnumerationType()) {
394 return TypeBeforePromotion;
397 return expr->getType();
401 Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
403 ExprResult CondResult;
405 VarDecl *ConditionVar = 0;
407 ConditionVar = cast<VarDecl>(CondVar);
408 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
409 if (CondResult.isInvalid())
412 Cond = CondResult.release();
419 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond,
420 PDiag(diag::err_typecheck_statement_requires_integer),
421 PDiag(diag::err_switch_incomplete_class_type)
422 << Cond->getSourceRange(),
423 PDiag(diag::err_switch_explicit_conversion),
424 PDiag(diag::note_switch_conversion),
425 PDiag(diag::err_switch_multiple_conversions),
426 PDiag(diag::note_switch_conversion),
428 if (CondResult.isInvalid()) return StmtError();
429 Cond = CondResult.take();
432 CheckImplicitConversions(Cond, SwitchLoc);
433 CondResult = MaybeCreateExprWithCleanups(Cond);
434 if (CondResult.isInvalid())
436 Cond = CondResult.take();
439 getCurFunction()->setHasBranchIntoScope();
441 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
442 getCurFunction()->SwitchStack.push_back(SS);
446 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
447 if (Val.getBitWidth() < BitWidth)
448 Val = Val.extend(BitWidth);
449 else if (Val.getBitWidth() > BitWidth)
450 Val = Val.trunc(BitWidth);
451 Val.setIsSigned(IsSigned);
455 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
457 SwitchStmt *SS = cast<SwitchStmt>(Switch);
458 assert(SS == getCurFunction()->SwitchStack.back() &&
459 "switch stack missing push/pop!");
461 SS->setBody(BodyStmt, SwitchLoc);
462 getCurFunction()->SwitchStack.pop_back();
464 if (SS->getCond() == 0)
467 Expr *CondExpr = SS->getCond();
468 Expr *CondExprBeforePromotion = CondExpr;
469 QualType CondTypeBeforePromotion =
470 GetTypeBeforeIntegralPromotion(CondExpr);
472 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
473 UsualUnaryConversions(CondExpr);
474 QualType CondType = CondExpr->getType();
475 SS->setCond(CondExpr);
478 // Integral promotions are performed (on the switch condition).
480 // A case value unrepresentable by the original switch condition
481 // type (before the promotion) doesn't make sense, even when it can
482 // be represented by the promoted type. Therefore we need to find
483 // the pre-promotion type of the switch condition.
484 if (!CondExpr->isTypeDependent()) {
485 // We have already converted the expression to an integral or enumeration
486 // type, when we started the switch statement. If we don't have an
487 // appropriate type now, just return an error.
488 if (!CondType->isIntegralOrEnumerationType())
491 if (CondExpr->isKnownToHaveBooleanValue()) {
492 // switch(bool_expr) {...} is often a programmer error, e.g.
493 // switch(n && mask) { ... } // Doh - should be "n & mask".
494 // One can always use an if statement instead of switch(bool_expr).
495 Diag(SwitchLoc, diag::warn_bool_switch_condition)
496 << CondExpr->getSourceRange();
500 // Get the bitwidth of the switched-on value before promotions. We must
501 // convert the integer case values to this width before comparison.
502 bool HasDependentValue
503 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
505 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
506 bool CondIsSigned = CondTypeBeforePromotion->isSignedIntegerType();
508 // Accumulate all of the case values in a vector so that we can sort them
509 // and detect duplicates. This vector contains the APInt for the case after
510 // it has been converted to the condition type.
511 typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
514 // Keep track of any GNU case ranges we see. The APSInt is the low value.
515 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
516 CaseRangesTy CaseRanges;
518 DefaultStmt *TheDefaultStmt = 0;
520 bool CaseListIsErroneous = false;
522 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
523 SC = SC->getNextSwitchCase()) {
525 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
526 if (TheDefaultStmt) {
527 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
528 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
530 // FIXME: Remove the default statement from the switch block so that
531 // we'll return a valid AST. This requires recursing down the AST and
532 // finding it, not something we are set up to do right now. For now,
533 // just lop the entire switch stmt out of the AST.
534 CaseListIsErroneous = true;
539 CaseStmt *CS = cast<CaseStmt>(SC);
541 // We already verified that the expression has a i-c-e value (C99
542 // 6.8.4.2p3) - get that value now.
543 Expr *Lo = CS->getLHS();
545 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
546 HasDependentValue = true;
550 llvm::APSInt LoVal = Lo->EvaluateAsInt(Context);
552 // Convert the value to the same width/sign as the condition.
553 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
555 diag::warn_case_value_overflow);
557 // If the LHS is not the same type as the condition, insert an implicit
559 ImpCastExprToType(Lo, CondType, CK_IntegralCast);
562 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
564 if (CS->getRHS()->isTypeDependent() ||
565 CS->getRHS()->isValueDependent()) {
566 HasDependentValue = true;
569 CaseRanges.push_back(std::make_pair(LoVal, CS));
571 CaseVals.push_back(std::make_pair(LoVal, CS));
575 if (!HasDependentValue) {
576 // If we don't have a default statement, check whether the
577 // condition is constant.
578 llvm::APSInt ConstantCondValue;
579 bool HasConstantCond = false;
580 bool ShouldCheckConstantCond = false;
581 if (!HasDependentValue && !TheDefaultStmt) {
582 Expr::EvalResult Result;
583 HasConstantCond = CondExprBeforePromotion->Evaluate(Result, Context);
584 if (HasConstantCond) {
585 assert(Result.Val.isInt() && "switch condition evaluated to non-int");
586 ConstantCondValue = Result.Val.getInt();
587 ShouldCheckConstantCond = true;
589 assert(ConstantCondValue.getBitWidth() == CondWidth &&
590 ConstantCondValue.isSigned() == CondIsSigned);
594 // Sort all the scalar case values so we can easily detect duplicates.
595 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
597 if (!CaseVals.empty()) {
598 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
599 if (ShouldCheckConstantCond &&
600 CaseVals[i].first == ConstantCondValue)
601 ShouldCheckConstantCond = false;
603 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
604 // If we have a duplicate, report it.
605 Diag(CaseVals[i].second->getLHS()->getLocStart(),
606 diag::err_duplicate_case) << CaseVals[i].first.toString(10);
607 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
608 diag::note_duplicate_case_prev);
609 // FIXME: We really want to remove the bogus case stmt from the
610 // substmt, but we have no way to do this right now.
611 CaseListIsErroneous = true;
616 // Detect duplicate case ranges, which usually don't exist at all in
618 if (!CaseRanges.empty()) {
619 // Sort all the case ranges by their low value so we can easily detect
620 // overlaps between ranges.
621 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
623 // Scan the ranges, computing the high values and removing empty ranges.
624 std::vector<llvm::APSInt> HiVals;
625 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
626 llvm::APSInt &LoVal = CaseRanges[i].first;
627 CaseStmt *CR = CaseRanges[i].second;
628 Expr *Hi = CR->getRHS();
629 llvm::APSInt HiVal = Hi->EvaluateAsInt(Context);
631 // Convert the value to the same width/sign as the condition.
632 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
634 diag::warn_case_value_overflow);
636 // If the LHS is not the same type as the condition, insert an implicit
638 ImpCastExprToType(Hi, CondType, CK_IntegralCast);
641 // If the low value is bigger than the high value, the case is empty.
643 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
644 << SourceRange(CR->getLHS()->getLocStart(),
646 CaseRanges.erase(CaseRanges.begin()+i);
651 if (ShouldCheckConstantCond &&
652 LoVal <= ConstantCondValue &&
653 ConstantCondValue <= HiVal)
654 ShouldCheckConstantCond = false;
656 HiVals.push_back(HiVal);
659 // Rescan the ranges, looking for overlap with singleton values and other
660 // ranges. Since the range list is sorted, we only need to compare case
661 // ranges with their neighbors.
662 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
663 llvm::APSInt &CRLo = CaseRanges[i].first;
664 llvm::APSInt &CRHi = HiVals[i];
665 CaseStmt *CR = CaseRanges[i].second;
667 // Check to see whether the case range overlaps with any
669 CaseStmt *OverlapStmt = 0;
670 llvm::APSInt OverlapVal(32);
672 // Find the smallest value >= the lower bound. If I is in the
673 // case range, then we have overlap.
674 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
675 CaseVals.end(), CRLo,
676 CaseCompareFunctor());
677 if (I != CaseVals.end() && I->first < CRHi) {
678 OverlapVal = I->first; // Found overlap with scalar.
679 OverlapStmt = I->second;
682 // Find the smallest value bigger than the upper bound.
683 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
684 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
685 OverlapVal = (I-1)->first; // Found overlap with scalar.
686 OverlapStmt = (I-1)->second;
689 // Check to see if this case stmt overlaps with the subsequent
691 if (i && CRLo <= HiVals[i-1]) {
692 OverlapVal = HiVals[i-1]; // Found overlap with range.
693 OverlapStmt = CaseRanges[i-1].second;
697 // If we have a duplicate, report it.
698 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
699 << OverlapVal.toString(10);
700 Diag(OverlapStmt->getLHS()->getLocStart(),
701 diag::note_duplicate_case_prev);
702 // FIXME: We really want to remove the bogus case stmt from the
703 // substmt, but we have no way to do this right now.
704 CaseListIsErroneous = true;
709 // Complain if we have a constant condition and we didn't find a match.
710 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
711 // TODO: it would be nice if we printed enums as enums, chars as
713 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
714 << ConstantCondValue.toString(10)
715 << CondExpr->getSourceRange();
718 // Check to see if switch is over an Enum and handles all of its
719 // values. We only issue a warning if there is not 'default:', but
720 // we still do the analysis to preserve this information in the AST
721 // (which can be used by flow-based analyes).
723 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
725 // If switch has default case, then ignore it.
726 if (!CaseListIsErroneous && !HasConstantCond && ET) {
727 const EnumDecl *ED = ET->getDecl();
728 typedef llvm::SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
731 // Gather all enum values, set their type and sort them,
732 // allowing easier comparison with CaseVals.
733 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
734 EDI != ED->enumerator_end(); ++EDI) {
735 llvm::APSInt Val = EDI->getInitVal();
736 AdjustAPSInt(Val, CondWidth, CondIsSigned);
737 EnumVals.push_back(std::make_pair(Val, *EDI));
739 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
740 EnumValsTy::iterator EIend =
741 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
743 // See which case values aren't in enum.
744 // TODO: we might want to check whether case values are out of the
745 // enum even if we don't want to check whether all cases are handled.
746 if (!TheDefaultStmt) {
747 EnumValsTy::const_iterator EI = EnumVals.begin();
748 for (CaseValsTy::const_iterator CI = CaseVals.begin();
749 CI != CaseVals.end(); CI++) {
750 while (EI != EIend && EI->first < CI->first)
752 if (EI == EIend || EI->first > CI->first)
753 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
754 << ED->getDeclName();
756 // See which of case ranges aren't in enum
757 EI = EnumVals.begin();
758 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
759 RI != CaseRanges.end() && EI != EIend; RI++) {
760 while (EI != EIend && EI->first < RI->first)
763 if (EI == EIend || EI->first != RI->first) {
764 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
765 << ED->getDeclName();
768 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
769 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
770 while (EI != EIend && EI->first < Hi)
772 if (EI == EIend || EI->first != Hi)
773 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
774 << ED->getDeclName();
778 // Check which enum vals aren't in switch
779 CaseValsTy::const_iterator CI = CaseVals.begin();
780 CaseRangesTy::const_iterator RI = CaseRanges.begin();
781 bool hasCasesNotInSwitch = false;
783 llvm::SmallVector<DeclarationName,8> UnhandledNames;
785 for (EnumValsTy::const_iterator EI = EnumVals.begin(); EI != EIend; EI++){
786 // Drop unneeded case values
788 while (CI != CaseVals.end() && CI->first < EI->first)
791 if (CI != CaseVals.end() && CI->first == EI->first)
794 // Drop unneeded case ranges
795 for (; RI != CaseRanges.end(); RI++) {
796 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
797 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
802 if (RI == CaseRanges.end() || EI->first < RI->first) {
803 hasCasesNotInSwitch = true;
805 UnhandledNames.push_back(EI->second->getDeclName());
809 // Produce a nice diagnostic if multiple values aren't handled.
810 switch (UnhandledNames.size()) {
813 Diag(CondExpr->getExprLoc(), diag::warn_missing_case1)
814 << UnhandledNames[0];
817 Diag(CondExpr->getExprLoc(), diag::warn_missing_case2)
818 << UnhandledNames[0] << UnhandledNames[1];
821 Diag(CondExpr->getExprLoc(), diag::warn_missing_case3)
822 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
825 Diag(CondExpr->getExprLoc(), diag::warn_missing_cases)
826 << (unsigned)UnhandledNames.size()
827 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
831 if (!hasCasesNotInSwitch)
832 SS->setAllEnumCasesCovered();
836 // FIXME: If the case list was broken is some way, we don't have a good system
837 // to patch it up. Instead, just return the whole substmt as broken.
838 if (CaseListIsErroneous)
845 Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
846 Decl *CondVar, Stmt *Body) {
847 ExprResult CondResult(Cond.release());
849 VarDecl *ConditionVar = 0;
851 ConditionVar = cast<VarDecl>(CondVar);
852 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
853 if (CondResult.isInvalid())
856 Expr *ConditionExpr = CondResult.take();
860 DiagnoseUnusedExprResult(Body);
862 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
867 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
868 SourceLocation WhileLoc, SourceLocation CondLParen,
869 Expr *Cond, SourceLocation CondRParen) {
870 assert(Cond && "ActOnDoStmt(): missing expression");
872 if (CheckBooleanCondition(Cond, DoLoc))
875 CheckImplicitConversions(Cond, DoLoc);
876 ExprResult CondResult = MaybeCreateExprWithCleanups(Cond);
877 if (CondResult.isInvalid())
879 Cond = CondResult.take();
881 DiagnoseUnusedExprResult(Body);
883 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
887 Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
888 Stmt *First, FullExprArg second, Decl *secondVar,
890 SourceLocation RParenLoc, Stmt *Body) {
891 if (!getLangOptions().CPlusPlus) {
892 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
893 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
894 // declare identifiers for objects having storage class 'auto' or
896 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
898 VarDecl *VD = dyn_cast<VarDecl>(*DI);
899 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
902 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
903 // FIXME: mark decl erroneous!
908 ExprResult SecondResult(second.release());
909 VarDecl *ConditionVar = 0;
911 ConditionVar = cast<VarDecl>(secondVar);
912 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
913 if (SecondResult.isInvalid())
917 Expr *Third = third.release().takeAs<Expr>();
919 DiagnoseUnusedExprResult(First);
920 DiagnoseUnusedExprResult(Third);
921 DiagnoseUnusedExprResult(Body);
923 return Owned(new (Context) ForStmt(Context, First,
924 SecondResult.take(), ConditionVar,
925 Third, Body, ForLoc, LParenLoc,
929 /// In an Objective C collection iteration statement:
931 /// x can be an arbitrary l-value expression. Bind it up as a
933 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
934 CheckImplicitConversions(E);
935 ExprResult Result = MaybeCreateExprWithCleanups(E);
936 if (Result.isInvalid()) return StmtError();
937 return Owned(static_cast<Stmt*>(Result.get()));
941 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
942 SourceLocation LParenLoc,
943 Stmt *First, Expr *Second,
944 SourceLocation RParenLoc, Stmt *Body) {
947 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
948 if (!DS->isSingleDecl())
949 return StmtError(Diag((*DS->decl_begin())->getLocation(),
950 diag::err_toomany_element_decls));
952 Decl *D = DS->getSingleDecl();
953 FirstType = cast<ValueDecl>(D)->getType();
954 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
955 // declare identifiers for objects having storage class 'auto' or
957 VarDecl *VD = cast<VarDecl>(D);
958 if (VD->isLocalVarDecl() && !VD->hasLocalStorage())
959 return StmtError(Diag(VD->getLocation(),
960 diag::err_non_variable_decl_in_for));
962 Expr *FirstE = cast<Expr>(First);
963 if (!FirstE->isTypeDependent() && !FirstE->isLValue())
964 return StmtError(Diag(First->getLocStart(),
965 diag::err_selector_element_not_lvalue)
966 << First->getSourceRange());
968 FirstType = static_cast<Expr*>(First)->getType();
970 if (!FirstType->isDependentType() &&
971 !FirstType->isObjCObjectPointerType() &&
972 !FirstType->isBlockPointerType())
973 Diag(ForLoc, diag::err_selector_element_type)
974 << FirstType << First->getSourceRange();
976 if (Second && !Second->isTypeDependent()) {
977 DefaultFunctionArrayLvalueConversion(Second);
978 QualType SecondType = Second->getType();
979 if (!SecondType->isObjCObjectPointerType())
980 Diag(ForLoc, diag::err_collection_expr_type)
981 << SecondType << Second->getSourceRange();
982 else if (const ObjCObjectPointerType *OPT =
983 SecondType->getAsObjCInterfacePointerType()) {
984 llvm::SmallVector<IdentifierInfo *, 4> KeyIdents;
985 IdentifierInfo* selIdent =
986 &Context.Idents.get("countByEnumeratingWithState");
987 KeyIdents.push_back(selIdent);
988 selIdent = &Context.Idents.get("objects");
989 KeyIdents.push_back(selIdent);
990 selIdent = &Context.Idents.get("count");
991 KeyIdents.push_back(selIdent);
992 Selector CSelector = Context.Selectors.getSelector(3, &KeyIdents[0]);
993 if (ObjCInterfaceDecl *IDecl = OPT->getInterfaceDecl()) {
994 if (!IDecl->isForwardDecl() &&
995 !IDecl->lookupInstanceMethod(CSelector)) {
996 // Must further look into private implementation methods.
997 if (!LookupPrivateInstanceMethod(CSelector, IDecl))
998 Diag(ForLoc, diag::warn_collection_expr_type)
999 << SecondType << CSelector << Second->getSourceRange();
1004 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
1005 ForLoc, RParenLoc));
1008 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
1009 SourceLocation LabelLoc,
1010 LabelDecl *TheDecl) {
1011 getCurFunction()->setHasBranchIntoScope();
1013 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
1017 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
1019 // Convert operand to void*
1020 if (!E->isTypeDependent()) {
1021 QualType ETy = E->getType();
1022 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
1023 AssignConvertType ConvTy =
1024 CheckSingleAssignmentConstraints(DestTy, E);
1025 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
1029 getCurFunction()->setHasIndirectGoto();
1031 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
1035 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
1036 Scope *S = CurScope->getContinueParent();
1038 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
1039 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
1042 return Owned(new (Context) ContinueStmt(ContinueLoc));
1046 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
1047 Scope *S = CurScope->getBreakParent();
1049 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
1050 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
1053 return Owned(new (Context) BreakStmt(BreakLoc));
1056 /// \brief Determine whether the given expression is a candidate for
1057 /// copy elision in either a return statement or a throw expression.
1059 /// \param ReturnType If we're determining the copy elision candidate for
1060 /// a return statement, this is the return type of the function. If we're
1061 /// determining the copy elision candidate for a throw expression, this will
1064 /// \param E The expression being returned from the function or block, or
1067 /// \param AllowFunctionParameter
1069 /// \returns The NRVO candidate variable, if the return statement may use the
1070 /// NRVO, or NULL if there is no such candidate.
1071 const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
1073 bool AllowFunctionParameter) {
1074 QualType ExprType = E->getType();
1075 // - in a return statement in a function with ...
1076 // ... a class return type ...
1077 if (!ReturnType.isNull()) {
1078 if (!ReturnType->isRecordType())
1080 // ... the same cv-unqualified type as the function return type ...
1081 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
1085 // ... the expression is the name of a non-volatile automatic object
1086 // (other than a function or catch-clause parameter)) ...
1087 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
1090 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1094 if (VD->hasLocalStorage() && !VD->isExceptionVariable() &&
1095 !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() &&
1096 !VD->getType().isVolatileQualified() &&
1097 ((VD->getKind() == Decl::Var) ||
1098 (AllowFunctionParameter && VD->getKind() == Decl::ParmVar)))
1104 /// \brief Perform the initialization of a potentially-movable value, which
1105 /// is the result of return value.
1107 /// This routine implements C++0x [class.copy]p33, which attempts to treat
1108 /// returned lvalues as rvalues in certain cases (to prefer move construction),
1109 /// then falls back to treating them as lvalues if that failed.
1111 Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
1112 const VarDecl *NRVOCandidate,
1113 QualType ResultType,
1115 // C++0x [class.copy]p33:
1116 // When the criteria for elision of a copy operation are met or would
1117 // be met save for the fact that the source object is a function
1118 // parameter, and the object to be copied is designated by an lvalue,
1119 // overload resolution to select the constructor for the copy is first
1120 // performed as if the object were designated by an rvalue.
1121 ExprResult Res = ExprError();
1122 if (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true)) {
1123 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
1124 Value->getType(), CK_LValueToRValue,
1127 Expr *InitExpr = &AsRvalue;
1128 InitializationKind Kind
1129 = InitializationKind::CreateCopy(Value->getLocStart(),
1130 Value->getLocStart());
1131 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
1133 // [...] If overload resolution fails, or if the type of the first
1134 // parameter of the selected constructor is not an rvalue reference
1135 // to the object's type (possibly cv-qualified), overload resolution
1136 // is performed again, considering the object as an lvalue.
1137 if (Seq.getKind() != InitializationSequence::FailedSequence) {
1138 for (InitializationSequence::step_iterator Step = Seq.step_begin(),
1139 StepEnd = Seq.step_end();
1140 Step != StepEnd; ++Step) {
1142 != InitializationSequence::SK_ConstructorInitialization)
1145 CXXConstructorDecl *Constructor
1146 = cast<CXXConstructorDecl>(Step->Function.Function);
1148 const RValueReferenceType *RRefType
1149 = Constructor->getParamDecl(0)->getType()
1150 ->getAs<RValueReferenceType>();
1152 // If we don't meet the criteria, break out now.
1154 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
1155 Context.getTypeDeclType(Constructor->getParent())))
1158 // Promote "AsRvalue" to the heap, since we now need this
1159 // expression node to persist.
1160 Value = ImplicitCastExpr::Create(Context, Value->getType(),
1161 CK_LValueToRValue, Value, 0,
1164 // Complete type-checking the initialization of the return type
1165 // using the constructor we found.
1166 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
1171 // Either we didn't meet the criteria for treating an lvalue as an rvalue,
1172 // above, or overload resolution failed. Either way, we need to try
1173 // (again) now with the return value expression as written.
1174 if (Res.isInvalid())
1175 Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
1180 /// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
1183 Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
1184 // If this is the first return we've seen in the block, infer the type of
1185 // the block from it.
1186 BlockScopeInfo *CurBlock = getCurBlock();
1187 if (CurBlock->ReturnType.isNull()) {
1189 // Don't call UsualUnaryConversions(), since we don't want to do
1190 // integer promotions here.
1191 DefaultFunctionArrayLvalueConversion(RetValExp);
1192 CurBlock->ReturnType = RetValExp->getType();
1193 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
1194 // We have to remove a 'const' added to copied-in variable which was
1195 // part of the implementation spec. and not the actual qualifier for
1197 if (CDRE->isConstQualAdded())
1198 CurBlock->ReturnType.removeLocalConst(); // FIXME: local???
1201 CurBlock->ReturnType = Context.VoidTy;
1203 QualType FnRetType = CurBlock->ReturnType;
1205 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
1206 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
1207 << getCurFunctionOrMethodDecl()->getDeclName();
1211 // Otherwise, verify that this result type matches the previous one. We are
1212 // pickier with blocks than for normal functions because we don't have GCC
1213 // compatibility to worry about here.
1214 ReturnStmt *Result = 0;
1215 if (CurBlock->ReturnType->isVoidType()) {
1217 Diag(ReturnLoc, diag::err_return_block_has_expr);
1220 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1221 } else if (!RetValExp) {
1222 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
1224 const VarDecl *NRVOCandidate = 0;
1226 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1227 // we have a non-void block with an expression, continue checking
1229 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1230 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1233 // In C++ the return statement is handled via a copy initialization.
1234 // the C version of which boils down to CheckSingleAssignmentConstraints.
1235 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
1236 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
1238 NRVOCandidate != 0);
1239 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
1240 FnRetType, RetValExp);
1241 if (Res.isInvalid()) {
1242 // FIXME: Cleanup temporaries here, anyway?
1247 CheckImplicitConversions(RetValExp, ReturnLoc);
1248 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
1251 RetValExp = Res.takeAs<Expr>();
1253 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1256 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
1259 // If we need to check for the named return value optimization, save the
1260 // return statement in our scope for later processing.
1261 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1262 !CurContext->isDependentContext())
1263 FunctionScopes.back()->Returns.push_back(Result);
1265 return Owned(Result);
1269 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
1271 return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
1274 if (const FunctionDecl *FD = getCurFunctionDecl()) {
1275 FnRetType = FD->getResultType();
1276 if (FD->hasAttr<NoReturnAttr>() ||
1277 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
1278 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
1279 << getCurFunctionOrMethodDecl()->getDeclName();
1280 } else if (ObjCMethodDecl *MD = getCurMethodDecl())
1281 FnRetType = MD->getResultType();
1282 else // If we don't have a function/method context, bail.
1285 ReturnStmt *Result = 0;
1286 if (FnRetType->isVoidType()) {
1287 if (RetValExp && !RetValExp->isTypeDependent()) {
1288 // C99 6.8.6.4p1 (ext_ since GCC warns)
1289 unsigned D = diag::ext_return_has_expr;
1290 if (RetValExp->getType()->isVoidType())
1291 D = diag::ext_return_has_void_expr;
1293 IgnoredValueConversions(RetValExp);
1294 ImpCastExprToType(RetValExp, Context.VoidTy, CK_ToVoid);
1297 // return (some void expression); is legal in C++.
1298 if (D != diag::ext_return_has_void_expr ||
1299 !getLangOptions().CPlusPlus) {
1300 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
1302 << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl)
1303 << RetValExp->getSourceRange();
1306 CheckImplicitConversions(RetValExp, ReturnLoc);
1307 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
1310 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1311 } else if (!RetValExp && !FnRetType->isDependentType()) {
1312 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
1313 // C99 6.8.6.4p1 (ext_ since GCC warns)
1314 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
1316 if (FunctionDecl *FD = getCurFunctionDecl())
1317 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
1319 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
1320 Result = new (Context) ReturnStmt(ReturnLoc);
1322 const VarDecl *NRVOCandidate = 0;
1323 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1324 // we have a non-void function with an expression, continue checking
1326 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1327 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1330 // In C++ the return statement is handled via a copy initialization.
1331 // the C version of which boils down to CheckSingleAssignmentConstraints.
1332 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
1333 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
1335 NRVOCandidate != 0);
1336 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
1337 FnRetType, RetValExp);
1338 if (Res.isInvalid()) {
1339 // FIXME: Cleanup temporaries here, anyway?
1343 RetValExp = Res.takeAs<Expr>();
1345 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1349 CheckImplicitConversions(RetValExp, ReturnLoc);
1350 RetValExp = MaybeCreateExprWithCleanups(RetValExp);
1352 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
1355 // If we need to check for the named return value optimization, save the
1356 // return statement in our scope for later processing.
1357 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1358 !CurContext->isDependentContext())
1359 FunctionScopes.back()->Returns.push_back(Result);
1361 return Owned(Result);
1364 /// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
1365 /// ignore "noop" casts in places where an lvalue is required by an inline asm.
1366 /// We emulate this behavior when -fheinous-gnu-extensions is specified, but
1367 /// provide a strong guidance to not use it.
1369 /// This method checks to see if the argument is an acceptable l-value and
1370 /// returns false if it is a case we can handle.
1371 static bool CheckAsmLValue(const Expr *E, Sema &S) {
1372 // Type dependent expressions will be checked during instantiation.
1373 if (E->isTypeDependent())
1377 return false; // Cool, this is an lvalue.
1379 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
1380 // are supposed to allow.
1381 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
1382 if (E != E2 && E2->isLValue()) {
1383 if (!S.getLangOptions().HeinousExtensions)
1384 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
1385 << E->getSourceRange();
1387 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
1388 << E->getSourceRange();
1389 // Accept, even if we emitted an error diagnostic.
1393 // None of the above, just randomly invalid non-lvalue.
1397 /// isOperandMentioned - Return true if the specified operand # is mentioned
1398 /// anywhere in the decomposed asm string.
1399 static bool isOperandMentioned(unsigned OpNo,
1400 llvm::ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) {
1401 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
1402 const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
1403 if (!Piece.isOperand()) continue;
1405 // If this is a reference to the input and if the input was the smaller
1406 // one, then we have to reject this asm.
1407 if (Piece.getOperandNo() == OpNo)
1414 StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1415 bool IsVolatile, unsigned NumOutputs,
1416 unsigned NumInputs, IdentifierInfo **Names,
1417 MultiExprArg constraints, MultiExprArg exprs,
1418 Expr *asmString, MultiExprArg clobbers,
1419 SourceLocation RParenLoc, bool MSAsm) {
1420 unsigned NumClobbers = clobbers.size();
1421 StringLiteral **Constraints =
1422 reinterpret_cast<StringLiteral**>(constraints.get());
1423 Expr **Exprs = exprs.get();
1424 StringLiteral *AsmString = cast<StringLiteral>(asmString);
1425 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
1427 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1429 // The parser verifies that there is a string literal here.
1430 if (AsmString->isWide())
1431 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
1432 << AsmString->getSourceRange());
1434 for (unsigned i = 0; i != NumOutputs; i++) {
1435 StringLiteral *Literal = Constraints[i];
1436 if (Literal->isWide())
1437 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1438 << Literal->getSourceRange());
1440 llvm::StringRef OutputName;
1442 OutputName = Names[i]->getName();
1444 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
1445 if (!Context.Target.validateOutputConstraint(Info))
1446 return StmtError(Diag(Literal->getLocStart(),
1447 diag::err_asm_invalid_output_constraint)
1448 << Info.getConstraintStr());
1450 // Check that the output exprs are valid lvalues.
1451 Expr *OutputExpr = Exprs[i];
1452 if (CheckAsmLValue(OutputExpr, *this)) {
1453 return StmtError(Diag(OutputExpr->getLocStart(),
1454 diag::err_asm_invalid_lvalue_in_output)
1455 << OutputExpr->getSourceRange());
1458 OutputConstraintInfos.push_back(Info);
1461 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1463 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
1464 StringLiteral *Literal = Constraints[i];
1465 if (Literal->isWide())
1466 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1467 << Literal->getSourceRange());
1469 llvm::StringRef InputName;
1471 InputName = Names[i]->getName();
1473 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
1474 if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(),
1475 NumOutputs, Info)) {
1476 return StmtError(Diag(Literal->getLocStart(),
1477 diag::err_asm_invalid_input_constraint)
1478 << Info.getConstraintStr());
1481 Expr *InputExpr = Exprs[i];
1483 // Only allow void types for memory constraints.
1484 if (Info.allowsMemory() && !Info.allowsRegister()) {
1485 if (CheckAsmLValue(InputExpr, *this))
1486 return StmtError(Diag(InputExpr->getLocStart(),
1487 diag::err_asm_invalid_lvalue_in_input)
1488 << Info.getConstraintStr()
1489 << InputExpr->getSourceRange());
1492 if (Info.allowsRegister()) {
1493 if (InputExpr->getType()->isVoidType()) {
1494 return StmtError(Diag(InputExpr->getLocStart(),
1495 diag::err_asm_invalid_type_in_input)
1496 << InputExpr->getType() << Info.getConstraintStr()
1497 << InputExpr->getSourceRange());
1501 DefaultFunctionArrayLvalueConversion(Exprs[i]);
1503 InputConstraintInfos.push_back(Info);
1506 // Check that the clobbers are valid.
1507 for (unsigned i = 0; i != NumClobbers; i++) {
1508 StringLiteral *Literal = Clobbers[i];
1509 if (Literal->isWide())
1510 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1511 << Literal->getSourceRange());
1513 llvm::StringRef Clobber = Literal->getString();
1515 if (!Context.Target.isValidGCCRegisterName(Clobber))
1516 return StmtError(Diag(Literal->getLocStart(),
1517 diag::err_asm_unknown_register_name) << Clobber);
1521 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
1522 NumOutputs, NumInputs, Names, Constraints, Exprs,
1523 AsmString, NumClobbers, Clobbers, RParenLoc);
1524 // Validate the asm string, ensuring it makes sense given the operands we
1526 llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
1528 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
1529 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
1530 << AsmString->getSourceRange();
1534 // Validate tied input operands for type mismatches.
1535 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
1536 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1538 // If this is a tied constraint, verify that the output and input have
1539 // either exactly the same type, or that they are int/ptr operands with the
1540 // same size (int/long, int*/long, are ok etc).
1541 if (!Info.hasTiedOperand()) continue;
1543 unsigned TiedTo = Info.getTiedOperand();
1544 unsigned InputOpNo = i+NumOutputs;
1545 Expr *OutputExpr = Exprs[TiedTo];
1546 Expr *InputExpr = Exprs[InputOpNo];
1547 QualType InTy = InputExpr->getType();
1548 QualType OutTy = OutputExpr->getType();
1549 if (Context.hasSameType(InTy, OutTy))
1550 continue; // All types can be tied to themselves.
1552 // Decide if the input and output are in the same domain (integer/ptr or
1555 AD_Int, AD_FP, AD_Other
1556 } InputDomain, OutputDomain;
1558 if (InTy->isIntegerType() || InTy->isPointerType())
1559 InputDomain = AD_Int;
1560 else if (InTy->isRealFloatingType())
1561 InputDomain = AD_FP;
1563 InputDomain = AD_Other;
1565 if (OutTy->isIntegerType() || OutTy->isPointerType())
1566 OutputDomain = AD_Int;
1567 else if (OutTy->isRealFloatingType())
1568 OutputDomain = AD_FP;
1570 OutputDomain = AD_Other;
1572 // They are ok if they are the same size and in the same domain. This
1573 // allows tying things like:
1575 // void* to int if they are the same size.
1576 // double to long double if they are the same size.
1578 uint64_t OutSize = Context.getTypeSize(OutTy);
1579 uint64_t InSize = Context.getTypeSize(InTy);
1580 if (OutSize == InSize && InputDomain == OutputDomain &&
1581 InputDomain != AD_Other)
1584 // If the smaller input/output operand is not mentioned in the asm string,
1585 // then we can promote the smaller one to a larger input and the asm string
1587 bool SmallerValueMentioned = false;
1589 // If this is a reference to the input and if the input was the smaller
1590 // one, then we have to reject this asm.
1591 if (isOperandMentioned(InputOpNo, Pieces)) {
1592 // This is a use in the asm string of the smaller operand. Since we
1593 // codegen this by promoting to a wider value, the asm will get printed
1595 SmallerValueMentioned |= InSize < OutSize;
1597 if (isOperandMentioned(TiedTo, Pieces)) {
1598 // If this is a reference to the output, and if the output is the larger
1599 // value, then it's ok because we'll promote the input to the larger type.
1600 SmallerValueMentioned |= OutSize < InSize;
1603 // If the smaller value wasn't mentioned in the asm string, and if the
1604 // output was a register, just extend the shorter one to the size of the
1606 if (!SmallerValueMentioned && InputDomain != AD_Other &&
1607 OutputConstraintInfos[TiedTo].allowsRegister())
1610 // Either both of the operands were mentioned or the smaller one was
1611 // mentioned. One more special case that we'll allow: if the tied input is
1612 // integer, unmentioned, and is a constant, then we'll allow truncating it
1613 // down to the size of the destination.
1614 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
1615 !isOperandMentioned(InputOpNo, Pieces) &&
1616 InputExpr->isEvaluatable(Context)) {
1617 ImpCastExprToType(InputExpr, OutTy, CK_IntegralCast);
1618 Exprs[InputOpNo] = InputExpr;
1619 NS->setInputExpr(i, InputExpr);
1623 Diag(InputExpr->getLocStart(),
1624 diag::err_asm_tying_incompatible_types)
1625 << InTy << OutTy << OutputExpr->getSourceRange()
1626 << InputExpr->getSourceRange();
1634 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
1635 SourceLocation RParen, Decl *Parm,
1637 VarDecl *Var = cast_or_null<VarDecl>(Parm);
1638 if (Var && Var->isInvalidDecl())
1641 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
1645 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
1646 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
1650 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
1651 MultiStmtArg CatchStmts, Stmt *Finally) {
1652 if (!getLangOptions().ObjCExceptions)
1653 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
1655 getCurFunction()->setHasBranchProtectedScope();
1656 unsigned NumCatchStmts = CatchStmts.size();
1657 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
1658 CatchStmts.release(),
1663 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc,
1666 DefaultLvalueConversion(Throw);
1668 QualType ThrowType = Throw->getType();
1669 // Make sure the expression type is an ObjC pointer or "void *".
1670 if (!ThrowType->isDependentType() &&
1671 !ThrowType->isObjCObjectPointerType()) {
1672 const PointerType *PT = ThrowType->getAs<PointerType>();
1673 if (!PT || !PT->getPointeeType()->isVoidType())
1674 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
1675 << Throw->getType() << Throw->getSourceRange());
1679 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
1683 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
1685 if (!getLangOptions().ObjCExceptions)
1686 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
1689 // @throw without an expression designates a rethrow (which much occur
1690 // in the context of an @catch clause).
1691 Scope *AtCatchParent = CurScope;
1692 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
1693 AtCatchParent = AtCatchParent->getParent();
1695 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
1698 return BuildObjCAtThrowStmt(AtLoc, Throw);
1702 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
1704 getCurFunction()->setHasBranchProtectedScope();
1706 DefaultLvalueConversion(SyncExpr);
1708 // Make sure the expression type is an ObjC pointer or "void *".
1709 if (!SyncExpr->getType()->isDependentType() &&
1710 !SyncExpr->getType()->isObjCObjectPointerType()) {
1711 const PointerType *PT = SyncExpr->getType()->getAs<PointerType>();
1712 if (!PT || !PT->getPointeeType()->isVoidType())
1713 return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object)
1714 << SyncExpr->getType() << SyncExpr->getSourceRange());
1717 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
1720 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
1721 /// and creates a proper catch handler from them.
1723 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
1724 Stmt *HandlerBlock) {
1725 // There's nothing to test that ActOnExceptionDecl didn't already test.
1726 return Owned(new (Context) CXXCatchStmt(CatchLoc,
1727 cast_or_null<VarDecl>(ExDecl),
1733 class TypeWithHandler {
1737 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
1738 : t(type), stmt(statement) {}
1740 // An arbitrary order is fine as long as it places identical
1741 // types next to each other.
1742 bool operator<(const TypeWithHandler &y) const {
1743 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
1745 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
1748 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
1751 bool operator==(const TypeWithHandler& other) const {
1752 return t == other.t;
1755 CXXCatchStmt *getCatchStmt() const { return stmt; }
1756 SourceLocation getTypeSpecStartLoc() const {
1757 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
1763 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
1764 /// handlers and creates a try statement from them.
1766 Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
1767 MultiStmtArg RawHandlers) {
1768 // Don't report an error if 'try' is used in system headers.
1769 if (!getLangOptions().Exceptions &&
1770 !getSourceManager().isInSystemHeader(TryLoc))
1771 Diag(TryLoc, diag::err_exceptions_disabled) << "try";
1773 unsigned NumHandlers = RawHandlers.size();
1774 assert(NumHandlers > 0 &&
1775 "The parser shouldn't call this if there are no handlers.");
1776 Stmt **Handlers = RawHandlers.get();
1778 llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers;
1780 for (unsigned i = 0; i < NumHandlers; ++i) {
1781 CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]);
1782 if (!Handler->getExceptionDecl()) {
1783 if (i < NumHandlers - 1)
1784 return StmtError(Diag(Handler->getLocStart(),
1785 diag::err_early_catch_all));
1790 const QualType CaughtType = Handler->getCaughtType();
1791 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
1792 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
1795 // Detect handlers for the same type as an earlier one.
1796 if (NumHandlers > 1) {
1797 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
1799 TypeWithHandler prev = TypesWithHandlers[0];
1800 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
1801 TypeWithHandler curr = TypesWithHandlers[i];
1804 Diag(curr.getTypeSpecStartLoc(),
1805 diag::warn_exception_caught_by_earlier_handler)
1806 << curr.getCatchStmt()->getCaughtType().getAsString();
1807 Diag(prev.getTypeSpecStartLoc(),
1808 diag::note_previous_exception_handler)
1809 << prev.getCatchStmt()->getCaughtType().getAsString();
1816 getCurFunction()->setHasBranchProtectedScope();
1818 // FIXME: We should detect handlers that cannot catch anything because an
1819 // earlier handler catches a superclass. Need to find a method that is not
1820 // quadratic for this.
1821 // Neither of these are explicitly forbidden, but every compiler detects them
1824 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
1825 Handlers, NumHandlers));