Handle member initializer in C++ ctor.
[clang.git] / lib / Sema / SemaStmt.cpp
bloba4f1d34aec36a0f82ccfd73eac9eb0de36dff6a2
1 //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements semantic analysis for statements.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Scope.h"
16 #include "clang/Sema/ScopeInfo.h"
17 #include "clang/Sema/Initialization.h"
18 #include "clang/AST/APValue.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/StmtObjC.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/Lex/Preprocessor.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SmallVector.h"
30 using namespace clang;
31 using namespace sema;
33 StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
34 Expr *E = expr.get();
35 assert(E && "ActOnExprStmt(): missing expression");
36 // C99 6.8.3p2: The expression in an expression statement is evaluated as a
37 // void expression for its side effects. Conversion to void allows any
38 // operand, even incomplete types.
40 // Same thing in for stmt first clause (when expr) and third clause.
41 return Owned(static_cast<Stmt*>(E));
45 StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc) {
46 return Owned(new (Context) NullStmt(SemiLoc));
49 StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg,
50 SourceLocation StartLoc,
51 SourceLocation EndLoc) {
52 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
54 // If we have an invalid decl, just return an error.
55 if (DG.isNull()) return StmtError();
57 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
60 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
61 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
63 // If we have an invalid decl, just return.
64 if (DG.isNull() || !DG.isSingleDecl()) return;
65 // suppress any potential 'unused variable' warning.
66 DG.getSingleDecl()->setUsed();
69 void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
70 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
71 return DiagnoseUnusedExprResult(Label->getSubStmt());
73 const Expr *E = dyn_cast_or_null<Expr>(S);
74 if (!E)
75 return;
77 if (E->isBoundMemberFunction(Context)) {
78 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
79 << E->getSourceRange();
80 return;
83 SourceLocation Loc;
84 SourceRange R1, R2;
85 if (!E->isUnusedResultAWarning(Loc, R1, R2, Context))
86 return;
88 // Okay, we have an unused result. Depending on what the base expression is,
89 // we might want to make a more specific diagnostic. Check for one of these
90 // cases now.
91 unsigned DiagID = diag::warn_unused_expr;
92 E = E->IgnoreParens();
93 if (isa<ObjCImplicitSetterGetterRefExpr>(E))
94 DiagID = diag::warn_unused_property_expr;
96 if (const CXXExprWithTemporaries *Temps = dyn_cast<CXXExprWithTemporaries>(E))
97 E = Temps->getSubExpr();
99 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
100 if (E->getType()->isVoidType())
101 return;
103 // If the callee has attribute pure, const, or warn_unused_result, warn with
104 // a more specific message to make it clear what is happening.
105 if (const Decl *FD = CE->getCalleeDecl()) {
106 if (FD->getAttr<WarnUnusedResultAttr>()) {
107 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
108 return;
110 if (FD->getAttr<PureAttr>()) {
111 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
112 return;
114 if (FD->getAttr<ConstAttr>()) {
115 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
116 return;
120 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
121 const ObjCMethodDecl *MD = ME->getMethodDecl();
122 if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
123 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
124 return;
126 } else if (const CXXFunctionalCastExpr *FC
127 = dyn_cast<CXXFunctionalCastExpr>(E)) {
128 if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
129 isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
130 return;
132 // Diagnose "(void*) blah" as a typo for "(void) blah".
133 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
134 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
135 QualType T = TI->getType();
137 // We really do want to use the non-canonical type here.
138 if (T == Context.VoidPtrTy) {
139 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
141 Diag(Loc, diag::warn_unused_voidptr)
142 << FixItHint::CreateRemoval(TL.getStarLoc());
143 return;
147 DiagRuntimeBehavior(Loc, PDiag(DiagID) << R1 << R2);
150 StmtResult
151 Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
152 MultiStmtArg elts, bool isStmtExpr) {
153 unsigned NumElts = elts.size();
154 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
155 // If we're in C89 mode, check that we don't have any decls after stmts. If
156 // so, emit an extension diagnostic.
157 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
158 // Note that __extension__ can be around a decl.
159 unsigned i = 0;
160 // Skip over all declarations.
161 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
162 /*empty*/;
164 // We found the end of the list or a statement. Scan for another declstmt.
165 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
166 /*empty*/;
168 if (i != NumElts) {
169 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
170 Diag(D->getLocation(), diag::ext_mixed_decls_code);
173 // Warn about unused expressions in statements.
174 for (unsigned i = 0; i != NumElts; ++i) {
175 // Ignore statements that are last in a statement expression.
176 if (isStmtExpr && i == NumElts - 1)
177 continue;
179 DiagnoseUnusedExprResult(Elts[i]);
182 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
185 StmtResult
186 Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
187 SourceLocation DotDotDotLoc, Expr *RHSVal,
188 SourceLocation ColonLoc) {
189 assert((LHSVal != 0) && "missing expression in case statement");
191 // C99 6.8.4.2p3: The expression shall be an integer constant.
192 // However, GCC allows any evaluatable integer expression.
193 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() &&
194 VerifyIntegerConstantExpression(LHSVal))
195 return StmtError();
197 // GCC extension: The expression shall be an integer constant.
199 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() &&
200 VerifyIntegerConstantExpression(RHSVal)) {
201 RHSVal = 0; // Recover by just forgetting about it.
204 if (getCurFunction()->SwitchStack.empty()) {
205 Diag(CaseLoc, diag::err_case_not_in_switch);
206 return StmtError();
209 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
210 ColonLoc);
211 getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
212 return Owned(CS);
215 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
216 void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
217 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
218 CS->setSubStmt(SubStmt);
221 StmtResult
222 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
223 Stmt *SubStmt, Scope *CurScope) {
224 if (getCurFunction()->SwitchStack.empty()) {
225 Diag(DefaultLoc, diag::err_default_not_in_switch);
226 return Owned(SubStmt);
229 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
230 getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
231 return Owned(DS);
234 StmtResult
235 Sema::ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II,
236 SourceLocation ColonLoc, Stmt *SubStmt,
237 const AttributeList *Attr) {
238 // According to GCC docs, "the only attribute that makes sense after a label
239 // is 'unused'".
240 bool HasUnusedAttr = false;
241 for ( ; Attr; Attr = Attr->getNext()) {
242 if (Attr->getKind() == AttributeList::AT_unused) {
243 HasUnusedAttr = true;
244 } else {
245 Diag(Attr->getLoc(), diag::warn_label_attribute_not_unused);
246 Attr->setInvalid(true);
250 return ActOnLabelStmt(IdentLoc, II, ColonLoc, SubStmt, HasUnusedAttr);
253 StmtResult
254 Sema::ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II,
255 SourceLocation ColonLoc, Stmt *SubStmt,
256 bool HasUnusedAttr) {
257 // Look up the record for this label identifier.
258 LabelStmt *&LabelDecl = getCurFunction()->LabelMap[II];
260 // If not forward referenced or defined already, just create a new LabelStmt.
261 if (LabelDecl == 0)
262 return Owned(LabelDecl = new (Context) LabelStmt(IdentLoc, II, SubStmt,
263 HasUnusedAttr));
265 assert(LabelDecl->getID() == II && "Label mismatch!");
267 // Otherwise, this label was either forward reference or multiply defined. If
268 // multiply defined, reject it now.
269 if (LabelDecl->getSubStmt()) {
270 Diag(IdentLoc, diag::err_redefinition_of_label) << LabelDecl->getID();
271 Diag(LabelDecl->getIdentLoc(), diag::note_previous_definition);
272 return Owned(SubStmt);
275 // Otherwise, this label was forward declared, and we just found its real
276 // definition. Fill in the forward definition and return it.
277 LabelDecl->setIdentLoc(IdentLoc);
278 LabelDecl->setSubStmt(SubStmt);
279 LabelDecl->setUnusedAttribute(HasUnusedAttr);
280 return Owned(LabelDecl);
283 StmtResult
284 Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
285 Stmt *thenStmt, SourceLocation ElseLoc,
286 Stmt *elseStmt) {
287 ExprResult CondResult(CondVal.release());
289 VarDecl *ConditionVar = 0;
290 if (CondVar) {
291 ConditionVar = cast<VarDecl>(CondVar);
292 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
293 if (CondResult.isInvalid())
294 return StmtError();
296 Expr *ConditionExpr = CondResult.takeAs<Expr>();
297 if (!ConditionExpr)
298 return StmtError();
300 DiagnoseUnusedExprResult(thenStmt);
302 // Warn if the if block has a null body without an else value.
303 // this helps prevent bugs due to typos, such as
304 // if (condition);
305 // do_stuff();
307 // NOTE: Do not emit this warning if the body is expanded from a macro.
308 if (!elseStmt) {
309 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
310 if (!stmt->getLocStart().isMacroID())
311 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
314 DiagnoseUnusedExprResult(elseStmt);
316 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
317 thenStmt, ElseLoc, elseStmt));
320 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
321 /// the specified width and sign. If an overflow occurs, detect it and emit
322 /// the specified diagnostic.
323 void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
324 unsigned NewWidth, bool NewSign,
325 SourceLocation Loc,
326 unsigned DiagID) {
327 // Perform a conversion to the promoted condition type if needed.
328 if (NewWidth > Val.getBitWidth()) {
329 // If this is an extension, just do it.
330 Val.extend(NewWidth);
331 Val.setIsSigned(NewSign);
333 // If the input was signed and negative and the output is
334 // unsigned, don't bother to warn: this is implementation-defined
335 // behavior.
336 // FIXME: Introduce a second, default-ignored warning for this case?
337 } else if (NewWidth < Val.getBitWidth()) {
338 // If this is a truncation, check for overflow.
339 llvm::APSInt ConvVal(Val);
340 ConvVal.trunc(NewWidth);
341 ConvVal.setIsSigned(NewSign);
342 ConvVal.extend(Val.getBitWidth());
343 ConvVal.setIsSigned(Val.isSigned());
344 if (ConvVal != Val)
345 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
347 // Regardless of whether a diagnostic was emitted, really do the
348 // truncation.
349 Val.trunc(NewWidth);
350 Val.setIsSigned(NewSign);
351 } else if (NewSign != Val.isSigned()) {
352 // Convert the sign to match the sign of the condition. This can cause
353 // overflow as well: unsigned(INTMIN)
354 // We don't diagnose this overflow, because it is implementation-defined
355 // behavior.
356 // FIXME: Introduce a second, default-ignored warning for this case?
357 llvm::APSInt OldVal(Val);
358 Val.setIsSigned(NewSign);
362 namespace {
363 struct CaseCompareFunctor {
364 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
365 const llvm::APSInt &RHS) {
366 return LHS.first < RHS;
368 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
369 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
370 return LHS.first < RHS.first;
372 bool operator()(const llvm::APSInt &LHS,
373 const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
374 return LHS < RHS.first;
379 /// CmpCaseVals - Comparison predicate for sorting case values.
381 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
382 const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
383 if (lhs.first < rhs.first)
384 return true;
386 if (lhs.first == rhs.first &&
387 lhs.second->getCaseLoc().getRawEncoding()
388 < rhs.second->getCaseLoc().getRawEncoding())
389 return true;
390 return false;
393 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
395 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
396 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
398 return lhs.first < rhs.first;
401 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
403 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
404 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
406 return lhs.first == rhs.first;
409 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
410 /// potentially integral-promoted expression @p expr.
411 static QualType GetTypeBeforeIntegralPromotion(const Expr* expr) {
412 if (const CastExpr *ImplicitCast = dyn_cast<ImplicitCastExpr>(expr)) {
413 const Expr *ExprBeforePromotion = ImplicitCast->getSubExpr();
414 QualType TypeBeforePromotion = ExprBeforePromotion->getType();
415 if (TypeBeforePromotion->isIntegralOrEnumerationType()) {
416 return TypeBeforePromotion;
419 return expr->getType();
422 StmtResult
423 Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
424 Decl *CondVar) {
425 ExprResult CondResult;
427 VarDecl *ConditionVar = 0;
428 if (CondVar) {
429 ConditionVar = cast<VarDecl>(CondVar);
430 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
431 if (CondResult.isInvalid())
432 return StmtError();
434 Cond = CondResult.release();
437 if (!Cond)
438 return StmtError();
440 CondResult
441 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond,
442 PDiag(diag::err_typecheck_statement_requires_integer),
443 PDiag(diag::err_switch_incomplete_class_type)
444 << Cond->getSourceRange(),
445 PDiag(diag::err_switch_explicit_conversion),
446 PDiag(diag::note_switch_conversion),
447 PDiag(diag::err_switch_multiple_conversions),
448 PDiag(diag::note_switch_conversion),
449 PDiag(0));
450 if (CondResult.isInvalid()) return StmtError();
451 Cond = CondResult.take();
453 if (!CondVar) {
454 CheckImplicitConversions(Cond, SwitchLoc);
455 CondResult = MaybeCreateCXXExprWithTemporaries(Cond);
456 if (CondResult.isInvalid())
457 return StmtError();
458 Cond = CondResult.take();
461 getCurFunction()->setHasBranchIntoScope();
463 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
464 getCurFunction()->SwitchStack.push_back(SS);
465 return Owned(SS);
468 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
469 if (Val.getBitWidth() < BitWidth)
470 Val.extend(BitWidth);
471 else if (Val.getBitWidth() > BitWidth)
472 Val.trunc(BitWidth);
473 Val.setIsSigned(IsSigned);
476 StmtResult
477 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
478 Stmt *BodyStmt) {
479 SwitchStmt *SS = cast<SwitchStmt>(Switch);
480 assert(SS == getCurFunction()->SwitchStack.back() &&
481 "switch stack missing push/pop!");
483 SS->setBody(BodyStmt, SwitchLoc);
484 getCurFunction()->SwitchStack.pop_back();
486 if (SS->getCond() == 0)
487 return StmtError();
489 Expr *CondExpr = SS->getCond();
490 Expr *CondExprBeforePromotion = CondExpr;
491 QualType CondTypeBeforePromotion =
492 GetTypeBeforeIntegralPromotion(CondExpr);
494 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
495 UsualUnaryConversions(CondExpr);
496 QualType CondType = CondExpr->getType();
497 SS->setCond(CondExpr);
499 // C++ 6.4.2.p2:
500 // Integral promotions are performed (on the switch condition).
502 // A case value unrepresentable by the original switch condition
503 // type (before the promotion) doesn't make sense, even when it can
504 // be represented by the promoted type. Therefore we need to find
505 // the pre-promotion type of the switch condition.
506 if (!CondExpr->isTypeDependent()) {
507 // We have already converted the expression to an integral or enumeration
508 // type, when we started the switch statement. If we don't have an
509 // appropriate type now, just return an error.
510 if (!CondType->isIntegralOrEnumerationType())
511 return StmtError();
513 if (CondExpr->isKnownToHaveBooleanValue()) {
514 // switch(bool_expr) {...} is often a programmer error, e.g.
515 // switch(n && mask) { ... } // Doh - should be "n & mask".
516 // One can always use an if statement instead of switch(bool_expr).
517 Diag(SwitchLoc, diag::warn_bool_switch_condition)
518 << CondExpr->getSourceRange();
522 // Get the bitwidth of the switched-on value before promotions. We must
523 // convert the integer case values to this width before comparison.
524 bool HasDependentValue
525 = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
526 unsigned CondWidth
527 = HasDependentValue? 0
528 : static_cast<unsigned>(Context.getTypeSize(CondTypeBeforePromotion));
529 bool CondIsSigned = CondTypeBeforePromotion->isSignedIntegerType();
531 // Accumulate all of the case values in a vector so that we can sort them
532 // and detect duplicates. This vector contains the APInt for the case after
533 // it has been converted to the condition type.
534 typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
535 CaseValsTy CaseVals;
537 // Keep track of any GNU case ranges we see. The APSInt is the low value.
538 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
539 CaseRangesTy CaseRanges;
541 DefaultStmt *TheDefaultStmt = 0;
543 bool CaseListIsErroneous = false;
545 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
546 SC = SC->getNextSwitchCase()) {
548 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
549 if (TheDefaultStmt) {
550 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
551 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
553 // FIXME: Remove the default statement from the switch block so that
554 // we'll return a valid AST. This requires recursing down the AST and
555 // finding it, not something we are set up to do right now. For now,
556 // just lop the entire switch stmt out of the AST.
557 CaseListIsErroneous = true;
559 TheDefaultStmt = DS;
561 } else {
562 CaseStmt *CS = cast<CaseStmt>(SC);
564 // We already verified that the expression has a i-c-e value (C99
565 // 6.8.4.2p3) - get that value now.
566 Expr *Lo = CS->getLHS();
568 if (Lo->isTypeDependent() || Lo->isValueDependent()) {
569 HasDependentValue = true;
570 break;
573 llvm::APSInt LoVal = Lo->EvaluateAsInt(Context);
575 // Convert the value to the same width/sign as the condition.
576 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
577 Lo->getLocStart(),
578 diag::warn_case_value_overflow);
580 // If the LHS is not the same type as the condition, insert an implicit
581 // cast.
582 ImpCastExprToType(Lo, CondType, CK_IntegralCast);
583 CS->setLHS(Lo);
585 // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
586 if (CS->getRHS()) {
587 if (CS->getRHS()->isTypeDependent() ||
588 CS->getRHS()->isValueDependent()) {
589 HasDependentValue = true;
590 break;
592 CaseRanges.push_back(std::make_pair(LoVal, CS));
593 } else
594 CaseVals.push_back(std::make_pair(LoVal, CS));
598 if (!HasDependentValue) {
599 // If we don't have a default statement, check whether the
600 // condition is constant.
601 llvm::APSInt ConstantCondValue;
602 bool HasConstantCond = false;
603 bool ShouldCheckConstantCond = false;
604 if (!HasDependentValue && !TheDefaultStmt) {
605 Expr::EvalResult Result;
606 HasConstantCond = CondExprBeforePromotion->Evaluate(Result, Context);
607 if (HasConstantCond) {
608 assert(Result.Val.isInt() && "switch condition evaluated to non-int");
609 ConstantCondValue = Result.Val.getInt();
610 ShouldCheckConstantCond = true;
612 assert(ConstantCondValue.getBitWidth() == CondWidth &&
613 ConstantCondValue.isSigned() == CondIsSigned);
617 // Sort all the scalar case values so we can easily detect duplicates.
618 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
620 if (!CaseVals.empty()) {
621 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
622 if (ShouldCheckConstantCond &&
623 CaseVals[i].first == ConstantCondValue)
624 ShouldCheckConstantCond = false;
626 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
627 // If we have a duplicate, report it.
628 Diag(CaseVals[i].second->getLHS()->getLocStart(),
629 diag::err_duplicate_case) << CaseVals[i].first.toString(10);
630 Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
631 diag::note_duplicate_case_prev);
632 // FIXME: We really want to remove the bogus case stmt from the
633 // substmt, but we have no way to do this right now.
634 CaseListIsErroneous = true;
639 // Detect duplicate case ranges, which usually don't exist at all in
640 // the first place.
641 if (!CaseRanges.empty()) {
642 // Sort all the case ranges by their low value so we can easily detect
643 // overlaps between ranges.
644 std::stable_sort(CaseRanges.begin(), CaseRanges.end());
646 // Scan the ranges, computing the high values and removing empty ranges.
647 std::vector<llvm::APSInt> HiVals;
648 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
649 llvm::APSInt &LoVal = CaseRanges[i].first;
650 CaseStmt *CR = CaseRanges[i].second;
651 Expr *Hi = CR->getRHS();
652 llvm::APSInt HiVal = Hi->EvaluateAsInt(Context);
654 // Convert the value to the same width/sign as the condition.
655 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
656 Hi->getLocStart(),
657 diag::warn_case_value_overflow);
659 // If the LHS is not the same type as the condition, insert an implicit
660 // cast.
661 ImpCastExprToType(Hi, CondType, CK_IntegralCast);
662 CR->setRHS(Hi);
664 // If the low value is bigger than the high value, the case is empty.
665 if (LoVal > HiVal) {
666 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
667 << SourceRange(CR->getLHS()->getLocStart(),
668 Hi->getLocEnd());
669 CaseRanges.erase(CaseRanges.begin()+i);
670 --i, --e;
671 continue;
674 if (ShouldCheckConstantCond &&
675 LoVal <= ConstantCondValue &&
676 ConstantCondValue <= HiVal)
677 ShouldCheckConstantCond = false;
679 HiVals.push_back(HiVal);
682 // Rescan the ranges, looking for overlap with singleton values and other
683 // ranges. Since the range list is sorted, we only need to compare case
684 // ranges with their neighbors.
685 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
686 llvm::APSInt &CRLo = CaseRanges[i].first;
687 llvm::APSInt &CRHi = HiVals[i];
688 CaseStmt *CR = CaseRanges[i].second;
690 // Check to see whether the case range overlaps with any
691 // singleton cases.
692 CaseStmt *OverlapStmt = 0;
693 llvm::APSInt OverlapVal(32);
695 // Find the smallest value >= the lower bound. If I is in the
696 // case range, then we have overlap.
697 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
698 CaseVals.end(), CRLo,
699 CaseCompareFunctor());
700 if (I != CaseVals.end() && I->first < CRHi) {
701 OverlapVal = I->first; // Found overlap with scalar.
702 OverlapStmt = I->second;
705 // Find the smallest value bigger than the upper bound.
706 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
707 if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
708 OverlapVal = (I-1)->first; // Found overlap with scalar.
709 OverlapStmt = (I-1)->second;
712 // Check to see if this case stmt overlaps with the subsequent
713 // case range.
714 if (i && CRLo <= HiVals[i-1]) {
715 OverlapVal = HiVals[i-1]; // Found overlap with range.
716 OverlapStmt = CaseRanges[i-1].second;
719 if (OverlapStmt) {
720 // If we have a duplicate, report it.
721 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
722 << OverlapVal.toString(10);
723 Diag(OverlapStmt->getLHS()->getLocStart(),
724 diag::note_duplicate_case_prev);
725 // FIXME: We really want to remove the bogus case stmt from the
726 // substmt, but we have no way to do this right now.
727 CaseListIsErroneous = true;
732 // Complain if we have a constant condition and we didn't find a match.
733 if (!CaseListIsErroneous && ShouldCheckConstantCond) {
734 // TODO: it would be nice if we printed enums as enums, chars as
735 // chars, etc.
736 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
737 << ConstantCondValue.toString(10)
738 << CondExpr->getSourceRange();
741 // Check to see if switch is over an Enum and handles all of its
742 // values. We only issue a warning if there is not 'default:', but
743 // we still do the analysis to preserve this information in the AST
744 // (which can be used by flow-based analyes).
746 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
748 // If switch has default case, then ignore it.
749 if (!CaseListIsErroneous && !HasConstantCond && ET) {
750 const EnumDecl *ED = ET->getDecl();
751 typedef llvm::SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy;
752 EnumValsTy EnumVals;
754 // Gather all enum values, set their type and sort them,
755 // allowing easier comparison with CaseVals.
756 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
757 EDI != ED->enumerator_end(); ++EDI) {
758 llvm::APSInt Val = EDI->getInitVal();
759 AdjustAPSInt(Val, CondWidth, CondIsSigned);
760 EnumVals.push_back(std::make_pair(Val, *EDI));
762 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
763 EnumValsTy::iterator EIend =
764 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
766 // See which case values aren't in enum.
767 // TODO: we might want to check whether case values are out of the
768 // enum even if we don't want to check whether all cases are handled.
769 if (!TheDefaultStmt) {
770 EnumValsTy::const_iterator EI = EnumVals.begin();
771 for (CaseValsTy::const_iterator CI = CaseVals.begin();
772 CI != CaseVals.end(); CI++) {
773 while (EI != EIend && EI->first < CI->first)
774 EI++;
775 if (EI == EIend || EI->first > CI->first)
776 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
777 << ED->getDeclName();
779 // See which of case ranges aren't in enum
780 EI = EnumVals.begin();
781 for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
782 RI != CaseRanges.end() && EI != EIend; RI++) {
783 while (EI != EIend && EI->first < RI->first)
784 EI++;
786 if (EI == EIend || EI->first != RI->first) {
787 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
788 << ED->getDeclName();
791 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
792 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
793 while (EI != EIend && EI->first < Hi)
794 EI++;
795 if (EI == EIend || EI->first != Hi)
796 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
797 << ED->getDeclName();
801 // Check which enum vals aren't in switch
802 CaseValsTy::const_iterator CI = CaseVals.begin();
803 CaseRangesTy::const_iterator RI = CaseRanges.begin();
804 bool hasCasesNotInSwitch = false;
806 llvm::SmallVector<DeclarationName,8> UnhandledNames;
808 for (EnumValsTy::const_iterator EI = EnumVals.begin(); EI != EIend; EI++){
809 // Drop unneeded case values
810 llvm::APSInt CIVal;
811 while (CI != CaseVals.end() && CI->first < EI->first)
812 CI++;
814 if (CI != CaseVals.end() && CI->first == EI->first)
815 continue;
817 // Drop unneeded case ranges
818 for (; RI != CaseRanges.end(); RI++) {
819 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context);
820 AdjustAPSInt(Hi, CondWidth, CondIsSigned);
821 if (EI->first <= Hi)
822 break;
825 if (RI == CaseRanges.end() || EI->first < RI->first) {
826 hasCasesNotInSwitch = true;
827 if (!TheDefaultStmt)
828 UnhandledNames.push_back(EI->second->getDeclName());
832 // Produce a nice diagnostic if multiple values aren't handled.
833 switch (UnhandledNames.size()) {
834 case 0: break;
835 case 1:
836 Diag(CondExpr->getExprLoc(), diag::warn_missing_case1)
837 << UnhandledNames[0];
838 break;
839 case 2:
840 Diag(CondExpr->getExprLoc(), diag::warn_missing_case2)
841 << UnhandledNames[0] << UnhandledNames[1];
842 break;
843 case 3:
844 Diag(CondExpr->getExprLoc(), diag::warn_missing_case3)
845 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
846 break;
847 default:
848 Diag(CondExpr->getExprLoc(), diag::warn_missing_cases)
849 << (unsigned)UnhandledNames.size()
850 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
851 break;
854 if (!hasCasesNotInSwitch)
855 SS->setAllEnumCasesCovered();
859 // FIXME: If the case list was broken is some way, we don't have a good system
860 // to patch it up. Instead, just return the whole substmt as broken.
861 if (CaseListIsErroneous)
862 return StmtError();
864 return Owned(SS);
867 StmtResult
868 Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
869 Decl *CondVar, Stmt *Body) {
870 ExprResult CondResult(Cond.release());
872 VarDecl *ConditionVar = 0;
873 if (CondVar) {
874 ConditionVar = cast<VarDecl>(CondVar);
875 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
876 if (CondResult.isInvalid())
877 return StmtError();
879 Expr *ConditionExpr = CondResult.take();
880 if (!ConditionExpr)
881 return StmtError();
883 DiagnoseUnusedExprResult(Body);
885 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
886 Body, WhileLoc));
889 StmtResult
890 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
891 SourceLocation WhileLoc, SourceLocation CondLParen,
892 Expr *Cond, SourceLocation CondRParen) {
893 assert(Cond && "ActOnDoStmt(): missing expression");
895 if (CheckBooleanCondition(Cond, DoLoc))
896 return StmtError();
898 CheckImplicitConversions(Cond, DoLoc);
899 ExprResult CondResult = MaybeCreateCXXExprWithTemporaries(Cond);
900 if (CondResult.isInvalid())
901 return StmtError();
902 Cond = CondResult.take();
904 DiagnoseUnusedExprResult(Body);
906 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
909 StmtResult
910 Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
911 Stmt *First, FullExprArg second, Decl *secondVar,
912 FullExprArg third,
913 SourceLocation RParenLoc, Stmt *Body) {
914 if (!getLangOptions().CPlusPlus) {
915 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
916 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
917 // declare identifiers for objects having storage class 'auto' or
918 // 'register'.
919 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
920 DI!=DE; ++DI) {
921 VarDecl *VD = dyn_cast<VarDecl>(*DI);
922 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
923 VD = 0;
924 if (VD == 0)
925 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
926 // FIXME: mark decl erroneous!
931 ExprResult SecondResult(second.release());
932 VarDecl *ConditionVar = 0;
933 if (secondVar) {
934 ConditionVar = cast<VarDecl>(secondVar);
935 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
936 if (SecondResult.isInvalid())
937 return StmtError();
940 Expr *Third = third.release().takeAs<Expr>();
942 DiagnoseUnusedExprResult(First);
943 DiagnoseUnusedExprResult(Third);
944 DiagnoseUnusedExprResult(Body);
946 return Owned(new (Context) ForStmt(Context, First,
947 SecondResult.take(), ConditionVar,
948 Third, Body, ForLoc, LParenLoc,
949 RParenLoc));
952 StmtResult
953 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
954 SourceLocation LParenLoc,
955 Stmt *First, Expr *Second,
956 SourceLocation RParenLoc, Stmt *Body) {
957 if (First) {
958 QualType FirstType;
959 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
960 if (!DS->isSingleDecl())
961 return StmtError(Diag((*DS->decl_begin())->getLocation(),
962 diag::err_toomany_element_decls));
964 Decl *D = DS->getSingleDecl();
965 FirstType = cast<ValueDecl>(D)->getType();
966 // C99 6.8.5p3: The declaration part of a 'for' statement shall only
967 // declare identifiers for objects having storage class 'auto' or
968 // 'register'.
969 VarDecl *VD = cast<VarDecl>(D);
970 if (VD->isLocalVarDecl() && !VD->hasLocalStorage())
971 return StmtError(Diag(VD->getLocation(),
972 diag::err_non_variable_decl_in_for));
973 } else {
974 Expr *FirstE = cast<Expr>(First);
975 if (!FirstE->isTypeDependent() &&
976 FirstE->isLvalue(Context) != Expr::LV_Valid)
977 return StmtError(Diag(First->getLocStart(),
978 diag::err_selector_element_not_lvalue)
979 << First->getSourceRange());
981 FirstType = static_cast<Expr*>(First)->getType();
983 if (!FirstType->isDependentType() &&
984 !FirstType->isObjCObjectPointerType() &&
985 !FirstType->isBlockPointerType())
986 Diag(ForLoc, diag::err_selector_element_type)
987 << FirstType << First->getSourceRange();
989 if (Second && !Second->isTypeDependent()) {
990 DefaultFunctionArrayLvalueConversion(Second);
991 QualType SecondType = Second->getType();
992 if (!SecondType->isObjCObjectPointerType())
993 Diag(ForLoc, diag::err_collection_expr_type)
994 << SecondType << Second->getSourceRange();
995 else if (const ObjCObjectPointerType *OPT =
996 SecondType->getAsObjCInterfacePointerType()) {
997 llvm::SmallVector<IdentifierInfo *, 4> KeyIdents;
998 IdentifierInfo* selIdent =
999 &Context.Idents.get("countByEnumeratingWithState");
1000 KeyIdents.push_back(selIdent);
1001 selIdent = &Context.Idents.get("objects");
1002 KeyIdents.push_back(selIdent);
1003 selIdent = &Context.Idents.get("count");
1004 KeyIdents.push_back(selIdent);
1005 Selector CSelector = Context.Selectors.getSelector(3, &KeyIdents[0]);
1006 if (ObjCInterfaceDecl *IDecl = OPT->getInterfaceDecl()) {
1007 if (!IDecl->isForwardDecl() &&
1008 !IDecl->lookupInstanceMethod(CSelector)) {
1009 // Must further look into private implementation methods.
1010 if (!LookupPrivateInstanceMethod(CSelector, IDecl))
1011 Diag(ForLoc, diag::warn_collection_expr_type)
1012 << SecondType << CSelector << Second->getSourceRange();
1017 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
1018 ForLoc, RParenLoc));
1021 StmtResult
1022 Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1023 IdentifierInfo *LabelII) {
1024 // Look up the record for this label identifier.
1025 LabelStmt *&LabelDecl = getCurFunction()->LabelMap[LabelII];
1027 getCurFunction()->setHasBranchIntoScope();
1029 // If we haven't seen this label yet, create a forward reference.
1030 if (LabelDecl == 0)
1031 LabelDecl = new (Context) LabelStmt(LabelLoc, LabelII, 0);
1033 LabelDecl->setUsed();
1034 return Owned(new (Context) GotoStmt(LabelDecl, GotoLoc, LabelLoc));
1037 StmtResult
1038 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
1039 Expr *E) {
1040 // Convert operand to void*
1041 if (!E->isTypeDependent()) {
1042 QualType ETy = E->getType();
1043 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
1044 AssignConvertType ConvTy =
1045 CheckSingleAssignmentConstraints(DestTy, E);
1046 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
1047 return StmtError();
1050 getCurFunction()->setHasIndirectGoto();
1052 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
1055 StmtResult
1056 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
1057 Scope *S = CurScope->getContinueParent();
1058 if (!S) {
1059 // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
1060 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
1063 return Owned(new (Context) ContinueStmt(ContinueLoc));
1066 StmtResult
1067 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
1068 Scope *S = CurScope->getBreakParent();
1069 if (!S) {
1070 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
1071 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
1074 return Owned(new (Context) BreakStmt(BreakLoc));
1077 /// \brief Determine whether a return statement is a candidate for the named
1078 /// return value optimization (C++0x 12.8p34, bullet 1).
1080 /// \param Ctx The context in which the return expression and type occur.
1082 /// \param RetType The return type of the function or block.
1084 /// \param RetExpr The expression being returned from the function or block.
1086 /// \returns The NRVO candidate variable, if the return statement may use the
1087 /// NRVO, or NULL if there is no such candidate.
1088 static const VarDecl *getNRVOCandidate(ASTContext &Ctx, QualType RetType,
1089 Expr *RetExpr) {
1090 QualType ExprType = RetExpr->getType();
1091 // - in a return statement in a function with ...
1092 // ... a class return type ...
1093 if (!RetType->isRecordType())
1094 return 0;
1095 // ... the same cv-unqualified type as the function return type ...
1096 if (!Ctx.hasSameUnqualifiedType(RetType, ExprType))
1097 return 0;
1098 // ... the expression is the name of a non-volatile automatic object ...
1099 // We ignore parentheses here.
1100 // FIXME: Is this compliant? (Everyone else does it)
1101 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetExpr->IgnoreParens());
1102 if (!DR)
1103 return 0;
1104 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1105 if (!VD)
1106 return 0;
1108 if (VD->getKind() == Decl::Var && VD->hasLocalStorage() &&
1109 !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() &&
1110 !VD->getType().isVolatileQualified())
1111 return VD;
1113 return 0;
1116 /// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
1118 StmtResult
1119 Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
1120 // If this is the first return we've seen in the block, infer the type of
1121 // the block from it.
1122 BlockScopeInfo *CurBlock = getCurBlock();
1123 if (CurBlock->ReturnType.isNull()) {
1124 if (RetValExp) {
1125 // Don't call UsualUnaryConversions(), since we don't want to do
1126 // integer promotions here.
1127 DefaultFunctionArrayLvalueConversion(RetValExp);
1128 CurBlock->ReturnType = RetValExp->getType();
1129 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
1130 // We have to remove a 'const' added to copied-in variable which was
1131 // part of the implementation spec. and not the actual qualifier for
1132 // the variable.
1133 if (CDRE->isConstQualAdded())
1134 CurBlock->ReturnType.removeConst();
1136 } else
1137 CurBlock->ReturnType = Context.VoidTy;
1139 QualType FnRetType = CurBlock->ReturnType;
1141 if (CurBlock->TheDecl->hasAttr<NoReturnAttr>()) {
1142 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
1143 << getCurFunctionOrMethodDecl()->getDeclName();
1144 return StmtError();
1147 // Otherwise, verify that this result type matches the previous one. We are
1148 // pickier with blocks than for normal functions because we don't have GCC
1149 // compatibility to worry about here.
1150 ReturnStmt *Result = 0;
1151 if (CurBlock->ReturnType->isVoidType()) {
1152 if (RetValExp) {
1153 Diag(ReturnLoc, diag::err_return_block_has_expr);
1154 RetValExp = 0;
1156 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1157 } else if (!RetValExp) {
1158 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
1159 } else {
1160 const VarDecl *NRVOCandidate = 0;
1162 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1163 // we have a non-void block with an expression, continue checking
1165 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1166 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1167 // function return.
1169 // In C++ the return statement is handled via a copy initialization.
1170 // the C version of which boils down to CheckSingleAssignmentConstraints.
1171 NRVOCandidate = getNRVOCandidate(Context, FnRetType, RetValExp);
1172 ExprResult Res = PerformCopyInitialization(
1173 InitializedEntity::InitializeResult(ReturnLoc,
1174 FnRetType,
1175 NRVOCandidate != 0),
1176 SourceLocation(),
1177 Owned(RetValExp));
1178 if (Res.isInvalid()) {
1179 // FIXME: Cleanup temporaries here, anyway?
1180 return StmtError();
1183 if (RetValExp) {
1184 CheckImplicitConversions(RetValExp, ReturnLoc);
1185 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
1188 RetValExp = Res.takeAs<Expr>();
1189 if (RetValExp)
1190 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1193 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
1196 // If we need to check for the named return value optimization, save the
1197 // return statement in our scope for later processing.
1198 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1199 !CurContext->isDependentContext())
1200 FunctionScopes.back()->Returns.push_back(Result);
1202 return Owned(Result);
1205 StmtResult
1206 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
1207 if (getCurBlock())
1208 return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
1210 QualType FnRetType;
1211 if (const FunctionDecl *FD = getCurFunctionDecl()) {
1212 FnRetType = FD->getResultType();
1213 if (FD->hasAttr<NoReturnAttr>() ||
1214 FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
1215 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
1216 << getCurFunctionOrMethodDecl()->getDeclName();
1217 } else if (ObjCMethodDecl *MD = getCurMethodDecl())
1218 FnRetType = MD->getResultType();
1219 else // If we don't have a function/method context, bail.
1220 return StmtError();
1222 ReturnStmt *Result = 0;
1223 if (FnRetType->isVoidType()) {
1224 if (RetValExp && !RetValExp->isTypeDependent()) {
1225 // C99 6.8.6.4p1 (ext_ since GCC warns)
1226 unsigned D = diag::ext_return_has_expr;
1227 if (RetValExp->getType()->isVoidType())
1228 D = diag::ext_return_has_void_expr;
1230 // return (some void expression); is legal in C++.
1231 if (D != diag::ext_return_has_void_expr ||
1232 !getLangOptions().CPlusPlus) {
1233 NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
1234 Diag(ReturnLoc, D)
1235 << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl)
1236 << RetValExp->getSourceRange();
1239 CheckImplicitConversions(RetValExp, ReturnLoc);
1240 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
1243 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
1244 } else if (!RetValExp && !FnRetType->isDependentType()) {
1245 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4
1246 // C99 6.8.6.4p1 (ext_ since GCC warns)
1247 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
1249 if (FunctionDecl *FD = getCurFunctionDecl())
1250 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
1251 else
1252 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
1253 Result = new (Context) ReturnStmt(ReturnLoc);
1254 } else {
1255 const VarDecl *NRVOCandidate = 0;
1256 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1257 // we have a non-void function with an expression, continue checking
1259 // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1260 // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1261 // function return.
1263 // In C++ the return statement is handled via a copy initialization.
1264 // the C version of which boils down to CheckSingleAssignmentConstraints.
1265 NRVOCandidate = getNRVOCandidate(Context, FnRetType, RetValExp);
1266 ExprResult Res = PerformCopyInitialization(
1267 InitializedEntity::InitializeResult(ReturnLoc,
1268 FnRetType,
1269 NRVOCandidate != 0),
1270 SourceLocation(),
1271 Owned(RetValExp));
1272 if (Res.isInvalid()) {
1273 // FIXME: Cleanup temporaries here, anyway?
1274 return StmtError();
1277 RetValExp = Res.takeAs<Expr>();
1278 if (RetValExp)
1279 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1282 if (RetValExp) {
1283 CheckImplicitConversions(RetValExp, ReturnLoc);
1284 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
1286 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
1289 // If we need to check for the named return value optimization, save the
1290 // return statement in our scope for later processing.
1291 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() &&
1292 !CurContext->isDependentContext())
1293 FunctionScopes.back()->Returns.push_back(Result);
1295 return Owned(Result);
1298 /// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
1299 /// ignore "noop" casts in places where an lvalue is required by an inline asm.
1300 /// We emulate this behavior when -fheinous-gnu-extensions is specified, but
1301 /// provide a strong guidance to not use it.
1303 /// This method checks to see if the argument is an acceptable l-value and
1304 /// returns false if it is a case we can handle.
1305 static bool CheckAsmLValue(const Expr *E, Sema &S) {
1306 // Type dependent expressions will be checked during instantiation.
1307 if (E->isTypeDependent())
1308 return false;
1310 if (E->isLvalue(S.Context) == Expr::LV_Valid)
1311 return false; // Cool, this is an lvalue.
1313 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
1314 // are supposed to allow.
1315 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
1316 if (E != E2 && E2->isLvalue(S.Context) == Expr::LV_Valid) {
1317 if (!S.getLangOptions().HeinousExtensions)
1318 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
1319 << E->getSourceRange();
1320 else
1321 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
1322 << E->getSourceRange();
1323 // Accept, even if we emitted an error diagnostic.
1324 return false;
1327 // None of the above, just randomly invalid non-lvalue.
1328 return true;
1332 StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc,
1333 bool IsSimple,
1334 bool IsVolatile,
1335 unsigned NumOutputs,
1336 unsigned NumInputs,
1337 IdentifierInfo **Names,
1338 MultiExprArg constraints,
1339 MultiExprArg exprs,
1340 Expr *asmString,
1341 MultiExprArg clobbers,
1342 SourceLocation RParenLoc,
1343 bool MSAsm) {
1344 unsigned NumClobbers = clobbers.size();
1345 StringLiteral **Constraints =
1346 reinterpret_cast<StringLiteral**>(constraints.get());
1347 Expr **Exprs = exprs.get();
1348 StringLiteral *AsmString = cast<StringLiteral>(asmString);
1349 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
1351 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1353 // The parser verifies that there is a string literal here.
1354 if (AsmString->isWide())
1355 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
1356 << AsmString->getSourceRange());
1358 for (unsigned i = 0; i != NumOutputs; i++) {
1359 StringLiteral *Literal = Constraints[i];
1360 if (Literal->isWide())
1361 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1362 << Literal->getSourceRange());
1364 llvm::StringRef OutputName;
1365 if (Names[i])
1366 OutputName = Names[i]->getName();
1368 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
1369 if (!Context.Target.validateOutputConstraint(Info))
1370 return StmtError(Diag(Literal->getLocStart(),
1371 diag::err_asm_invalid_output_constraint)
1372 << Info.getConstraintStr());
1374 // Check that the output exprs are valid lvalues.
1375 Expr *OutputExpr = Exprs[i];
1376 if (CheckAsmLValue(OutputExpr, *this)) {
1377 return StmtError(Diag(OutputExpr->getLocStart(),
1378 diag::err_asm_invalid_lvalue_in_output)
1379 << OutputExpr->getSourceRange());
1382 OutputConstraintInfos.push_back(Info);
1385 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1387 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
1388 StringLiteral *Literal = Constraints[i];
1389 if (Literal->isWide())
1390 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1391 << Literal->getSourceRange());
1393 llvm::StringRef InputName;
1394 if (Names[i])
1395 InputName = Names[i]->getName();
1397 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
1398 if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(),
1399 NumOutputs, Info)) {
1400 return StmtError(Diag(Literal->getLocStart(),
1401 diag::err_asm_invalid_input_constraint)
1402 << Info.getConstraintStr());
1405 Expr *InputExpr = Exprs[i];
1407 // Only allow void types for memory constraints.
1408 if (Info.allowsMemory() && !Info.allowsRegister()) {
1409 if (CheckAsmLValue(InputExpr, *this))
1410 return StmtError(Diag(InputExpr->getLocStart(),
1411 diag::err_asm_invalid_lvalue_in_input)
1412 << Info.getConstraintStr()
1413 << InputExpr->getSourceRange());
1416 if (Info.allowsRegister()) {
1417 if (InputExpr->getType()->isVoidType()) {
1418 return StmtError(Diag(InputExpr->getLocStart(),
1419 diag::err_asm_invalid_type_in_input)
1420 << InputExpr->getType() << Info.getConstraintStr()
1421 << InputExpr->getSourceRange());
1425 DefaultFunctionArrayLvalueConversion(Exprs[i]);
1427 InputConstraintInfos.push_back(Info);
1430 // Check that the clobbers are valid.
1431 for (unsigned i = 0; i != NumClobbers; i++) {
1432 StringLiteral *Literal = Clobbers[i];
1433 if (Literal->isWide())
1434 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1435 << Literal->getSourceRange());
1437 llvm::StringRef Clobber = Literal->getString();
1439 if (!Context.Target.isValidGCCRegisterName(Clobber))
1440 return StmtError(Diag(Literal->getLocStart(),
1441 diag::err_asm_unknown_register_name) << Clobber);
1444 AsmStmt *NS =
1445 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
1446 NumOutputs, NumInputs, Names, Constraints, Exprs,
1447 AsmString, NumClobbers, Clobbers, RParenLoc);
1448 // Validate the asm string, ensuring it makes sense given the operands we
1449 // have.
1450 llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
1451 unsigned DiagOffs;
1452 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
1453 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
1454 << AsmString->getSourceRange();
1455 return StmtError();
1458 // Validate tied input operands for type mismatches.
1459 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
1460 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1462 // If this is a tied constraint, verify that the output and input have
1463 // either exactly the same type, or that they are int/ptr operands with the
1464 // same size (int/long, int*/long, are ok etc).
1465 if (!Info.hasTiedOperand()) continue;
1467 unsigned TiedTo = Info.getTiedOperand();
1468 Expr *OutputExpr = Exprs[TiedTo];
1469 Expr *InputExpr = Exprs[i+NumOutputs];
1470 QualType InTy = InputExpr->getType();
1471 QualType OutTy = OutputExpr->getType();
1472 if (Context.hasSameType(InTy, OutTy))
1473 continue; // All types can be tied to themselves.
1475 // Decide if the input and output are in the same domain (integer/ptr or
1476 // floating point.
1477 enum AsmDomain {
1478 AD_Int, AD_FP, AD_Other
1479 } InputDomain, OutputDomain;
1481 if (InTy->isIntegerType() || InTy->isPointerType())
1482 InputDomain = AD_Int;
1483 else if (InTy->isRealFloatingType())
1484 InputDomain = AD_FP;
1485 else
1486 InputDomain = AD_Other;
1488 if (OutTy->isIntegerType() || OutTy->isPointerType())
1489 OutputDomain = AD_Int;
1490 else if (OutTy->isRealFloatingType())
1491 OutputDomain = AD_FP;
1492 else
1493 OutputDomain = AD_Other;
1495 // They are ok if they are the same size and in the same domain. This
1496 // allows tying things like:
1497 // void* to int*
1498 // void* to int if they are the same size.
1499 // double to long double if they are the same size.
1501 uint64_t OutSize = Context.getTypeSize(OutTy);
1502 uint64_t InSize = Context.getTypeSize(InTy);
1503 if (OutSize == InSize && InputDomain == OutputDomain &&
1504 InputDomain != AD_Other)
1505 continue;
1507 // If the smaller input/output operand is not mentioned in the asm string,
1508 // then we can promote it and the asm string won't notice. Check this
1509 // case now.
1510 bool SmallerValueMentioned = false;
1511 for (unsigned p = 0, e = Pieces.size(); p != e; ++p) {
1512 AsmStmt::AsmStringPiece &Piece = Pieces[p];
1513 if (!Piece.isOperand()) continue;
1515 // If this is a reference to the input and if the input was the smaller
1516 // one, then we have to reject this asm.
1517 if (Piece.getOperandNo() == i+NumOutputs) {
1518 if (InSize < OutSize) {
1519 SmallerValueMentioned = true;
1520 break;
1524 // If this is a reference to the input and if the input was the smaller
1525 // one, then we have to reject this asm.
1526 if (Piece.getOperandNo() == TiedTo) {
1527 if (InSize > OutSize) {
1528 SmallerValueMentioned = true;
1529 break;
1534 // If the smaller value wasn't mentioned in the asm string, and if the
1535 // output was a register, just extend the shorter one to the size of the
1536 // larger one.
1537 if (!SmallerValueMentioned && InputDomain != AD_Other &&
1538 OutputConstraintInfos[TiedTo].allowsRegister())
1539 continue;
1541 Diag(InputExpr->getLocStart(),
1542 diag::err_asm_tying_incompatible_types)
1543 << InTy << OutTy << OutputExpr->getSourceRange()
1544 << InputExpr->getSourceRange();
1545 return StmtError();
1548 return Owned(NS);
1551 StmtResult
1552 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
1553 SourceLocation RParen, Decl *Parm,
1554 Stmt *Body) {
1555 VarDecl *Var = cast_or_null<VarDecl>(Parm);
1556 if (Var && Var->isInvalidDecl())
1557 return StmtError();
1559 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
1562 StmtResult
1563 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
1564 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
1567 StmtResult
1568 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
1569 MultiStmtArg CatchStmts, Stmt *Finally) {
1570 getCurFunction()->setHasBranchProtectedScope();
1571 unsigned NumCatchStmts = CatchStmts.size();
1572 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
1573 CatchStmts.release(),
1574 NumCatchStmts,
1575 Finally));
1578 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc,
1579 Expr *Throw) {
1580 if (Throw) {
1581 QualType ThrowType = Throw->getType();
1582 // Make sure the expression type is an ObjC pointer or "void *".
1583 if (!ThrowType->isDependentType() &&
1584 !ThrowType->isObjCObjectPointerType()) {
1585 const PointerType *PT = ThrowType->getAs<PointerType>();
1586 if (!PT || !PT->getPointeeType()->isVoidType())
1587 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
1588 << Throw->getType() << Throw->getSourceRange());
1592 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
1595 StmtResult
1596 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
1597 Scope *CurScope) {
1598 if (!Throw) {
1599 // @throw without an expression designates a rethrow (which much occur
1600 // in the context of an @catch clause).
1601 Scope *AtCatchParent = CurScope;
1602 while (AtCatchParent && !AtCatchParent->isAtCatchScope())
1603 AtCatchParent = AtCatchParent->getParent();
1604 if (!AtCatchParent)
1605 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
1608 return BuildObjCAtThrowStmt(AtLoc, Throw);
1611 StmtResult
1612 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
1613 Stmt *SyncBody) {
1614 getCurFunction()->setHasBranchProtectedScope();
1616 // Make sure the expression type is an ObjC pointer or "void *".
1617 if (!SyncExpr->getType()->isDependentType() &&
1618 !SyncExpr->getType()->isObjCObjectPointerType()) {
1619 const PointerType *PT = SyncExpr->getType()->getAs<PointerType>();
1620 if (!PT || !PT->getPointeeType()->isVoidType())
1621 return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object)
1622 << SyncExpr->getType() << SyncExpr->getSourceRange());
1625 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
1628 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
1629 /// and creates a proper catch handler from them.
1630 StmtResult
1631 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
1632 Stmt *HandlerBlock) {
1633 // There's nothing to test that ActOnExceptionDecl didn't already test.
1634 return Owned(new (Context) CXXCatchStmt(CatchLoc,
1635 cast_or_null<VarDecl>(ExDecl),
1636 HandlerBlock));
1639 namespace {
1641 class TypeWithHandler {
1642 QualType t;
1643 CXXCatchStmt *stmt;
1644 public:
1645 TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
1646 : t(type), stmt(statement) {}
1648 // An arbitrary order is fine as long as it places identical
1649 // types next to each other.
1650 bool operator<(const TypeWithHandler &y) const {
1651 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
1652 return true;
1653 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
1654 return false;
1655 else
1656 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
1659 bool operator==(const TypeWithHandler& other) const {
1660 return t == other.t;
1663 CXXCatchStmt *getCatchStmt() const { return stmt; }
1664 SourceLocation getTypeSpecStartLoc() const {
1665 return stmt->getExceptionDecl()->getTypeSpecStartLoc();
1671 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
1672 /// handlers and creates a try statement from them.
1673 StmtResult
1674 Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
1675 MultiStmtArg RawHandlers) {
1676 unsigned NumHandlers = RawHandlers.size();
1677 assert(NumHandlers > 0 &&
1678 "The parser shouldn't call this if there are no handlers.");
1679 Stmt **Handlers = RawHandlers.get();
1681 llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers;
1683 for (unsigned i = 0; i < NumHandlers; ++i) {
1684 CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]);
1685 if (!Handler->getExceptionDecl()) {
1686 if (i < NumHandlers - 1)
1687 return StmtError(Diag(Handler->getLocStart(),
1688 diag::err_early_catch_all));
1690 continue;
1693 const QualType CaughtType = Handler->getCaughtType();
1694 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
1695 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
1698 // Detect handlers for the same type as an earlier one.
1699 if (NumHandlers > 1) {
1700 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
1702 TypeWithHandler prev = TypesWithHandlers[0];
1703 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
1704 TypeWithHandler curr = TypesWithHandlers[i];
1706 if (curr == prev) {
1707 Diag(curr.getTypeSpecStartLoc(),
1708 diag::warn_exception_caught_by_earlier_handler)
1709 << curr.getCatchStmt()->getCaughtType().getAsString();
1710 Diag(prev.getTypeSpecStartLoc(),
1711 diag::note_previous_exception_handler)
1712 << prev.getCatchStmt()->getCaughtType().getAsString();
1715 prev = curr;
1719 getCurFunction()->setHasBranchProtectedScope();
1721 // FIXME: We should detect handlers that cannot catch anything because an
1722 // earlier handler catches a superclass. Need to find a method that is not
1723 // quadratic for this.
1724 // Neither of these are explicitly forbidden, but every compiler detects them
1725 // and warns.
1727 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
1728 Handlers, NumHandlers));