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 //===----------------------------------------------------------------------===//
15 #include "clang/AST/APValue.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/ExprObjC.h"
19 #include "clang/AST/StmtObjC.h"
20 #include "clang/AST/StmtCXX.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallVector.h"
24 using namespace clang;
26 Sema::OwningStmtResult Sema::ActOnExprStmt(FullExprArg expr) {
27 Expr *E = expr->takeAs<Expr>();
28 assert(E && "ActOnExprStmt(): missing expression");
29 if (E->getType()->isObjCInterfaceType()) {
30 if (LangOpts.ObjCNonFragileABI)
31 Diag(E->getLocEnd(), diag::err_indirection_requires_nonfragile_object)
34 Diag(E->getLocEnd(), diag::err_direct_interface_unsupported)
38 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
39 // void expression for its side effects. Conversion to void allows any
40 // operand, even incomplete types.
42 // Same thing in for stmt first clause (when expr) and third clause.
43 return Owned(static_cast<Stmt*>(E));
47 Sema::OwningStmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc) {
48 return Owned(new (Context) NullStmt(SemiLoc));
51 Sema::OwningStmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg,
52 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::DiagnoseUnusedExprResult(const Stmt *S) {
63 const Expr *E = dyn_cast_or_null<Expr>(S);
67 // Ignore expressions that have void type.
68 if (E->getType()->isVoidType())
73 if (!E->isUnusedResultAWarning(Loc, R1, R2))
76 // Okay, we have an unused result. Depending on what the base expression is,
77 // we might want to make a more specific diagnostic. Check for one of these
79 unsigned DiagID = diag::warn_unused_expr;
80 E = E->IgnoreParens();
81 if (isa<ObjCImplicitSetterGetterRefExpr>(E))
82 DiagID = diag::warn_unused_property_expr;
84 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
85 // If the callee has attribute pure, const, or warn_unused_result, warn with
86 // a more specific message to make it clear what is happening.
87 if (const FunctionDecl *FD = CE->getDirectCallee()) {
88 if (FD->getAttr<WarnUnusedResultAttr>()) {
89 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
92 if (FD->getAttr<PureAttr>()) {
93 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
96 if (FD->getAttr<ConstAttr>()) {
97 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
103 Diag(Loc, DiagID) << R1 << R2;
106 Action::OwningStmtResult
107 Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
108 MultiStmtArg elts, bool isStmtExpr) {
109 unsigned NumElts = elts.size();
110 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
111 // If we're in C89 mode, check that we don't have any decls after stmts. If
112 // so, emit an extension diagnostic.
113 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
114 // Note that __extension__ can be around a decl.
116 // Skip over all declarations.
117 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
120 // We found the end of the list or a statement. Scan for another declstmt.
121 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
125 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
126 Diag(D->getLocation(), diag::ext_mixed_decls_code);
129 // Warn about unused expressions in statements.
130 for (unsigned i = 0; i != NumElts; ++i) {
131 // Ignore statements that are last in a statement expression.
132 if (isStmtExpr && i == NumElts - 1)
135 DiagnoseUnusedExprResult(Elts[i]);
138 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
141 Action::OwningStmtResult
142 Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprArg lhsval,
143 SourceLocation DotDotDotLoc, ExprArg rhsval,
144 SourceLocation ColonLoc) {
145 assert((lhsval.get() != 0) && "missing expression in case statement");
147 // C99 6.8.4.2p3: The expression shall be an integer constant.
148 // However, GCC allows any evaluatable integer expression.
149 Expr *LHSVal = static_cast<Expr*>(lhsval.get());
150 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() &&
151 VerifyIntegerConstantExpression(LHSVal))
154 // GCC extension: The expression shall be an integer constant.
156 Expr *RHSVal = static_cast<Expr*>(rhsval.get());
157 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() &&
158 VerifyIntegerConstantExpression(RHSVal)) {
159 RHSVal = 0; // Recover by just forgetting about it.
163 if (getSwitchStack().empty()) {
164 Diag(CaseLoc, diag::err_case_not_in_switch);
168 // Only now release the smart pointers.
171 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
173 getSwitchStack().back()->addSwitchCase(CS);
177 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
178 void Sema::ActOnCaseStmtBody(StmtTy *caseStmt, StmtArg subStmt) {
179 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
180 Stmt *SubStmt = subStmt.takeAs<Stmt>();
181 CS->setSubStmt(SubStmt);
184 Action::OwningStmtResult
185 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
186 StmtArg subStmt, Scope *CurScope) {
187 Stmt *SubStmt = subStmt.takeAs<Stmt>();
189 if (getSwitchStack().empty()) {
190 Diag(DefaultLoc, diag::err_default_not_in_switch);
191 return Owned(SubStmt);
194 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
195 getSwitchStack().back()->addSwitchCase(DS);
199 Action::OwningStmtResult
200 Sema::ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II,
201 SourceLocation ColonLoc, StmtArg subStmt) {
202 Stmt *SubStmt = subStmt.takeAs<Stmt>();
203 // Look up the record for this label identifier.
204 LabelStmt *&LabelDecl = getLabelMap()[II];
206 // If not forward referenced or defined already, just create a new LabelStmt.
208 return Owned(LabelDecl = new (Context) LabelStmt(IdentLoc, II, SubStmt));
210 assert(LabelDecl->getID() == II && "Label mismatch!");
212 // Otherwise, this label was either forward reference or multiply defined. If
213 // multiply defined, reject it now.
214 if (LabelDecl->getSubStmt()) {
215 Diag(IdentLoc, diag::err_redefinition_of_label) << LabelDecl->getID();
216 Diag(LabelDecl->getIdentLoc(), diag::note_previous_definition);
217 return Owned(SubStmt);
220 // Otherwise, this label was forward declared, and we just found its real
221 // definition. Fill in the forward definition and return it.
222 LabelDecl->setIdentLoc(IdentLoc);
223 LabelDecl->setSubStmt(SubStmt);
224 return Owned(LabelDecl);
227 Action::OwningStmtResult
228 Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal,
229 StmtArg ThenVal, SourceLocation ElseLoc,
231 OwningExprResult CondResult(CondVal.release());
233 Expr *condExpr = CondResult.takeAs<Expr>();
235 assert(condExpr && "ActOnIfStmt(): missing expression");
236 if (CheckBooleanCondition(condExpr, IfLoc)) {
237 CondResult = condExpr;
241 Stmt *thenStmt = ThenVal.takeAs<Stmt>();
242 DiagnoseUnusedExprResult(thenStmt);
244 // Warn if the if block has a null body without an else value.
245 // this helps prevent bugs due to typos, such as
248 if (!ElseVal.get()) {
249 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
250 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
253 Stmt *elseStmt = ElseVal.takeAs<Stmt>();
254 DiagnoseUnusedExprResult(elseStmt);
256 CondResult.release();
257 return Owned(new (Context) IfStmt(IfLoc, condExpr, thenStmt,
261 Action::OwningStmtResult
262 Sema::ActOnStartOfSwitchStmt(ExprArg cond) {
263 Expr *Cond = cond.takeAs<Expr>();
265 if (getLangOptions().CPlusPlus) {
267 // The condition shall be of integral type, enumeration type, or of a class
268 // type for which a single conversion function to integral or enumeration
269 // type exists (12.3). If the condition is of class type, the condition is
270 // converted by calling that conversion function, and the result of the
271 // conversion is used in place of the original condition for the remainder
272 // of this section. Integral promotions are performed.
273 if (!Cond->isTypeDependent()) {
274 QualType Ty = Cond->getType();
276 // FIXME: Handle class types.
278 // If the type is wrong a diagnostic will be emitted later at
279 // ActOnFinishSwitchStmt.
280 if (Ty->isIntegralType() || Ty->isEnumeralType()) {
281 // Integral promotions are performed.
282 // FIXME: Integral promotions for C++ are not complete.
283 UsualUnaryConversions(Cond);
287 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
288 UsualUnaryConversions(Cond);
291 SwitchStmt *SS = new (Context) SwitchStmt(Cond);
292 getSwitchStack().push_back(SS);
296 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
297 /// the specified width and sign. If an overflow occurs, detect it and emit
298 /// the specified diagnostic.
299 void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
300 unsigned NewWidth, bool NewSign,
303 // Perform a conversion to the promoted condition type if needed.
304 if (NewWidth > Val.getBitWidth()) {
305 // If this is an extension, just do it.
306 llvm::APSInt OldVal(Val);
307 Val.extend(NewWidth);
309 // If the input was signed and negative and the output is unsigned,
311 if (!NewSign && OldVal.isSigned() && OldVal.isNegative())
312 Diag(Loc, DiagID) << OldVal.toString(10) << Val.toString(10);
314 Val.setIsSigned(NewSign);
315 } else if (NewWidth < Val.getBitWidth()) {
316 // If this is a truncation, check for overflow.
317 llvm::APSInt ConvVal(Val);
318 ConvVal.trunc(NewWidth);
319 ConvVal.setIsSigned(NewSign);
320 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
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 llvm::APSInt OldVal(Val);
333 Val.setIsSigned(NewSign);
335 if (Val.isNegative()) // Sign bit changes meaning.
336 Diag(Loc, DiagID) << OldVal.toString(10) << Val.toString(10);
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 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
372 /// potentially integral-promoted expression @p expr.
373 static QualType GetTypeBeforeIntegralPromotion(const Expr* expr) {
374 const ImplicitCastExpr *ImplicitCast =
375 dyn_cast_or_null<ImplicitCastExpr>(expr);
376 if (ImplicitCast != NULL) {
377 const Expr *ExprBeforePromotion = ImplicitCast->getSubExpr();
378 QualType TypeBeforePromotion = ExprBeforePromotion->getType();
379 if (TypeBeforePromotion->isIntegralType()) {
380 return TypeBeforePromotion;
383 return expr->getType();
386 Action::OwningStmtResult
387 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, StmtArg Switch,
389 Stmt *BodyStmt = Body.takeAs<Stmt>();
391 SwitchStmt *SS = getSwitchStack().back();
392 assert(SS == (SwitchStmt*)Switch.get() && "switch stack missing push/pop!");
394 SS->setBody(BodyStmt, SwitchLoc);
395 getSwitchStack().pop_back();
397 Expr *CondExpr = SS->getCond();
398 QualType CondType = CondExpr->getType();
401 // Integral promotions are performed (on the switch condition).
403 // A case value unrepresentable by the original switch condition
404 // type (before the promotion) doesn't make sense, even when it can
405 // be represented by the promoted type. Therefore we need to find
406 // the pre-promotion type of the switch condition.
407 QualType CondTypeBeforePromotion =
408 GetTypeBeforeIntegralPromotion(CondExpr);
410 if (!CondExpr->isTypeDependent()) {
411 if (!CondType->isIntegerType()) { // C99 6.8.4.2p1
412 Diag(SwitchLoc, diag::err_typecheck_statement_requires_integer)
413 << CondType << CondExpr->getSourceRange();
417 if (CondTypeBeforePromotion->isBooleanType()) {
418 // switch(bool_expr) {...} is often a programmer error, e.g.
419 // switch(n && mask) { ... } // Doh - should be "n & mask".
420 // One can always use an if statement instead of switch(bool_expr).
421 Diag(SwitchLoc, diag::warn_bool_switch_condition)
422 << CondExpr->getSourceRange();
426 // Get the bitwidth of the switched-on value before promotions. We must
427 // convert the integer case values to this width before comparison.
428 bool HasDependentValue
429 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
431 = HasDependentValue? 0
432 : static_cast<unsigned>(Context.getTypeSize(CondTypeBeforePromotion));
433 bool CondIsSigned = CondTypeBeforePromotion->isSignedIntegerType();
435 // Accumulate all of the case values in a vector so that we can sort them
436 // and detect duplicates. This vector contains the APInt for the case after
437 // it has been converted to the condition type.
438 typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
441 // Keep track of any GNU case ranges we see. The APSInt is the low value.
442 std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRanges;
444 DefaultStmt *TheDefaultStmt = 0;
446 bool CaseListIsErroneous = false;
448 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
449 SC = SC->getNextSwitchCase()) {
451 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
452 if (TheDefaultStmt) {
453 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
454 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
456 // FIXME: Remove the default statement from the switch block so that
457 // we'll return a valid AST. This requires recursing down the AST and
458 // finding it, not something we are set up to do right now. For now,
459 // just lop the entire switch stmt out of the AST.
460 CaseListIsErroneous = true;
465 CaseStmt *CS = cast<CaseStmt>(SC);
467 // We already verified that the expression has a i-c-e value (C99
468 // 6.8.4.2p3) - get that value now.
469 Expr *Lo = CS->getLHS();
471 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
472 HasDependentValue = true;
476 llvm::APSInt LoVal = Lo->EvaluateAsInt(Context);
478 // Convert the value to the same width/sign as the condition.
479 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
480 CS->getLHS()->getLocStart(),
481 diag::warn_case_value_overflow);
483 // If the LHS is not the same type as the condition, insert an implicit
485 ImpCastExprToType(Lo, CondType, CastExpr::CK_IntegralCast);
488 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
490 if (CS->getRHS()->isTypeDependent() ||
491 CS->getRHS()->isValueDependent()) {
492 HasDependentValue = true;
495 CaseRanges.push_back(std::make_pair(LoVal, CS));
497 CaseVals.push_back(std::make_pair(LoVal, CS));
501 if (!HasDependentValue) {
502 // Sort all the scalar case values so we can easily detect duplicates.
503 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
505 if (!CaseVals.empty()) {
506 for (unsigned i = 0, e = CaseVals.size()-1; i != e; ++i) {
507 if (CaseVals[i].first == CaseVals[i+1].first) {
508 // If we have a duplicate, report it.
509 Diag(CaseVals[i+1].second->getLHS()->getLocStart(),
510 diag::err_duplicate_case) << CaseVals[i].first.toString(10);
511 Diag(CaseVals[i].second->getLHS()->getLocStart(),
512 diag::note_duplicate_case_prev);
513 // FIXME: We really want to remove the bogus case stmt from the
514 // substmt, but we have no way to do this right now.
515 CaseListIsErroneous = true;
520 // Detect duplicate case ranges, which usually don't exist at all in
522 if (!CaseRanges.empty()) {
523 // Sort all the case ranges by their low value so we can easily detect
524 // overlaps between ranges.
525 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
527 // Scan the ranges, computing the high values and removing empty ranges.
528 std::vector<llvm::APSInt> HiVals;
529 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
530 CaseStmt *CR = CaseRanges[i].second;
531 Expr *Hi = CR->getRHS();
532 llvm::APSInt HiVal = Hi->EvaluateAsInt(Context);
534 // Convert the value to the same width/sign as the condition.
535 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
536 CR->getRHS()->getLocStart(),
537 diag::warn_case_value_overflow);
539 // If the LHS is not the same type as the condition, insert an implicit
541 ImpCastExprToType(Hi, CondType, CastExpr::CK_IntegralCast);
544 // If the low value is bigger than the high value, the case is empty.
545 if (CaseRanges[i].first > HiVal) {
546 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
547 << SourceRange(CR->getLHS()->getLocStart(),
548 CR->getRHS()->getLocEnd());
549 CaseRanges.erase(CaseRanges.begin()+i);
553 HiVals.push_back(HiVal);
556 // Rescan the ranges, looking for overlap with singleton values and other
557 // ranges. Since the range list is sorted, we only need to compare case
558 // ranges with their neighbors.
559 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
560 llvm::APSInt &CRLo = CaseRanges[i].first;
561 llvm::APSInt &CRHi = HiVals[i];
562 CaseStmt *CR = CaseRanges[i].second;
564 // Check to see whether the case range overlaps with any
566 CaseStmt *OverlapStmt = 0;
567 llvm::APSInt OverlapVal(32);
569 // Find the smallest value >= the lower bound. If I is in the
570 // case range, then we have overlap.
571 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
572 CaseVals.end(), CRLo,
573 CaseCompareFunctor());
574 if (I != CaseVals.end() && I->first < CRHi) {
575 OverlapVal = I->first; // Found overlap with scalar.
576 OverlapStmt = I->second;
579 // Find the smallest value bigger than the upper bound.
580 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
581 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
582 OverlapVal = (I-1)->first; // Found overlap with scalar.
583 OverlapStmt = (I-1)->second;
586 // Check to see if this case stmt overlaps with the subsequent
588 if (i && CRLo <= HiVals[i-1]) {
589 OverlapVal = HiVals[i-1]; // Found overlap with range.
590 OverlapStmt = CaseRanges[i-1].second;
594 // If we have a duplicate, report it.
595 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
596 << OverlapVal.toString(10);
597 Diag(OverlapStmt->getLHS()->getLocStart(),
598 diag::note_duplicate_case_prev);
599 // FIXME: We really want to remove the bogus case stmt from the
600 // substmt, but we have no way to do this right now.
601 CaseListIsErroneous = true;
607 // FIXME: If the case list was broken is some way, we don't have a good system
608 // to patch it up. Instead, just return the whole substmt as broken.
609 if (CaseListIsErroneous)
616 Action::OwningStmtResult
617 Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond, StmtArg Body) {
618 ExprArg CondArg(Cond.release());
619 Expr *condExpr = CondArg.takeAs<Expr>();
620 assert(condExpr && "ActOnWhileStmt(): missing expression");
622 if (CheckBooleanCondition(condExpr, WhileLoc)) {
627 Stmt *bodyStmt = Body.takeAs<Stmt>();
628 DiagnoseUnusedExprResult(bodyStmt);
631 return Owned(new (Context) WhileStmt(condExpr, bodyStmt, WhileLoc));
634 Action::OwningStmtResult
635 Sema::ActOnDoStmt(SourceLocation DoLoc, StmtArg Body,
636 SourceLocation WhileLoc, SourceLocation CondLParen,
637 ExprArg Cond, SourceLocation CondRParen) {
638 Expr *condExpr = Cond.takeAs<Expr>();
639 assert(condExpr && "ActOnDoStmt(): missing expression");
641 if (CheckBooleanCondition(condExpr, DoLoc)) {
646 Stmt *bodyStmt = Body.takeAs<Stmt>();
647 DiagnoseUnusedExprResult(bodyStmt);
650 return Owned(new (Context) DoStmt(bodyStmt, condExpr, DoLoc,
651 WhileLoc, CondRParen));
654 Action::OwningStmtResult
655 Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
656 StmtArg first, ExprArg second, ExprArg third,
657 SourceLocation RParenLoc, StmtArg body) {
658 Stmt *First = static_cast<Stmt*>(first.get());
659 Expr *Second = second.takeAs<Expr>();
660 Expr *Third = static_cast<Expr*>(third.get());
661 Stmt *Body = static_cast<Stmt*>(body.get());
663 if (!getLangOptions().CPlusPlus) {
664 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
665 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
666 // declare identifiers for objects having storage class 'auto' or
668 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
670 VarDecl *VD = dyn_cast<VarDecl>(*DI);
671 if (VD && VD->isBlockVarDecl() && !VD->hasLocalStorage())
674 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
675 // FIXME: mark decl erroneous!
679 if (Second && CheckBooleanCondition(Second, ForLoc)) {
684 DiagnoseUnusedExprResult(First);
685 DiagnoseUnusedExprResult(Third);
686 DiagnoseUnusedExprResult(Body);
691 return Owned(new (Context) ForStmt(First, Second, Third, Body, ForLoc,
692 LParenLoc, RParenLoc));
695 Action::OwningStmtResult
696 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
697 SourceLocation LParenLoc,
698 StmtArg first, ExprArg second,
699 SourceLocation RParenLoc, StmtArg body) {
700 Stmt *First = static_cast<Stmt*>(first.get());
701 Expr *Second = static_cast<Expr*>(second.get());
702 Stmt *Body = static_cast<Stmt*>(body.get());
705 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
706 if (!DS->isSingleDecl())
707 return StmtError(Diag((*DS->decl_begin())->getLocation(),
708 diag::err_toomany_element_decls));
710 Decl *D = DS->getSingleDecl();
711 FirstType = cast<ValueDecl>(D)->getType();
712 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
713 // declare identifiers for objects having storage class 'auto' or
715 VarDecl *VD = cast<VarDecl>(D);
716 if (VD->isBlockVarDecl() && !VD->hasLocalStorage())
717 return StmtError(Diag(VD->getLocation(),
718 diag::err_non_variable_decl_in_for));
720 if (cast<Expr>(First)->isLvalue(Context) != Expr::LV_Valid)
721 return StmtError(Diag(First->getLocStart(),
722 diag::err_selector_element_not_lvalue)
723 << First->getSourceRange());
725 FirstType = static_cast<Expr*>(First)->getType();
727 if (!FirstType->isObjCObjectPointerType() &&
728 !FirstType->isBlockPointerType())
729 Diag(ForLoc, diag::err_selector_element_type)
730 << FirstType << First->getSourceRange();
733 DefaultFunctionArrayConversion(Second);
734 QualType SecondType = Second->getType();
735 if (!SecondType->isObjCObjectPointerType())
736 Diag(ForLoc, diag::err_collection_expr_type)
737 << SecondType << Second->getSourceRange();
742 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
746 Action::OwningStmtResult
747 Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
748 IdentifierInfo *LabelII) {
749 // If we are in a block, reject all gotos for now.
751 return StmtError(Diag(GotoLoc, diag::err_goto_in_block));
753 // Look up the record for this label identifier.
754 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
756 // If we haven't seen this label yet, create a forward reference.
758 LabelDecl = new (Context) LabelStmt(LabelLoc, LabelII, 0);
760 return Owned(new (Context) GotoStmt(LabelDecl, GotoLoc, LabelLoc));
763 Action::OwningStmtResult
764 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
766 // Convert operand to void*
767 Expr* E = DestExp.takeAs<Expr>();
768 if (!E->isTypeDependent()) {
769 QualType ETy = E->getType();
770 AssignConvertType ConvTy =
771 CheckSingleAssignmentConstraints(Context.VoidPtrTy, E);
772 if (DiagnoseAssignmentResult(ConvTy, StarLoc, Context.VoidPtrTy, ETy,
776 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
779 Action::OwningStmtResult
780 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
781 Scope *S = CurScope->getContinueParent();
783 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
784 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
787 return Owned(new (Context) ContinueStmt(ContinueLoc));
790 Action::OwningStmtResult
791 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
792 Scope *S = CurScope->getBreakParent();
794 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
795 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
798 return Owned(new (Context) BreakStmt(BreakLoc));
801 /// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
803 Action::OwningStmtResult
804 Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
805 // If this is the first return we've seen in the block, infer the type of
806 // the block from it.
807 if (CurBlock->ReturnType.isNull()) {
809 // Don't call UsualUnaryConversions(), since we don't want to do
810 // integer promotions here.
811 DefaultFunctionArrayConversion(RetValExp);
812 CurBlock->ReturnType = RetValExp->getType();
813 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
814 // We have to remove a 'const' added to copied-in variable which was
815 // part of the implementation spec. and not the actual qualifier for
817 if (CDRE->isConstQualAdded())
818 CurBlock->ReturnType.removeConst();
821 CurBlock->ReturnType = Context.VoidTy;
823 QualType FnRetType = CurBlock->ReturnType;
825 if (CurBlock->TheDecl->hasAttr<NoReturnAttr>()) {
826 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
827 << getCurFunctionOrMethodDecl()->getDeclName();
831 // Otherwise, verify that this result type matches the previous one. We are
832 // pickier with blocks than for normal functions because we don't have GCC
833 // compatibility to worry about here.
834 if (CurBlock->ReturnType->isVoidType()) {
836 Diag(ReturnLoc, diag::err_return_block_has_expr);
837 RetValExp->Destroy(Context);
840 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
844 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
846 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
847 // we have a non-void block with an expression, continue checking
848 QualType RetValType = RetValExp->getType();
850 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
851 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
854 // In C++ the return statement is handled via a copy initialization.
855 // the C version of which boils down to CheckSingleAssignmentConstraints.
856 // FIXME: Leaks RetValExp.
857 if (PerformCopyInitialization(RetValExp, FnRetType, "returning"))
860 if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
863 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
866 /// IsReturnCopyElidable - Whether returning @p RetExpr from a function that
867 /// returns a @p RetType fulfills the criteria for copy elision (C++0x 12.8p15).
868 static bool IsReturnCopyElidable(ASTContext &Ctx, QualType RetType,
870 QualType ExprType = RetExpr->getType();
871 // - in a return statement in a function with ...
872 // ... a class return type ...
873 if (!RetType->isRecordType())
875 // ... the same cv-unqualified type as the function return type ...
876 if (Ctx.getCanonicalType(RetType).getUnqualifiedType() !=
877 Ctx.getCanonicalType(ExprType).getUnqualifiedType())
879 // ... the expression is the name of a non-volatile automatic object ...
880 // We ignore parentheses here.
881 // FIXME: Is this compliant?
882 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetExpr->IgnoreParens());
885 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
888 return VD->hasLocalStorage() && !VD->getType()->isReferenceType()
889 && !VD->getType().isVolatileQualified();
892 Action::OwningStmtResult
893 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, ExprArg rex) {
894 Expr *RetValExp = rex.takeAs<Expr>();
896 return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
899 if (const FunctionDecl *FD = getCurFunctionDecl()) {
900 FnRetType = FD->getResultType();
901 if (FD->hasAttr<NoReturnAttr>())
902 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
903 << getCurFunctionOrMethodDecl()->getDeclName();
904 } else if (ObjCMethodDecl *MD = getCurMethodDecl())
905 FnRetType = MD->getResultType();
906 else // If we don't have a function/method context, bail.
909 if (FnRetType->isVoidType()) {
910 if (RetValExp && !RetValExp->isTypeDependent()) {
911 // C99 6.8.6.4p1 (ext_ since GCC warns)
912 unsigned D = diag::ext_return_has_expr;
913 if (RetValExp->getType()->isVoidType())
914 D = diag::ext_return_has_void_expr;
916 // return (some void expression); is legal in C++.
917 if (D != diag::ext_return_has_void_expr ||
918 !getLangOptions().CPlusPlus) {
919 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
921 << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl)
922 << RetValExp->getSourceRange();
925 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp, true);
927 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
930 if (!RetValExp && !FnRetType->isDependentType()) {
931 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
932 // C99 6.8.6.4p1 (ext_ since GCC warns)
933 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
935 if (FunctionDecl *FD = getCurFunctionDecl())
936 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
938 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
939 return Owned(new (Context) ReturnStmt(ReturnLoc, (Expr*)0));
942 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
943 // we have a non-void function with an expression, continue checking
945 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
946 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
949 // C++0x 12.8p15: When certain criteria are met, an implementation is
950 // allowed to omit the copy construction of a class object, [...]
951 // - in a return statement in a function with a class return type, when
952 // the expression is the name of a non-volatile automatic object with
953 // the same cv-unqualified type as the function return type, the copy
954 // operation can be omitted [...]
955 // C++0x 12.8p16: When the criteria for elision of a copy operation are met
956 // and the object to be copied is designated by an lvalue, overload
957 // resolution to select the constructor for the copy is first performed
958 // as if the object were designated by an rvalue.
959 // Note that we only compute Elidable if we're in C++0x, since we don't
961 bool Elidable = getLangOptions().CPlusPlus0x ?
962 IsReturnCopyElidable(Context, FnRetType, RetValExp) :
965 // In C++ the return statement is handled via a copy initialization.
966 // the C version of which boils down to CheckSingleAssignmentConstraints.
967 // FIXME: Leaks RetValExp on error.
968 if (PerformCopyInitialization(RetValExp, FnRetType, "returning", Elidable))
971 if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
975 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp, true);
976 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
979 /// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
980 /// ignore "noop" casts in places where an lvalue is required by an inline asm.
981 /// We emulate this behavior when -fheinous-gnu-extensions is specified, but
982 /// provide a strong guidance to not use it.
984 /// This method checks to see if the argument is an acceptable l-value and
985 /// returns false if it is a case we can handle.
986 static bool CheckAsmLValue(const Expr *E, Sema &S) {
987 if (E->isLvalue(S.Context) == Expr::LV_Valid)
988 return false; // Cool, this is an lvalue.
990 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
991 // are supposed to allow.
992 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
993 if (E != E2 && E2->isLvalue(S.Context) == Expr::LV_Valid) {
994 if (!S.getLangOptions().HeinousExtensions)
995 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
996 << E->getSourceRange();
998 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
999 << E->getSourceRange();
1000 // Accept, even if we emitted an error diagnostic.
1004 // None of the above, just randomly invalid non-lvalue.
1009 Sema::OwningStmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc,
1012 unsigned NumOutputs,
1015 MultiExprArg constraints,
1018 MultiExprArg clobbers,
1019 SourceLocation RParenLoc) {
1020 unsigned NumClobbers = clobbers.size();
1021 StringLiteral **Constraints =
1022 reinterpret_cast<StringLiteral**>(constraints.get());
1023 Expr **Exprs = reinterpret_cast<Expr **>(exprs.get());
1024 StringLiteral *AsmString = cast<StringLiteral>((Expr *)asmString.get());
1025 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
1027 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1029 // The parser verifies that there is a string literal here.
1030 if (AsmString->isWide())
1031 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
1032 << AsmString->getSourceRange());
1034 for (unsigned i = 0; i != NumOutputs; i++) {
1035 StringLiteral *Literal = Constraints[i];
1036 if (Literal->isWide())
1037 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1038 << Literal->getSourceRange());
1040 TargetInfo::ConstraintInfo Info(Literal->getStrData(),
1041 Literal->getByteLength(),
1043 if (!Context.Target.validateOutputConstraint(Info))
1044 return StmtError(Diag(Literal->getLocStart(),
1045 diag::err_asm_invalid_output_constraint)
1046 << Info.getConstraintStr());
1048 // Check that the output exprs are valid lvalues.
1049 Expr *OutputExpr = Exprs[i];
1050 if (CheckAsmLValue(OutputExpr, *this)) {
1051 return StmtError(Diag(OutputExpr->getLocStart(),
1052 diag::err_asm_invalid_lvalue_in_output)
1053 << OutputExpr->getSourceRange());
1056 OutputConstraintInfos.push_back(Info);
1059 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1061 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
1062 StringLiteral *Literal = Constraints[i];
1063 if (Literal->isWide())
1064 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1065 << Literal->getSourceRange());
1067 TargetInfo::ConstraintInfo Info(Literal->getStrData(),
1068 Literal->getByteLength(),
1070 if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(),
1071 NumOutputs, Info)) {
1072 return StmtError(Diag(Literal->getLocStart(),
1073 diag::err_asm_invalid_input_constraint)
1074 << Info.getConstraintStr());
1077 Expr *InputExpr = Exprs[i];
1079 // Only allow void types for memory constraints.
1080 if (Info.allowsMemory() && !Info.allowsRegister()) {
1081 if (CheckAsmLValue(InputExpr, *this))
1082 return StmtError(Diag(InputExpr->getLocStart(),
1083 diag::err_asm_invalid_lvalue_in_input)
1084 << Info.getConstraintStr()
1085 << InputExpr->getSourceRange());
1088 if (Info.allowsRegister()) {
1089 if (InputExpr->getType()->isVoidType()) {
1090 return StmtError(Diag(InputExpr->getLocStart(),
1091 diag::err_asm_invalid_type_in_input)
1092 << InputExpr->getType() << Info.getConstraintStr()
1093 << InputExpr->getSourceRange());
1097 DefaultFunctionArrayConversion(Exprs[i]);
1099 InputConstraintInfos.push_back(Info);
1102 // Check that the clobbers are valid.
1103 for (unsigned i = 0; i != NumClobbers; i++) {
1104 StringLiteral *Literal = Clobbers[i];
1105 if (Literal->isWide())
1106 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1107 << Literal->getSourceRange());
1109 std::string Clobber(Literal->getStrData(),
1110 Literal->getStrData() +
1111 Literal->getByteLength());
1113 if (!Context.Target.isValidGCCRegisterName(Clobber.c_str()))
1114 return StmtError(Diag(Literal->getLocStart(),
1115 diag::err_asm_unknown_register_name) << Clobber);
1118 constraints.release();
1120 asmString.release();
1123 new (Context) AsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs,
1124 Names, Constraints, Exprs, AsmString, NumClobbers,
1125 Clobbers, RParenLoc);
1126 // Validate the asm string, ensuring it makes sense given the operands we
1128 llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
1130 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
1131 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
1132 << AsmString->getSourceRange();
1137 // Validate tied input operands for type mismatches.
1138 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
1139 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1141 // If this is a tied constraint, verify that the output and input have
1142 // either exactly the same type, or that they are int/ptr operands with the
1143 // same size (int/long, int*/long, are ok etc).
1144 if (!Info.hasTiedOperand()) continue;
1146 unsigned TiedTo = Info.getTiedOperand();
1147 Expr *OutputExpr = Exprs[TiedTo];
1148 Expr *InputExpr = Exprs[i+NumOutputs];
1149 QualType InTy = InputExpr->getType();
1150 QualType OutTy = OutputExpr->getType();
1151 if (Context.hasSameType(InTy, OutTy))
1152 continue; // All types can be tied to themselves.
1154 // Int/ptr operands have some special cases that we allow.
1155 if ((OutTy->isIntegerType() || OutTy->isPointerType()) &&
1156 (InTy->isIntegerType() || InTy->isPointerType())) {
1158 // They are ok if they are the same size. Tying void* to int is ok if
1159 // they are the same size, for example. This also allows tying void* to
1161 uint64_t OutSize = Context.getTypeSize(OutTy);
1162 uint64_t InSize = Context.getTypeSize(InTy);
1163 if (OutSize == InSize)
1166 // If the smaller input/output operand is not mentioned in the asm string,
1167 // then we can promote it and the asm string won't notice. Check this
1169 bool SmallerValueMentioned = false;
1170 for (unsigned p = 0, e = Pieces.size(); p != e; ++p) {
1171 AsmStmt::AsmStringPiece &Piece = Pieces[p];
1172 if (!Piece.isOperand()) continue;
1174 // If this is a reference to the input and if the input was the smaller
1175 // one, then we have to reject this asm.
1176 if (Piece.getOperandNo() == i+NumOutputs) {
1177 if (InSize < OutSize) {
1178 SmallerValueMentioned = true;
1183 // If this is a reference to the input and if the input was the smaller
1184 // one, then we have to reject this asm.
1185 if (Piece.getOperandNo() == TiedTo) {
1186 if (InSize > OutSize) {
1187 SmallerValueMentioned = true;
1193 // If the smaller value wasn't mentioned in the asm string, and if the
1194 // output was a register, just extend the shorter one to the size of the
1196 if (!SmallerValueMentioned &&
1197 OutputConstraintInfos[TiedTo].allowsRegister())
1201 Diag(InputExpr->getLocStart(),
1202 diag::err_asm_tying_incompatible_types)
1203 << InTy << OutTy << OutputExpr->getSourceRange()
1204 << InputExpr->getSourceRange();
1212 Action::OwningStmtResult
1213 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
1214 SourceLocation RParen, DeclPtrTy Parm,
1215 StmtArg Body, StmtArg catchList) {
1216 Stmt *CatchList = catchList.takeAs<Stmt>();
1217 ParmVarDecl *PVD = cast_or_null<ParmVarDecl>(Parm.getAs<Decl>());
1219 // PVD == 0 implies @catch(...).
1221 // If we already know the decl is invalid, reject it.
1222 if (PVD->isInvalidDecl())
1225 if (!PVD->getType()->isObjCObjectPointerType())
1226 return StmtError(Diag(PVD->getLocation(),
1227 diag::err_catch_param_not_objc_type));
1228 if (PVD->getType()->isObjCQualifiedIdType())
1229 return StmtError(Diag(PVD->getLocation(),
1230 diag::err_illegal_qualifiers_on_catch_parm));
1233 ObjCAtCatchStmt *CS = new (Context) ObjCAtCatchStmt(AtLoc, RParen,
1234 PVD, Body.takeAs<Stmt>(), CatchList);
1235 return Owned(CatchList ? CatchList : CS);
1238 Action::OwningStmtResult
1239 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, StmtArg Body) {
1240 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc,
1241 static_cast<Stmt*>(Body.release())));
1244 Action::OwningStmtResult
1245 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc,
1246 StmtArg Try, StmtArg Catch, StmtArg Finally) {
1247 CurFunctionNeedsScopeChecking = true;
1248 return Owned(new (Context) ObjCAtTryStmt(AtLoc, Try.takeAs<Stmt>(),
1249 Catch.takeAs<Stmt>(),
1250 Finally.takeAs<Stmt>()));
1253 Action::OwningStmtResult
1254 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, ExprArg expr,Scope *CurScope) {
1255 Expr *ThrowExpr = expr.takeAs<Expr>();
1257 // @throw without an expression designates a rethrow (which much occur
1258 // in the context of an @catch clause).
1259 Scope *AtCatchParent = CurScope;
1260 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
1261 AtCatchParent = AtCatchParent->getParent();
1263 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
1265 QualType ThrowType = ThrowExpr->getType();
1266 // Make sure the expression type is an ObjC pointer or "void *".
1267 if (!ThrowType->isObjCObjectPointerType()) {
1268 const PointerType *PT = ThrowType->getAs<PointerType>();
1269 if (!PT || !PT->getPointeeType()->isVoidType())
1270 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
1271 << ThrowExpr->getType() << ThrowExpr->getSourceRange());
1274 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, ThrowExpr));
1277 Action::OwningStmtResult
1278 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, ExprArg SynchExpr,
1279 StmtArg SynchBody) {
1280 CurFunctionNeedsScopeChecking = true;
1282 // Make sure the expression type is an ObjC pointer or "void *".
1283 Expr *SyncExpr = static_cast<Expr*>(SynchExpr.get());
1284 if (!SyncExpr->getType()->isObjCObjectPointerType()) {
1285 const PointerType *PT = SyncExpr->getType()->getAs<PointerType>();
1286 if (!PT || !PT->getPointeeType()->isVoidType())
1287 return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object)
1288 << SyncExpr->getType() << SyncExpr->getSourceRange());
1291 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc,
1292 SynchExpr.takeAs<Stmt>(),
1293 SynchBody.takeAs<Stmt>()));
1296 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
1297 /// and creates a proper catch handler from them.
1298 Action::OwningStmtResult
1299 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, DeclPtrTy ExDecl,
1300 StmtArg HandlerBlock) {
1301 // There's nothing to test that ActOnExceptionDecl didn't already test.
1302 return Owned(new (Context) CXXCatchStmt(CatchLoc,
1303 cast_or_null<VarDecl>(ExDecl.getAs<Decl>()),
1304 HandlerBlock.takeAs<Stmt>()));
1307 class TypeWithHandler {
1311 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
1312 : t(type), stmt(statement) {}
1314 // An arbitrary order is fine as long as it places identical
1315 // types next to each other.
1316 bool operator<(const TypeWithHandler &y) const {
1317 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
1319 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
1322 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
1325 bool operator==(const TypeWithHandler& other) const {
1326 return t == other.t;
1329 QualType getQualType() const { return t; }
1330 CXXCatchStmt *getCatchStmt() const { return stmt; }
1331 SourceLocation getTypeSpecStartLoc() const {
1332 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
1336 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
1337 /// handlers and creates a try statement from them.
1338 Action::OwningStmtResult
1339 Sema::ActOnCXXTryBlock(SourceLocation TryLoc, StmtArg TryBlock,
1340 MultiStmtArg RawHandlers) {
1341 unsigned NumHandlers = RawHandlers.size();
1342 assert(NumHandlers > 0 &&
1343 "The parser shouldn't call this if there are no handlers.");
1344 Stmt **Handlers = reinterpret_cast<Stmt**>(RawHandlers.get());
1346 llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers;
1348 for (unsigned i = 0; i < NumHandlers; ++i) {
1349 CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]);
1350 if (!Handler->getExceptionDecl()) {
1351 if (i < NumHandlers - 1)
1352 return StmtError(Diag(Handler->getLocStart(),
1353 diag::err_early_catch_all));
1358 const QualType CaughtType = Handler->getCaughtType();
1359 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
1360 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
1363 // Detect handlers for the same type as an earlier one.
1364 if (NumHandlers > 1) {
1365 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
1367 TypeWithHandler prev = TypesWithHandlers[0];
1368 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
1369 TypeWithHandler curr = TypesWithHandlers[i];
1372 Diag(curr.getTypeSpecStartLoc(),
1373 diag::warn_exception_caught_by_earlier_handler)
1374 << curr.getCatchStmt()->getCaughtType().getAsString();
1375 Diag(prev.getTypeSpecStartLoc(),
1376 diag::note_previous_exception_handler)
1377 << prev.getCatchStmt()->getCaughtType().getAsString();
1384 // FIXME: We should detect handlers that cannot catch anything because an
1385 // earlier handler catches a superclass. Need to find a method that is not
1386 // quadratic for this.
1387 // Neither of these are explicitly forbidden, but every compiler detects them
1390 CurFunctionNeedsScopeChecking = true;
1391 RawHandlers.release();
1392 return Owned(new (Context) CXXTryStmt(TryLoc,
1393 static_cast<Stmt*>(TryBlock.release()),
1394 Handlers, NumHandlers));