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 //===----------------------------------------------------------------------===//
16 #include "clang/AST/APValue.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/StmtObjC.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "clang/AST/TypeLoc.h"
24 #include "clang/Lex/Preprocessor.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SmallVector.h"
28 using namespace clang;
30 Sema::OwningStmtResult Sema::ActOnExprStmt(FullExprArg expr) {
31 Expr *E = expr->takeAs<Expr>();
32 assert(E && "ActOnExprStmt(): missing expression");
33 if (E->getType()->isObjCObjectType()) {
34 if (LangOpts.ObjCNonFragileABI)
35 Diag(E->getLocEnd(), diag::err_indirection_requires_nonfragile_object)
38 Diag(E->getLocEnd(), diag::err_direct_interface_unsupported)
42 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
43 // void expression for its side effects. Conversion to void allows any
44 // operand, even incomplete types.
46 // Same thing in for stmt first clause (when expr) and third clause.
47 return Owned(static_cast<Stmt*>(E));
51 Sema::OwningStmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc) {
52 return Owned(new (Context) NullStmt(SemiLoc));
55 Sema::OwningStmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg,
56 SourceLocation StartLoc,
57 SourceLocation EndLoc) {
58 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
60 // If we have an invalid decl, just return an error.
61 if (DG.isNull()) return StmtError();
63 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
66 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
67 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
69 // If we have an invalid decl, just return.
70 if (DG.isNull() || !DG.isSingleDecl()) return;
71 // suppress any potential 'unused variable' warning.
72 DG.getSingleDecl()->setUsed();
75 void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
76 const Expr *E = dyn_cast_or_null<Expr>(S);
82 if (!E->isUnusedResultAWarning(Loc, R1, R2, Context))
85 // Okay, we have an unused result. Depending on what the base expression is,
86 // we might want to make a more specific diagnostic. Check for one of these
88 unsigned DiagID = diag::warn_unused_expr;
89 E = E->IgnoreParens();
90 if (isa<ObjCImplicitSetterGetterRefExpr>(E))
91 DiagID = diag::warn_unused_property_expr;
93 if (const CXXExprWithTemporaries *Temps = dyn_cast<CXXExprWithTemporaries>(E))
94 E = Temps->getSubExpr();
96 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
97 if (E->getType()->isVoidType())
100 // If the callee has attribute pure, const, or warn_unused_result, warn with
101 // a more specific message to make it clear what is happening.
102 if (const Decl *FD = CE->getCalleeDecl()) {
103 if (FD->getAttr<WarnUnusedResultAttr>()) {
104 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
107 if (FD->getAttr<PureAttr>()) {
108 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
111 if (FD->getAttr<ConstAttr>()) {
112 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
117 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
118 const ObjCMethodDecl *MD = ME->getMethodDecl();
119 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
120 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
123 } else if (const CXXFunctionalCastExpr *FC
124 = dyn_cast<CXXFunctionalCastExpr>(E)) {
125 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
126 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
129 // Diagnose "(void*) blah" as a typo for "(void) blah".
130 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
131 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
132 QualType T = TI->getType();
134 // We really do want to use the non-canonical type here.
135 if (T == Context.VoidPtrTy) {
136 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
138 Diag(Loc, diag::warn_unused_voidptr)
139 << FixItHint::CreateRemoval(TL.getStarLoc());
144 Diag(Loc, DiagID) << R1 << R2;
147 Action::OwningStmtResult
148 Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
149 MultiStmtArg elts, bool isStmtExpr) {
150 unsigned NumElts = elts.size();
151 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
152 // If we're in C89 mode, check that we don't have any decls after stmts. If
153 // so, emit an extension diagnostic.
154 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
155 // Note that __extension__ can be around a decl.
157 // Skip over all declarations.
158 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
161 // We found the end of the list or a statement. Scan for another declstmt.
162 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
166 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
167 Diag(D->getLocation(), diag::ext_mixed_decls_code);
170 // Warn about unused expressions in statements.
171 for (unsigned i = 0; i != NumElts; ++i) {
172 // Ignore statements that are last in a statement expression.
173 if (isStmtExpr && i == NumElts - 1)
176 DiagnoseUnusedExprResult(Elts[i]);
179 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
182 Action::OwningStmtResult
183 Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprArg lhsval,
184 SourceLocation DotDotDotLoc, ExprArg rhsval,
185 SourceLocation ColonLoc) {
186 assert((lhsval.get() != 0) && "missing expression in case statement");
188 // C99 6.8.4.2p3: The expression shall be an integer constant.
189 // However, GCC allows any evaluatable integer expression.
190 Expr *LHSVal = static_cast<Expr*>(lhsval.get());
191 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() &&
192 VerifyIntegerConstantExpression(LHSVal))
195 // GCC extension: The expression shall be an integer constant.
197 Expr *RHSVal = static_cast<Expr*>(rhsval.get());
198 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() &&
199 VerifyIntegerConstantExpression(RHSVal)) {
200 RHSVal = 0; // Recover by just forgetting about it.
204 if (getSwitchStack().empty()) {
205 Diag(CaseLoc, diag::err_case_not_in_switch);
209 // Only now release the smart pointers.
212 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
214 getSwitchStack().back()->addSwitchCase(CS);
218 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
219 void Sema::ActOnCaseStmtBody(StmtTy *caseStmt, StmtArg subStmt) {
220 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
221 Stmt *SubStmt = subStmt.takeAs<Stmt>();
222 CS->setSubStmt(SubStmt);
225 Action::OwningStmtResult
226 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
227 StmtArg subStmt, Scope *CurScope) {
228 Stmt *SubStmt = subStmt.takeAs<Stmt>();
230 if (getSwitchStack().empty()) {
231 Diag(DefaultLoc, diag::err_default_not_in_switch);
232 return Owned(SubStmt);
235 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
236 getSwitchStack().back()->addSwitchCase(DS);
240 Action::OwningStmtResult
241 Sema::ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II,
242 SourceLocation ColonLoc, StmtArg subStmt) {
243 Stmt *SubStmt = subStmt.takeAs<Stmt>();
244 // Look up the record for this label identifier.
245 LabelStmt *&LabelDecl = getLabelMap()[II];
247 // If not forward referenced or defined already, just create a new LabelStmt.
249 return Owned(LabelDecl = new (Context) LabelStmt(IdentLoc, II, SubStmt));
251 assert(LabelDecl->getID() == II && "Label mismatch!");
253 // Otherwise, this label was either forward reference or multiply defined. If
254 // multiply defined, reject it now.
255 if (LabelDecl->getSubStmt()) {
256 Diag(IdentLoc, diag::err_redefinition_of_label) << LabelDecl->getID();
257 Diag(LabelDecl->getIdentLoc(), diag::note_previous_definition);
258 return Owned(SubStmt);
261 // Otherwise, this label was forward declared, and we just found its real
262 // definition. Fill in the forward definition and return it.
263 LabelDecl->setIdentLoc(IdentLoc);
264 LabelDecl->setSubStmt(SubStmt);
265 return Owned(LabelDecl);
268 Action::OwningStmtResult
269 Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, DeclPtrTy CondVar,
270 StmtArg ThenVal, SourceLocation ElseLoc,
272 OwningExprResult CondResult(CondVal.release());
274 VarDecl *ConditionVar = 0;
276 ConditionVar = CondVar.getAs<VarDecl>();
277 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
278 if (CondResult.isInvalid())
281 Expr *ConditionExpr = CondResult.takeAs<Expr>();
285 Stmt *thenStmt = ThenVal.takeAs<Stmt>();
286 DiagnoseUnusedExprResult(thenStmt);
288 // Warn if the if block has a null body without an else value.
289 // this helps prevent bugs due to typos, such as
292 if (!ElseVal.get()) {
293 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
294 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
297 Stmt *elseStmt = ElseVal.takeAs<Stmt>();
298 DiagnoseUnusedExprResult(elseStmt);
300 CondResult.release();
301 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
302 thenStmt, ElseLoc, elseStmt));
305 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
306 /// the specified width and sign. If an overflow occurs, detect it and emit
307 /// the specified diagnostic.
308 void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
309 unsigned NewWidth, bool NewSign,
312 // Perform a conversion to the promoted condition type if needed.
313 if (NewWidth > Val.getBitWidth()) {
314 // If this is an extension, just do it.
315 Val.extend(NewWidth);
316 Val.setIsSigned(NewSign);
318 // If the input was signed and negative and the output is
319 // unsigned, don't bother to warn: this is implementation-defined
321 // FIXME: Introduce a second, default-ignored warning for this case?
322 } else if (NewWidth < Val.getBitWidth()) {
323 // If this is a truncation, check for overflow.
324 llvm::APSInt ConvVal(Val);
325 ConvVal.trunc(NewWidth);
326 ConvVal.setIsSigned(NewSign);
327 ConvVal.extend(Val.getBitWidth());
328 ConvVal.setIsSigned(Val.isSigned());
330 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
332 // Regardless of whether a diagnostic was emitted, really do the
335 Val.setIsSigned(NewSign);
336 } else if (NewSign != Val.isSigned()) {
337 // Convert the sign to match the sign of the condition. This can cause
338 // overflow as well: unsigned(INTMIN)
339 // We don't diagnose this overflow, because it is implementation-defined
341 // FIXME: Introduce a second, default-ignored warning for this case?
342 llvm::APSInt OldVal(Val);
343 Val.setIsSigned(NewSign);
348 struct CaseCompareFunctor {
349 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
350 const llvm::APSInt &RHS) {
351 return LHS.first < RHS;
353 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
354 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
355 return LHS.first < RHS.first;
357 bool operator()(const llvm::APSInt &LHS,
358 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
359 return LHS < RHS.first;
364 /// CmpCaseVals - Comparison predicate for sorting case values.
366 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
367 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
368 if (lhs.first < rhs.first)
371 if (lhs.first == rhs.first &&
372 lhs.second->getCaseLoc().getRawEncoding()
373 < rhs.second->getCaseLoc().getRawEncoding())
378 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
380 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
381 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
383 return lhs.first < rhs.first;
386 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
388 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
389 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
391 return lhs.first == rhs.first;
394 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
395 /// potentially integral-promoted expression @p expr.
396 static QualType GetTypeBeforeIntegralPromotion(const Expr* expr) {
397 if (const CastExpr *ImplicitCast = dyn_cast<ImplicitCastExpr>(expr)) {
398 const Expr *ExprBeforePromotion = ImplicitCast->getSubExpr();
399 QualType TypeBeforePromotion = ExprBeforePromotion->getType();
400 if (TypeBeforePromotion->isIntegralOrEnumerationType()) {
401 return TypeBeforePromotion;
404 return expr->getType();
407 Action::OwningStmtResult
408 Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, ExprArg Cond,
410 VarDecl *ConditionVar = 0;
412 ConditionVar = CondVar.getAs<VarDecl>();
413 OwningExprResult CondE = CheckConditionVariable(ConditionVar, SourceLocation(), false);
414 if (CondE.isInvalid())
423 Expr *CondExpr = static_cast<Expr *>(Cond.get());
424 OwningExprResult ConvertedCond
425 = ConvertToIntegralOrEnumerationType(SwitchLoc, move(Cond),
426 PDiag(diag::err_typecheck_statement_requires_integer),
427 PDiag(diag::err_switch_incomplete_class_type)
428 << CondExpr->getSourceRange(),
429 PDiag(diag::err_switch_explicit_conversion),
430 PDiag(diag::note_switch_conversion),
431 PDiag(diag::err_switch_multiple_conversions),
432 PDiag(diag::note_switch_conversion),
434 if (ConvertedCond.isInvalid())
437 CondExpr = ConvertedCond.takeAs<Expr>();
439 if (!CondVar.get()) {
440 CondExpr = MaybeCreateCXXExprWithTemporaries(CondExpr);
445 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, CondExpr);
446 getSwitchStack().push_back(SS);
450 Action::OwningStmtResult
451 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, StmtArg Switch,
453 Stmt *BodyStmt = Body.takeAs<Stmt>();
455 SwitchStmt *SS = getSwitchStack().back();
456 assert(SS == (SwitchStmt*)Switch.get() && "switch stack missing push/pop!");
458 SS->setBody(BodyStmt, SwitchLoc);
459 getSwitchStack().pop_back();
461 if (SS->getCond() == 0) {
462 SS->Destroy(Context);
466 Expr *CondExpr = SS->getCond();
467 Expr *CondExprBeforePromotion = CondExpr;
468 QualType CondTypeBeforePromotion =
469 GetTypeBeforeIntegralPromotion(CondExpr);
471 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
472 UsualUnaryConversions(CondExpr);
473 QualType CondType = CondExpr->getType();
474 SS->setCond(CondExpr);
477 // Integral promotions are performed (on the switch condition).
479 // A case value unrepresentable by the original switch condition
480 // type (before the promotion) doesn't make sense, even when it can
481 // be represented by the promoted type. Therefore we need to find
482 // the pre-promotion type of the switch condition.
483 if (!CondExpr->isTypeDependent()) {
484 // We have already converted the expression to an integral or enumeration
485 // type, when we started the switch statement. If we don't have an
486 // appropriate type now, just return an error.
487 if (!CondType->isIntegralOrEnumerationType())
490 if (CondExpr->isKnownToHaveBooleanValue()) {
491 // switch(bool_expr) {...} is often a programmer error, e.g.
492 // switch(n && mask) { ... } // Doh - should be "n & mask".
493 // One can always use an if statement instead of switch(bool_expr).
494 Diag(SwitchLoc, diag::warn_bool_switch_condition)
495 << CondExpr->getSourceRange();
499 // Get the bitwidth of the switched-on value before promotions. We must
500 // convert the integer case values to this width before comparison.
501 bool HasDependentValue
502 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
504 = HasDependentValue? 0
505 : static_cast<unsigned>(Context.getTypeSize(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,
554 CS->getLHS()->getLocStart(),
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, CastExpr::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,
633 CR->getRHS()->getLocStart(),
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, CastExpr::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(),
645 CR->getRHS()->getLocEnd());
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 don't need to do this if there's a default
720 // statement or if we have a constant condition.
722 // TODO: we might want to check whether case values are out of the
723 // enum even if we don't want to check whether all cases are handled.
724 const EnumType* ET = CondTypeBeforePromotion->getAs<EnumType>();
725 // If switch has default case, then ignore it.
726 if (!CaseListIsErroneous && !TheDefaultStmt && !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 if(Val.getBitWidth() < CondWidth)
737 Val.extend(CondWidth);
738 else if (Val.getBitWidth() > CondWidth)
739 Val.trunc(CondWidth);
740 Val.setIsSigned(CondIsSigned);
741 EnumVals.push_back(std::make_pair(Val, (*EDI)));
743 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
744 EnumValsTy::iterator EIend =
745 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
746 // See which case values aren't in enum
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 while (EI != EIend && EI->first < Hi)
771 if (EI == EIend || EI->first != Hi)
772 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
773 << ED->getDeclName();
775 //Check which enum vals aren't in switch
776 CaseValsTy::const_iterator CI = CaseVals.begin();
777 CaseRangesTy::const_iterator RI = CaseRanges.begin();
778 EI = EnumVals.begin();
779 for (; EI != EIend; EI++) {
780 //Drop unneeded case values
782 while (CI != CaseVals.end() && CI->first < EI->first)
785 if (CI != CaseVals.end() && CI->first == EI->first)
788 //Drop unneeded case ranges
789 for (; RI != CaseRanges.end(); RI++) {
790 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
795 if (RI == CaseRanges.end() || EI->first < RI->first)
796 Diag(CondExpr->getExprLoc(), diag::warn_missing_cases)
797 << EI->second->getDeclName();
802 // FIXME: If the case list was broken is some way, we don't have a good system
803 // to patch it up. Instead, just return the whole substmt as broken.
804 if (CaseListIsErroneous)
811 Action::OwningStmtResult
812 Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
813 DeclPtrTy CondVar, StmtArg Body) {
814 OwningExprResult CondResult(Cond.release());
816 VarDecl *ConditionVar = 0;
818 ConditionVar = CondVar.getAs<VarDecl>();
819 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
820 if (CondResult.isInvalid())
823 Expr *ConditionExpr = CondResult.takeAs<Expr>();
827 Stmt *bodyStmt = Body.takeAs<Stmt>();
828 DiagnoseUnusedExprResult(bodyStmt);
830 CondResult.release();
831 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
832 bodyStmt, WhileLoc));
835 Action::OwningStmtResult
836 Sema::ActOnDoStmt(SourceLocation DoLoc, StmtArg Body,
837 SourceLocation WhileLoc, SourceLocation CondLParen,
838 ExprArg Cond, SourceLocation CondRParen) {
839 Expr *condExpr = Cond.takeAs<Expr>();
840 assert(condExpr && "ActOnDoStmt(): missing expression");
842 if (CheckBooleanCondition(condExpr, DoLoc)) {
847 condExpr = MaybeCreateCXXExprWithTemporaries(condExpr);
851 Stmt *bodyStmt = Body.takeAs<Stmt>();
852 DiagnoseUnusedExprResult(bodyStmt);
855 return Owned(new (Context) DoStmt(bodyStmt, condExpr, DoLoc,
856 WhileLoc, CondRParen));
859 Action::OwningStmtResult
860 Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
861 StmtArg first, FullExprArg second, DeclPtrTy secondVar,
863 SourceLocation RParenLoc, StmtArg body) {
864 Stmt *First = static_cast<Stmt*>(first.get());
866 if (!getLangOptions().CPlusPlus) {
867 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
868 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
869 // declare identifiers for objects having storage class 'auto' or
871 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
873 VarDecl *VD = dyn_cast<VarDecl>(*DI);
874 if (VD && VD->isBlockVarDecl() && !VD->hasLocalStorage())
877 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
878 // FIXME: mark decl erroneous!
883 OwningExprResult SecondResult(second.release());
884 VarDecl *ConditionVar = 0;
885 if (secondVar.get()) {
886 ConditionVar = secondVar.getAs<VarDecl>();
887 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
888 if (SecondResult.isInvalid())
892 Expr *Third = third.release().takeAs<Expr>();
893 Stmt *Body = static_cast<Stmt*>(body.get());
895 DiagnoseUnusedExprResult(First);
896 DiagnoseUnusedExprResult(Third);
897 DiagnoseUnusedExprResult(Body);
901 return Owned(new (Context) ForStmt(Context, First,
902 SecondResult.takeAs<Expr>(), ConditionVar,
903 Third, Body, ForLoc, LParenLoc,
907 Action::OwningStmtResult
908 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
909 SourceLocation LParenLoc,
910 StmtArg first, ExprArg second,
911 SourceLocation RParenLoc, StmtArg body) {
912 Stmt *First = static_cast<Stmt*>(first.get());
913 Expr *Second = static_cast<Expr*>(second.get());
914 Stmt *Body = static_cast<Stmt*>(body.get());
917 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
918 if (!DS->isSingleDecl())
919 return StmtError(Diag((*DS->decl_begin())->getLocation(),
920 diag::err_toomany_element_decls));
922 Decl *D = DS->getSingleDecl();
923 FirstType = cast<ValueDecl>(D)->getType();
924 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
925 // declare identifiers for objects having storage class 'auto' or
927 VarDecl *VD = cast<VarDecl>(D);
928 if (VD->isBlockVarDecl() && !VD->hasLocalStorage())
929 return StmtError(Diag(VD->getLocation(),
930 diag::err_non_variable_decl_in_for));
932 Expr *FirstE = cast<Expr>(First);
933 if (!FirstE->isTypeDependent() &&
934 FirstE->isLvalue(Context) != Expr::LV_Valid)
935 return StmtError(Diag(First->getLocStart(),
936 diag::err_selector_element_not_lvalue)
937 << First->getSourceRange());
939 FirstType = static_cast<Expr*>(First)->getType();
941 if (!FirstType->isDependentType() &&
942 !FirstType->isObjCObjectPointerType() &&
943 !FirstType->isBlockPointerType())
944 Diag(ForLoc, diag::err_selector_element_type)
945 << FirstType << First->getSourceRange();
947 if (Second && !Second->isTypeDependent()) {
948 DefaultFunctionArrayLvalueConversion(Second);
949 QualType SecondType = Second->getType();
950 if (!SecondType->isObjCObjectPointerType())
951 Diag(ForLoc, diag::err_collection_expr_type)
952 << SecondType << Second->getSourceRange();
957 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
961 Action::OwningStmtResult
962 Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
963 IdentifierInfo *LabelII) {
964 // Look up the record for this label identifier.
965 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
967 // If we haven't seen this label yet, create a forward reference.
969 LabelDecl = new (Context) LabelStmt(LabelLoc, LabelII, 0);
971 return Owned(new (Context) GotoStmt(LabelDecl, GotoLoc, LabelLoc));
974 Action::OwningStmtResult
975 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
977 // Convert operand to void*
978 Expr* E = DestExp.takeAs<Expr>();
979 if (!E->isTypeDependent()) {
980 QualType ETy = E->getType();
981 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
982 AssignConvertType ConvTy =
983 CheckSingleAssignmentConstraints(DestTy, E);
984 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
987 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
990 Action::OwningStmtResult
991 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
992 Scope *S = CurScope->getContinueParent();
994 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
995 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
998 return Owned(new (Context) ContinueStmt(ContinueLoc));
1001 Action::OwningStmtResult
1002 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
1003 Scope *S = CurScope->getBreakParent();
1005 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
1006 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
1009 return Owned(new (Context) BreakStmt(BreakLoc));
1012 /// \brief Determine whether a return statement is a candidate for the named
1013 /// return value optimization (C++0x 12.8p34, bullet 1).
1015 /// \param Ctx The context in which the return expression and type occur.
1017 /// \param RetType The return type of the function or block.
1019 /// \param RetExpr The expression being returned from the function or block.
1021 /// \returns The NRVO candidate variable, if the return statement may use the
1022 /// NRVO, or NULL if there is no such candidate.
1023 static const VarDecl *getNRVOCandidate(ASTContext &Ctx, QualType RetType,
1025 QualType ExprType = RetExpr->getType();
1026 // - in a return statement in a function with ...
1027 // ... a class return type ...
1028 if (!RetType->isRecordType())
1030 // ... the same cv-unqualified type as the function return type ...
1031 if (!Ctx.hasSameUnqualifiedType(RetType, ExprType))
1033 // ... the expression is the name of a non-volatile automatic object ...
1034 // We ignore parentheses here.
1035 // FIXME: Is this compliant? (Everyone else does it)
1036 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetExpr->IgnoreParens());
1039 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1043 if (VD->getKind() == Decl::Var && VD->hasLocalStorage() &&
1044 !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() &&
1045 !VD->getType().isVolatileQualified())
1051 /// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
1053 Action::OwningStmtResult
1054 Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
1055 // If this is the first return we've seen in the block, infer the type of
1056 // the block from it.
1057 BlockScopeInfo *CurBlock = getCurBlock();
1058 if (CurBlock->ReturnType.isNull()) {
1060 // Don't call UsualUnaryConversions(), since we don't want to do
1061 // integer promotions here.
1062 DefaultFunctionArrayLvalueConversion(RetValExp);
1063 CurBlock->ReturnType = RetValExp->getType();
1064 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
1065 // We have to remove a 'const' added to copied-in variable which was
1066 // part of the implementation spec. and not the actual qualifier for
1068 if (CDRE->isConstQualAdded())
1069 CurBlock->ReturnType.removeConst();
1072 CurBlock->ReturnType = Context.VoidTy;
1074 QualType FnRetType = CurBlock->ReturnType;
1076 if (CurBlock->TheDecl->hasAttr<NoReturnAttr>()) {
1077 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
1078 << getCurFunctionOrMethodDecl()->getDeclName();
1082 // Otherwise, verify that this result type matches the previous one. We are
1083 // pickier with blocks than for normal functions because we don't have GCC
1084 // compatibility to worry about here.
1085 ReturnStmt *Result = 0;
1086 if (CurBlock->ReturnType->isVoidType()) {
1088 Diag(ReturnLoc, diag::err_return_block_has_expr);
1089 RetValExp->Destroy(Context);
1092 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1093 } else if (!RetValExp) {
1094 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
1096 const VarDecl *NRVOCandidate = 0;
1098 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1099 // we have a non-void block with an expression, continue checking
1101 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1102 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1105 // In C++ the return statement is handled via a copy initialization.
1106 // the C version of which boils down to CheckSingleAssignmentConstraints.
1107 NRVOCandidate = getNRVOCandidate(Context, FnRetType, RetValExp);
1108 OwningExprResult Res = PerformCopyInitialization(
1109 InitializedEntity::InitializeResult(ReturnLoc,
1111 NRVOCandidate != 0),
1114 if (Res.isInvalid()) {
1115 // FIXME: Cleanup temporaries here, anyway?
1120 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
1122 RetValExp = Res.takeAs<Expr>();
1124 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1127 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
1130 // If we need to check for the named return value optimization, save the
1131 // return statement in our scope for later processing.
1132 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1133 !CurContext->isDependentContext())
1134 FunctionScopes.back()->Returns.push_back(Result);
1136 return Owned(Result);
1139 Action::OwningStmtResult
1140 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, ExprArg rex) {
1141 Expr *RetValExp = rex.takeAs<Expr>();
1143 return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
1146 if (const FunctionDecl *FD = getCurFunctionDecl()) {
1147 FnRetType = FD->getResultType();
1148 if (FD->hasAttr<NoReturnAttr>() ||
1149 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
1150 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
1151 << getCurFunctionOrMethodDecl()->getDeclName();
1152 } else if (ObjCMethodDecl *MD = getCurMethodDecl())
1153 FnRetType = MD->getResultType();
1154 else // If we don't have a function/method context, bail.
1157 ReturnStmt *Result = 0;
1158 if (FnRetType->isVoidType()) {
1159 if (RetValExp && !RetValExp->isTypeDependent()) {
1160 // C99 6.8.6.4p1 (ext_ since GCC warns)
1161 unsigned D = diag::ext_return_has_expr;
1162 if (RetValExp->getType()->isVoidType())
1163 D = diag::ext_return_has_void_expr;
1165 // return (some void expression); is legal in C++.
1166 if (D != diag::ext_return_has_void_expr ||
1167 !getLangOptions().CPlusPlus) {
1168 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
1170 << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl)
1171 << RetValExp->getSourceRange();
1174 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
1177 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1178 } else if (!RetValExp && !FnRetType->isDependentType()) {
1179 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
1180 // C99 6.8.6.4p1 (ext_ since GCC warns)
1181 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
1183 if (FunctionDecl *FD = getCurFunctionDecl())
1184 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
1186 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
1187 Result = new (Context) ReturnStmt(ReturnLoc);
1189 const VarDecl *NRVOCandidate = 0;
1190 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1191 // we have a non-void function with an expression, continue checking
1193 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1194 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1197 // In C++ the return statement is handled via a copy initialization.
1198 // the C version of which boils down to CheckSingleAssignmentConstraints.
1199 NRVOCandidate = getNRVOCandidate(Context, FnRetType, RetValExp);
1200 OwningExprResult Res = PerformCopyInitialization(
1201 InitializedEntity::InitializeResult(ReturnLoc,
1203 NRVOCandidate != 0),
1206 if (Res.isInvalid()) {
1207 // FIXME: Cleanup temporaries here, anyway?
1211 RetValExp = Res.takeAs<Expr>();
1213 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1217 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
1218 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
1221 // If we need to check for the named return value optimization, save the
1222 // return statement in our scope for later processing.
1223 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1224 !CurContext->isDependentContext())
1225 FunctionScopes.back()->Returns.push_back(Result);
1227 return Owned(Result);
1230 /// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
1231 /// ignore "noop" casts in places where an lvalue is required by an inline asm.
1232 /// We emulate this behavior when -fheinous-gnu-extensions is specified, but
1233 /// provide a strong guidance to not use it.
1235 /// This method checks to see if the argument is an acceptable l-value and
1236 /// returns false if it is a case we can handle.
1237 static bool CheckAsmLValue(const Expr *E, Sema &S) {
1238 // Type dependent expressions will be checked during instantiation.
1239 if (E->isTypeDependent())
1242 if (E->isLvalue(S.Context) == Expr::LV_Valid)
1243 return false; // Cool, this is an lvalue.
1245 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
1246 // are supposed to allow.
1247 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
1248 if (E != E2 && E2->isLvalue(S.Context) == Expr::LV_Valid) {
1249 if (!S.getLangOptions().HeinousExtensions)
1250 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
1251 << E->getSourceRange();
1253 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
1254 << E->getSourceRange();
1255 // Accept, even if we emitted an error diagnostic.
1259 // None of the above, just randomly invalid non-lvalue.
1264 Sema::OwningStmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc,
1267 unsigned NumOutputs,
1269 IdentifierInfo **Names,
1270 MultiExprArg constraints,
1273 MultiExprArg clobbers,
1274 SourceLocation RParenLoc,
1276 unsigned NumClobbers = clobbers.size();
1277 StringLiteral **Constraints =
1278 reinterpret_cast<StringLiteral**>(constraints.get());
1279 Expr **Exprs = reinterpret_cast<Expr **>(exprs.get());
1280 StringLiteral *AsmString = cast<StringLiteral>((Expr *)asmString.get());
1281 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
1283 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1285 // The parser verifies that there is a string literal here.
1286 if (AsmString->isWide())
1287 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
1288 << AsmString->getSourceRange());
1290 for (unsigned i = 0; i != NumOutputs; i++) {
1291 StringLiteral *Literal = Constraints[i];
1292 if (Literal->isWide())
1293 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1294 << Literal->getSourceRange());
1296 llvm::StringRef OutputName;
1298 OutputName = Names[i]->getName();
1300 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
1301 if (!Context.Target.validateOutputConstraint(Info))
1302 return StmtError(Diag(Literal->getLocStart(),
1303 diag::err_asm_invalid_output_constraint)
1304 << Info.getConstraintStr());
1306 // Check that the output exprs are valid lvalues.
1307 Expr *OutputExpr = Exprs[i];
1308 if (CheckAsmLValue(OutputExpr, *this)) {
1309 return StmtError(Diag(OutputExpr->getLocStart(),
1310 diag::err_asm_invalid_lvalue_in_output)
1311 << OutputExpr->getSourceRange());
1314 OutputConstraintInfos.push_back(Info);
1317 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1319 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
1320 StringLiteral *Literal = Constraints[i];
1321 if (Literal->isWide())
1322 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1323 << Literal->getSourceRange());
1325 llvm::StringRef InputName;
1327 InputName = Names[i]->getName();
1329 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
1330 if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(),
1331 NumOutputs, Info)) {
1332 return StmtError(Diag(Literal->getLocStart(),
1333 diag::err_asm_invalid_input_constraint)
1334 << Info.getConstraintStr());
1337 Expr *InputExpr = Exprs[i];
1339 // Only allow void types for memory constraints.
1340 if (Info.allowsMemory() && !Info.allowsRegister()) {
1341 if (CheckAsmLValue(InputExpr, *this))
1342 return StmtError(Diag(InputExpr->getLocStart(),
1343 diag::err_asm_invalid_lvalue_in_input)
1344 << Info.getConstraintStr()
1345 << InputExpr->getSourceRange());
1348 if (Info.allowsRegister()) {
1349 if (InputExpr->getType()->isVoidType()) {
1350 return StmtError(Diag(InputExpr->getLocStart(),
1351 diag::err_asm_invalid_type_in_input)
1352 << InputExpr->getType() << Info.getConstraintStr()
1353 << InputExpr->getSourceRange());
1357 DefaultFunctionArrayLvalueConversion(Exprs[i]);
1359 InputConstraintInfos.push_back(Info);
1362 // Check that the clobbers are valid.
1363 for (unsigned i = 0; i != NumClobbers; i++) {
1364 StringLiteral *Literal = Clobbers[i];
1365 if (Literal->isWide())
1366 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1367 << Literal->getSourceRange());
1369 llvm::StringRef Clobber = Literal->getString();
1371 if (!Context.Target.isValidGCCRegisterName(Clobber))
1372 return StmtError(Diag(Literal->getLocStart(),
1373 diag::err_asm_unknown_register_name) << Clobber);
1376 constraints.release();
1378 asmString.release();
1381 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
1382 NumOutputs, NumInputs, Names, Constraints, Exprs,
1383 AsmString, NumClobbers, Clobbers, RParenLoc);
1384 // Validate the asm string, ensuring it makes sense given the operands we
1386 llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
1388 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
1389 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
1390 << AsmString->getSourceRange();
1395 // Validate tied input operands for type mismatches.
1396 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
1397 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1399 // If this is a tied constraint, verify that the output and input have
1400 // either exactly the same type, or that they are int/ptr operands with the
1401 // same size (int/long, int*/long, are ok etc).
1402 if (!Info.hasTiedOperand()) continue;
1404 unsigned TiedTo = Info.getTiedOperand();
1405 Expr *OutputExpr = Exprs[TiedTo];
1406 Expr *InputExpr = Exprs[i+NumOutputs];
1407 QualType InTy = InputExpr->getType();
1408 QualType OutTy = OutputExpr->getType();
1409 if (Context.hasSameType(InTy, OutTy))
1410 continue; // All types can be tied to themselves.
1412 // Decide if the input and output are in the same domain (integer/ptr or
1415 AD_Int, AD_FP, AD_Other
1416 } InputDomain, OutputDomain;
1418 if (InTy->isIntegerType() || InTy->isPointerType())
1419 InputDomain = AD_Int;
1420 else if (InTy->isRealFloatingType())
1421 InputDomain = AD_FP;
1423 InputDomain = AD_Other;
1425 if (OutTy->isIntegerType() || OutTy->isPointerType())
1426 OutputDomain = AD_Int;
1427 else if (OutTy->isRealFloatingType())
1428 OutputDomain = AD_FP;
1430 OutputDomain = AD_Other;
1432 // They are ok if they are the same size and in the same domain. This
1433 // allows tying things like:
1435 // void* to int if they are the same size.
1436 // double to long double if they are the same size.
1438 uint64_t OutSize = Context.getTypeSize(OutTy);
1439 uint64_t InSize = Context.getTypeSize(InTy);
1440 if (OutSize == InSize && InputDomain == OutputDomain &&
1441 InputDomain != AD_Other)
1444 // If the smaller input/output operand is not mentioned in the asm string,
1445 // then we can promote it and the asm string won't notice. Check this
1447 bool SmallerValueMentioned = false;
1448 for (unsigned p = 0, e = Pieces.size(); p != e; ++p) {
1449 AsmStmt::AsmStringPiece &Piece = Pieces[p];
1450 if (!Piece.isOperand()) continue;
1452 // If this is a reference to the input and if the input was the smaller
1453 // one, then we have to reject this asm.
1454 if (Piece.getOperandNo() == i+NumOutputs) {
1455 if (InSize < OutSize) {
1456 SmallerValueMentioned = true;
1461 // If this is a reference to the input and if the input was the smaller
1462 // one, then we have to reject this asm.
1463 if (Piece.getOperandNo() == TiedTo) {
1464 if (InSize > OutSize) {
1465 SmallerValueMentioned = true;
1471 // If the smaller value wasn't mentioned in the asm string, and if the
1472 // output was a register, just extend the shorter one to the size of the
1474 if (!SmallerValueMentioned && InputDomain != AD_Other &&
1475 OutputConstraintInfos[TiedTo].allowsRegister())
1478 Diag(InputExpr->getLocStart(),
1479 diag::err_asm_tying_incompatible_types)
1480 << InTy << OutTy << OutputExpr->getSourceRange()
1481 << InputExpr->getSourceRange();
1489 Action::OwningStmtResult
1490 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
1491 SourceLocation RParen, DeclPtrTy Parm,
1493 VarDecl *Var = cast_or_null<VarDecl>(Parm.getAs<Decl>());
1494 if (Var && Var->isInvalidDecl())
1497 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var,
1498 Body.takeAs<Stmt>()));
1501 Action::OwningStmtResult
1502 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, StmtArg Body) {
1503 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc,
1504 static_cast<Stmt*>(Body.release())));
1507 Action::OwningStmtResult
1508 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, StmtArg Try,
1509 MultiStmtArg CatchStmts, StmtArg Finally) {
1510 FunctionNeedsScopeChecking() = true;
1511 unsigned NumCatchStmts = CatchStmts.size();
1512 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try.takeAs<Stmt>(),
1513 (Stmt **)CatchStmts.release(),
1515 Finally.takeAs<Stmt>()));
1518 Sema::OwningStmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc,
1520 Expr *Throw = static_cast<Expr *>(ThrowE.get());
1522 QualType ThrowType = Throw->getType();
1523 // Make sure the expression type is an ObjC pointer or "void *".
1524 if (!ThrowType->isDependentType() &&
1525 !ThrowType->isObjCObjectPointerType()) {
1526 const PointerType *PT = ThrowType->getAs<PointerType>();
1527 if (!PT || !PT->getPointeeType()->isVoidType())
1528 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
1529 << Throw->getType() << Throw->getSourceRange());
1533 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, ThrowE.takeAs<Expr>()));
1536 Action::OwningStmtResult
1537 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, ExprArg Throw,
1540 // @throw without an expression designates a rethrow (which much occur
1541 // in the context of an @catch clause).
1542 Scope *AtCatchParent = CurScope;
1543 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
1544 AtCatchParent = AtCatchParent->getParent();
1546 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
1549 return BuildObjCAtThrowStmt(AtLoc, move(Throw));
1552 Action::OwningStmtResult
1553 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, ExprArg SynchExpr,
1554 StmtArg SynchBody) {
1555 FunctionNeedsScopeChecking() = true;
1557 // Make sure the expression type is an ObjC pointer or "void *".
1558 Expr *SyncExpr = static_cast<Expr*>(SynchExpr.get());
1559 if (!SyncExpr->getType()->isDependentType() &&
1560 !SyncExpr->getType()->isObjCObjectPointerType()) {
1561 const PointerType *PT = SyncExpr->getType()->getAs<PointerType>();
1562 if (!PT || !PT->getPointeeType()->isVoidType())
1563 return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object)
1564 << SyncExpr->getType() << SyncExpr->getSourceRange());
1567 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc,
1568 SynchExpr.takeAs<Stmt>(),
1569 SynchBody.takeAs<Stmt>()));
1572 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
1573 /// and creates a proper catch handler from them.
1574 Action::OwningStmtResult
1575 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, DeclPtrTy ExDecl,
1576 StmtArg HandlerBlock) {
1577 // There's nothing to test that ActOnExceptionDecl didn't already test.
1578 return Owned(new (Context) CXXCatchStmt(CatchLoc,
1579 cast_or_null<VarDecl>(ExDecl.getAs<Decl>()),
1580 HandlerBlock.takeAs<Stmt>()));
1583 class TypeWithHandler {
1587 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
1588 : t(type), stmt(statement) {}
1590 // An arbitrary order is fine as long as it places identical
1591 // types next to each other.
1592 bool operator<(const TypeWithHandler &y) const {
1593 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
1595 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
1598 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
1601 bool operator==(const TypeWithHandler& other) const {
1602 return t == other.t;
1605 QualType getQualType() const { return t; }
1606 CXXCatchStmt *getCatchStmt() const { return stmt; }
1607 SourceLocation getTypeSpecStartLoc() const {
1608 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
1612 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
1613 /// handlers and creates a try statement from them.
1614 Action::OwningStmtResult
1615 Sema::ActOnCXXTryBlock(SourceLocation TryLoc, StmtArg TryBlock,
1616 MultiStmtArg RawHandlers) {
1617 unsigned NumHandlers = RawHandlers.size();
1618 assert(NumHandlers > 0 &&
1619 "The parser shouldn't call this if there are no handlers.");
1620 Stmt **Handlers = reinterpret_cast<Stmt**>(RawHandlers.get());
1622 llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers;
1624 for (unsigned i = 0; i < NumHandlers; ++i) {
1625 CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]);
1626 if (!Handler->getExceptionDecl()) {
1627 if (i < NumHandlers - 1)
1628 return StmtError(Diag(Handler->getLocStart(),
1629 diag::err_early_catch_all));
1634 const QualType CaughtType = Handler->getCaughtType();
1635 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
1636 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
1639 // Detect handlers for the same type as an earlier one.
1640 if (NumHandlers > 1) {
1641 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
1643 TypeWithHandler prev = TypesWithHandlers[0];
1644 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
1645 TypeWithHandler curr = TypesWithHandlers[i];
1648 Diag(curr.getTypeSpecStartLoc(),
1649 diag::warn_exception_caught_by_earlier_handler)
1650 << curr.getCatchStmt()->getCaughtType().getAsString();
1651 Diag(prev.getTypeSpecStartLoc(),
1652 diag::note_previous_exception_handler)
1653 << prev.getCatchStmt()->getCaughtType().getAsString();
1660 // FIXME: We should detect handlers that cannot catch anything because an
1661 // earlier handler catches a superclass. Need to find a method that is not
1662 // quadratic for this.
1663 // Neither of these are explicitly forbidden, but every compiler detects them
1666 FunctionNeedsScopeChecking() = true;
1667 RawHandlers.release();
1668 return Owned(CXXTryStmt::Create(Context, TryLoc,
1669 static_cast<Stmt*>(TryBlock.release()),
1670 Handlers, NumHandlers));