SemaStmt.cpp revision 28be73f74c9e241a23ea24fe5756623de6bf1084
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.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/Stmt.h"
18#include "clang/Parse/Scope.h"
19#include "clang/Basic/TargetInfo.h"
20#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/LangOptions.h"
22#include "llvm/ADT/SmallString.h"
23using namespace clang;
24
25Sema::StmtResult Sema::ActOnExprStmt(ExprTy *expr) {
26  Expr *E = static_cast<Expr*>(expr);
27  assert(E && "ActOnExprStmt(): missing expression");
28
29  // C99 6.8.3p2: The expression in an expression statement is evaluated as a
30  // void expression for its side effects.  Conversion to void allows any
31  // operand, even incomplete types.
32
33  // Same thing in for stmt first clause (when expr) and third clause.
34  return E;
35}
36
37
38Sema::StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc) {
39  return new NullStmt(SemiLoc);
40}
41
42Sema::StmtResult Sema::ActOnDeclStmt(DeclTy *decl, SourceLocation StartLoc,
43                                     SourceLocation EndLoc) {
44  if (decl == 0)
45    return true;
46
47  ScopedDecl *SD = cast<ScopedDecl>(static_cast<Decl *>(decl));
48  return new DeclStmt(SD, StartLoc, EndLoc);
49}
50
51Action::StmtResult
52Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
53                        StmtTy **elts, unsigned NumElts, bool isStmtExpr) {
54  Stmt **Elts = reinterpret_cast<Stmt**>(elts);
55  // If we're in C89 mode, check that we don't have any decls after stmts.  If
56  // so, emit an extension diagnostic.
57  if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
58    // Note that __extension__ can be around a decl.
59    unsigned i = 0;
60    // Skip over all declarations.
61    for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
62      /*empty*/;
63
64    // We found the end of the list or a statement.  Scan for another declstmt.
65    for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
66      /*empty*/;
67
68    if (i != NumElts) {
69      ScopedDecl *D = cast<DeclStmt>(Elts[i])->getDecl();
70      Diag(D->getLocation(), diag::ext_mixed_decls_code);
71    }
72  }
73  // Warn about unused expressions in statements.
74  for (unsigned i = 0; i != NumElts; ++i) {
75    Expr *E = dyn_cast<Expr>(Elts[i]);
76    if (!E) continue;
77
78    // Warn about expressions with unused results.
79    if (E->hasLocalSideEffect() || E->getType()->isVoidType())
80      continue;
81
82    // The last expr in a stmt expr really is used.
83    if (isStmtExpr && i == NumElts-1)
84      continue;
85
86    /// DiagnoseDeadExpr - This expression is side-effect free and evaluated in
87    /// a context where the result is unused.  Emit a diagnostic to warn about
88    /// this.
89    if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
90      Diag(BO->getOperatorLoc(), diag::warn_unused_expr,
91           BO->getLHS()->getSourceRange(), BO->getRHS()->getSourceRange());
92    else if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
93      Diag(UO->getOperatorLoc(), diag::warn_unused_expr,
94           UO->getSubExpr()->getSourceRange());
95    else
96      Diag(E->getExprLoc(), diag::warn_unused_expr, E->getSourceRange());
97  }
98
99  return new CompoundStmt(Elts, NumElts, L, R);
100}
101
102Action::StmtResult
103Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprTy *lhsval,
104                    SourceLocation DotDotDotLoc, ExprTy *rhsval,
105                    SourceLocation ColonLoc, StmtTy *subStmt) {
106  Stmt *SubStmt = static_cast<Stmt*>(subStmt);
107  Expr *LHSVal = ((Expr *)lhsval), *RHSVal = ((Expr *)rhsval);
108  assert((LHSVal != 0) && "missing expression in case statement");
109
110  SourceLocation ExpLoc;
111  // C99 6.8.4.2p3: The expression shall be an integer constant.
112  if (!LHSVal->isIntegerConstantExpr(Context, &ExpLoc)) {
113    Diag(ExpLoc, diag::err_case_label_not_integer_constant_expr,
114         LHSVal->getSourceRange());
115    return SubStmt;
116  }
117
118  // GCC extension: The expression shall be an integer constant.
119  if (RHSVal && !RHSVal->isIntegerConstantExpr(Context, &ExpLoc)) {
120    Diag(ExpLoc, diag::err_case_label_not_integer_constant_expr,
121         RHSVal->getSourceRange());
122    RHSVal = 0;  // Recover by just forgetting about it.
123  }
124
125  if (SwitchStack.empty()) {
126    Diag(CaseLoc, diag::err_case_not_in_switch);
127    return SubStmt;
128  }
129
130  CaseStmt *CS = new CaseStmt(LHSVal, RHSVal, SubStmt, CaseLoc);
131  SwitchStack.back()->addSwitchCase(CS);
132  return CS;
133}
134
135Action::StmtResult
136Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
137                       StmtTy *subStmt, Scope *CurScope) {
138  Stmt *SubStmt = static_cast<Stmt*>(subStmt);
139
140  if (SwitchStack.empty()) {
141    Diag(DefaultLoc, diag::err_default_not_in_switch);
142    return SubStmt;
143  }
144
145  DefaultStmt *DS = new DefaultStmt(DefaultLoc, SubStmt);
146  SwitchStack.back()->addSwitchCase(DS);
147
148  return DS;
149}
150
151Action::StmtResult
152Sema::ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II,
153                     SourceLocation ColonLoc, StmtTy *subStmt) {
154  Stmt *SubStmt = static_cast<Stmt*>(subStmt);
155  // Look up the record for this label identifier.
156  LabelStmt *&LabelDecl = LabelMap[II];
157
158  // If not forward referenced or defined already, just create a new LabelStmt.
159  if (LabelDecl == 0)
160    return LabelDecl = new LabelStmt(IdentLoc, II, SubStmt);
161
162  assert(LabelDecl->getID() == II && "Label mismatch!");
163
164  // Otherwise, this label was either forward reference or multiply defined.  If
165  // multiply defined, reject it now.
166  if (LabelDecl->getSubStmt()) {
167    Diag(IdentLoc, diag::err_redefinition_of_label, LabelDecl->getName());
168    Diag(LabelDecl->getIdentLoc(), diag::err_previous_definition);
169    return SubStmt;
170  }
171
172  // Otherwise, this label was forward declared, and we just found its real
173  // definition.  Fill in the forward definition and return it.
174  LabelDecl->setIdentLoc(IdentLoc);
175  LabelDecl->setSubStmt(SubStmt);
176  return LabelDecl;
177}
178
179Action::StmtResult
180Sema::ActOnIfStmt(SourceLocation IfLoc, ExprTy *CondVal,
181                  StmtTy *ThenVal, SourceLocation ElseLoc,
182                  StmtTy *ElseVal) {
183  Expr *condExpr = (Expr *)CondVal;
184  Stmt *thenStmt = (Stmt *)ThenVal;
185
186  assert(condExpr && "ActOnIfStmt(): missing expression");
187
188  DefaultFunctionArrayConversion(condExpr);
189  QualType condType = condExpr->getType();
190
191  if (!condType->isScalarType()) // C99 6.8.4.1p1
192    return Diag(IfLoc, diag::err_typecheck_statement_requires_scalar,
193             condType.getAsString(), condExpr->getSourceRange());
194
195  // Warn if the if block has a null body without an else value.
196  // this helps prevent bugs due to typos, such as
197  // if (condition);
198  //   do_stuff();
199  if (!ElseVal) {
200    if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
201      Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
202  }
203
204  return new IfStmt(IfLoc, condExpr, thenStmt, (Stmt*)ElseVal);
205}
206
207Action::StmtResult
208Sema::ActOnStartOfSwitchStmt(ExprTy *cond) {
209  Expr *Cond = static_cast<Expr*>(cond);
210
211  // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
212  UsualUnaryConversions(Cond);
213
214  SwitchStmt *SS = new SwitchStmt(Cond);
215  SwitchStack.push_back(SS);
216  return SS;
217}
218
219/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
220/// the specified width and sign.  If an overflow occurs, detect it and emit
221/// the specified diagnostic.
222void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
223                                              unsigned NewWidth, bool NewSign,
224                                              SourceLocation Loc,
225                                              unsigned DiagID) {
226  // Perform a conversion to the promoted condition type if needed.
227  if (NewWidth > Val.getBitWidth()) {
228    // If this is an extension, just do it.
229    llvm::APSInt OldVal(Val);
230    Val.extend(NewWidth);
231
232    // If the input was signed and negative and the output is unsigned,
233    // warn.
234    if (!NewSign && OldVal.isSigned() && OldVal.isNegative())
235      Diag(Loc, DiagID, OldVal.toString(), Val.toString());
236
237    Val.setIsSigned(NewSign);
238  } else if (NewWidth < Val.getBitWidth()) {
239    // If this is a truncation, check for overflow.
240    llvm::APSInt ConvVal(Val);
241    ConvVal.trunc(NewWidth);
242    ConvVal.setIsSigned(NewSign);
243    ConvVal.extend(Val.getBitWidth());
244    ConvVal.setIsSigned(Val.isSigned());
245    if (ConvVal != Val)
246      Diag(Loc, DiagID, Val.toString(), ConvVal.toString());
247
248    // Regardless of whether a diagnostic was emitted, really do the
249    // truncation.
250    Val.trunc(NewWidth);
251    Val.setIsSigned(NewSign);
252  } else if (NewSign != Val.isSigned()) {
253    // Convert the sign to match the sign of the condition.  This can cause
254    // overflow as well: unsigned(INTMIN)
255    llvm::APSInt OldVal(Val);
256    Val.setIsSigned(NewSign);
257
258    if (Val.isNegative())  // Sign bit changes meaning.
259      Diag(Loc, DiagID, OldVal.toString(), Val.toString());
260  }
261}
262
263namespace {
264  struct CaseCompareFunctor {
265    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
266                    const llvm::APSInt &RHS) {
267      return LHS.first < RHS;
268    }
269    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
270                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
271      return LHS.first < RHS.first;
272    }
273    bool operator()(const llvm::APSInt &LHS,
274                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
275      return LHS < RHS.first;
276    }
277  };
278}
279
280/// CmpCaseVals - Comparison predicate for sorting case values.
281///
282static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
283                        const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
284  if (lhs.first < rhs.first)
285    return true;
286
287  if (lhs.first == rhs.first &&
288      lhs.second->getCaseLoc().getRawEncoding()
289       < rhs.second->getCaseLoc().getRawEncoding())
290    return true;
291  return false;
292}
293
294Action::StmtResult
295Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, StmtTy *Switch,
296                            ExprTy *Body) {
297  Stmt *BodyStmt = (Stmt*)Body;
298
299  SwitchStmt *SS = SwitchStack.back();
300  assert(SS == (SwitchStmt*)Switch && "switch stack missing push/pop!");
301
302  SS->setBody(BodyStmt, SwitchLoc);
303  SwitchStack.pop_back();
304
305  Expr *CondExpr = SS->getCond();
306  QualType CondType = CondExpr->getType();
307
308  if (!CondType->isIntegerType()) { // C99 6.8.4.2p1
309    Diag(SwitchLoc, diag::err_typecheck_statement_requires_integer,
310         CondType.getAsString(), CondExpr->getSourceRange());
311    return true;
312  }
313
314  // Get the bitwidth of the switched-on value before promotions.  We must
315  // convert the integer case values to this width before comparison.
316  unsigned CondWidth = static_cast<unsigned>(Context.getTypeSize(CondType));
317  bool CondIsSigned = CondType->isSignedIntegerType();
318
319  // Accumulate all of the case values in a vector so that we can sort them
320  // and detect duplicates.  This vector contains the APInt for the case after
321  // it has been converted to the condition type.
322  typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
323  CaseValsTy CaseVals;
324
325  // Keep track of any GNU case ranges we see.  The APSInt is the low value.
326  std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRanges;
327
328  DefaultStmt *TheDefaultStmt = 0;
329
330  bool CaseListIsErroneous = false;
331
332  for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
333       SC = SC->getNextSwitchCase()) {
334
335    if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
336      if (TheDefaultStmt) {
337        Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
338        Diag(TheDefaultStmt->getDefaultLoc(), diag::err_first_label);
339
340        // FIXME: Remove the default statement from the switch block so that
341        // we'll return a valid AST.  This requires recursing down the
342        // AST and finding it, not something we are set up to do right now.  For
343        // now, just lop the entire switch stmt out of the AST.
344        CaseListIsErroneous = true;
345      }
346      TheDefaultStmt = DS;
347
348    } else {
349      CaseStmt *CS = cast<CaseStmt>(SC);
350
351      // We already verified that the expression has a i-c-e value (C99
352      // 6.8.4.2p3) - get that value now.
353      llvm::APSInt LoVal(32);
354      Expr *Lo = CS->getLHS();
355      Lo->isIntegerConstantExpr(LoVal, Context);
356
357      // Convert the value to the same width/sign as the condition.
358      ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
359                                         CS->getLHS()->getLocStart(),
360                                         diag::warn_case_value_overflow);
361
362      // If the LHS is not the same type as the condition, insert an implicit
363      // cast.
364      ImpCastExprToType(Lo, CondType);
365      CS->setLHS(Lo);
366
367      // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
368      if (CS->getRHS())
369        CaseRanges.push_back(std::make_pair(LoVal, CS));
370      else
371        CaseVals.push_back(std::make_pair(LoVal, CS));
372    }
373  }
374
375  // Sort all the scalar case values so we can easily detect duplicates.
376  std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
377
378  if (!CaseVals.empty()) {
379    for (unsigned i = 0, e = CaseVals.size()-1; i != e; ++i) {
380      if (CaseVals[i].first == CaseVals[i+1].first) {
381        // If we have a duplicate, report it.
382        Diag(CaseVals[i+1].second->getLHS()->getLocStart(),
383             diag::err_duplicate_case, CaseVals[i].first.toString());
384        Diag(CaseVals[i].second->getLHS()->getLocStart(),
385             diag::err_duplicate_case_prev);
386        // FIXME: We really want to remove the bogus case stmt from the substmt,
387        // but we have no way to do this right now.
388        CaseListIsErroneous = true;
389      }
390    }
391  }
392
393  // Detect duplicate case ranges, which usually don't exist at all in the first
394  // place.
395  if (!CaseRanges.empty()) {
396    // Sort all the case ranges by their low value so we can easily detect
397    // overlaps between ranges.
398    std::stable_sort(CaseRanges.begin(), CaseRanges.end());
399
400    // Scan the ranges, computing the high values and removing empty ranges.
401    std::vector<llvm::APSInt> HiVals;
402    for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
403      CaseStmt *CR = CaseRanges[i].second;
404      llvm::APSInt HiVal(32);
405      Expr *Hi = CR->getRHS();
406      Hi->isIntegerConstantExpr(HiVal, Context);
407
408      // Convert the value to the same width/sign as the condition.
409      ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
410                                         CR->getRHS()->getLocStart(),
411                                         diag::warn_case_value_overflow);
412
413      // If the LHS is not the same type as the condition, insert an implicit
414      // cast.
415      ImpCastExprToType(Hi, CondType);
416      CR->setRHS(Hi);
417
418      // If the low value is bigger than the high value, the case is empty.
419      if (CaseRanges[i].first > HiVal) {
420        Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range,
421             SourceRange(CR->getLHS()->getLocStart(),
422                         CR->getRHS()->getLocEnd()));
423        CaseRanges.erase(CaseRanges.begin()+i);
424        --i, --e;
425        continue;
426      }
427      HiVals.push_back(HiVal);
428    }
429
430    // Rescan the ranges, looking for overlap with singleton values and other
431    // ranges.  Since the range list is sorted, we only need to compare case
432    // ranges with their neighbors.
433    for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
434      llvm::APSInt &CRLo = CaseRanges[i].first;
435      llvm::APSInt &CRHi = HiVals[i];
436      CaseStmt *CR = CaseRanges[i].second;
437
438      // Check to see whether the case range overlaps with any singleton cases.
439      CaseStmt *OverlapStmt = 0;
440      llvm::APSInt OverlapVal(32);
441
442      // Find the smallest value >= the lower bound.  If I is in the case range,
443      // then we have overlap.
444      CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
445                                                CaseVals.end(), CRLo,
446                                                CaseCompareFunctor());
447      if (I != CaseVals.end() && I->first < CRHi) {
448        OverlapVal  = I->first;   // Found overlap with scalar.
449        OverlapStmt = I->second;
450      }
451
452      // Find the smallest value bigger than the upper bound.
453      I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
454      if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
455        OverlapVal  = (I-1)->first;      // Found overlap with scalar.
456        OverlapStmt = (I-1)->second;
457      }
458
459      // Check to see if this case stmt overlaps with the subsequent case range.
460      if (i && CRLo <= HiVals[i-1]) {
461        OverlapVal  = HiVals[i-1];       // Found overlap with range.
462        OverlapStmt = CaseRanges[i-1].second;
463      }
464
465      if (OverlapStmt) {
466        // If we have a duplicate, report it.
467        Diag(CR->getLHS()->getLocStart(),
468             diag::err_duplicate_case, OverlapVal.toString());
469        Diag(OverlapStmt->getLHS()->getLocStart(),
470             diag::err_duplicate_case_prev);
471        // FIXME: We really want to remove the bogus case stmt from the substmt,
472        // but we have no way to do this right now.
473        CaseListIsErroneous = true;
474      }
475    }
476  }
477
478  // FIXME: If the case list was broken is some way, we don't have a good system
479  // to patch it up.  Instead, just return the whole substmt as broken.
480  if (CaseListIsErroneous)
481    return true;
482
483  return SS;
484}
485
486Action::StmtResult
487Sema::ActOnWhileStmt(SourceLocation WhileLoc, ExprTy *Cond, StmtTy *Body) {
488  Expr *condExpr = (Expr *)Cond;
489  assert(condExpr && "ActOnWhileStmt(): missing expression");
490
491  DefaultFunctionArrayConversion(condExpr);
492  QualType condType = condExpr->getType();
493
494  if (!condType->isScalarType()) // C99 6.8.5p2
495    return Diag(WhileLoc, diag::err_typecheck_statement_requires_scalar,
496             condType.getAsString(), condExpr->getSourceRange());
497
498  return new WhileStmt(condExpr, (Stmt*)Body, WhileLoc);
499}
500
501Action::StmtResult
502Sema::ActOnDoStmt(SourceLocation DoLoc, StmtTy *Body,
503                  SourceLocation WhileLoc, ExprTy *Cond) {
504  Expr *condExpr = (Expr *)Cond;
505  assert(condExpr && "ActOnDoStmt(): missing expression");
506
507  DefaultFunctionArrayConversion(condExpr);
508  QualType condType = condExpr->getType();
509
510  if (!condType->isScalarType()) // C99 6.8.5p2
511    return Diag(DoLoc, diag::err_typecheck_statement_requires_scalar,
512             condType.getAsString(), condExpr->getSourceRange());
513
514  return new DoStmt((Stmt*)Body, condExpr, DoLoc);
515}
516
517Action::StmtResult
518Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
519                   StmtTy *first, ExprTy *second, ExprTy *third,
520                   SourceLocation RParenLoc, StmtTy *body) {
521  Stmt *First  = static_cast<Stmt*>(first);
522  Expr *Second = static_cast<Expr*>(second);
523  Expr *Third  = static_cast<Expr*>(third);
524  Stmt *Body  = static_cast<Stmt*>(body);
525
526  if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
527    // C99 6.8.5p3: The declaration part of a 'for' statement shall only declare
528    // identifiers for objects having storage class 'auto' or 'register'.
529    for (ScopedDecl *D = DS->getDecl(); D; D = D->getNextDeclarator()) {
530      VarDecl *VD = dyn_cast<VarDecl>(D);
531      if (VD && VD->isBlockVarDecl() && !VD->hasLocalStorage())
532        VD = 0;
533      if (VD == 0)
534        Diag(dyn_cast<ScopedDecl>(D)->getLocation(),
535             diag::err_non_variable_decl_in_for);
536      // FIXME: mark decl erroneous!
537    }
538  }
539  if (Second) {
540    DefaultFunctionArrayConversion(Second);
541    QualType SecondType = Second->getType();
542
543    if (!SecondType->isScalarType()) // C99 6.8.5p2
544      return Diag(ForLoc, diag::err_typecheck_statement_requires_scalar,
545                  SecondType.getAsString(), Second->getSourceRange());
546  }
547  return new ForStmt(First, Second, Third, Body, ForLoc);
548}
549
550Action::StmtResult
551Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
552                                 SourceLocation LParenLoc,
553                                 StmtTy *first, ExprTy *second,
554                                 SourceLocation RParenLoc, StmtTy *body) {
555  Stmt *First  = static_cast<Stmt*>(first);
556  Expr *Second = static_cast<Expr*>(second);
557  Stmt *Body  = static_cast<Stmt*>(body);
558  if (First) {
559    QualType FirstType;
560    if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
561      FirstType = cast<ValueDecl>(DS->getDecl())->getType();
562      // C99 6.8.5p3: The declaration part of a 'for' statement shall only declare
563      // identifiers for objects having storage class 'auto' or 'register'.
564      ScopedDecl *D = DS->getDecl();
565      VarDecl *VD = cast<VarDecl>(D);
566      if (VD->isBlockVarDecl() && !VD->hasLocalStorage())
567        return Diag(VD->getLocation(), diag::err_non_variable_decl_in_for);
568      if (D->getNextDeclarator())
569        return Diag(D->getLocation(), diag::err_toomany_element_decls);
570    } else
571      FirstType = static_cast<Expr*>(first)->getType();
572    if (!Context.isObjCObjectPointerType(FirstType))
573        Diag(ForLoc, diag::err_selector_element_type,
574             FirstType.getAsString(), First->getSourceRange());
575  }
576  if (Second) {
577    DefaultFunctionArrayConversion(Second);
578    QualType SecondType = Second->getType();
579    if (!Context.isObjCObjectPointerType(SecondType))
580      Diag(ForLoc, diag::err_collection_expr_type,
581           SecondType.getAsString(), Second->getSourceRange());
582  }
583  return new ObjCForCollectionStmt(First, Second, Body, ForLoc, RParenLoc);
584}
585
586Action::StmtResult
587Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
588                    IdentifierInfo *LabelII) {
589  // Look up the record for this label identifier.
590  LabelStmt *&LabelDecl = LabelMap[LabelII];
591
592  // If we haven't seen this label yet, create a forward reference.
593  if (LabelDecl == 0)
594    LabelDecl = new LabelStmt(LabelLoc, LabelII, 0);
595
596  return new GotoStmt(LabelDecl, GotoLoc, LabelLoc);
597}
598
599Action::StmtResult
600Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc,SourceLocation StarLoc,
601                            ExprTy *DestExp) {
602  // FIXME: Verify that the operand is convertible to void*.
603
604  return new IndirectGotoStmt((Expr*)DestExp);
605}
606
607Action::StmtResult
608Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
609  Scope *S = CurScope->getContinueParent();
610  if (!S) {
611    // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
612    Diag(ContinueLoc, diag::err_continue_not_in_loop);
613    return true;
614  }
615
616  return new ContinueStmt(ContinueLoc);
617}
618
619Action::StmtResult
620Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
621  Scope *S = CurScope->getBreakParent();
622  if (!S) {
623    // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
624    Diag(BreakLoc, diag::err_break_not_in_loop_or_switch);
625    return true;
626  }
627
628  return new BreakStmt(BreakLoc);
629}
630
631
632Action::StmtResult
633Sema::ActOnReturnStmt(SourceLocation ReturnLoc, ExprTy *rex) {
634  Expr *RetValExp = static_cast<Expr *>(rex);
635  QualType FnRetType =
636        getCurFunctionDecl() ? getCurFunctionDecl()->getResultType() :
637                               getCurMethodDecl()->getResultType();
638
639  if (FnRetType->isVoidType()) {
640    if (RetValExp) // C99 6.8.6.4p1 (ext_ since GCC warns)
641      Diag(ReturnLoc, diag::ext_return_has_expr,
642           ( getCurFunctionDecl() ?
643                getCurFunctionDecl()->getIdentifier()->getName() :
644                getCurMethodDecl()->getSelector().getName()       ),
645           RetValExp->getSourceRange());
646    return new ReturnStmt(ReturnLoc, RetValExp);
647  } else {
648    if (!RetValExp) {
649      const char *funcName =
650                getCurFunctionDecl() ?
651                   getCurFunctionDecl()->getIdentifier()->getName() :
652                   getCurMethodDecl()->getSelector().getName().c_str();
653      if (getLangOptions().C99)  // C99 6.8.6.4p1 (ext_ since GCC warns)
654        Diag(ReturnLoc, diag::ext_return_missing_expr, funcName);
655      else  // C90 6.6.6.4p4
656        Diag(ReturnLoc, diag::warn_return_missing_expr, funcName);
657      return new ReturnStmt(ReturnLoc, (Expr*)0);
658    }
659  }
660  // we have a non-void function with an expression, continue checking
661  QualType RetValType = RetValExp->getType();
662
663  // C99 6.8.6.4p3(136): The return statement is not an assignment. The
664  // overlap restriction of subclause 6.5.16.1 does not apply to the case of
665  // function return.
666  AssignConvertType ConvTy = CheckSingleAssignmentConstraints(FnRetType,
667                                                              RetValExp);
668  if (DiagnoseAssignmentResult(ConvTy, ReturnLoc, FnRetType,
669                               RetValType, RetValExp, "returning"))
670    return true;
671
672  if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
673
674  return new ReturnStmt(ReturnLoc, (Expr*)RetValExp);
675}
676
677Sema::StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc,
678                                    bool IsSimple,
679                                    bool IsVolatile,
680                                    unsigned NumOutputs,
681                                    unsigned NumInputs,
682                                    std::string *Names,
683                                    ExprTy **Constraints,
684                                    ExprTy **Exprs,
685                                    ExprTy *asmString,
686                                    unsigned NumClobbers,
687                                    ExprTy **Clobbers,
688                                    SourceLocation RParenLoc) {
689  // The parser verifies that there is a string literal here.
690  StringLiteral *AsmString = cast<StringLiteral>((Expr *)asmString);
691  if (AsmString->isWide())
692    // FIXME: We currently leak memory here.
693    return Diag(AsmString->getLocStart(), diag::err_asm_wide_character,
694                AsmString->getSourceRange());
695
696
697  for (unsigned i = 0; i < NumOutputs; i++) {
698    StringLiteral *Literal = cast<StringLiteral>((Expr *)Constraints[i]);
699    if (Literal->isWide())
700      // FIXME: We currently leak memory here.
701      return Diag(Literal->getLocStart(), diag::err_asm_wide_character,
702                  Literal->getSourceRange());
703
704    std::string OutputConstraint(Literal->getStrData(),
705                                 Literal->getByteLength());
706
707    TargetInfo::ConstraintInfo info;
708    if (!Context.Target.validateOutputConstraint(OutputConstraint.c_str(),info))
709      // FIXME: We currently leak memory here.
710      return Diag(Literal->getLocStart(),
711                  diag::err_invalid_output_constraint_in_asm);
712
713    // Check that the output exprs are valid lvalues.
714    Expr *OutputExpr = (Expr *)Exprs[i];
715    Expr::isLvalueResult Result = OutputExpr->isLvalue(Context);
716    if (Result != Expr::LV_Valid) {
717      ParenExpr *PE = cast<ParenExpr>(OutputExpr);
718
719      // FIXME: We currently leak memory here.
720      return Diag(PE->getSubExpr()->getLocStart(),
721                  diag::err_invalid_lvalue_in_asm_output,
722                  PE->getSubExpr()->getSourceRange());
723    }
724  }
725
726  for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
727    StringLiteral *Literal = cast<StringLiteral>((Expr *)Constraints[i]);
728    if (Literal->isWide())
729      // FIXME: We currently leak memory here.
730      return Diag(Literal->getLocStart(), diag::err_asm_wide_character,
731                  Literal->getSourceRange());
732
733    std::string InputConstraint(Literal->getStrData(),
734                                Literal->getByteLength());
735
736    TargetInfo::ConstraintInfo info;
737    if (!Context.Target.validateInputConstraint(InputConstraint.c_str(),
738                                                NumOutputs,
739                                                info)) {
740      // FIXME: We currently leak memory here.
741      return Diag(Literal->getLocStart(),
742                  diag::err_invalid_input_constraint_in_asm);
743    }
744
745    // Check that the input exprs aren't of type void.
746    Expr *InputExpr = (Expr *)Exprs[i];
747    if (InputExpr->getType()->isVoidType()) {
748      ParenExpr *PE = cast<ParenExpr>(InputExpr);
749
750      // FIXME: We currently leak memory here.
751      return Diag(PE->getSubExpr()->getLocStart(),
752                  diag::err_invalid_type_in_asm_input,
753                  PE->getType().getAsString(),
754                  PE->getSubExpr()->getSourceRange());
755    }
756  }
757
758  // Check that the clobbers are valid.
759  for (unsigned i = 0; i < NumClobbers; i++) {
760    StringLiteral *Literal = cast<StringLiteral>((Expr *)Clobbers[i]);
761    if (Literal->isWide())
762      // FIXME: We currently leak memory here.
763      return Diag(Literal->getLocStart(), diag::err_asm_wide_character,
764                  Literal->getSourceRange());
765
766    llvm::SmallString<16> Clobber(Literal->getStrData(),
767                                  Literal->getStrData() +
768                                  Literal->getByteLength());
769
770    if (!Context.Target.isValidGCCRegisterName(Clobber.c_str()))
771      // FIXME: We currently leak memory here.
772      return Diag(Literal->getLocStart(),
773                  diag::err_unknown_register_name_in_asm, Clobber.c_str());
774  }
775
776  return new AsmStmt(AsmLoc,
777                     IsSimple,
778                     IsVolatile,
779                     NumOutputs,
780                     NumInputs,
781                     Names,
782                     reinterpret_cast<StringLiteral**>(Constraints),
783                     reinterpret_cast<Expr**>(Exprs),
784                     AsmString, NumClobbers,
785                     reinterpret_cast<StringLiteral**>(Clobbers),
786                     RParenLoc);
787}
788
789Action::StmtResult
790Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
791                           SourceLocation RParen, StmtTy *Parm,
792                           StmtTy *Body, StmtTy *CatchList) {
793  ObjCAtCatchStmt *CS = new ObjCAtCatchStmt(AtLoc, RParen,
794    static_cast<Stmt*>(Parm), static_cast<Stmt*>(Body),
795    static_cast<Stmt*>(CatchList));
796  return CatchList ? CatchList : CS;
797}
798
799Action::StmtResult
800Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, StmtTy *Body) {
801  ObjCAtFinallyStmt *FS = new ObjCAtFinallyStmt(AtLoc,
802                                                static_cast<Stmt*>(Body));
803  return FS;
804}
805
806Action::StmtResult
807Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc,
808                         StmtTy *Try, StmtTy *Catch, StmtTy *Finally) {
809  ObjCAtTryStmt *TS = new ObjCAtTryStmt(AtLoc, static_cast<Stmt*>(Try),
810                                        static_cast<Stmt*>(Catch),
811                                        static_cast<Stmt*>(Finally));
812  return TS;
813}
814
815Action::StmtResult
816Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, StmtTy *Throw) {
817  ObjCAtThrowStmt *TS = new ObjCAtThrowStmt(AtLoc, static_cast<Stmt*>(Throw));
818  return TS;
819}
820
821Action::StmtResult
822Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, ExprTy *SynchExpr,
823                                  StmtTy *SynchBody) {
824  ObjCAtSynchronizedStmt *SS = new ObjCAtSynchronizedStmt(AtLoc,
825    static_cast<Stmt*>(SynchExpr), static_cast<Stmt*>(SynchBody));
826  return SS;
827}
828