SemaStmt.cpp revision 3f1172d26f28f44501d422546566ac29a7c656d0
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/APValue.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/AST/StmtObjC.h"
21#include "clang/AST/StmtCXX.h"
22#include "clang/Lex/Preprocessor.h"
23#include "clang/Basic/TargetInfo.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/SmallVector.h"
26using namespace clang;
27
28Sema::OwningStmtResult Sema::ActOnExprStmt(FullExprArg expr) {
29  Expr *E = expr->takeAs<Expr>();
30  assert(E && "ActOnExprStmt(): missing expression");
31  if (E->getType()->isObjCInterfaceType()) {
32    if (LangOpts.ObjCNonFragileABI)
33      Diag(E->getLocEnd(), diag::err_indirection_requires_nonfragile_object)
34             << E->getType();
35    else
36      Diag(E->getLocEnd(), diag::err_direct_interface_unsupported)
37             << E->getType();
38    return StmtError();
39  }
40  // C99 6.8.3p2: The expression in an expression statement is evaluated as a
41  // void expression for its side effects.  Conversion to void allows any
42  // operand, even incomplete types.
43
44  // Same thing in for stmt first clause (when expr) and third clause.
45  return Owned(static_cast<Stmt*>(E));
46}
47
48
49Sema::OwningStmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc) {
50  return Owned(new (Context) NullStmt(SemiLoc));
51}
52
53Sema::OwningStmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg,
54                                           SourceLocation StartLoc,
55                                           SourceLocation EndLoc) {
56  DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
57
58  // If we have an invalid decl, just return an error.
59  if (DG.isNull()) return StmtError();
60
61  return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
62}
63
64void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
65  DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
66
67  // If we have an invalid decl, just return.
68  if (DG.isNull() || !DG.isSingleDecl()) return;
69  // suppress any potential 'unused variable' warning.
70  DG.getSingleDecl()->setUsed();
71}
72
73void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
74  const Expr *E = dyn_cast_or_null<Expr>(S);
75  if (!E)
76    return;
77
78  // Ignore expressions that have void type.
79  if (E->getType()->isVoidType())
80    return;
81
82  SourceLocation Loc;
83  SourceRange R1, R2;
84  if (!E->isUnusedResultAWarning(Loc, R1, R2, Context))
85    return;
86
87  // Okay, we have an unused result.  Depending on what the base expression is,
88  // we might want to make a more specific diagnostic.  Check for one of these
89  // cases now.
90  unsigned DiagID = diag::warn_unused_expr;
91  E = E->IgnoreParens();
92  if (isa<ObjCImplicitSetterGetterRefExpr>(E))
93    DiagID = diag::warn_unused_property_expr;
94
95  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
96    // If the callee has attribute pure, const, or warn_unused_result, warn with
97    // a more specific message to make it clear what is happening.
98    if (const FunctionDecl *FD = CE->getDirectCallee()) {
99      if (FD->getAttr<WarnUnusedResultAttr>()) {
100        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result";
101        return;
102      }
103      if (FD->getAttr<PureAttr>()) {
104        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
105        return;
106      }
107      if (FD->getAttr<ConstAttr>()) {
108        Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
109        return;
110      }
111    }
112  }
113
114  Diag(Loc, DiagID) << R1 << R2;
115}
116
117Action::OwningStmtResult
118Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
119                        MultiStmtArg elts, bool isStmtExpr) {
120  unsigned NumElts = elts.size();
121  Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
122  // If we're in C89 mode, check that we don't have any decls after stmts.  If
123  // so, emit an extension diagnostic.
124  if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) {
125    // Note that __extension__ can be around a decl.
126    unsigned i = 0;
127    // Skip over all declarations.
128    for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
129      /*empty*/;
130
131    // We found the end of the list or a statement.  Scan for another declstmt.
132    for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
133      /*empty*/;
134
135    if (i != NumElts) {
136      Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
137      Diag(D->getLocation(), diag::ext_mixed_decls_code);
138    }
139  }
140  // Warn about unused expressions in statements.
141  for (unsigned i = 0; i != NumElts; ++i) {
142    // Ignore statements that are last in a statement expression.
143    if (isStmtExpr && i == NumElts - 1)
144      continue;
145
146    DiagnoseUnusedExprResult(Elts[i]);
147  }
148
149  return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
150}
151
152Action::OwningStmtResult
153Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprArg lhsval,
154                    SourceLocation DotDotDotLoc, ExprArg rhsval,
155                    SourceLocation ColonLoc) {
156  assert((lhsval.get() != 0) && "missing expression in case statement");
157
158  // C99 6.8.4.2p3: The expression shall be an integer constant.
159  // However, GCC allows any evaluatable integer expression.
160  Expr *LHSVal = static_cast<Expr*>(lhsval.get());
161  if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() &&
162      VerifyIntegerConstantExpression(LHSVal))
163    return StmtError();
164
165  // GCC extension: The expression shall be an integer constant.
166
167  Expr *RHSVal = static_cast<Expr*>(rhsval.get());
168  if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() &&
169      VerifyIntegerConstantExpression(RHSVal)) {
170    RHSVal = 0;  // Recover by just forgetting about it.
171    rhsval = 0;
172  }
173
174  if (getSwitchStack().empty()) {
175    Diag(CaseLoc, diag::err_case_not_in_switch);
176    return StmtError();
177  }
178
179  // Only now release the smart pointers.
180  lhsval.release();
181  rhsval.release();
182  CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
183                                        ColonLoc);
184  getSwitchStack().back()->addSwitchCase(CS);
185  return Owned(CS);
186}
187
188/// ActOnCaseStmtBody - This installs a statement as the body of a case.
189void Sema::ActOnCaseStmtBody(StmtTy *caseStmt, StmtArg subStmt) {
190  CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
191  Stmt *SubStmt = subStmt.takeAs<Stmt>();
192  CS->setSubStmt(SubStmt);
193}
194
195Action::OwningStmtResult
196Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
197                       StmtArg subStmt, Scope *CurScope) {
198  Stmt *SubStmt = subStmt.takeAs<Stmt>();
199
200  if (getSwitchStack().empty()) {
201    Diag(DefaultLoc, diag::err_default_not_in_switch);
202    return Owned(SubStmt);
203  }
204
205  DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
206  getSwitchStack().back()->addSwitchCase(DS);
207  return Owned(DS);
208}
209
210Action::OwningStmtResult
211Sema::ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II,
212                     SourceLocation ColonLoc, StmtArg subStmt) {
213  Stmt *SubStmt = subStmt.takeAs<Stmt>();
214  // Look up the record for this label identifier.
215  LabelStmt *&LabelDecl = getLabelMap()[II];
216
217  // If not forward referenced or defined already, just create a new LabelStmt.
218  if (LabelDecl == 0)
219    return Owned(LabelDecl = new (Context) LabelStmt(IdentLoc, II, SubStmt));
220
221  assert(LabelDecl->getID() == II && "Label mismatch!");
222
223  // Otherwise, this label was either forward reference or multiply defined.  If
224  // multiply defined, reject it now.
225  if (LabelDecl->getSubStmt()) {
226    Diag(IdentLoc, diag::err_redefinition_of_label) << LabelDecl->getID();
227    Diag(LabelDecl->getIdentLoc(), diag::note_previous_definition);
228    return Owned(SubStmt);
229  }
230
231  // Otherwise, this label was forward declared, and we just found its real
232  // definition.  Fill in the forward definition and return it.
233  LabelDecl->setIdentLoc(IdentLoc);
234  LabelDecl->setSubStmt(SubStmt);
235  return Owned(LabelDecl);
236}
237
238Action::OwningStmtResult
239Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, DeclPtrTy CondVar,
240                  StmtArg ThenVal, SourceLocation ElseLoc,
241                  StmtArg ElseVal) {
242  OwningExprResult CondResult(CondVal.release());
243
244  VarDecl *ConditionVar = 0;
245  if (CondVar.get()) {
246    ConditionVar = CondVar.getAs<VarDecl>();
247    CondResult = CheckConditionVariable(ConditionVar);
248    if (CondResult.isInvalid())
249      return StmtError();
250  }
251  Expr *ConditionExpr = CondResult.takeAs<Expr>();
252  if (!ConditionExpr)
253    return StmtError();
254
255  if (CheckBooleanCondition(ConditionExpr, IfLoc)) {
256    CondResult = ConditionExpr;
257    return StmtError();
258  }
259
260  Stmt *thenStmt = ThenVal.takeAs<Stmt>();
261  DiagnoseUnusedExprResult(thenStmt);
262
263  // Warn if the if block has a null body without an else value.
264  // this helps prevent bugs due to typos, such as
265  // if (condition);
266  //   do_stuff();
267  if (!ElseVal.get()) {
268    if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt))
269      Diag(stmt->getSemiLoc(), diag::warn_empty_if_body);
270  }
271
272  Stmt *elseStmt = ElseVal.takeAs<Stmt>();
273  DiagnoseUnusedExprResult(elseStmt);
274
275  CondResult.release();
276  return Owned(new (Context) IfStmt(IfLoc, ConditionVar, ConditionExpr,
277                                    thenStmt, ElseLoc, elseStmt));
278}
279
280Action::OwningStmtResult
281Sema::ActOnStartOfSwitchStmt(FullExprArg cond, DeclPtrTy CondVar) {
282  OwningExprResult CondResult(cond.release());
283
284  VarDecl *ConditionVar = 0;
285  if (CondVar.get()) {
286    ConditionVar = CondVar.getAs<VarDecl>();
287    CondResult = CheckConditionVariable(ConditionVar);
288    if (CondResult.isInvalid())
289      return StmtError();
290  }
291  SwitchStmt *SS = new (Context) SwitchStmt(ConditionVar,
292                                            CondResult.takeAs<Expr>());
293  getSwitchStack().push_back(SS);
294  return Owned(SS);
295}
296
297/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
298/// the specified width and sign.  If an overflow occurs, detect it and emit
299/// the specified diagnostic.
300void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
301                                              unsigned NewWidth, bool NewSign,
302                                              SourceLocation Loc,
303                                              unsigned DiagID) {
304  // Perform a conversion to the promoted condition type if needed.
305  if (NewWidth > Val.getBitWidth()) {
306    // If this is an extension, just do it.
307    llvm::APSInt OldVal(Val);
308    Val.extend(NewWidth);
309
310    // If the input was signed and negative and the output is unsigned,
311    // warn.
312    if (!NewSign && OldVal.isSigned() && OldVal.isNegative())
313      Diag(Loc, DiagID) << OldVal.toString(10) << Val.toString(10);
314
315    Val.setIsSigned(NewSign);
316  } else if (NewWidth < Val.getBitWidth()) {
317    // If this is a truncation, check for overflow.
318    llvm::APSInt ConvVal(Val);
319    ConvVal.trunc(NewWidth);
320    ConvVal.setIsSigned(NewSign);
321    ConvVal.extend(Val.getBitWidth());
322    ConvVal.setIsSigned(Val.isSigned());
323    if (ConvVal != Val)
324      Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
325
326    // Regardless of whether a diagnostic was emitted, really do the
327    // truncation.
328    Val.trunc(NewWidth);
329    Val.setIsSigned(NewSign);
330  } else if (NewSign != Val.isSigned()) {
331    // Convert the sign to match the sign of the condition.  This can cause
332    // overflow as well: unsigned(INTMIN)
333    llvm::APSInt OldVal(Val);
334    Val.setIsSigned(NewSign);
335
336    if (Val.isNegative())  // Sign bit changes meaning.
337      Diag(Loc, DiagID) << OldVal.toString(10) << Val.toString(10);
338  }
339}
340
341namespace {
342  struct CaseCompareFunctor {
343    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
344                    const llvm::APSInt &RHS) {
345      return LHS.first < RHS;
346    }
347    bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
348                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
349      return LHS.first < RHS.first;
350    }
351    bool operator()(const llvm::APSInt &LHS,
352                    const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
353      return LHS < RHS.first;
354    }
355  };
356}
357
358/// CmpCaseVals - Comparison predicate for sorting case values.
359///
360static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
361                        const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
362  if (lhs.first < rhs.first)
363    return true;
364
365  if (lhs.first == rhs.first &&
366      lhs.second->getCaseLoc().getRawEncoding()
367       < rhs.second->getCaseLoc().getRawEncoding())
368    return true;
369  return false;
370}
371
372/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
373/// potentially integral-promoted expression @p expr.
374static QualType GetTypeBeforeIntegralPromotion(const Expr* expr) {
375  const ImplicitCastExpr *ImplicitCast =
376      dyn_cast_or_null<ImplicitCastExpr>(expr);
377  if (ImplicitCast != NULL) {
378    const Expr *ExprBeforePromotion = ImplicitCast->getSubExpr();
379    QualType TypeBeforePromotion = ExprBeforePromotion->getType();
380    if (TypeBeforePromotion->isIntegralType()) {
381      return TypeBeforePromotion;
382    }
383  }
384  return expr->getType();
385}
386
387/// \brief Check (and possibly convert) the condition in a switch
388/// statement in C++.
389static bool CheckCXXSwitchCondition(Sema &S, SourceLocation SwitchLoc,
390                                    Expr *&CondExpr) {
391  if (CondExpr->isTypeDependent())
392    return false;
393
394  QualType CondType = CondExpr->getType();
395
396  // C++ 6.4.2.p2:
397  // The condition shall be of integral type, enumeration type, or of a class
398  // type for which a single conversion function to integral or enumeration
399  // type exists (12.3). If the condition is of class type, the condition is
400  // converted by calling that conversion function, and the result of the
401  // conversion is used in place of the original condition for the remainder
402  // of this section. Integral promotions are performed.
403
404  // Make sure that the condition expression has a complete type,
405  // otherwise we'll never find any conversions.
406  if (S.RequireCompleteType(SwitchLoc, CondType,
407                            PDiag(diag::err_switch_incomplete_class_type)
408                              << CondExpr->getSourceRange()))
409    return true;
410
411  llvm::SmallVector<CXXConversionDecl *, 4> ViableConversions;
412  llvm::SmallVector<CXXConversionDecl *, 4> ExplicitConversions;
413  if (const RecordType *RecordTy = CondType->getAs<RecordType>()) {
414    const UnresolvedSet *Conversions
415      = cast<CXXRecordDecl>(RecordTy->getDecl())
416                                             ->getVisibleConversionFunctions();
417    for (UnresolvedSet::iterator I = Conversions->begin(),
418           E = Conversions->end(); I != E; ++I) {
419      if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(*I))
420        if (Conversion->getConversionType().getNonReferenceType()
421              ->isIntegralType()) {
422          if (Conversion->isExplicit())
423            ExplicitConversions.push_back(Conversion);
424          else
425          ViableConversions.push_back(Conversion);
426        }
427    }
428
429    switch (ViableConversions.size()) {
430    case 0:
431      if (ExplicitConversions.size() == 1) {
432        // The user probably meant to invoke the given explicit
433        // conversion; use it.
434        QualType ConvTy
435          = ExplicitConversions[0]->getConversionType()
436                        .getNonReferenceType();
437        std::string TypeStr;
438        ConvTy.getAsStringInternal(TypeStr, S.Context.PrintingPolicy);
439
440        S.Diag(SwitchLoc, diag::err_switch_explicit_conversion)
441          << CondType << ConvTy << CondExpr->getSourceRange()
442          << CodeModificationHint::CreateInsertion(CondExpr->getLocStart(),
443                                         "static_cast<" + TypeStr + ">(")
444          << CodeModificationHint::CreateInsertion(
445                            S.PP.getLocForEndOfToken(CondExpr->getLocEnd()),
446                               ")");
447        S.Diag(ExplicitConversions[0]->getLocation(),
448             diag::note_switch_conversion)
449          << ConvTy->isEnumeralType() << ConvTy;
450
451        // If we aren't in a SFINAE context, build a call to the
452        // explicit conversion function.
453        if (S.isSFINAEContext())
454          return true;
455
456        CondExpr = S.BuildCXXMemberCallExpr(CondExpr, ExplicitConversions[0]);
457      }
458
459      // We'll complain below about a non-integral condition type.
460      break;
461
462    case 1:
463      // Apply this conversion.
464      CondExpr = S.BuildCXXMemberCallExpr(CondExpr, ViableConversions[0]);
465      break;
466
467    default:
468      S.Diag(SwitchLoc, diag::err_switch_multiple_conversions)
469        << CondType << CondExpr->getSourceRange();
470      for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
471        QualType ConvTy
472          = ViableConversions[I]->getConversionType().getNonReferenceType();
473        S.Diag(ViableConversions[I]->getLocation(),
474             diag::note_switch_conversion)
475          << ConvTy->isEnumeralType() << ConvTy;
476      }
477      return true;
478    }
479  }
480
481  return false;
482}
483
484Action::OwningStmtResult
485Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, StmtArg Switch,
486                            StmtArg Body) {
487  Stmt *BodyStmt = Body.takeAs<Stmt>();
488
489  SwitchStmt *SS = getSwitchStack().back();
490  assert(SS == (SwitchStmt*)Switch.get() && "switch stack missing push/pop!");
491
492  SS->setBody(BodyStmt, SwitchLoc);
493  getSwitchStack().pop_back();
494
495  if (SS->getCond() == 0) {
496    SS->Destroy(Context);
497    return StmtError();
498  }
499
500  Expr *CondExpr = SS->getCond();
501  QualType CondTypeBeforePromotion =
502      GetTypeBeforeIntegralPromotion(CondExpr);
503
504  if (getLangOptions().CPlusPlus &&
505      CheckCXXSwitchCondition(*this, SwitchLoc, CondExpr))
506    return StmtError();
507
508  // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
509  UsualUnaryConversions(CondExpr);
510  QualType CondType = CondExpr->getType();
511  SS->setCond(CondExpr);
512
513  // C++ 6.4.2.p2:
514  // Integral promotions are performed (on the switch condition).
515  //
516  // A case value unrepresentable by the original switch condition
517  // type (before the promotion) doesn't make sense, even when it can
518  // be represented by the promoted type.  Therefore we need to find
519  // the pre-promotion type of the switch condition.
520  if (!CondExpr->isTypeDependent()) {
521    if (!CondType->isIntegerType()) { // C99 6.8.4.2p1
522      Diag(SwitchLoc, diag::err_typecheck_statement_requires_integer)
523          << CondType << CondExpr->getSourceRange();
524      return StmtError();
525    }
526
527    if (CondTypeBeforePromotion->isBooleanType()) {
528      // switch(bool_expr) {...} is often a programmer error, e.g.
529      //   switch(n && mask) { ... }  // Doh - should be "n & mask".
530      // One can always use an if statement instead of switch(bool_expr).
531      Diag(SwitchLoc, diag::warn_bool_switch_condition)
532          << CondExpr->getSourceRange();
533    }
534  }
535
536  // Get the bitwidth of the switched-on value before promotions.  We must
537  // convert the integer case values to this width before comparison.
538  bool HasDependentValue
539    = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
540  unsigned CondWidth
541    = HasDependentValue? 0
542      : static_cast<unsigned>(Context.getTypeSize(CondTypeBeforePromotion));
543  bool CondIsSigned = CondTypeBeforePromotion->isSignedIntegerType();
544
545  // Accumulate all of the case values in a vector so that we can sort them
546  // and detect duplicates.  This vector contains the APInt for the case after
547  // it has been converted to the condition type.
548  typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
549  CaseValsTy CaseVals;
550
551  // Keep track of any GNU case ranges we see.  The APSInt is the low value.
552  std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRanges;
553
554  DefaultStmt *TheDefaultStmt = 0;
555
556  bool CaseListIsErroneous = false;
557
558  for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
559       SC = SC->getNextSwitchCase()) {
560
561    if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
562      if (TheDefaultStmt) {
563        Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
564        Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
565
566        // FIXME: Remove the default statement from the switch block so that
567        // we'll return a valid AST.  This requires recursing down the AST and
568        // finding it, not something we are set up to do right now.  For now,
569        // just lop the entire switch stmt out of the AST.
570        CaseListIsErroneous = true;
571      }
572      TheDefaultStmt = DS;
573
574    } else {
575      CaseStmt *CS = cast<CaseStmt>(SC);
576
577      // We already verified that the expression has a i-c-e value (C99
578      // 6.8.4.2p3) - get that value now.
579      Expr *Lo = CS->getLHS();
580
581      if (Lo->isTypeDependent() || Lo->isValueDependent()) {
582        HasDependentValue = true;
583        break;
584      }
585
586      llvm::APSInt LoVal = Lo->EvaluateAsInt(Context);
587
588      // Convert the value to the same width/sign as the condition.
589      ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
590                                         CS->getLHS()->getLocStart(),
591                                         diag::warn_case_value_overflow);
592
593      // If the LHS is not the same type as the condition, insert an implicit
594      // cast.
595      ImpCastExprToType(Lo, CondType, CastExpr::CK_IntegralCast);
596      CS->setLHS(Lo);
597
598      // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
599      if (CS->getRHS()) {
600        if (CS->getRHS()->isTypeDependent() ||
601            CS->getRHS()->isValueDependent()) {
602          HasDependentValue = true;
603          break;
604        }
605        CaseRanges.push_back(std::make_pair(LoVal, CS));
606      } else
607        CaseVals.push_back(std::make_pair(LoVal, CS));
608    }
609  }
610
611  if (!HasDependentValue) {
612    // Sort all the scalar case values so we can easily detect duplicates.
613    std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
614
615    if (!CaseVals.empty()) {
616      for (unsigned i = 0, e = CaseVals.size()-1; i != e; ++i) {
617        if (CaseVals[i].first == CaseVals[i+1].first) {
618          // If we have a duplicate, report it.
619          Diag(CaseVals[i+1].second->getLHS()->getLocStart(),
620               diag::err_duplicate_case) << CaseVals[i].first.toString(10);
621          Diag(CaseVals[i].second->getLHS()->getLocStart(),
622               diag::note_duplicate_case_prev);
623          // FIXME: We really want to remove the bogus case stmt from the
624          // substmt, but we have no way to do this right now.
625          CaseListIsErroneous = true;
626        }
627      }
628    }
629
630    // Detect duplicate case ranges, which usually don't exist at all in
631    // the first place.
632    if (!CaseRanges.empty()) {
633      // Sort all the case ranges by their low value so we can easily detect
634      // overlaps between ranges.
635      std::stable_sort(CaseRanges.begin(), CaseRanges.end());
636
637      // Scan the ranges, computing the high values and removing empty ranges.
638      std::vector<llvm::APSInt> HiVals;
639      for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
640        CaseStmt *CR = CaseRanges[i].second;
641        Expr *Hi = CR->getRHS();
642        llvm::APSInt HiVal = Hi->EvaluateAsInt(Context);
643
644        // Convert the value to the same width/sign as the condition.
645        ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
646                                           CR->getRHS()->getLocStart(),
647                                           diag::warn_case_value_overflow);
648
649        // If the LHS is not the same type as the condition, insert an implicit
650        // cast.
651        ImpCastExprToType(Hi, CondType, CastExpr::CK_IntegralCast);
652        CR->setRHS(Hi);
653
654        // If the low value is bigger than the high value, the case is empty.
655        if (CaseRanges[i].first > HiVal) {
656          Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
657            << SourceRange(CR->getLHS()->getLocStart(),
658                           CR->getRHS()->getLocEnd());
659          CaseRanges.erase(CaseRanges.begin()+i);
660          --i, --e;
661          continue;
662        }
663        HiVals.push_back(HiVal);
664      }
665
666      // Rescan the ranges, looking for overlap with singleton values and other
667      // ranges.  Since the range list is sorted, we only need to compare case
668      // ranges with their neighbors.
669      for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
670        llvm::APSInt &CRLo = CaseRanges[i].first;
671        llvm::APSInt &CRHi = HiVals[i];
672        CaseStmt *CR = CaseRanges[i].second;
673
674        // Check to see whether the case range overlaps with any
675        // singleton cases.
676        CaseStmt *OverlapStmt = 0;
677        llvm::APSInt OverlapVal(32);
678
679        // Find the smallest value >= the lower bound.  If I is in the
680        // case range, then we have overlap.
681        CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
682                                                  CaseVals.end(), CRLo,
683                                                  CaseCompareFunctor());
684        if (I != CaseVals.end() && I->first < CRHi) {
685          OverlapVal  = I->first;   // Found overlap with scalar.
686          OverlapStmt = I->second;
687        }
688
689        // Find the smallest value bigger than the upper bound.
690        I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
691        if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
692          OverlapVal  = (I-1)->first;      // Found overlap with scalar.
693          OverlapStmt = (I-1)->second;
694        }
695
696        // Check to see if this case stmt overlaps with the subsequent
697        // case range.
698        if (i && CRLo <= HiVals[i-1]) {
699          OverlapVal  = HiVals[i-1];       // Found overlap with range.
700          OverlapStmt = CaseRanges[i-1].second;
701        }
702
703        if (OverlapStmt) {
704          // If we have a duplicate, report it.
705          Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
706            << OverlapVal.toString(10);
707          Diag(OverlapStmt->getLHS()->getLocStart(),
708               diag::note_duplicate_case_prev);
709          // FIXME: We really want to remove the bogus case stmt from the
710          // substmt, but we have no way to do this right now.
711          CaseListIsErroneous = true;
712        }
713      }
714    }
715  }
716
717  // FIXME: If the case list was broken is some way, we don't have a good system
718  // to patch it up.  Instead, just return the whole substmt as broken.
719  if (CaseListIsErroneous)
720    return StmtError();
721
722  Switch.release();
723  return Owned(SS);
724}
725
726Action::OwningStmtResult
727Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
728                     DeclPtrTy CondVar, StmtArg Body) {
729  OwningExprResult CondResult(Cond.release());
730
731  VarDecl *ConditionVar = 0;
732  if (CondVar.get()) {
733    ConditionVar = CondVar.getAs<VarDecl>();
734    CondResult = CheckConditionVariable(ConditionVar);
735    if (CondResult.isInvalid())
736      return StmtError();
737  }
738  Expr *ConditionExpr = CondResult.takeAs<Expr>();
739  if (!ConditionExpr)
740    return StmtError();
741
742  if (CheckBooleanCondition(ConditionExpr, WhileLoc)) {
743    CondResult = ConditionExpr;
744    return StmtError();
745  }
746
747  Stmt *bodyStmt = Body.takeAs<Stmt>();
748  DiagnoseUnusedExprResult(bodyStmt);
749
750  CondResult.release();
751  return Owned(new (Context) WhileStmt(ConditionVar, ConditionExpr, bodyStmt,
752                                       WhileLoc));
753}
754
755Action::OwningStmtResult
756Sema::ActOnDoStmt(SourceLocation DoLoc, StmtArg Body,
757                  SourceLocation WhileLoc, SourceLocation CondLParen,
758                  ExprArg Cond, SourceLocation CondRParen) {
759  Expr *condExpr = Cond.takeAs<Expr>();
760  assert(condExpr && "ActOnDoStmt(): missing expression");
761
762  if (CheckBooleanCondition(condExpr, DoLoc)) {
763    Cond = condExpr;
764    return StmtError();
765  }
766
767  Stmt *bodyStmt = Body.takeAs<Stmt>();
768  DiagnoseUnusedExprResult(bodyStmt);
769
770  Cond.release();
771  return Owned(new (Context) DoStmt(bodyStmt, condExpr, DoLoc,
772                                    WhileLoc, CondRParen));
773}
774
775Action::OwningStmtResult
776Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
777                   StmtArg first, FullExprArg second, DeclPtrTy secondVar,
778                   FullExprArg third,
779                   SourceLocation RParenLoc, StmtArg body) {
780  Stmt *First  = static_cast<Stmt*>(first.get());
781
782  if (!getLangOptions().CPlusPlus) {
783    if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
784      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
785      // declare identifiers for objects having storage class 'auto' or
786      // 'register'.
787      for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
788           DI!=DE; ++DI) {
789        VarDecl *VD = dyn_cast<VarDecl>(*DI);
790        if (VD && VD->isBlockVarDecl() && !VD->hasLocalStorage())
791          VD = 0;
792        if (VD == 0)
793          Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
794        // FIXME: mark decl erroneous!
795      }
796    }
797  }
798
799  OwningExprResult SecondResult(second.release());
800  VarDecl *ConditionVar = 0;
801  if (secondVar.get()) {
802    ConditionVar = secondVar.getAs<VarDecl>();
803    SecondResult = CheckConditionVariable(ConditionVar);
804    if (SecondResult.isInvalid())
805      return StmtError();
806  }
807
808  Expr *Second = SecondResult.takeAs<Expr>();
809  if (Second && CheckBooleanCondition(Second, ForLoc)) {
810    SecondResult = Second;
811    return StmtError();
812  }
813
814  Expr *Third  = third.release().takeAs<Expr>();
815  Stmt *Body  = static_cast<Stmt*>(body.get());
816
817  DiagnoseUnusedExprResult(First);
818  DiagnoseUnusedExprResult(Third);
819  DiagnoseUnusedExprResult(Body);
820
821  first.release();
822  body.release();
823  return Owned(new (Context) ForStmt(First, Second, ConditionVar, Third, Body,
824                                     ForLoc, LParenLoc, RParenLoc));
825}
826
827Action::OwningStmtResult
828Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
829                                 SourceLocation LParenLoc,
830                                 StmtArg first, ExprArg second,
831                                 SourceLocation RParenLoc, StmtArg body) {
832  Stmt *First  = static_cast<Stmt*>(first.get());
833  Expr *Second = static_cast<Expr*>(second.get());
834  Stmt *Body  = static_cast<Stmt*>(body.get());
835  if (First) {
836    QualType FirstType;
837    if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
838      if (!DS->isSingleDecl())
839        return StmtError(Diag((*DS->decl_begin())->getLocation(),
840                         diag::err_toomany_element_decls));
841
842      Decl *D = DS->getSingleDecl();
843      FirstType = cast<ValueDecl>(D)->getType();
844      // C99 6.8.5p3: The declaration part of a 'for' statement shall only
845      // declare identifiers for objects having storage class 'auto' or
846      // 'register'.
847      VarDecl *VD = cast<VarDecl>(D);
848      if (VD->isBlockVarDecl() && !VD->hasLocalStorage())
849        return StmtError(Diag(VD->getLocation(),
850                              diag::err_non_variable_decl_in_for));
851    } else {
852      if (cast<Expr>(First)->isLvalue(Context) != Expr::LV_Valid)
853        return StmtError(Diag(First->getLocStart(),
854                   diag::err_selector_element_not_lvalue)
855          << First->getSourceRange());
856
857      FirstType = static_cast<Expr*>(First)->getType();
858    }
859    if (!FirstType->isObjCObjectPointerType() &&
860        !FirstType->isBlockPointerType())
861        Diag(ForLoc, diag::err_selector_element_type)
862          << FirstType << First->getSourceRange();
863  }
864  if (Second) {
865    DefaultFunctionArrayConversion(Second);
866    QualType SecondType = Second->getType();
867    if (!SecondType->isObjCObjectPointerType())
868      Diag(ForLoc, diag::err_collection_expr_type)
869        << SecondType << Second->getSourceRange();
870  }
871  first.release();
872  second.release();
873  body.release();
874  return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
875                                                   ForLoc, RParenLoc));
876}
877
878Action::OwningStmtResult
879Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
880                    IdentifierInfo *LabelII) {
881  // If we are in a block, reject all gotos for now.
882  if (CurBlock)
883    return StmtError(Diag(GotoLoc, diag::err_goto_in_block));
884
885  // Look up the record for this label identifier.
886  LabelStmt *&LabelDecl = getLabelMap()[LabelII];
887
888  // If we haven't seen this label yet, create a forward reference.
889  if (LabelDecl == 0)
890    LabelDecl = new (Context) LabelStmt(LabelLoc, LabelII, 0);
891
892  return Owned(new (Context) GotoStmt(LabelDecl, GotoLoc, LabelLoc));
893}
894
895Action::OwningStmtResult
896Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
897                            ExprArg DestExp) {
898  // Convert operand to void*
899  Expr* E = DestExp.takeAs<Expr>();
900  if (!E->isTypeDependent()) {
901    QualType ETy = E->getType();
902    AssignConvertType ConvTy =
903      CheckSingleAssignmentConstraints(Context.VoidPtrTy, E);
904    if (DiagnoseAssignmentResult(ConvTy, StarLoc, Context.VoidPtrTy, ETy,
905                                 E, AA_Passing))
906      return StmtError();
907  }
908  return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
909}
910
911Action::OwningStmtResult
912Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
913  Scope *S = CurScope->getContinueParent();
914  if (!S) {
915    // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
916    return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
917  }
918
919  return Owned(new (Context) ContinueStmt(ContinueLoc));
920}
921
922Action::OwningStmtResult
923Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
924  Scope *S = CurScope->getBreakParent();
925  if (!S) {
926    // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
927    return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
928  }
929
930  return Owned(new (Context) BreakStmt(BreakLoc));
931}
932
933/// ActOnBlockReturnStmt - Utility routine to figure out block's return type.
934///
935Action::OwningStmtResult
936Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
937  // If this is the first return we've seen in the block, infer the type of
938  // the block from it.
939  if (CurBlock->ReturnType.isNull()) {
940    if (RetValExp) {
941      // Don't call UsualUnaryConversions(), since we don't want to do
942      // integer promotions here.
943      DefaultFunctionArrayConversion(RetValExp);
944      CurBlock->ReturnType = RetValExp->getType();
945      if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) {
946        // We have to remove a 'const' added to copied-in variable which was
947        // part of the implementation spec. and not the actual qualifier for
948        // the variable.
949        if (CDRE->isConstQualAdded())
950           CurBlock->ReturnType.removeConst();
951      }
952    } else
953      CurBlock->ReturnType = Context.VoidTy;
954  }
955  QualType FnRetType = CurBlock->ReturnType;
956
957  if (CurBlock->TheDecl->hasAttr<NoReturnAttr>()) {
958    Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr)
959      << getCurFunctionOrMethodDecl()->getDeclName();
960    return StmtError();
961  }
962
963  // Otherwise, verify that this result type matches the previous one.  We are
964  // pickier with blocks than for normal functions because we don't have GCC
965  // compatibility to worry about here.
966  if (CurBlock->ReturnType->isVoidType()) {
967    if (RetValExp) {
968      Diag(ReturnLoc, diag::err_return_block_has_expr);
969      RetValExp->Destroy(Context);
970      RetValExp = 0;
971    }
972    return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
973  }
974
975  if (!RetValExp)
976    return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
977
978  if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
979    // we have a non-void block with an expression, continue checking
980    QualType RetValType = RetValExp->getType();
981
982    // C99 6.8.6.4p3(136): The return statement is not an assignment. The
983    // overlap restriction of subclause 6.5.16.1 does not apply to the case of
984    // function return.
985
986    // In C++ the return statement is handled via a copy initialization.
987    // the C version of which boils down to CheckSingleAssignmentConstraints.
988    // FIXME: Leaks RetValExp.
989    if (PerformCopyInitialization(RetValExp, FnRetType, AA_Returning))
990      return StmtError();
991
992    if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
993  }
994
995  return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
996}
997
998/// IsReturnCopyElidable - Whether returning @p RetExpr from a function that
999/// returns a @p RetType fulfills the criteria for copy elision (C++0x 12.8p15).
1000static bool IsReturnCopyElidable(ASTContext &Ctx, QualType RetType,
1001                                 Expr *RetExpr) {
1002  QualType ExprType = RetExpr->getType();
1003  // - in a return statement in a function with ...
1004  // ... a class return type ...
1005  if (!RetType->isRecordType())
1006    return false;
1007  // ... the same cv-unqualified type as the function return type ...
1008  if (!Ctx.hasSameUnqualifiedType(RetType, ExprType))
1009    return false;
1010  // ... the expression is the name of a non-volatile automatic object ...
1011  // We ignore parentheses here.
1012  // FIXME: Is this compliant?
1013  const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetExpr->IgnoreParens());
1014  if (!DR)
1015    return false;
1016  const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
1017  if (!VD)
1018    return false;
1019  return VD->hasLocalStorage() && !VD->getType()->isReferenceType()
1020    && !VD->getType().isVolatileQualified();
1021}
1022
1023Action::OwningStmtResult
1024Sema::ActOnReturnStmt(SourceLocation ReturnLoc, ExprArg rex) {
1025  Expr *RetValExp = rex.takeAs<Expr>();
1026  if (CurBlock)
1027    return ActOnBlockReturnStmt(ReturnLoc, RetValExp);
1028
1029  QualType FnRetType;
1030  if (const FunctionDecl *FD = getCurFunctionDecl()) {
1031    FnRetType = FD->getResultType();
1032    if (FD->hasAttr<NoReturnAttr>())
1033      Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
1034        << getCurFunctionOrMethodDecl()->getDeclName();
1035  } else if (ObjCMethodDecl *MD = getCurMethodDecl())
1036    FnRetType = MD->getResultType();
1037  else // If we don't have a function/method context, bail.
1038    return StmtError();
1039
1040  if (FnRetType->isVoidType()) {
1041    if (RetValExp && !RetValExp->isTypeDependent()) {
1042      // C99 6.8.6.4p1 (ext_ since GCC warns)
1043      unsigned D = diag::ext_return_has_expr;
1044      if (RetValExp->getType()->isVoidType())
1045        D = diag::ext_return_has_void_expr;
1046
1047      // return (some void expression); is legal in C++.
1048      if (D != diag::ext_return_has_void_expr ||
1049          !getLangOptions().CPlusPlus) {
1050        NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
1051        Diag(ReturnLoc, D)
1052          << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl)
1053          << RetValExp->getSourceRange();
1054      }
1055
1056      RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
1057    }
1058    return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
1059  }
1060
1061  if (!RetValExp && !FnRetType->isDependentType()) {
1062    unsigned DiagID = diag::warn_return_missing_expr;  // C90 6.6.6.4p4
1063    // C99 6.8.6.4p1 (ext_ since GCC warns)
1064    if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr;
1065
1066    if (FunctionDecl *FD = getCurFunctionDecl())
1067      Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
1068    else
1069      Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
1070    return Owned(new (Context) ReturnStmt(ReturnLoc, (Expr*)0));
1071  }
1072
1073  if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
1074    // we have a non-void function with an expression, continue checking
1075
1076    // C99 6.8.6.4p3(136): The return statement is not an assignment. The
1077    // overlap restriction of subclause 6.5.16.1 does not apply to the case of
1078    // function return.
1079
1080    // C++0x 12.8p15: When certain criteria are met, an implementation is
1081    //   allowed to omit the copy construction of a class object, [...]
1082    //   - in a return statement in a function with a class return type, when
1083    //     the expression is the name of a non-volatile automatic object with
1084    //     the same cv-unqualified type as the function return type, the copy
1085    //     operation can be omitted [...]
1086    // C++0x 12.8p16: When the criteria for elision of a copy operation are met
1087    //   and the object to be copied is designated by an lvalue, overload
1088    //   resolution to select the constructor for the copy is first performed
1089    //   as if the object were designated by an rvalue.
1090    // Note that we only compute Elidable if we're in C++0x, since we don't
1091    // care otherwise.
1092    bool Elidable = getLangOptions().CPlusPlus0x ?
1093                      IsReturnCopyElidable(Context, FnRetType, RetValExp) :
1094                      false;
1095
1096    // In C++ the return statement is handled via a copy initialization.
1097    // the C version of which boils down to CheckSingleAssignmentConstraints.
1098    // FIXME: Leaks RetValExp on error.
1099    if (PerformCopyInitialization(RetValExp, FnRetType, AA_Returning, Elidable)){
1100      // We should still clean up our temporaries, even when we're failing!
1101      RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
1102      return StmtError();
1103    }
1104
1105    if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
1106  }
1107
1108  if (RetValExp)
1109    RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp);
1110  return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp));
1111}
1112
1113/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
1114/// ignore "noop" casts in places where an lvalue is required by an inline asm.
1115/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
1116/// provide a strong guidance to not use it.
1117///
1118/// This method checks to see if the argument is an acceptable l-value and
1119/// returns false if it is a case we can handle.
1120static bool CheckAsmLValue(const Expr *E, Sema &S) {
1121  if (E->isLvalue(S.Context) == Expr::LV_Valid)
1122    return false;  // Cool, this is an lvalue.
1123
1124  // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
1125  // are supposed to allow.
1126  const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
1127  if (E != E2 && E2->isLvalue(S.Context) == Expr::LV_Valid) {
1128    if (!S.getLangOptions().HeinousExtensions)
1129      S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
1130        << E->getSourceRange();
1131    else
1132      S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
1133        << E->getSourceRange();
1134    // Accept, even if we emitted an error diagnostic.
1135    return false;
1136  }
1137
1138  // None of the above, just randomly invalid non-lvalue.
1139  return true;
1140}
1141
1142
1143Sema::OwningStmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc,
1144                                          bool IsSimple,
1145                                          bool IsVolatile,
1146                                          unsigned NumOutputs,
1147                                          unsigned NumInputs,
1148                                          std::string *Names,
1149                                          MultiExprArg constraints,
1150                                          MultiExprArg exprs,
1151                                          ExprArg asmString,
1152                                          MultiExprArg clobbers,
1153                                          SourceLocation RParenLoc) {
1154  unsigned NumClobbers = clobbers.size();
1155  StringLiteral **Constraints =
1156    reinterpret_cast<StringLiteral**>(constraints.get());
1157  Expr **Exprs = reinterpret_cast<Expr **>(exprs.get());
1158  StringLiteral *AsmString = cast<StringLiteral>((Expr *)asmString.get());
1159  StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
1160
1161  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
1162
1163  // The parser verifies that there is a string literal here.
1164  if (AsmString->isWide())
1165    return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
1166      << AsmString->getSourceRange());
1167
1168  for (unsigned i = 0; i != NumOutputs; i++) {
1169    StringLiteral *Literal = Constraints[i];
1170    if (Literal->isWide())
1171      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1172        << Literal->getSourceRange());
1173
1174    TargetInfo::ConstraintInfo Info(Literal->getStrData(),
1175                                    Literal->getByteLength(),
1176                                    Names[i]);
1177    if (!Context.Target.validateOutputConstraint(Info))
1178      return StmtError(Diag(Literal->getLocStart(),
1179                            diag::err_asm_invalid_output_constraint)
1180                       << Info.getConstraintStr());
1181
1182    // Check that the output exprs are valid lvalues.
1183    Expr *OutputExpr = Exprs[i];
1184    if (CheckAsmLValue(OutputExpr, *this)) {
1185      return StmtError(Diag(OutputExpr->getLocStart(),
1186                  diag::err_asm_invalid_lvalue_in_output)
1187        << OutputExpr->getSourceRange());
1188    }
1189
1190    OutputConstraintInfos.push_back(Info);
1191  }
1192
1193  llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
1194
1195  for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
1196    StringLiteral *Literal = Constraints[i];
1197    if (Literal->isWide())
1198      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1199        << Literal->getSourceRange());
1200
1201    TargetInfo::ConstraintInfo Info(Literal->getStrData(),
1202                                    Literal->getByteLength(),
1203                                    Names[i]);
1204    if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(),
1205                                                NumOutputs, Info)) {
1206      return StmtError(Diag(Literal->getLocStart(),
1207                            diag::err_asm_invalid_input_constraint)
1208                       << Info.getConstraintStr());
1209    }
1210
1211    Expr *InputExpr = Exprs[i];
1212
1213    // Only allow void types for memory constraints.
1214    if (Info.allowsMemory() && !Info.allowsRegister()) {
1215      if (CheckAsmLValue(InputExpr, *this))
1216        return StmtError(Diag(InputExpr->getLocStart(),
1217                              diag::err_asm_invalid_lvalue_in_input)
1218                         << Info.getConstraintStr()
1219                         << InputExpr->getSourceRange());
1220    }
1221
1222    if (Info.allowsRegister()) {
1223      if (InputExpr->getType()->isVoidType()) {
1224        return StmtError(Diag(InputExpr->getLocStart(),
1225                              diag::err_asm_invalid_type_in_input)
1226          << InputExpr->getType() << Info.getConstraintStr()
1227          << InputExpr->getSourceRange());
1228      }
1229    }
1230
1231    DefaultFunctionArrayConversion(Exprs[i]);
1232
1233    InputConstraintInfos.push_back(Info);
1234  }
1235
1236  // Check that the clobbers are valid.
1237  for (unsigned i = 0; i != NumClobbers; i++) {
1238    StringLiteral *Literal = Clobbers[i];
1239    if (Literal->isWide())
1240      return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
1241        << Literal->getSourceRange());
1242
1243    std::string Clobber(Literal->getStrData(),
1244                        Literal->getStrData() +
1245                        Literal->getByteLength());
1246
1247    if (!Context.Target.isValidGCCRegisterName(Clobber.c_str()))
1248      return StmtError(Diag(Literal->getLocStart(),
1249                  diag::err_asm_unknown_register_name) << Clobber);
1250  }
1251
1252  constraints.release();
1253  exprs.release();
1254  asmString.release();
1255  clobbers.release();
1256  AsmStmt *NS =
1257    new (Context) AsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs,
1258                          Names, Constraints, Exprs, AsmString, NumClobbers,
1259                          Clobbers, RParenLoc);
1260  // Validate the asm string, ensuring it makes sense given the operands we
1261  // have.
1262  llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
1263  unsigned DiagOffs;
1264  if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
1265    Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
1266           << AsmString->getSourceRange();
1267    DeleteStmt(NS);
1268    return StmtError();
1269  }
1270
1271  // Validate tied input operands for type mismatches.
1272  for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
1273    TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
1274
1275    // If this is a tied constraint, verify that the output and input have
1276    // either exactly the same type, or that they are int/ptr operands with the
1277    // same size (int/long, int*/long, are ok etc).
1278    if (!Info.hasTiedOperand()) continue;
1279
1280    unsigned TiedTo = Info.getTiedOperand();
1281    Expr *OutputExpr = Exprs[TiedTo];
1282    Expr *InputExpr = Exprs[i+NumOutputs];
1283    QualType InTy = InputExpr->getType();
1284    QualType OutTy = OutputExpr->getType();
1285    if (Context.hasSameType(InTy, OutTy))
1286      continue;  // All types can be tied to themselves.
1287
1288    // Int/ptr operands have some special cases that we allow.
1289    if ((OutTy->isIntegerType() || OutTy->isPointerType()) &&
1290        (InTy->isIntegerType() || InTy->isPointerType())) {
1291
1292      // They are ok if they are the same size.  Tying void* to int is ok if
1293      // they are the same size, for example.  This also allows tying void* to
1294      // int*.
1295      uint64_t OutSize = Context.getTypeSize(OutTy);
1296      uint64_t InSize = Context.getTypeSize(InTy);
1297      if (OutSize == InSize)
1298        continue;
1299
1300      // If the smaller input/output operand is not mentioned in the asm string,
1301      // then we can promote it and the asm string won't notice.  Check this
1302      // case now.
1303      bool SmallerValueMentioned = false;
1304      for (unsigned p = 0, e = Pieces.size(); p != e; ++p) {
1305        AsmStmt::AsmStringPiece &Piece = Pieces[p];
1306        if (!Piece.isOperand()) continue;
1307
1308        // If this is a reference to the input and if the input was the smaller
1309        // one, then we have to reject this asm.
1310        if (Piece.getOperandNo() == i+NumOutputs) {
1311          if (InSize < OutSize) {
1312            SmallerValueMentioned = true;
1313            break;
1314          }
1315        }
1316
1317        // If this is a reference to the input and if the input was the smaller
1318        // one, then we have to reject this asm.
1319        if (Piece.getOperandNo() == TiedTo) {
1320          if (InSize > OutSize) {
1321            SmallerValueMentioned = true;
1322            break;
1323          }
1324        }
1325      }
1326
1327      // If the smaller value wasn't mentioned in the asm string, and if the
1328      // output was a register, just extend the shorter one to the size of the
1329      // larger one.
1330      if (!SmallerValueMentioned &&
1331          OutputConstraintInfos[TiedTo].allowsRegister())
1332        continue;
1333    }
1334
1335    Diag(InputExpr->getLocStart(),
1336         diag::err_asm_tying_incompatible_types)
1337      << InTy << OutTy << OutputExpr->getSourceRange()
1338      << InputExpr->getSourceRange();
1339    DeleteStmt(NS);
1340    return StmtError();
1341  }
1342
1343  return Owned(NS);
1344}
1345
1346Action::OwningStmtResult
1347Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
1348                           SourceLocation RParen, DeclPtrTy Parm,
1349                           StmtArg Body, StmtArg catchList) {
1350  Stmt *CatchList = catchList.takeAs<Stmt>();
1351  ParmVarDecl *PVD = cast_or_null<ParmVarDecl>(Parm.getAs<Decl>());
1352
1353  // PVD == 0 implies @catch(...).
1354  if (PVD) {
1355    // If we already know the decl is invalid, reject it.
1356    if (PVD->isInvalidDecl())
1357      return StmtError();
1358
1359    if (!PVD->getType()->isObjCObjectPointerType())
1360      return StmtError(Diag(PVD->getLocation(),
1361                       diag::err_catch_param_not_objc_type));
1362    if (PVD->getType()->isObjCQualifiedIdType())
1363      return StmtError(Diag(PVD->getLocation(),
1364                       diag::err_illegal_qualifiers_on_catch_parm));
1365  }
1366
1367  ObjCAtCatchStmt *CS = new (Context) ObjCAtCatchStmt(AtLoc, RParen,
1368    PVD, Body.takeAs<Stmt>(), CatchList);
1369  return Owned(CatchList ? CatchList : CS);
1370}
1371
1372Action::OwningStmtResult
1373Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, StmtArg Body) {
1374  return Owned(new (Context) ObjCAtFinallyStmt(AtLoc,
1375                                           static_cast<Stmt*>(Body.release())));
1376}
1377
1378Action::OwningStmtResult
1379Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc,
1380                         StmtArg Try, StmtArg Catch, StmtArg Finally) {
1381  CurFunctionNeedsScopeChecking = true;
1382  return Owned(new (Context) ObjCAtTryStmt(AtLoc, Try.takeAs<Stmt>(),
1383                                           Catch.takeAs<Stmt>(),
1384                                           Finally.takeAs<Stmt>()));
1385}
1386
1387Action::OwningStmtResult
1388Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, ExprArg expr,Scope *CurScope) {
1389  Expr *ThrowExpr = expr.takeAs<Expr>();
1390  if (!ThrowExpr) {
1391    // @throw without an expression designates a rethrow (which much occur
1392    // in the context of an @catch clause).
1393    Scope *AtCatchParent = CurScope;
1394    while (AtCatchParent && !AtCatchParent->isAtCatchScope())
1395      AtCatchParent = AtCatchParent->getParent();
1396    if (!AtCatchParent)
1397      return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
1398  } else {
1399    QualType ThrowType = ThrowExpr->getType();
1400    // Make sure the expression type is an ObjC pointer or "void *".
1401    if (!ThrowType->isObjCObjectPointerType()) {
1402      const PointerType *PT = ThrowType->getAs<PointerType>();
1403      if (!PT || !PT->getPointeeType()->isVoidType())
1404        return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
1405                        << ThrowExpr->getType() << ThrowExpr->getSourceRange());
1406    }
1407  }
1408  return Owned(new (Context) ObjCAtThrowStmt(AtLoc, ThrowExpr));
1409}
1410
1411Action::OwningStmtResult
1412Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, ExprArg SynchExpr,
1413                                  StmtArg SynchBody) {
1414  CurFunctionNeedsScopeChecking = true;
1415
1416  // Make sure the expression type is an ObjC pointer or "void *".
1417  Expr *SyncExpr = static_cast<Expr*>(SynchExpr.get());
1418  if (!SyncExpr->getType()->isObjCObjectPointerType()) {
1419    const PointerType *PT = SyncExpr->getType()->getAs<PointerType>();
1420    if (!PT || !PT->getPointeeType()->isVoidType())
1421      return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object)
1422                       << SyncExpr->getType() << SyncExpr->getSourceRange());
1423  }
1424
1425  return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc,
1426                                                    SynchExpr.takeAs<Stmt>(),
1427                                                    SynchBody.takeAs<Stmt>()));
1428}
1429
1430/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
1431/// and creates a proper catch handler from them.
1432Action::OwningStmtResult
1433Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, DeclPtrTy ExDecl,
1434                         StmtArg HandlerBlock) {
1435  // There's nothing to test that ActOnExceptionDecl didn't already test.
1436  return Owned(new (Context) CXXCatchStmt(CatchLoc,
1437                                  cast_or_null<VarDecl>(ExDecl.getAs<Decl>()),
1438                                          HandlerBlock.takeAs<Stmt>()));
1439}
1440
1441class TypeWithHandler {
1442  QualType t;
1443  CXXCatchStmt *stmt;
1444public:
1445  TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
1446  : t(type), stmt(statement) {}
1447
1448  // An arbitrary order is fine as long as it places identical
1449  // types next to each other.
1450  bool operator<(const TypeWithHandler &y) const {
1451    if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
1452      return true;
1453    if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
1454      return false;
1455    else
1456      return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
1457  }
1458
1459  bool operator==(const TypeWithHandler& other) const {
1460    return t == other.t;
1461  }
1462
1463  QualType getQualType() const { return t; }
1464  CXXCatchStmt *getCatchStmt() const { return stmt; }
1465  SourceLocation getTypeSpecStartLoc() const {
1466    return stmt->getExceptionDecl()->getTypeSpecStartLoc();
1467  }
1468};
1469
1470/// ActOnCXXTryBlock - Takes a try compound-statement and a number of
1471/// handlers and creates a try statement from them.
1472Action::OwningStmtResult
1473Sema::ActOnCXXTryBlock(SourceLocation TryLoc, StmtArg TryBlock,
1474                       MultiStmtArg RawHandlers) {
1475  unsigned NumHandlers = RawHandlers.size();
1476  assert(NumHandlers > 0 &&
1477         "The parser shouldn't call this if there are no handlers.");
1478  Stmt **Handlers = reinterpret_cast<Stmt**>(RawHandlers.get());
1479
1480  llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers;
1481
1482  for (unsigned i = 0; i < NumHandlers; ++i) {
1483    CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]);
1484    if (!Handler->getExceptionDecl()) {
1485      if (i < NumHandlers - 1)
1486        return StmtError(Diag(Handler->getLocStart(),
1487                              diag::err_early_catch_all));
1488
1489      continue;
1490    }
1491
1492    const QualType CaughtType = Handler->getCaughtType();
1493    const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
1494    TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
1495  }
1496
1497  // Detect handlers for the same type as an earlier one.
1498  if (NumHandlers > 1) {
1499    llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
1500
1501    TypeWithHandler prev = TypesWithHandlers[0];
1502    for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
1503      TypeWithHandler curr = TypesWithHandlers[i];
1504
1505      if (curr == prev) {
1506        Diag(curr.getTypeSpecStartLoc(),
1507             diag::warn_exception_caught_by_earlier_handler)
1508          << curr.getCatchStmt()->getCaughtType().getAsString();
1509        Diag(prev.getTypeSpecStartLoc(),
1510             diag::note_previous_exception_handler)
1511          << prev.getCatchStmt()->getCaughtType().getAsString();
1512      }
1513
1514      prev = curr;
1515    }
1516  }
1517
1518  // FIXME: We should detect handlers that cannot catch anything because an
1519  // earlier handler catches a superclass. Need to find a method that is not
1520  // quadratic for this.
1521  // Neither of these are explicitly forbidden, but every compiler detects them
1522  // and warns.
1523
1524  CurFunctionNeedsScopeChecking = true;
1525  RawHandlers.release();
1526  return Owned(new (Context) CXXTryStmt(TryLoc,
1527                                        static_cast<Stmt*>(TryBlock.release()),
1528                                        Handlers, NumHandlers));
1529}
1530