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 "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Scope.h"
16 #include "clang/Sema/ScopeInfo.h"
17 #include "clang/Sema/Initialization.h"
18 #include "clang/Sema/Lookup.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "llvm/ADT/ArrayRef.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallString.h"
34 #include "llvm/ADT/SmallVector.h"
35 using namespace clang;
36 using namespace sema;
37 
38 StmtResult Sema::ActOnExprStmt(FullExprArg expr) {
39   Expr *E = expr.get();
40   if (!E) // FIXME: FullExprArg has no error state?
41     return StmtError();
42 
43   // C99 6.8.3p2: The expression in an expression statement is evaluated as a
44   // void expression for its side effects.  Conversion to void allows any
45   // operand, even incomplete types.
46 
47   // Same thing in for stmt first clause (when expr) and third clause.
48   return Owned(static_cast<Stmt*>(E));
49 }
50 
51 
52 StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc,
53                                bool HasLeadingEmptyMacro) {
54   return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro));
55 }
56 
57 StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc,
58                                SourceLocation EndLoc) {
59   DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
60 
61   // If we have an invalid decl, just return an error.
62   if (DG.isNull()) return StmtError();
63 
64   return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc));
65 }
66 
67 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) {
68   DeclGroupRef DG = dg.getAsVal<DeclGroupRef>();
69 
70   // If we have an invalid decl, just return.
71   if (DG.isNull() || !DG.isSingleDecl()) return;
72   VarDecl *var = cast<VarDecl>(DG.getSingleDecl());
73 
74   // suppress any potential 'unused variable' warning.
75   var->setUsed();
76 
77   // foreach variables are never actually initialized in the way that
78   // the parser came up with.
79   var->setInit(0);
80 
81   // In ARC, we don't need to retain the iteration variable of a fast
82   // enumeration loop.  Rather than actually trying to catch that
83   // during declaration processing, we remove the consequences here.
84   if (getLangOpts().ObjCAutoRefCount) {
85     QualType type = var->getType();
86 
87     // Only do this if we inferred the lifetime.  Inferred lifetime
88     // will show up as a local qualifier because explicit lifetime
89     // should have shown up as an AttributedType instead.
90     if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) {
91       // Add 'const' and mark the variable as pseudo-strong.
92       var->setType(type.withConst());
93       var->setARCPseudoStrong(true);
94     }
95   }
96 }
97 
98 /// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='.
99 ///
100 /// Adding a cast to void (or other expression wrappers) will prevent the
101 /// warning from firing.
102 static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) {
103   SourceLocation Loc;
104   bool IsNotEqual, CanAssign;
105 
106   if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
107     if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE)
108       return false;
109 
110     Loc = Op->getOperatorLoc();
111     IsNotEqual = Op->getOpcode() == BO_NE;
112     CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue();
113   } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
114     if (Op->getOperator() != OO_EqualEqual &&
115         Op->getOperator() != OO_ExclaimEqual)
116       return false;
117 
118     Loc = Op->getOperatorLoc();
119     IsNotEqual = Op->getOperator() == OO_ExclaimEqual;
120     CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue();
121   } else {
122     // Not a typo-prone comparison.
123     return false;
124   }
125 
126   // Suppress warnings when the operator, suspicious as it may be, comes from
127   // a macro expansion.
128   if (Loc.isMacroID())
129     return false;
130 
131   S.Diag(Loc, diag::warn_unused_comparison)
132     << (unsigned)IsNotEqual << E->getSourceRange();
133 
134   // If the LHS is a plausible entity to assign to, provide a fixit hint to
135   // correct common typos.
136   if (CanAssign) {
137     if (IsNotEqual)
138       S.Diag(Loc, diag::note_inequality_comparison_to_or_assign)
139         << FixItHint::CreateReplacement(Loc, "|=");
140     else
141       S.Diag(Loc, diag::note_equality_comparison_to_assign)
142         << FixItHint::CreateReplacement(Loc, "=");
143   }
144 
145   return true;
146 }
147 
148 void Sema::DiagnoseUnusedExprResult(const Stmt *S) {
149   if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
150     return DiagnoseUnusedExprResult(Label->getSubStmt());
151 
152   const Expr *E = dyn_cast_or_null<Expr>(S);
153   if (!E)
154     return;
155 
156   const Expr *WarnExpr;
157   SourceLocation Loc;
158   SourceRange R1, R2;
159   if (SourceMgr.isInSystemMacro(E->getExprLoc()) ||
160       !E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context))
161     return;
162 
163   // Okay, we have an unused result.  Depending on what the base expression is,
164   // we might want to make a more specific diagnostic.  Check for one of these
165   // cases now.
166   unsigned DiagID = diag::warn_unused_expr;
167   if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E))
168     E = Temps->getSubExpr();
169   if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E))
170     E = TempExpr->getSubExpr();
171 
172   if (DiagnoseUnusedComparison(*this, E))
173     return;
174 
175   E = WarnExpr;
176   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
177     if (E->getType()->isVoidType())
178       return;
179 
180     // If the callee has attribute pure, const, or warn_unused_result, warn with
181     // a more specific message to make it clear what is happening.
182     if (const Decl *FD = CE->getCalleeDecl()) {
183       if (FD->getAttr<WarnUnusedResultAttr>()) {
184         Diag(Loc, diag::warn_unused_result) << R1 << R2;
185         return;
186       }
187       if (FD->getAttr<PureAttr>()) {
188         Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure";
189         return;
190       }
191       if (FD->getAttr<ConstAttr>()) {
192         Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const";
193         return;
194       }
195     }
196   } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) {
197     if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) {
198       Diag(Loc, diag::err_arc_unused_init_message) << R1;
199       return;
200     }
201     const ObjCMethodDecl *MD = ME->getMethodDecl();
202     if (MD && MD->getAttr<WarnUnusedResultAttr>()) {
203       Diag(Loc, diag::warn_unused_result) << R1 << R2;
204       return;
205     }
206   } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
207     const Expr *Source = POE->getSyntacticForm();
208     if (isa<ObjCSubscriptRefExpr>(Source))
209       DiagID = diag::warn_unused_container_subscript_expr;
210     else
211       DiagID = diag::warn_unused_property_expr;
212   } else if (const CXXFunctionalCastExpr *FC
213                                        = dyn_cast<CXXFunctionalCastExpr>(E)) {
214     if (isa<CXXConstructExpr>(FC->getSubExpr()) ||
215         isa<CXXTemporaryObjectExpr>(FC->getSubExpr()))
216       return;
217   }
218   // Diagnose "(void*) blah" as a typo for "(void) blah".
219   else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) {
220     TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
221     QualType T = TI->getType();
222 
223     // We really do want to use the non-canonical type here.
224     if (T == Context.VoidPtrTy) {
225       PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc());
226 
227       Diag(Loc, diag::warn_unused_voidptr)
228         << FixItHint::CreateRemoval(TL.getStarLoc());
229       return;
230     }
231   }
232 
233   if (E->isGLValue() && E->getType().isVolatileQualified()) {
234     Diag(Loc, diag::warn_unused_volatile) << R1 << R2;
235     return;
236   }
237 
238   DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2);
239 }
240 
241 void Sema::ActOnStartOfCompoundStmt() {
242   PushCompoundScope();
243 }
244 
245 void Sema::ActOnFinishOfCompoundStmt() {
246   PopCompoundScope();
247 }
248 
249 sema::CompoundScopeInfo &Sema::getCurCompoundScope() const {
250   return getCurFunction()->CompoundScopes.back();
251 }
252 
253 StmtResult
254 Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R,
255                         MultiStmtArg elts, bool isStmtExpr) {
256   unsigned NumElts = elts.size();
257   Stmt **Elts = reinterpret_cast<Stmt**>(elts.release());
258   // If we're in C89 mode, check that we don't have any decls after stmts.  If
259   // so, emit an extension diagnostic.
260   if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) {
261     // Note that __extension__ can be around a decl.
262     unsigned i = 0;
263     // Skip over all declarations.
264     for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i)
265       /*empty*/;
266 
267     // We found the end of the list or a statement.  Scan for another declstmt.
268     for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i)
269       /*empty*/;
270 
271     if (i != NumElts) {
272       Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin();
273       Diag(D->getLocation(), diag::ext_mixed_decls_code);
274     }
275   }
276   // Warn about unused expressions in statements.
277   for (unsigned i = 0; i != NumElts; ++i) {
278     // Ignore statements that are last in a statement expression.
279     if (isStmtExpr && i == NumElts - 1)
280       continue;
281 
282     DiagnoseUnusedExprResult(Elts[i]);
283   }
284 
285   // Check for suspicious empty body (null statement) in `for' and `while'
286   // statements.  Don't do anything for template instantiations, this just adds
287   // noise.
288   if (NumElts != 0 && !CurrentInstantiationScope &&
289       getCurCompoundScope().HasEmptyLoopBodies) {
290     for (unsigned i = 0; i != NumElts - 1; ++i)
291       DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]);
292   }
293 
294   return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R));
295 }
296 
297 StmtResult
298 Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
299                     SourceLocation DotDotDotLoc, Expr *RHSVal,
300                     SourceLocation ColonLoc) {
301   assert((LHSVal != 0) && "missing expression in case statement");
302 
303   if (getCurFunction()->SwitchStack.empty()) {
304     Diag(CaseLoc, diag::err_case_not_in_switch);
305     return StmtError();
306   }
307 
308   if (!getLangOpts().CPlusPlus0x) {
309     // C99 6.8.4.2p3: The expression shall be an integer constant.
310     // However, GCC allows any evaluatable integer expression.
311     if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) {
312       LHSVal = VerifyIntegerConstantExpression(LHSVal).take();
313       if (!LHSVal)
314         return StmtError();
315     }
316 
317     // GCC extension: The expression shall be an integer constant.
318 
319     if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) {
320       RHSVal = VerifyIntegerConstantExpression(RHSVal).take();
321       // Recover from an error by just forgetting about it.
322     }
323   }
324 
325   CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc,
326                                         ColonLoc);
327   getCurFunction()->SwitchStack.back()->addSwitchCase(CS);
328   return Owned(CS);
329 }
330 
331 /// ActOnCaseStmtBody - This installs a statement as the body of a case.
332 void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) {
333   DiagnoseUnusedExprResult(SubStmt);
334 
335   CaseStmt *CS = static_cast<CaseStmt*>(caseStmt);
336   CS->setSubStmt(SubStmt);
337 }
338 
339 StmtResult
340 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc,
341                        Stmt *SubStmt, Scope *CurScope) {
342   DiagnoseUnusedExprResult(SubStmt);
343 
344   if (getCurFunction()->SwitchStack.empty()) {
345     Diag(DefaultLoc, diag::err_default_not_in_switch);
346     return Owned(SubStmt);
347   }
348 
349   DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt);
350   getCurFunction()->SwitchStack.back()->addSwitchCase(DS);
351   return Owned(DS);
352 }
353 
354 StmtResult
355 Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
356                      SourceLocation ColonLoc, Stmt *SubStmt) {
357   // If the label was multiply defined, reject it now.
358   if (TheDecl->getStmt()) {
359     Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName();
360     Diag(TheDecl->getLocation(), diag::note_previous_definition);
361     return Owned(SubStmt);
362   }
363 
364   // Otherwise, things are good.  Fill in the declaration and return it.
365   LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt);
366   TheDecl->setStmt(LS);
367   if (!TheDecl->isGnuLocal())
368     TheDecl->setLocation(IdentLoc);
369   return Owned(LS);
370 }
371 
372 StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc,
373                                      const AttrVec &Attrs,
374                                      Stmt *SubStmt) {
375   // Fill in the declaration and return it. Variable length will require to
376   // change this to AttributedStmt::Create(Context, ....);
377   // and probably using ArrayRef
378   AttributedStmt *LS = new (Context) AttributedStmt(AttrLoc, Attrs, SubStmt);
379   return Owned(LS);
380 }
381 
382 StmtResult
383 Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar,
384                   Stmt *thenStmt, SourceLocation ElseLoc,
385                   Stmt *elseStmt) {
386   ExprResult CondResult(CondVal.release());
387 
388   VarDecl *ConditionVar = 0;
389   if (CondVar) {
390     ConditionVar = cast<VarDecl>(CondVar);
391     CondResult = CheckConditionVariable(ConditionVar, IfLoc, true);
392     if (CondResult.isInvalid())
393       return StmtError();
394   }
395   Expr *ConditionExpr = CondResult.takeAs<Expr>();
396   if (!ConditionExpr)
397     return StmtError();
398 
399   DiagnoseUnusedExprResult(thenStmt);
400 
401   if (!elseStmt) {
402     DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt,
403                           diag::warn_empty_if_body);
404   }
405 
406   DiagnoseUnusedExprResult(elseStmt);
407 
408   return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr,
409                                     thenStmt, ElseLoc, elseStmt));
410 }
411 
412 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
413 /// the specified width and sign.  If an overflow occurs, detect it and emit
414 /// the specified diagnostic.
415 void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val,
416                                               unsigned NewWidth, bool NewSign,
417                                               SourceLocation Loc,
418                                               unsigned DiagID) {
419   // Perform a conversion to the promoted condition type if needed.
420   if (NewWidth > Val.getBitWidth()) {
421     // If this is an extension, just do it.
422     Val = Val.extend(NewWidth);
423     Val.setIsSigned(NewSign);
424 
425     // If the input was signed and negative and the output is
426     // unsigned, don't bother to warn: this is implementation-defined
427     // behavior.
428     // FIXME: Introduce a second, default-ignored warning for this case?
429   } else if (NewWidth < Val.getBitWidth()) {
430     // If this is a truncation, check for overflow.
431     llvm::APSInt ConvVal(Val);
432     ConvVal = ConvVal.trunc(NewWidth);
433     ConvVal.setIsSigned(NewSign);
434     ConvVal = ConvVal.extend(Val.getBitWidth());
435     ConvVal.setIsSigned(Val.isSigned());
436     if (ConvVal != Val)
437       Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10);
438 
439     // Regardless of whether a diagnostic was emitted, really do the
440     // truncation.
441     Val = Val.trunc(NewWidth);
442     Val.setIsSigned(NewSign);
443   } else if (NewSign != Val.isSigned()) {
444     // Convert the sign to match the sign of the condition.  This can cause
445     // overflow as well: unsigned(INTMIN)
446     // We don't diagnose this overflow, because it is implementation-defined
447     // behavior.
448     // FIXME: Introduce a second, default-ignored warning for this case?
449     llvm::APSInt OldVal(Val);
450     Val.setIsSigned(NewSign);
451   }
452 }
453 
454 namespace {
455   struct CaseCompareFunctor {
456     bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
457                     const llvm::APSInt &RHS) {
458       return LHS.first < RHS;
459     }
460     bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS,
461                     const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
462       return LHS.first < RHS.first;
463     }
464     bool operator()(const llvm::APSInt &LHS,
465                     const std::pair<llvm::APSInt, CaseStmt*> &RHS) {
466       return LHS < RHS.first;
467     }
468   };
469 }
470 
471 /// CmpCaseVals - Comparison predicate for sorting case values.
472 ///
473 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs,
474                         const std::pair<llvm::APSInt, CaseStmt*>& rhs) {
475   if (lhs.first < rhs.first)
476     return true;
477 
478   if (lhs.first == rhs.first &&
479       lhs.second->getCaseLoc().getRawEncoding()
480        < rhs.second->getCaseLoc().getRawEncoding())
481     return true;
482   return false;
483 }
484 
485 /// CmpEnumVals - Comparison predicate for sorting enumeration values.
486 ///
487 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
488                         const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
489 {
490   return lhs.first < rhs.first;
491 }
492 
493 /// EqEnumVals - Comparison preficate for uniqing enumeration values.
494 ///
495 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs,
496                        const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs)
497 {
498   return lhs.first == rhs.first;
499 }
500 
501 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of
502 /// potentially integral-promoted expression @p expr.
503 static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) {
504   if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr))
505     expr = cleanups->getSubExpr();
506   while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) {
507     if (impcast->getCastKind() != CK_IntegralCast) break;
508     expr = impcast->getSubExpr();
509   }
510   return expr->getType();
511 }
512 
513 StmtResult
514 Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond,
515                              Decl *CondVar) {
516   ExprResult CondResult;
517 
518   VarDecl *ConditionVar = 0;
519   if (CondVar) {
520     ConditionVar = cast<VarDecl>(CondVar);
521     CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false);
522     if (CondResult.isInvalid())
523       return StmtError();
524 
525     Cond = CondResult.release();
526   }
527 
528   if (!Cond)
529     return StmtError();
530 
531   class SwitchConvertDiagnoser : public ICEConvertDiagnoser {
532     Expr *Cond;
533 
534   public:
535     SwitchConvertDiagnoser(Expr *Cond)
536       : ICEConvertDiagnoser(false, true), Cond(Cond) { }
537 
538     virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
539                                              QualType T) {
540       return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T;
541     }
542 
543     virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
544                                                  QualType T) {
545       return S.Diag(Loc, diag::err_switch_incomplete_class_type)
546                << T << Cond->getSourceRange();
547     }
548 
549     virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
550                                                    QualType T,
551                                                    QualType ConvTy) {
552       return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy;
553     }
554 
555     virtual DiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
556                                                QualType ConvTy) {
557       return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
558         << ConvTy->isEnumeralType() << ConvTy;
559     }
560 
561     virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
562                                                 QualType T) {
563       return S.Diag(Loc, diag::err_switch_multiple_conversions) << T;
564     }
565 
566     virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
567                                             QualType ConvTy) {
568       return S.Diag(Conv->getLocation(), diag::note_switch_conversion)
569       << ConvTy->isEnumeralType() << ConvTy;
570     }
571 
572     virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
573                                                  QualType T,
574                                                  QualType ConvTy) {
575       return DiagnosticBuilder::getEmpty();
576     }
577   } SwitchDiagnoser(Cond);
578 
579   CondResult
580     = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, SwitchDiagnoser,
581                                          /*AllowScopedEnumerations*/ true);
582   if (CondResult.isInvalid()) return StmtError();
583   Cond = CondResult.take();
584 
585   // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr.
586   CondResult = UsualUnaryConversions(Cond);
587   if (CondResult.isInvalid()) return StmtError();
588   Cond = CondResult.take();
589 
590   if (!CondVar) {
591     CheckImplicitConversions(Cond, SwitchLoc);
592     CondResult = MaybeCreateExprWithCleanups(Cond);
593     if (CondResult.isInvalid())
594       return StmtError();
595     Cond = CondResult.take();
596   }
597 
598   getCurFunction()->setHasBranchIntoScope();
599 
600   SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond);
601   getCurFunction()->SwitchStack.push_back(SS);
602   return Owned(SS);
603 }
604 
605 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) {
606   if (Val.getBitWidth() < BitWidth)
607     Val = Val.extend(BitWidth);
608   else if (Val.getBitWidth() > BitWidth)
609     Val = Val.trunc(BitWidth);
610   Val.setIsSigned(IsSigned);
611 }
612 
613 StmtResult
614 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch,
615                             Stmt *BodyStmt) {
616   SwitchStmt *SS = cast<SwitchStmt>(Switch);
617   assert(SS == getCurFunction()->SwitchStack.back() &&
618          "switch stack missing push/pop!");
619 
620   SS->setBody(BodyStmt, SwitchLoc);
621   getCurFunction()->SwitchStack.pop_back();
622 
623   Expr *CondExpr = SS->getCond();
624   if (!CondExpr) return StmtError();
625 
626   QualType CondType = CondExpr->getType();
627 
628   Expr *CondExprBeforePromotion = CondExpr;
629   QualType CondTypeBeforePromotion =
630       GetTypeBeforeIntegralPromotion(CondExprBeforePromotion);
631 
632   // C++ 6.4.2.p2:
633   // Integral promotions are performed (on the switch condition).
634   //
635   // A case value unrepresentable by the original switch condition
636   // type (before the promotion) doesn't make sense, even when it can
637   // be represented by the promoted type.  Therefore we need to find
638   // the pre-promotion type of the switch condition.
639   if (!CondExpr->isTypeDependent()) {
640     // We have already converted the expression to an integral or enumeration
641     // type, when we started the switch statement. If we don't have an
642     // appropriate type now, just return an error.
643     if (!CondType->isIntegralOrEnumerationType())
644       return StmtError();
645 
646     if (CondExpr->isKnownToHaveBooleanValue()) {
647       // switch(bool_expr) {...} is often a programmer error, e.g.
648       //   switch(n && mask) { ... }  // Doh - should be "n & mask".
649       // One can always use an if statement instead of switch(bool_expr).
650       Diag(SwitchLoc, diag::warn_bool_switch_condition)
651           << CondExpr->getSourceRange();
652     }
653   }
654 
655   // Get the bitwidth of the switched-on value before promotions.  We must
656   // convert the integer case values to this width before comparison.
657   bool HasDependentValue
658     = CondExpr->isTypeDependent() || CondExpr->isValueDependent();
659   unsigned CondWidth
660     = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion);
661   bool CondIsSigned
662     = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType();
663 
664   // Accumulate all of the case values in a vector so that we can sort them
665   // and detect duplicates.  This vector contains the APInt for the case after
666   // it has been converted to the condition type.
667   typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy;
668   CaseValsTy CaseVals;
669 
670   // Keep track of any GNU case ranges we see.  The APSInt is the low value.
671   typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy;
672   CaseRangesTy CaseRanges;
673 
674   DefaultStmt *TheDefaultStmt = 0;
675 
676   bool CaseListIsErroneous = false;
677 
678   for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
679        SC = SC->getNextSwitchCase()) {
680 
681     if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) {
682       if (TheDefaultStmt) {
683         Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined);
684         Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev);
685 
686         // FIXME: Remove the default statement from the switch block so that
687         // we'll return a valid AST.  This requires recursing down the AST and
688         // finding it, not something we are set up to do right now.  For now,
689         // just lop the entire switch stmt out of the AST.
690         CaseListIsErroneous = true;
691       }
692       TheDefaultStmt = DS;
693 
694     } else {
695       CaseStmt *CS = cast<CaseStmt>(SC);
696 
697       Expr *Lo = CS->getLHS();
698 
699       if (Lo->isTypeDependent() || Lo->isValueDependent()) {
700         HasDependentValue = true;
701         break;
702       }
703 
704       llvm::APSInt LoVal;
705 
706       if (getLangOpts().CPlusPlus0x) {
707         // C++11 [stmt.switch]p2: the constant-expression shall be a converted
708         // constant expression of the promoted type of the switch condition.
709         ExprResult ConvLo =
710           CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue);
711         if (ConvLo.isInvalid()) {
712           CaseListIsErroneous = true;
713           continue;
714         }
715         Lo = ConvLo.take();
716       } else {
717         // We already verified that the expression has a i-c-e value (C99
718         // 6.8.4.2p3) - get that value now.
719         LoVal = Lo->EvaluateKnownConstInt(Context);
720 
721         // If the LHS is not the same type as the condition, insert an implicit
722         // cast.
723         Lo = DefaultLvalueConversion(Lo).take();
724         Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take();
725       }
726 
727       // Convert the value to the same width/sign as the condition had prior to
728       // integral promotions.
729       //
730       // FIXME: This causes us to reject valid code:
731       //   switch ((char)c) { case 256: case 0: return 0; }
732       // Here we claim there is a duplicated condition value, but there is not.
733       ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned,
734                                          Lo->getLocStart(),
735                                          diag::warn_case_value_overflow);
736 
737       CS->setLHS(Lo);
738 
739       // If this is a case range, remember it in CaseRanges, otherwise CaseVals.
740       if (CS->getRHS()) {
741         if (CS->getRHS()->isTypeDependent() ||
742             CS->getRHS()->isValueDependent()) {
743           HasDependentValue = true;
744           break;
745         }
746         CaseRanges.push_back(std::make_pair(LoVal, CS));
747       } else
748         CaseVals.push_back(std::make_pair(LoVal, CS));
749     }
750   }
751 
752   if (!HasDependentValue) {
753     // If we don't have a default statement, check whether the
754     // condition is constant.
755     llvm::APSInt ConstantCondValue;
756     bool HasConstantCond = false;
757     if (!HasDependentValue && !TheDefaultStmt) {
758       HasConstantCond
759         = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context,
760                                                  Expr::SE_AllowSideEffects);
761       assert(!HasConstantCond ||
762              (ConstantCondValue.getBitWidth() == CondWidth &&
763               ConstantCondValue.isSigned() == CondIsSigned));
764     }
765     bool ShouldCheckConstantCond = HasConstantCond;
766 
767     // Sort all the scalar case values so we can easily detect duplicates.
768     std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals);
769 
770     if (!CaseVals.empty()) {
771       for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) {
772         if (ShouldCheckConstantCond &&
773             CaseVals[i].first == ConstantCondValue)
774           ShouldCheckConstantCond = false;
775 
776         if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) {
777           // If we have a duplicate, report it.
778           // First, determine if either case value has a name
779           StringRef PrevString, CurrString;
780           Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts();
781           Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts();
782           if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) {
783             PrevString = DeclRef->getDecl()->getName();
784           }
785           if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) {
786             CurrString = DeclRef->getDecl()->getName();
787           }
788           llvm::SmallString<16> CaseValStr;
789           CaseVals[i-1].first.toString(CaseValStr);
790 
791           if (PrevString == CurrString)
792             Diag(CaseVals[i].second->getLHS()->getLocStart(),
793                  diag::err_duplicate_case) <<
794                  (PrevString.empty() ? CaseValStr.str() : PrevString);
795           else
796             Diag(CaseVals[i].second->getLHS()->getLocStart(),
797                  diag::err_duplicate_case_differing_expr) <<
798                  (PrevString.empty() ? CaseValStr.str() : PrevString) <<
799                  (CurrString.empty() ? CaseValStr.str() : CurrString) <<
800                  CaseValStr;
801 
802           Diag(CaseVals[i-1].second->getLHS()->getLocStart(),
803                diag::note_duplicate_case_prev);
804           // FIXME: We really want to remove the bogus case stmt from the
805           // substmt, but we have no way to do this right now.
806           CaseListIsErroneous = true;
807         }
808       }
809     }
810 
811     // Detect duplicate case ranges, which usually don't exist at all in
812     // the first place.
813     if (!CaseRanges.empty()) {
814       // Sort all the case ranges by their low value so we can easily detect
815       // overlaps between ranges.
816       std::stable_sort(CaseRanges.begin(), CaseRanges.end());
817 
818       // Scan the ranges, computing the high values and removing empty ranges.
819       std::vector<llvm::APSInt> HiVals;
820       for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
821         llvm::APSInt &LoVal = CaseRanges[i].first;
822         CaseStmt *CR = CaseRanges[i].second;
823         Expr *Hi = CR->getRHS();
824         llvm::APSInt HiVal;
825 
826         if (getLangOpts().CPlusPlus0x) {
827           // C++11 [stmt.switch]p2: the constant-expression shall be a converted
828           // constant expression of the promoted type of the switch condition.
829           ExprResult ConvHi =
830             CheckConvertedConstantExpression(Hi, CondType, HiVal,
831                                              CCEK_CaseValue);
832           if (ConvHi.isInvalid()) {
833             CaseListIsErroneous = true;
834             continue;
835           }
836           Hi = ConvHi.take();
837         } else {
838           HiVal = Hi->EvaluateKnownConstInt(Context);
839 
840           // If the RHS is not the same type as the condition, insert an
841           // implicit cast.
842           Hi = DefaultLvalueConversion(Hi).take();
843           Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take();
844         }
845 
846         // Convert the value to the same width/sign as the condition.
847         ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned,
848                                            Hi->getLocStart(),
849                                            diag::warn_case_value_overflow);
850 
851         CR->setRHS(Hi);
852 
853         // If the low value is bigger than the high value, the case is empty.
854         if (LoVal > HiVal) {
855           Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range)
856             << SourceRange(CR->getLHS()->getLocStart(),
857                            Hi->getLocEnd());
858           CaseRanges.erase(CaseRanges.begin()+i);
859           --i, --e;
860           continue;
861         }
862 
863         if (ShouldCheckConstantCond &&
864             LoVal <= ConstantCondValue &&
865             ConstantCondValue <= HiVal)
866           ShouldCheckConstantCond = false;
867 
868         HiVals.push_back(HiVal);
869       }
870 
871       // Rescan the ranges, looking for overlap with singleton values and other
872       // ranges.  Since the range list is sorted, we only need to compare case
873       // ranges with their neighbors.
874       for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) {
875         llvm::APSInt &CRLo = CaseRanges[i].first;
876         llvm::APSInt &CRHi = HiVals[i];
877         CaseStmt *CR = CaseRanges[i].second;
878 
879         // Check to see whether the case range overlaps with any
880         // singleton cases.
881         CaseStmt *OverlapStmt = 0;
882         llvm::APSInt OverlapVal(32);
883 
884         // Find the smallest value >= the lower bound.  If I is in the
885         // case range, then we have overlap.
886         CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(),
887                                                   CaseVals.end(), CRLo,
888                                                   CaseCompareFunctor());
889         if (I != CaseVals.end() && I->first < CRHi) {
890           OverlapVal  = I->first;   // Found overlap with scalar.
891           OverlapStmt = I->second;
892         }
893 
894         // Find the smallest value bigger than the upper bound.
895         I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor());
896         if (I != CaseVals.begin() && (I-1)->first >= CRLo) {
897           OverlapVal  = (I-1)->first;      // Found overlap with scalar.
898           OverlapStmt = (I-1)->second;
899         }
900 
901         // Check to see if this case stmt overlaps with the subsequent
902         // case range.
903         if (i && CRLo <= HiVals[i-1]) {
904           OverlapVal  = HiVals[i-1];       // Found overlap with range.
905           OverlapStmt = CaseRanges[i-1].second;
906         }
907 
908         if (OverlapStmt) {
909           // If we have a duplicate, report it.
910           Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case)
911             << OverlapVal.toString(10);
912           Diag(OverlapStmt->getLHS()->getLocStart(),
913                diag::note_duplicate_case_prev);
914           // FIXME: We really want to remove the bogus case stmt from the
915           // substmt, but we have no way to do this right now.
916           CaseListIsErroneous = true;
917         }
918       }
919     }
920 
921     // Complain if we have a constant condition and we didn't find a match.
922     if (!CaseListIsErroneous && ShouldCheckConstantCond) {
923       // TODO: it would be nice if we printed enums as enums, chars as
924       // chars, etc.
925       Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition)
926         << ConstantCondValue.toString(10)
927         << CondExpr->getSourceRange();
928     }
929 
930     // Check to see if switch is over an Enum and handles all of its
931     // values.  We only issue a warning if there is not 'default:', but
932     // we still do the analysis to preserve this information in the AST
933     // (which can be used by flow-based analyes).
934     //
935     const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>();
936 
937     // If switch has default case, then ignore it.
938     if (!CaseListIsErroneous  && !HasConstantCond && ET) {
939       const EnumDecl *ED = ET->getDecl();
940       typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64>
941         EnumValsTy;
942       EnumValsTy EnumVals;
943 
944       // Gather all enum values, set their type and sort them,
945       // allowing easier comparison with CaseVals.
946       for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin();
947            EDI != ED->enumerator_end(); ++EDI) {
948         llvm::APSInt Val = EDI->getInitVal();
949         AdjustAPSInt(Val, CondWidth, CondIsSigned);
950         EnumVals.push_back(std::make_pair(Val, *EDI));
951       }
952       std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals);
953       EnumValsTy::iterator EIend =
954         std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals);
955 
956       // See which case values aren't in enum.
957       EnumValsTy::const_iterator EI = EnumVals.begin();
958       for (CaseValsTy::const_iterator CI = CaseVals.begin();
959            CI != CaseVals.end(); CI++) {
960         while (EI != EIend && EI->first < CI->first)
961           EI++;
962         if (EI == EIend || EI->first > CI->first)
963           Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
964             << CondTypeBeforePromotion;
965       }
966       // See which of case ranges aren't in enum
967       EI = EnumVals.begin();
968       for (CaseRangesTy::const_iterator RI = CaseRanges.begin();
969            RI != CaseRanges.end() && EI != EIend; RI++) {
970         while (EI != EIend && EI->first < RI->first)
971           EI++;
972 
973         if (EI == EIend || EI->first != RI->first) {
974           Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum)
975             << CondTypeBeforePromotion;
976         }
977 
978         llvm::APSInt Hi =
979           RI->second->getRHS()->EvaluateKnownConstInt(Context);
980         AdjustAPSInt(Hi, CondWidth, CondIsSigned);
981         while (EI != EIend && EI->first < Hi)
982           EI++;
983         if (EI == EIend || EI->first != Hi)
984           Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum)
985             << CondTypeBeforePromotion;
986       }
987 
988       // Check which enum vals aren't in switch
989       CaseValsTy::const_iterator CI = CaseVals.begin();
990       CaseRangesTy::const_iterator RI = CaseRanges.begin();
991       bool hasCasesNotInSwitch = false;
992 
993       SmallVector<DeclarationName,8> UnhandledNames;
994 
995       for (EI = EnumVals.begin(); EI != EIend; EI++){
996         // Drop unneeded case values
997         llvm::APSInt CIVal;
998         while (CI != CaseVals.end() && CI->first < EI->first)
999           CI++;
1000 
1001         if (CI != CaseVals.end() && CI->first == EI->first)
1002           continue;
1003 
1004         // Drop unneeded case ranges
1005         for (; RI != CaseRanges.end(); RI++) {
1006           llvm::APSInt Hi =
1007             RI->second->getRHS()->EvaluateKnownConstInt(Context);
1008           AdjustAPSInt(Hi, CondWidth, CondIsSigned);
1009           if (EI->first <= Hi)
1010             break;
1011         }
1012 
1013         if (RI == CaseRanges.end() || EI->first < RI->first) {
1014           hasCasesNotInSwitch = true;
1015           UnhandledNames.push_back(EI->second->getDeclName());
1016         }
1017       }
1018 
1019       if (TheDefaultStmt && UnhandledNames.empty())
1020         Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default);
1021 
1022       // Produce a nice diagnostic if multiple values aren't handled.
1023       switch (UnhandledNames.size()) {
1024       case 0: break;
1025       case 1:
1026         Diag(CondExpr->getExprLoc(), TheDefaultStmt
1027           ? diag::warn_def_missing_case1 : diag::warn_missing_case1)
1028           << UnhandledNames[0];
1029         break;
1030       case 2:
1031         Diag(CondExpr->getExprLoc(), TheDefaultStmt
1032           ? diag::warn_def_missing_case2 : diag::warn_missing_case2)
1033           << UnhandledNames[0] << UnhandledNames[1];
1034         break;
1035       case 3:
1036         Diag(CondExpr->getExprLoc(), TheDefaultStmt
1037           ? diag::warn_def_missing_case3 : diag::warn_missing_case3)
1038           << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1039         break;
1040       default:
1041         Diag(CondExpr->getExprLoc(), TheDefaultStmt
1042           ? diag::warn_def_missing_cases : diag::warn_missing_cases)
1043           << (unsigned)UnhandledNames.size()
1044           << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2];
1045         break;
1046       }
1047 
1048       if (!hasCasesNotInSwitch)
1049         SS->setAllEnumCasesCovered();
1050     }
1051   }
1052 
1053   DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt,
1054                         diag::warn_empty_switch_body);
1055 
1056   // FIXME: If the case list was broken is some way, we don't have a good system
1057   // to patch it up.  Instead, just return the whole substmt as broken.
1058   if (CaseListIsErroneous)
1059     return StmtError();
1060 
1061   return Owned(SS);
1062 }
1063 
1064 StmtResult
1065 Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond,
1066                      Decl *CondVar, Stmt *Body) {
1067   ExprResult CondResult(Cond.release());
1068 
1069   VarDecl *ConditionVar = 0;
1070   if (CondVar) {
1071     ConditionVar = cast<VarDecl>(CondVar);
1072     CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true);
1073     if (CondResult.isInvalid())
1074       return StmtError();
1075   }
1076   Expr *ConditionExpr = CondResult.take();
1077   if (!ConditionExpr)
1078     return StmtError();
1079 
1080   DiagnoseUnusedExprResult(Body);
1081 
1082   if (isa<NullStmt>(Body))
1083     getCurCompoundScope().setHasEmptyLoopBodies();
1084 
1085   return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr,
1086                                        Body, WhileLoc));
1087 }
1088 
1089 StmtResult
1090 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
1091                   SourceLocation WhileLoc, SourceLocation CondLParen,
1092                   Expr *Cond, SourceLocation CondRParen) {
1093   assert(Cond && "ActOnDoStmt(): missing expression");
1094 
1095   ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc);
1096   if (CondResult.isInvalid() || CondResult.isInvalid())
1097     return StmtError();
1098   Cond = CondResult.take();
1099 
1100   CheckImplicitConversions(Cond, DoLoc);
1101   CondResult = MaybeCreateExprWithCleanups(Cond);
1102   if (CondResult.isInvalid())
1103     return StmtError();
1104   Cond = CondResult.take();
1105 
1106   DiagnoseUnusedExprResult(Body);
1107 
1108   return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen));
1109 }
1110 
1111 namespace {
1112   // This visitor will traverse a conditional statement and store all
1113   // the evaluated decls into a vector.  Simple is set to true if none
1114   // of the excluded constructs are used.
1115   class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> {
1116     llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1117     llvm::SmallVector<SourceRange, 10> &Ranges;
1118     bool Simple;
1119 public:
1120   typedef EvaluatedExprVisitor<DeclExtractor> Inherited;
1121 
1122   DeclExtractor(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls,
1123                 llvm::SmallVector<SourceRange, 10> &Ranges) :
1124       Inherited(S.Context),
1125       Decls(Decls),
1126       Ranges(Ranges),
1127       Simple(true) {}
1128 
1129   bool isSimple() { return Simple; }
1130 
1131   // Replaces the method in EvaluatedExprVisitor.
1132   void VisitMemberExpr(MemberExpr* E) {
1133     Simple = false;
1134   }
1135 
1136   // Any Stmt not whitelisted will cause the condition to be marked complex.
1137   void VisitStmt(Stmt *S) {
1138     Simple = false;
1139   }
1140 
1141   void VisitBinaryOperator(BinaryOperator *E) {
1142     Visit(E->getLHS());
1143     Visit(E->getRHS());
1144   }
1145 
1146   void VisitCastExpr(CastExpr *E) {
1147     Visit(E->getSubExpr());
1148   }
1149 
1150   void VisitUnaryOperator(UnaryOperator *E) {
1151     // Skip checking conditionals with derefernces.
1152     if (E->getOpcode() == UO_Deref)
1153       Simple = false;
1154     else
1155       Visit(E->getSubExpr());
1156   }
1157 
1158   void VisitConditionalOperator(ConditionalOperator *E) {
1159     Visit(E->getCond());
1160     Visit(E->getTrueExpr());
1161     Visit(E->getFalseExpr());
1162   }
1163 
1164   void VisitParenExpr(ParenExpr *E) {
1165     Visit(E->getSubExpr());
1166   }
1167 
1168   void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
1169     Visit(E->getOpaqueValue()->getSourceExpr());
1170     Visit(E->getFalseExpr());
1171   }
1172 
1173   void VisitIntegerLiteral(IntegerLiteral *E) { }
1174   void VisitFloatingLiteral(FloatingLiteral *E) { }
1175   void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { }
1176   void VisitCharacterLiteral(CharacterLiteral *E) { }
1177   void VisitGNUNullExpr(GNUNullExpr *E) { }
1178   void VisitImaginaryLiteral(ImaginaryLiteral *E) { }
1179 
1180   void VisitDeclRefExpr(DeclRefExpr *E) {
1181     VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
1182     if (!VD) return;
1183 
1184     Ranges.push_back(E->getSourceRange());
1185 
1186     Decls.insert(VD);
1187   }
1188 
1189   }; // end class DeclExtractor
1190 
1191   // DeclMatcher checks to see if the decls are used in a non-evauluated
1192   // context.
1193   class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> {
1194     llvm::SmallPtrSet<VarDecl*, 8> &Decls;
1195     bool FoundDecl;
1196 
1197 public:
1198   typedef EvaluatedExprVisitor<DeclMatcher> Inherited;
1199 
1200   DeclMatcher(Sema &S, llvm::SmallPtrSet<VarDecl*, 8> &Decls, Stmt *Statement) :
1201       Inherited(S.Context), Decls(Decls), FoundDecl(false) {
1202     if (!Statement) return;
1203 
1204     Visit(Statement);
1205   }
1206 
1207   void VisitReturnStmt(ReturnStmt *S) {
1208     FoundDecl = true;
1209   }
1210 
1211   void VisitBreakStmt(BreakStmt *S) {
1212     FoundDecl = true;
1213   }
1214 
1215   void VisitGotoStmt(GotoStmt *S) {
1216     FoundDecl = true;
1217   }
1218 
1219   void VisitCastExpr(CastExpr *E) {
1220     if (E->getCastKind() == CK_LValueToRValue)
1221       CheckLValueToRValueCast(E->getSubExpr());
1222     else
1223       Visit(E->getSubExpr());
1224   }
1225 
1226   void CheckLValueToRValueCast(Expr *E) {
1227     E = E->IgnoreParenImpCasts();
1228 
1229     if (isa<DeclRefExpr>(E)) {
1230       return;
1231     }
1232 
1233     if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1234       Visit(CO->getCond());
1235       CheckLValueToRValueCast(CO->getTrueExpr());
1236       CheckLValueToRValueCast(CO->getFalseExpr());
1237       return;
1238     }
1239 
1240     if (BinaryConditionalOperator *BCO =
1241             dyn_cast<BinaryConditionalOperator>(E)) {
1242       CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr());
1243       CheckLValueToRValueCast(BCO->getFalseExpr());
1244       return;
1245     }
1246 
1247     Visit(E);
1248   }
1249 
1250   void VisitDeclRefExpr(DeclRefExpr *E) {
1251     if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
1252       if (Decls.count(VD))
1253         FoundDecl = true;
1254   }
1255 
1256   bool FoundDeclInUse() { return FoundDecl; }
1257 
1258   };  // end class DeclMatcher
1259 
1260   void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
1261                                         Expr *Third, Stmt *Body) {
1262     // Condition is empty
1263     if (!Second) return;
1264 
1265     if (S.Diags.getDiagnosticLevel(diag::warn_variables_not_in_loop_body,
1266                                    Second->getLocStart())
1267         == DiagnosticsEngine::Ignored)
1268       return;
1269 
1270     PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body);
1271     llvm::SmallPtrSet<VarDecl*, 8> Decls;
1272     llvm::SmallVector<SourceRange, 10> Ranges;
1273     DeclExtractor DE(S, Decls, Ranges);
1274     DE.Visit(Second);
1275 
1276     // Don't analyze complex conditionals.
1277     if (!DE.isSimple()) return;
1278 
1279     // No decls found.
1280     if (Decls.size() == 0) return;
1281 
1282     // Don't warn on volatile, static, or global variables.
1283     for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1284                                                   E = Decls.end();
1285          I != E; ++I)
1286       if ((*I)->getType().isVolatileQualified() ||
1287           (*I)->hasGlobalStorage()) return;
1288 
1289     if (DeclMatcher(S, Decls, Second).FoundDeclInUse() ||
1290         DeclMatcher(S, Decls, Third).FoundDeclInUse() ||
1291         DeclMatcher(S, Decls, Body).FoundDeclInUse())
1292       return;
1293 
1294     // Load decl names into diagnostic.
1295     if (Decls.size() > 4)
1296       PDiag << 0;
1297     else {
1298       PDiag << Decls.size();
1299       for (llvm::SmallPtrSet<VarDecl*, 8>::iterator I = Decls.begin(),
1300                                                     E = Decls.end();
1301            I != E; ++I)
1302         PDiag << (*I)->getDeclName();
1303     }
1304 
1305     // Load SourceRanges into diagnostic if there is room.
1306     // Otherwise, load the SourceRange of the conditional expression.
1307     if (Ranges.size() <= PartialDiagnostic::MaxArguments)
1308       for (llvm::SmallVector<SourceRange, 10>::iterator I = Ranges.begin(),
1309                                                         E = Ranges.end();
1310            I != E; ++I)
1311         PDiag << *I;
1312     else
1313       PDiag << Second->getSourceRange();
1314 
1315     S.Diag(Ranges.begin()->getBegin(), PDiag);
1316   }
1317 
1318 } // end namespace
1319 
1320 StmtResult
1321 Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1322                    Stmt *First, FullExprArg second, Decl *secondVar,
1323                    FullExprArg third,
1324                    SourceLocation RParenLoc, Stmt *Body) {
1325   if (!getLangOpts().CPlusPlus) {
1326     if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) {
1327       // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1328       // declare identifiers for objects having storage class 'auto' or
1329       // 'register'.
1330       for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
1331            DI!=DE; ++DI) {
1332         VarDecl *VD = dyn_cast<VarDecl>(*DI);
1333         if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage())
1334           VD = 0;
1335         if (VD == 0)
1336           Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for);
1337         // FIXME: mark decl erroneous!
1338       }
1339     }
1340   }
1341 
1342   CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body);
1343 
1344   ExprResult SecondResult(second.release());
1345   VarDecl *ConditionVar = 0;
1346   if (secondVar) {
1347     ConditionVar = cast<VarDecl>(secondVar);
1348     SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true);
1349     if (SecondResult.isInvalid())
1350       return StmtError();
1351   }
1352 
1353   Expr *Third  = third.release().takeAs<Expr>();
1354 
1355   DiagnoseUnusedExprResult(First);
1356   DiagnoseUnusedExprResult(Third);
1357   DiagnoseUnusedExprResult(Body);
1358 
1359   if (isa<NullStmt>(Body))
1360     getCurCompoundScope().setHasEmptyLoopBodies();
1361 
1362   return Owned(new (Context) ForStmt(Context, First,
1363                                      SecondResult.take(), ConditionVar,
1364                                      Third, Body, ForLoc, LParenLoc,
1365                                      RParenLoc));
1366 }
1367 
1368 /// In an Objective C collection iteration statement:
1369 ///   for (x in y)
1370 /// x can be an arbitrary l-value expression.  Bind it up as a
1371 /// full-expression.
1372 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) {
1373   // Reduce placeholder expressions here.  Note that this rejects the
1374   // use of pseudo-object l-values in this position.
1375   ExprResult result = CheckPlaceholderExpr(E);
1376   if (result.isInvalid()) return StmtError();
1377   E = result.take();
1378 
1379   CheckImplicitConversions(E);
1380 
1381   result = MaybeCreateExprWithCleanups(E);
1382   if (result.isInvalid()) return StmtError();
1383 
1384   return Owned(static_cast<Stmt*>(result.take()));
1385 }
1386 
1387 ExprResult
1388 Sema::ActOnObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) {
1389   assert(collection);
1390 
1391   // Bail out early if we've got a type-dependent expression.
1392   if (collection->isTypeDependent()) return Owned(collection);
1393 
1394   // Perform normal l-value conversion.
1395   ExprResult result = DefaultFunctionArrayLvalueConversion(collection);
1396   if (result.isInvalid())
1397     return ExprError();
1398   collection = result.take();
1399 
1400   // The operand needs to have object-pointer type.
1401   // TODO: should we do a contextual conversion?
1402   const ObjCObjectPointerType *pointerType =
1403     collection->getType()->getAs<ObjCObjectPointerType>();
1404   if (!pointerType)
1405     return Diag(forLoc, diag::err_collection_expr_type)
1406              << collection->getType() << collection->getSourceRange();
1407 
1408   // Check that the operand provides
1409   //   - countByEnumeratingWithState:objects:count:
1410   const ObjCObjectType *objectType = pointerType->getObjectType();
1411   ObjCInterfaceDecl *iface = objectType->getInterface();
1412 
1413   // If we have a forward-declared type, we can't do this check.
1414   // Under ARC, it is an error not to have a forward-declared class.
1415   if (iface &&
1416       RequireCompleteType(forLoc, QualType(objectType, 0),
1417                           getLangOpts().ObjCAutoRefCount
1418                             ? diag::err_arc_collection_forward
1419                             : 0,
1420                           collection)) {
1421     // Otherwise, if we have any useful type information, check that
1422     // the type declares the appropriate method.
1423   } else if (iface || !objectType->qual_empty()) {
1424     IdentifierInfo *selectorIdents[] = {
1425       &Context.Idents.get("countByEnumeratingWithState"),
1426       &Context.Idents.get("objects"),
1427       &Context.Idents.get("count")
1428     };
1429     Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]);
1430 
1431     ObjCMethodDecl *method = 0;
1432 
1433     // If there's an interface, look in both the public and private APIs.
1434     if (iface) {
1435       method = iface->lookupInstanceMethod(selector);
1436       if (!method) method = LookupPrivateInstanceMethod(selector, iface);
1437     }
1438 
1439     // Also check protocol qualifiers.
1440     if (!method)
1441       method = LookupMethodInQualifiedType(selector, pointerType,
1442                                            /*instance*/ true);
1443 
1444     // If we didn't find it anywhere, give up.
1445     if (!method) {
1446       Diag(forLoc, diag::warn_collection_expr_type)
1447         << collection->getType() << selector << collection->getSourceRange();
1448     }
1449 
1450     // TODO: check for an incompatible signature?
1451   }
1452 
1453   // Wrap up any cleanups in the expression.
1454   return Owned(MaybeCreateExprWithCleanups(collection));
1455 }
1456 
1457 StmtResult
1458 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc,
1459                                  SourceLocation LParenLoc,
1460                                  Stmt *First, Expr *Second,
1461                                  SourceLocation RParenLoc, Stmt *Body) {
1462   if (First) {
1463     QualType FirstType;
1464     if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) {
1465       if (!DS->isSingleDecl())
1466         return StmtError(Diag((*DS->decl_begin())->getLocation(),
1467                          diag::err_toomany_element_decls));
1468 
1469       VarDecl *D = cast<VarDecl>(DS->getSingleDecl());
1470       FirstType = D->getType();
1471       // C99 6.8.5p3: The declaration part of a 'for' statement shall only
1472       // declare identifiers for objects having storage class 'auto' or
1473       // 'register'.
1474       if (!D->hasLocalStorage())
1475         return StmtError(Diag(D->getLocation(),
1476                               diag::err_non_variable_decl_in_for));
1477     } else {
1478       Expr *FirstE = cast<Expr>(First);
1479       if (!FirstE->isTypeDependent() && !FirstE->isLValue())
1480         return StmtError(Diag(First->getLocStart(),
1481                    diag::err_selector_element_not_lvalue)
1482           << First->getSourceRange());
1483 
1484       FirstType = static_cast<Expr*>(First)->getType();
1485     }
1486     if (!FirstType->isDependentType() &&
1487         !FirstType->isObjCObjectPointerType() &&
1488         !FirstType->isBlockPointerType())
1489         Diag(ForLoc, diag::err_selector_element_type)
1490           << FirstType << First->getSourceRange();
1491   }
1492 
1493   return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body,
1494                                                    ForLoc, RParenLoc));
1495 }
1496 
1497 namespace {
1498 
1499 enum BeginEndFunction {
1500   BEF_begin,
1501   BEF_end
1502 };
1503 
1504 /// Build a variable declaration for a for-range statement.
1505 static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc,
1506                                      QualType Type, const char *Name) {
1507   DeclContext *DC = SemaRef.CurContext;
1508   IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1509   TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
1510   VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type,
1511                                   TInfo, SC_Auto, SC_None);
1512   Decl->setImplicit();
1513   return Decl;
1514 }
1515 
1516 /// Finish building a variable declaration for a for-range statement.
1517 /// \return true if an error occurs.
1518 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init,
1519                                   SourceLocation Loc, int diag) {
1520   // Deduce the type for the iterator variable now rather than leaving it to
1521   // AddInitializerToDecl, so we can produce a more suitable diagnostic.
1522   TypeSourceInfo *InitTSI = 0;
1523   if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) ||
1524       SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) ==
1525           Sema::DAR_Failed)
1526     SemaRef.Diag(Loc, diag) << Init->getType();
1527   if (!InitTSI) {
1528     Decl->setInvalidDecl();
1529     return true;
1530   }
1531   Decl->setTypeSourceInfo(InitTSI);
1532   Decl->setType(InitTSI->getType());
1533 
1534   // In ARC, infer lifetime.
1535   // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if
1536   // we're doing the equivalent of fast iteration.
1537   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1538       SemaRef.inferObjCARCLifetime(Decl))
1539     Decl->setInvalidDecl();
1540 
1541   SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false,
1542                                /*TypeMayContainAuto=*/false);
1543   SemaRef.FinalizeDeclaration(Decl);
1544   SemaRef.CurContext->addHiddenDecl(Decl);
1545   return false;
1546 }
1547 
1548 /// Produce a note indicating which begin/end function was implicitly called
1549 /// by a C++0x for-range statement. This is often not obvious from the code,
1550 /// nor from the diagnostics produced when analysing the implicit expressions
1551 /// required in a for-range statement.
1552 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E,
1553                                   BeginEndFunction BEF) {
1554   CallExpr *CE = dyn_cast<CallExpr>(E);
1555   if (!CE)
1556     return;
1557   FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1558   if (!D)
1559     return;
1560   SourceLocation Loc = D->getLocation();
1561 
1562   std::string Description;
1563   bool IsTemplate = false;
1564   if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) {
1565     Description = SemaRef.getTemplateArgumentBindingsText(
1566       FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs());
1567     IsTemplate = true;
1568   }
1569 
1570   SemaRef.Diag(Loc, diag::note_for_range_begin_end)
1571     << BEF << IsTemplate << Description << E->getType();
1572 }
1573 
1574 /// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the
1575 /// given LookupResult is non-empty, it is assumed to describe a member which
1576 /// will be invoked. Otherwise, the function will be found via argument
1577 /// dependent lookup.
1578 static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S,
1579                                             SourceLocation Loc,
1580                                             VarDecl *Decl,
1581                                             BeginEndFunction BEF,
1582                                             const DeclarationNameInfo &NameInfo,
1583                                             LookupResult &MemberLookup,
1584                                             Expr *Range) {
1585   ExprResult CallExpr;
1586   if (!MemberLookup.empty()) {
1587     ExprResult MemberRef =
1588       SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc,
1589                                        /*IsPtr=*/false, CXXScopeSpec(),
1590                                        /*TemplateKWLoc=*/SourceLocation(),
1591                                        /*FirstQualifierInScope=*/0,
1592                                        MemberLookup,
1593                                        /*TemplateArgs=*/0);
1594     if (MemberRef.isInvalid())
1595       return ExprError();
1596     CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(),
1597                                      Loc, 0);
1598     if (CallExpr.isInvalid())
1599       return ExprError();
1600   } else {
1601     UnresolvedSet<0> FoundNames;
1602     // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace
1603     // std is an associated namespace.
1604     UnresolvedLookupExpr *Fn =
1605       UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0,
1606                                    NestedNameSpecifierLoc(), NameInfo,
1607                                    /*NeedsADL=*/true, /*Overloaded=*/false,
1608                                    FoundNames.begin(), FoundNames.end(),
1609                                    /*LookInStdNamespace=*/true);
1610     CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc,
1611                                                0, /*AllowTypoCorrection=*/false);
1612     if (CallExpr.isInvalid()) {
1613       SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type)
1614         << Range->getType();
1615       return ExprError();
1616     }
1617   }
1618   if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc,
1619                             diag::err_for_range_iter_deduction_failure)) {
1620     NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF);
1621     return ExprError();
1622   }
1623   return CallExpr;
1624 }
1625 
1626 }
1627 
1628 /// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement.
1629 ///
1630 /// C++0x [stmt.ranged]:
1631 ///   A range-based for statement is equivalent to
1632 ///
1633 ///   {
1634 ///     auto && __range = range-init;
1635 ///     for ( auto __begin = begin-expr,
1636 ///           __end = end-expr;
1637 ///           __begin != __end;
1638 ///           ++__begin ) {
1639 ///       for-range-declaration = *__begin;
1640 ///       statement
1641 ///     }
1642 ///   }
1643 ///
1644 /// The body of the loop is not available yet, since it cannot be analysed until
1645 /// we have determined the type of the for-range-declaration.
1646 StmtResult
1647 Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1648                            Stmt *First, SourceLocation ColonLoc, Expr *Range,
1649                            SourceLocation RParenLoc) {
1650   if (!First || !Range)
1651     return StmtError();
1652 
1653   DeclStmt *DS = dyn_cast<DeclStmt>(First);
1654   assert(DS && "first part of for range not a decl stmt");
1655 
1656   if (!DS->isSingleDecl()) {
1657     Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range);
1658     return StmtError();
1659   }
1660   if (DS->getSingleDecl()->isInvalidDecl())
1661     return StmtError();
1662 
1663   if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression))
1664     return StmtError();
1665 
1666   // Build  auto && __range = range-init
1667   SourceLocation RangeLoc = Range->getLocStart();
1668   VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc,
1669                                            Context.getAutoRRefDeductType(),
1670                                            "__range");
1671   if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc,
1672                             diag::err_for_range_deduction_failure))
1673     return StmtError();
1674 
1675   // Claim the type doesn't contain auto: we've already done the checking.
1676   DeclGroupPtrTy RangeGroup =
1677     BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false);
1678   StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc);
1679   if (RangeDecl.isInvalid())
1680     return StmtError();
1681 
1682   return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(),
1683                               /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS,
1684                               RParenLoc);
1685 }
1686 
1687 /// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement.
1688 StmtResult
1689 Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc,
1690                            Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond,
1691                            Expr *Inc, Stmt *LoopVarDecl,
1692                            SourceLocation RParenLoc) {
1693   Scope *S = getCurScope();
1694 
1695   DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl);
1696   VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl());
1697   QualType RangeVarType = RangeVar->getType();
1698 
1699   DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl);
1700   VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl());
1701 
1702   StmtResult BeginEndDecl = BeginEnd;
1703   ExprResult NotEqExpr = Cond, IncrExpr = Inc;
1704 
1705   if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) {
1706     SourceLocation RangeLoc = RangeVar->getLocation();
1707 
1708     const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType();
1709 
1710     ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1711                                                 VK_LValue, ColonLoc);
1712     if (BeginRangeRef.isInvalid())
1713       return StmtError();
1714 
1715     ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType,
1716                                               VK_LValue, ColonLoc);
1717     if (EndRangeRef.isInvalid())
1718       return StmtError();
1719 
1720     QualType AutoType = Context.getAutoDeductType();
1721     Expr *Range = RangeVar->getInit();
1722     if (!Range)
1723       return StmtError();
1724     QualType RangeType = Range->getType();
1725 
1726     if (RequireCompleteType(RangeLoc, RangeType,
1727                             diag::err_for_range_incomplete_type))
1728       return StmtError();
1729 
1730     // Build auto __begin = begin-expr, __end = end-expr.
1731     VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1732                                              "__begin");
1733     VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType,
1734                                            "__end");
1735 
1736     // Build begin-expr and end-expr and attach to __begin and __end variables.
1737     ExprResult BeginExpr, EndExpr;
1738     if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) {
1739       // - if _RangeT is an array type, begin-expr and end-expr are __range and
1740       //   __range + __bound, respectively, where __bound is the array bound. If
1741       //   _RangeT is an array of unknown size or an array of incomplete type,
1742       //   the program is ill-formed;
1743 
1744       // begin-expr is __range.
1745       BeginExpr = BeginRangeRef;
1746       if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc,
1747                                 diag::err_for_range_iter_deduction_failure)) {
1748         NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1749         return StmtError();
1750       }
1751 
1752       // Find the array bound.
1753       ExprResult BoundExpr;
1754       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT))
1755         BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(),
1756                                                  Context.getPointerDiffType(),
1757                                                  RangeLoc));
1758       else if (const VariableArrayType *VAT =
1759                dyn_cast<VariableArrayType>(UnqAT))
1760         BoundExpr = VAT->getSizeExpr();
1761       else {
1762         // Can't be a DependentSizedArrayType or an IncompleteArrayType since
1763         // UnqAT is not incomplete and Range is not type-dependent.
1764         llvm_unreachable("Unexpected array type in for-range");
1765       }
1766 
1767       // end-expr is __range + __bound.
1768       EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(),
1769                            BoundExpr.get());
1770       if (EndExpr.isInvalid())
1771         return StmtError();
1772       if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc,
1773                                 diag::err_for_range_iter_deduction_failure)) {
1774         NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1775         return StmtError();
1776       }
1777     } else {
1778       DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"),
1779                                         ColonLoc);
1780       DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"),
1781                                       ColonLoc);
1782 
1783       LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName);
1784       LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName);
1785 
1786       if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) {
1787         // - if _RangeT is a class type, the unqualified-ids begin and end are
1788         //   looked up in the scope of class _RangeT as if by class member access
1789         //   lookup (3.4.5), and if either (or both) finds at least one
1790         //   declaration, begin-expr and end-expr are __range.begin() and
1791         //   __range.end(), respectively;
1792         LookupQualifiedName(BeginMemberLookup, D);
1793         LookupQualifiedName(EndMemberLookup, D);
1794 
1795         if (BeginMemberLookup.empty() != EndMemberLookup.empty()) {
1796           Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch)
1797             << RangeType << BeginMemberLookup.empty();
1798           return StmtError();
1799         }
1800       } else {
1801         // - otherwise, begin-expr and end-expr are begin(__range) and
1802         //   end(__range), respectively, where begin and end are looked up with
1803         //   argument-dependent lookup (3.4.2). For the purposes of this name
1804         //   lookup, namespace std is an associated namespace.
1805       }
1806 
1807       BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar,
1808                                             BEF_begin, BeginNameInfo,
1809                                             BeginMemberLookup,
1810                                             BeginRangeRef.get());
1811       if (BeginExpr.isInvalid())
1812         return StmtError();
1813 
1814       EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar,
1815                                           BEF_end, EndNameInfo,
1816                                           EndMemberLookup, EndRangeRef.get());
1817       if (EndExpr.isInvalid())
1818         return StmtError();
1819     }
1820 
1821     // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same.
1822     QualType BeginType = BeginVar->getType(), EndType = EndVar->getType();
1823     if (!Context.hasSameType(BeginType, EndType)) {
1824       Diag(RangeLoc, diag::err_for_range_begin_end_types_differ)
1825         << BeginType << EndType;
1826       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1827       NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1828     }
1829 
1830     Decl *BeginEndDecls[] = { BeginVar, EndVar };
1831     // Claim the type doesn't contain auto: we've already done the checking.
1832     DeclGroupPtrTy BeginEndGroup =
1833       BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false);
1834     BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc);
1835 
1836     const QualType BeginRefNonRefType = BeginType.getNonReferenceType();
1837     ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1838                                            VK_LValue, ColonLoc);
1839     if (BeginRef.isInvalid())
1840       return StmtError();
1841 
1842     ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(),
1843                                          VK_LValue, ColonLoc);
1844     if (EndRef.isInvalid())
1845       return StmtError();
1846 
1847     // Build and check __begin != __end expression.
1848     NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal,
1849                            BeginRef.get(), EndRef.get());
1850     NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get());
1851     NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get());
1852     if (NotEqExpr.isInvalid()) {
1853       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1854       if (!Context.hasSameType(BeginType, EndType))
1855         NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end);
1856       return StmtError();
1857     }
1858 
1859     // Build and check ++__begin expression.
1860     BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1861                                 VK_LValue, ColonLoc);
1862     if (BeginRef.isInvalid())
1863       return StmtError();
1864 
1865     IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get());
1866     IncrExpr = ActOnFinishFullExpr(IncrExpr.get());
1867     if (IncrExpr.isInvalid()) {
1868       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1869       return StmtError();
1870     }
1871 
1872     // Build and check *__begin  expression.
1873     BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType,
1874                                 VK_LValue, ColonLoc);
1875     if (BeginRef.isInvalid())
1876       return StmtError();
1877 
1878     ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get());
1879     if (DerefExpr.isInvalid()) {
1880       NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1881       return StmtError();
1882     }
1883 
1884     // Attach  *__begin  as initializer for VD.
1885     if (!LoopVar->isInvalidDecl()) {
1886       AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false,
1887                            /*TypeMayContainAuto=*/true);
1888       if (LoopVar->isInvalidDecl())
1889         NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin);
1890     }
1891   } else {
1892     // The range is implicitly used as a placeholder when it is dependent.
1893     RangeVar->setUsed();
1894   }
1895 
1896   return Owned(new (Context) CXXForRangeStmt(RangeDS,
1897                                      cast_or_null<DeclStmt>(BeginEndDecl.get()),
1898                                              NotEqExpr.take(), IncrExpr.take(),
1899                                              LoopVarDS, /*Body=*/0, ForLoc,
1900                                              ColonLoc, RParenLoc));
1901 }
1902 
1903 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement.
1904 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the
1905 /// body cannot be performed until after the type of the range variable is
1906 /// determined.
1907 StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) {
1908   if (!S || !B)
1909     return StmtError();
1910 
1911   CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S);
1912   ForStmt->setBody(B);
1913 
1914   DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B,
1915                         diag::warn_empty_range_based_for_body);
1916 
1917   return S;
1918 }
1919 
1920 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc,
1921                                SourceLocation LabelLoc,
1922                                LabelDecl *TheDecl) {
1923   getCurFunction()->setHasBranchIntoScope();
1924   TheDecl->setUsed();
1925   return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc));
1926 }
1927 
1928 StmtResult
1929 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc,
1930                             Expr *E) {
1931   // Convert operand to void*
1932   if (!E->isTypeDependent()) {
1933     QualType ETy = E->getType();
1934     QualType DestTy = Context.getPointerType(Context.VoidTy.withConst());
1935     ExprResult ExprRes = Owned(E);
1936     AssignConvertType ConvTy =
1937       CheckSingleAssignmentConstraints(DestTy, ExprRes);
1938     if (ExprRes.isInvalid())
1939       return StmtError();
1940     E = ExprRes.take();
1941     if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing))
1942       return StmtError();
1943     E = MaybeCreateExprWithCleanups(E);
1944   }
1945 
1946   getCurFunction()->setHasIndirectGoto();
1947 
1948   return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E));
1949 }
1950 
1951 StmtResult
1952 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) {
1953   Scope *S = CurScope->getContinueParent();
1954   if (!S) {
1955     // C99 6.8.6.2p1: A break shall appear only in or as a loop body.
1956     return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop));
1957   }
1958 
1959   return Owned(new (Context) ContinueStmt(ContinueLoc));
1960 }
1961 
1962 StmtResult
1963 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) {
1964   Scope *S = CurScope->getBreakParent();
1965   if (!S) {
1966     // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body.
1967     return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch));
1968   }
1969 
1970   return Owned(new (Context) BreakStmt(BreakLoc));
1971 }
1972 
1973 /// \brief Determine whether the given expression is a candidate for
1974 /// copy elision in either a return statement or a throw expression.
1975 ///
1976 /// \param ReturnType If we're determining the copy elision candidate for
1977 /// a return statement, this is the return type of the function. If we're
1978 /// determining the copy elision candidate for a throw expression, this will
1979 /// be a NULL type.
1980 ///
1981 /// \param E The expression being returned from the function or block, or
1982 /// being thrown.
1983 ///
1984 /// \param AllowFunctionParameter Whether we allow function parameters to
1985 /// be considered NRVO candidates. C++ prohibits this for NRVO itself, but
1986 /// we re-use this logic to determine whether we should try to move as part of
1987 /// a return or throw (which does allow function parameters).
1988 ///
1989 /// \returns The NRVO candidate variable, if the return statement may use the
1990 /// NRVO, or NULL if there is no such candidate.
1991 const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType,
1992                                              Expr *E,
1993                                              bool AllowFunctionParameter) {
1994   QualType ExprType = E->getType();
1995   // - in a return statement in a function with ...
1996   // ... a class return type ...
1997   if (!ReturnType.isNull()) {
1998     if (!ReturnType->isRecordType())
1999       return 0;
2000     // ... the same cv-unqualified type as the function return type ...
2001     if (!Context.hasSameUnqualifiedType(ReturnType, ExprType))
2002       return 0;
2003   }
2004 
2005   // ... the expression is the name of a non-volatile automatic object
2006   // (other than a function or catch-clause parameter)) ...
2007   const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens());
2008   if (!DR)
2009     return 0;
2010   const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
2011   if (!VD)
2012     return 0;
2013 
2014   // ...object (other than a function or catch-clause parameter)...
2015   if (VD->getKind() != Decl::Var &&
2016       !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar))
2017     return 0;
2018   if (VD->isExceptionVariable()) return 0;
2019 
2020   // ...automatic...
2021   if (!VD->hasLocalStorage()) return 0;
2022 
2023   // ...non-volatile...
2024   if (VD->getType().isVolatileQualified()) return 0;
2025   if (VD->getType()->isReferenceType()) return 0;
2026 
2027   // __block variables can't be allocated in a way that permits NRVO.
2028   if (VD->hasAttr<BlocksAttr>()) return 0;
2029 
2030   // Variables with higher required alignment than their type's ABI
2031   // alignment cannot use NRVO.
2032   if (VD->hasAttr<AlignedAttr>() &&
2033       Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType()))
2034     return 0;
2035 
2036   return VD;
2037 }
2038 
2039 /// \brief Perform the initialization of a potentially-movable value, which
2040 /// is the result of return value.
2041 ///
2042 /// This routine implements C++0x [class.copy]p33, which attempts to treat
2043 /// returned lvalues as rvalues in certain cases (to prefer move construction),
2044 /// then falls back to treating them as lvalues if that failed.
2045 ExprResult
2046 Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
2047                                       const VarDecl *NRVOCandidate,
2048                                       QualType ResultType,
2049                                       Expr *Value,
2050                                       bool AllowNRVO) {
2051   // C++0x [class.copy]p33:
2052   //   When the criteria for elision of a copy operation are met or would
2053   //   be met save for the fact that the source object is a function
2054   //   parameter, and the object to be copied is designated by an lvalue,
2055   //   overload resolution to select the constructor for the copy is first
2056   //   performed as if the object were designated by an rvalue.
2057   ExprResult Res = ExprError();
2058   if (AllowNRVO &&
2059       (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) {
2060     ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack,
2061                               Value->getType(), CK_NoOp, Value, VK_XValue);
2062 
2063     Expr *InitExpr = &AsRvalue;
2064     InitializationKind Kind
2065       = InitializationKind::CreateCopy(Value->getLocStart(),
2066                                        Value->getLocStart());
2067     InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1);
2068 
2069     //   [...] If overload resolution fails, or if the type of the first
2070     //   parameter of the selected constructor is not an rvalue reference
2071     //   to the object's type (possibly cv-qualified), overload resolution
2072     //   is performed again, considering the object as an lvalue.
2073     if (Seq) {
2074       for (InitializationSequence::step_iterator Step = Seq.step_begin(),
2075            StepEnd = Seq.step_end();
2076            Step != StepEnd; ++Step) {
2077         if (Step->Kind != InitializationSequence::SK_ConstructorInitialization)
2078           continue;
2079 
2080         CXXConstructorDecl *Constructor
2081         = cast<CXXConstructorDecl>(Step->Function.Function);
2082 
2083         const RValueReferenceType *RRefType
2084           = Constructor->getParamDecl(0)->getType()
2085                                                  ->getAs<RValueReferenceType>();
2086 
2087         // If we don't meet the criteria, break out now.
2088         if (!RRefType ||
2089             !Context.hasSameUnqualifiedType(RRefType->getPointeeType(),
2090                             Context.getTypeDeclType(Constructor->getParent())))
2091           break;
2092 
2093         // Promote "AsRvalue" to the heap, since we now need this
2094         // expression node to persist.
2095         Value = ImplicitCastExpr::Create(Context, Value->getType(),
2096                                          CK_NoOp, Value, 0, VK_XValue);
2097 
2098         // Complete type-checking the initialization of the return type
2099         // using the constructor we found.
2100         Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1));
2101       }
2102     }
2103   }
2104 
2105   // Either we didn't meet the criteria for treating an lvalue as an rvalue,
2106   // above, or overload resolution failed. Either way, we need to try
2107   // (again) now with the return value expression as written.
2108   if (Res.isInvalid())
2109     Res = PerformCopyInitialization(Entity, SourceLocation(), Value);
2110 
2111   return Res;
2112 }
2113 
2114 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements
2115 /// for capturing scopes.
2116 ///
2117 StmtResult
2118 Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2119   // If this is the first return we've seen, infer the return type.
2120   // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those
2121   // rules which allows multiple return statements.
2122   CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction());
2123   if (CurCap->HasImplicitReturnType) {
2124     QualType ReturnT;
2125     if (RetValExp && !isa<InitListExpr>(RetValExp)) {
2126       ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp);
2127       if (Result.isInvalid())
2128         return StmtError();
2129       RetValExp = Result.take();
2130 
2131       if (!RetValExp->isTypeDependent()) {
2132         ReturnT = RetValExp->getType();
2133 
2134         // In C, enum constants have the type of their underlying integer type,
2135         // not the enum. When inferring block return values, we should infer
2136         // the enum type if an enum constant is used, unless the enum is
2137         // anonymous (in which case there can be no variables of its type).
2138         if (!getLangOpts().CPlusPlus) {
2139           Expr *InsideExpr = RetValExp->IgnoreParenImpCasts();
2140           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InsideExpr)) {
2141             Decl *D = DRE->getDecl();
2142             if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
2143               EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
2144               if (Enum->getDeclName() || Enum->getTypedefNameForAnonDecl()) {
2145                 ReturnT = Context.getTypeDeclType(Enum);
2146                 ExprResult Casted = ImpCastExprToType(RetValExp, ReturnT,
2147                                                       CK_IntegralCast);
2148                 assert(Casted.isUsable());
2149                 RetValExp = Casted.take();
2150               }
2151             }
2152           }
2153         }
2154       } else {
2155         ReturnT = Context.DependentTy;
2156       }
2157     } else {
2158       if (RetValExp) {
2159         // C++11 [expr.lambda.prim]p4 bans inferring the result from an
2160         // initializer list, because it is not an expression (even
2161         // though we represent it as one). We still deduce 'void'.
2162         Diag(ReturnLoc, diag::err_lambda_return_init_list)
2163           << RetValExp->getSourceRange();
2164       }
2165 
2166       ReturnT = Context.VoidTy;
2167     }
2168     // We require the return types to strictly match here.
2169     if (!CurCap->ReturnType.isNull() &&
2170         !CurCap->ReturnType->isDependentType() &&
2171         !ReturnT->isDependentType() &&
2172         !Context.hasSameType(ReturnT, CurCap->ReturnType)) {
2173       Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible)
2174           << ReturnT << CurCap->ReturnType
2175           << (getCurLambda() != 0);
2176       return StmtError();
2177     }
2178     CurCap->ReturnType = ReturnT;
2179   }
2180   QualType FnRetType = CurCap->ReturnType;
2181   assert(!FnRetType.isNull());
2182 
2183   if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) {
2184     if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) {
2185       Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr);
2186       return StmtError();
2187     }
2188   } else {
2189     LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap);
2190     if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){
2191       Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr);
2192       return StmtError();
2193     }
2194   }
2195 
2196   // Otherwise, verify that this result type matches the previous one.  We are
2197   // pickier with blocks than for normal functions because we don't have GCC
2198   // compatibility to worry about here.
2199   const VarDecl *NRVOCandidate = 0;
2200   if (FnRetType->isDependentType()) {
2201     // Delay processing for now.  TODO: there are lots of dependent
2202     // types we can conclusively prove aren't void.
2203   } else if (FnRetType->isVoidType()) {
2204     if (RetValExp && !isa<InitListExpr>(RetValExp) &&
2205         !(getLangOpts().CPlusPlus &&
2206           (RetValExp->isTypeDependent() ||
2207            RetValExp->getType()->isVoidType()))) {
2208       if (!getLangOpts().CPlusPlus &&
2209           RetValExp->getType()->isVoidType())
2210         Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2;
2211       else {
2212         Diag(ReturnLoc, diag::err_return_block_has_expr);
2213         RetValExp = 0;
2214       }
2215     }
2216   } else if (!RetValExp) {
2217     return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr));
2218   } else if (!RetValExp->isTypeDependent()) {
2219     // we have a non-void block with an expression, continue checking
2220 
2221     // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2222     // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2223     // function return.
2224 
2225     // In C++ the return statement is handled via a copy initialization.
2226     // the C version of which boils down to CheckSingleAssignmentConstraints.
2227     NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2228     InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2229                                                                    FnRetType,
2230                                                           NRVOCandidate != 0);
2231     ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2232                                                      FnRetType, RetValExp);
2233     if (Res.isInvalid()) {
2234       // FIXME: Cleanup temporaries here, anyway?
2235       return StmtError();
2236     }
2237     RetValExp = Res.take();
2238     CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
2239   }
2240 
2241   if (RetValExp) {
2242     CheckImplicitConversions(RetValExp, ReturnLoc);
2243     RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2244   }
2245   ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp,
2246                                                 NRVOCandidate);
2247 
2248   // If we need to check for the named return value optimization, save the
2249   // return statement in our scope for later processing.
2250   if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2251       !CurContext->isDependentContext())
2252     FunctionScopes.back()->Returns.push_back(Result);
2253 
2254   return Owned(Result);
2255 }
2256 
2257 StmtResult
2258 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) {
2259   // Check for unexpanded parameter packs.
2260   if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp))
2261     return StmtError();
2262 
2263   if (isa<CapturingScopeInfo>(getCurFunction()))
2264     return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp);
2265 
2266   QualType FnRetType;
2267   QualType RelatedRetType;
2268   if (const FunctionDecl *FD = getCurFunctionDecl()) {
2269     FnRetType = FD->getResultType();
2270     if (FD->hasAttr<NoReturnAttr>() ||
2271         FD->getType()->getAs<FunctionType>()->getNoReturnAttr())
2272       Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr)
2273         << FD->getDeclName();
2274   } else if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2275     FnRetType = MD->getResultType();
2276     if (MD->hasRelatedResultType() && MD->getClassInterface()) {
2277       // In the implementation of a method with a related return type, the
2278       // type used to type-check the validity of return statements within the
2279       // method body is a pointer to the type of the class being implemented.
2280       RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface());
2281       RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType);
2282     }
2283   } else // If we don't have a function/method context, bail.
2284     return StmtError();
2285 
2286   ReturnStmt *Result = 0;
2287   if (FnRetType->isVoidType()) {
2288     if (RetValExp) {
2289       if (isa<InitListExpr>(RetValExp)) {
2290         // We simply never allow init lists as the return value of void
2291         // functions. This is compatible because this was never allowed before,
2292         // so there's no legacy code to deal with.
2293         NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2294         int FunctionKind = 0;
2295         if (isa<ObjCMethodDecl>(CurDecl))
2296           FunctionKind = 1;
2297         else if (isa<CXXConstructorDecl>(CurDecl))
2298           FunctionKind = 2;
2299         else if (isa<CXXDestructorDecl>(CurDecl))
2300           FunctionKind = 3;
2301 
2302         Diag(ReturnLoc, diag::err_return_init_list)
2303           << CurDecl->getDeclName() << FunctionKind
2304           << RetValExp->getSourceRange();
2305 
2306         // Drop the expression.
2307         RetValExp = 0;
2308       } else if (!RetValExp->isTypeDependent()) {
2309         // C99 6.8.6.4p1 (ext_ since GCC warns)
2310         unsigned D = diag::ext_return_has_expr;
2311         if (RetValExp->getType()->isVoidType())
2312           D = diag::ext_return_has_void_expr;
2313         else {
2314           ExprResult Result = Owned(RetValExp);
2315           Result = IgnoredValueConversions(Result.take());
2316           if (Result.isInvalid())
2317             return StmtError();
2318           RetValExp = Result.take();
2319           RetValExp = ImpCastExprToType(RetValExp,
2320                                         Context.VoidTy, CK_ToVoid).take();
2321         }
2322 
2323         // return (some void expression); is legal in C++.
2324         if (D != diag::ext_return_has_void_expr ||
2325             !getLangOpts().CPlusPlus) {
2326           NamedDecl *CurDecl = getCurFunctionOrMethodDecl();
2327 
2328           int FunctionKind = 0;
2329           if (isa<ObjCMethodDecl>(CurDecl))
2330             FunctionKind = 1;
2331           else if (isa<CXXConstructorDecl>(CurDecl))
2332             FunctionKind = 2;
2333           else if (isa<CXXDestructorDecl>(CurDecl))
2334             FunctionKind = 3;
2335 
2336           Diag(ReturnLoc, D)
2337             << CurDecl->getDeclName() << FunctionKind
2338             << RetValExp->getSourceRange();
2339         }
2340       }
2341 
2342       if (RetValExp) {
2343         CheckImplicitConversions(RetValExp, ReturnLoc);
2344         RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2345       }
2346     }
2347 
2348     Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0);
2349   } else if (!RetValExp && !FnRetType->isDependentType()) {
2350     unsigned DiagID = diag::warn_return_missing_expr;  // C90 6.6.6.4p4
2351     // C99 6.8.6.4p1 (ext_ since GCC warns)
2352     if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr;
2353 
2354     if (FunctionDecl *FD = getCurFunctionDecl())
2355       Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/;
2356     else
2357       Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/;
2358     Result = new (Context) ReturnStmt(ReturnLoc);
2359   } else {
2360     const VarDecl *NRVOCandidate = 0;
2361     if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) {
2362       // we have a non-void function with an expression, continue checking
2363 
2364       if (!RelatedRetType.isNull()) {
2365         // If we have a related result type, perform an extra conversion here.
2366         // FIXME: The diagnostics here don't really describe what is happening.
2367         InitializedEntity Entity =
2368             InitializedEntity::InitializeTemporary(RelatedRetType);
2369 
2370         ExprResult Res = PerformCopyInitialization(Entity, SourceLocation(),
2371                                                    RetValExp);
2372         if (Res.isInvalid()) {
2373           // FIXME: Cleanup temporaries here, anyway?
2374           return StmtError();
2375         }
2376         RetValExp = Res.takeAs<Expr>();
2377       }
2378 
2379       // C99 6.8.6.4p3(136): The return statement is not an assignment. The
2380       // overlap restriction of subclause 6.5.16.1 does not apply to the case of
2381       // function return.
2382 
2383       // In C++ the return statement is handled via a copy initialization,
2384       // the C version of which boils down to CheckSingleAssignmentConstraints.
2385       NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false);
2386       InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc,
2387                                                                      FnRetType,
2388                                                             NRVOCandidate != 0);
2389       ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate,
2390                                                        FnRetType, RetValExp);
2391       if (Res.isInvalid()) {
2392         // FIXME: Cleanup temporaries here, anyway?
2393         return StmtError();
2394       }
2395 
2396       RetValExp = Res.takeAs<Expr>();
2397       if (RetValExp)
2398         CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc);
2399     }
2400 
2401     if (RetValExp) {
2402       CheckImplicitConversions(RetValExp, ReturnLoc);
2403       RetValExp = MaybeCreateExprWithCleanups(RetValExp);
2404     }
2405     Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate);
2406   }
2407 
2408   // If we need to check for the named return value optimization, save the
2409   // return statement in our scope for later processing.
2410   if (getLangOpts().CPlusPlus && FnRetType->isRecordType() &&
2411       !CurContext->isDependentContext())
2412     FunctionScopes.back()->Returns.push_back(Result);
2413 
2414   return Owned(Result);
2415 }
2416 
2417 /// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
2418 /// ignore "noop" casts in places where an lvalue is required by an inline asm.
2419 /// We emulate this behavior when -fheinous-gnu-extensions is specified, but
2420 /// provide a strong guidance to not use it.
2421 ///
2422 /// This method checks to see if the argument is an acceptable l-value and
2423 /// returns false if it is a case we can handle.
2424 static bool CheckAsmLValue(const Expr *E, Sema &S) {
2425   // Type dependent expressions will be checked during instantiation.
2426   if (E->isTypeDependent())
2427     return false;
2428 
2429   if (E->isLValue())
2430     return false;  // Cool, this is an lvalue.
2431 
2432   // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
2433   // are supposed to allow.
2434   const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
2435   if (E != E2 && E2->isLValue()) {
2436     if (!S.getLangOpts().HeinousExtensions)
2437       S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
2438         << E->getSourceRange();
2439     else
2440       S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
2441         << E->getSourceRange();
2442     // Accept, even if we emitted an error diagnostic.
2443     return false;
2444   }
2445 
2446   // None of the above, just randomly invalid non-lvalue.
2447   return true;
2448 }
2449 
2450 /// isOperandMentioned - Return true if the specified operand # is mentioned
2451 /// anywhere in the decomposed asm string.
2452 static bool isOperandMentioned(unsigned OpNo,
2453                          ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) {
2454   for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
2455     const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
2456     if (!Piece.isOperand()) continue;
2457 
2458     // If this is a reference to the input and if the input was the smaller
2459     // one, then we have to reject this asm.
2460     if (Piece.getOperandNo() == OpNo)
2461       return true;
2462   }
2463   return false;
2464 }
2465 
2466 StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple,
2467                               bool IsVolatile, unsigned NumOutputs,
2468                               unsigned NumInputs, IdentifierInfo **Names,
2469                               MultiExprArg constraints, MultiExprArg exprs,
2470                               Expr *asmString, MultiExprArg clobbers,
2471                               SourceLocation RParenLoc, bool MSAsm) {
2472   unsigned NumClobbers = clobbers.size();
2473   StringLiteral **Constraints =
2474     reinterpret_cast<StringLiteral**>(constraints.get());
2475   Expr **Exprs = exprs.get();
2476   StringLiteral *AsmString = cast<StringLiteral>(asmString);
2477   StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get());
2478 
2479   SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
2480 
2481   // The parser verifies that there is a string literal here.
2482   if (!AsmString->isAscii())
2483     return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character)
2484       << AsmString->getSourceRange());
2485 
2486   for (unsigned i = 0; i != NumOutputs; i++) {
2487     StringLiteral *Literal = Constraints[i];
2488     if (!Literal->isAscii())
2489       return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2490         << Literal->getSourceRange());
2491 
2492     StringRef OutputName;
2493     if (Names[i])
2494       OutputName = Names[i]->getName();
2495 
2496     TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
2497     if (!Context.getTargetInfo().validateOutputConstraint(Info))
2498       return StmtError(Diag(Literal->getLocStart(),
2499                             diag::err_asm_invalid_output_constraint)
2500                        << Info.getConstraintStr());
2501 
2502     // Check that the output exprs are valid lvalues.
2503     Expr *OutputExpr = Exprs[i];
2504     if (CheckAsmLValue(OutputExpr, *this)) {
2505       return StmtError(Diag(OutputExpr->getLocStart(),
2506                   diag::err_asm_invalid_lvalue_in_output)
2507         << OutputExpr->getSourceRange());
2508     }
2509 
2510     OutputConstraintInfos.push_back(Info);
2511   }
2512 
2513   SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
2514 
2515   for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
2516     StringLiteral *Literal = Constraints[i];
2517     if (!Literal->isAscii())
2518       return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2519         << Literal->getSourceRange());
2520 
2521     StringRef InputName;
2522     if (Names[i])
2523       InputName = Names[i]->getName();
2524 
2525     TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
2526     if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
2527                                                 NumOutputs, Info)) {
2528       return StmtError(Diag(Literal->getLocStart(),
2529                             diag::err_asm_invalid_input_constraint)
2530                        << Info.getConstraintStr());
2531     }
2532 
2533     Expr *InputExpr = Exprs[i];
2534 
2535     // Only allow void types for memory constraints.
2536     if (Info.allowsMemory() && !Info.allowsRegister()) {
2537       if (CheckAsmLValue(InputExpr, *this))
2538         return StmtError(Diag(InputExpr->getLocStart(),
2539                               diag::err_asm_invalid_lvalue_in_input)
2540                          << Info.getConstraintStr()
2541                          << InputExpr->getSourceRange());
2542     }
2543 
2544     if (Info.allowsRegister()) {
2545       if (InputExpr->getType()->isVoidType()) {
2546         return StmtError(Diag(InputExpr->getLocStart(),
2547                               diag::err_asm_invalid_type_in_input)
2548           << InputExpr->getType() << Info.getConstraintStr()
2549           << InputExpr->getSourceRange());
2550       }
2551     }
2552 
2553     ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
2554     if (Result.isInvalid())
2555       return StmtError();
2556 
2557     Exprs[i] = Result.take();
2558     InputConstraintInfos.push_back(Info);
2559   }
2560 
2561   // Check that the clobbers are valid.
2562   for (unsigned i = 0; i != NumClobbers; i++) {
2563     StringLiteral *Literal = Clobbers[i];
2564     if (!Literal->isAscii())
2565       return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character)
2566         << Literal->getSourceRange());
2567 
2568     StringRef Clobber = Literal->getString();
2569 
2570     if (!Context.getTargetInfo().isValidClobber(Clobber))
2571       return StmtError(Diag(Literal->getLocStart(),
2572                   diag::err_asm_unknown_register_name) << Clobber);
2573   }
2574 
2575   AsmStmt *NS =
2576     new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm,
2577                           NumOutputs, NumInputs, Names, Constraints, Exprs,
2578                           AsmString, NumClobbers, Clobbers, RParenLoc);
2579   // Validate the asm string, ensuring it makes sense given the operands we
2580   // have.
2581   SmallVector<AsmStmt::AsmStringPiece, 8> Pieces;
2582   unsigned DiagOffs;
2583   if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
2584     Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
2585            << AsmString->getSourceRange();
2586     return StmtError();
2587   }
2588 
2589   // Validate tied input operands for type mismatches.
2590   for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
2591     TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
2592 
2593     // If this is a tied constraint, verify that the output and input have
2594     // either exactly the same type, or that they are int/ptr operands with the
2595     // same size (int/long, int*/long, are ok etc).
2596     if (!Info.hasTiedOperand()) continue;
2597 
2598     unsigned TiedTo = Info.getTiedOperand();
2599     unsigned InputOpNo = i+NumOutputs;
2600     Expr *OutputExpr = Exprs[TiedTo];
2601     Expr *InputExpr = Exprs[InputOpNo];
2602 
2603     if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
2604       continue;
2605 
2606     QualType InTy = InputExpr->getType();
2607     QualType OutTy = OutputExpr->getType();
2608     if (Context.hasSameType(InTy, OutTy))
2609       continue;  // All types can be tied to themselves.
2610 
2611     // Decide if the input and output are in the same domain (integer/ptr or
2612     // floating point.
2613     enum AsmDomain {
2614       AD_Int, AD_FP, AD_Other
2615     } InputDomain, OutputDomain;
2616 
2617     if (InTy->isIntegerType() || InTy->isPointerType())
2618       InputDomain = AD_Int;
2619     else if (InTy->isRealFloatingType())
2620       InputDomain = AD_FP;
2621     else
2622       InputDomain = AD_Other;
2623 
2624     if (OutTy->isIntegerType() || OutTy->isPointerType())
2625       OutputDomain = AD_Int;
2626     else if (OutTy->isRealFloatingType())
2627       OutputDomain = AD_FP;
2628     else
2629       OutputDomain = AD_Other;
2630 
2631     // They are ok if they are the same size and in the same domain.  This
2632     // allows tying things like:
2633     //   void* to int*
2634     //   void* to int            if they are the same size.
2635     //   double to long double   if they are the same size.
2636     //
2637     uint64_t OutSize = Context.getTypeSize(OutTy);
2638     uint64_t InSize = Context.getTypeSize(InTy);
2639     if (OutSize == InSize && InputDomain == OutputDomain &&
2640         InputDomain != AD_Other)
2641       continue;
2642 
2643     // If the smaller input/output operand is not mentioned in the asm string,
2644     // then we can promote the smaller one to a larger input and the asm string
2645     // won't notice.
2646     bool SmallerValueMentioned = false;
2647 
2648     // If this is a reference to the input and if the input was the smaller
2649     // one, then we have to reject this asm.
2650     if (isOperandMentioned(InputOpNo, Pieces)) {
2651       // This is a use in the asm string of the smaller operand.  Since we
2652       // codegen this by promoting to a wider value, the asm will get printed
2653       // "wrong".
2654       SmallerValueMentioned |= InSize < OutSize;
2655     }
2656     if (isOperandMentioned(TiedTo, Pieces)) {
2657       // If this is a reference to the output, and if the output is the larger
2658       // value, then it's ok because we'll promote the input to the larger type.
2659       SmallerValueMentioned |= OutSize < InSize;
2660     }
2661 
2662     // If the smaller value wasn't mentioned in the asm string, and if the
2663     // output was a register, just extend the shorter one to the size of the
2664     // larger one.
2665     if (!SmallerValueMentioned && InputDomain != AD_Other &&
2666         OutputConstraintInfos[TiedTo].allowsRegister())
2667       continue;
2668 
2669     // Either both of the operands were mentioned or the smaller one was
2670     // mentioned.  One more special case that we'll allow: if the tied input is
2671     // integer, unmentioned, and is a constant, then we'll allow truncating it
2672     // down to the size of the destination.
2673     if (InputDomain == AD_Int && OutputDomain == AD_Int &&
2674         !isOperandMentioned(InputOpNo, Pieces) &&
2675         InputExpr->isEvaluatable(Context)) {
2676       CastKind castKind =
2677         (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
2678       InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take();
2679       Exprs[InputOpNo] = InputExpr;
2680       NS->setInputExpr(i, InputExpr);
2681       continue;
2682     }
2683 
2684     Diag(InputExpr->getLocStart(),
2685          diag::err_asm_tying_incompatible_types)
2686       << InTy << OutTy << OutputExpr->getSourceRange()
2687       << InputExpr->getSourceRange();
2688     return StmtError();
2689   }
2690 
2691   return Owned(NS);
2692 }
2693 
2694 StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc,
2695                                 std::string &AsmString,
2696                                 SourceLocation EndLoc) {
2697   // MS-style inline assembly is not fully supported, so emit a warning.
2698   Diag(AsmLoc, diag::warn_unsupported_msasm);
2699 
2700   MSAsmStmt *NS =
2701     new (Context) MSAsmStmt(Context, AsmLoc, AsmString, EndLoc);
2702 
2703   return Owned(NS);
2704 }
2705 
2706 StmtResult
2707 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc,
2708                            SourceLocation RParen, Decl *Parm,
2709                            Stmt *Body) {
2710   VarDecl *Var = cast_or_null<VarDecl>(Parm);
2711   if (Var && Var->isInvalidDecl())
2712     return StmtError();
2713 
2714   return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body));
2715 }
2716 
2717 StmtResult
2718 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) {
2719   return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body));
2720 }
2721 
2722 StmtResult
2723 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
2724                          MultiStmtArg CatchStmts, Stmt *Finally) {
2725   if (!getLangOpts().ObjCExceptions)
2726     Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try";
2727 
2728   getCurFunction()->setHasBranchProtectedScope();
2729   unsigned NumCatchStmts = CatchStmts.size();
2730   return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try,
2731                                      CatchStmts.release(),
2732                                      NumCatchStmts,
2733                                      Finally));
2734 }
2735 
2736 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) {
2737   if (Throw) {
2738     ExprResult Result = DefaultLvalueConversion(Throw);
2739     if (Result.isInvalid())
2740       return StmtError();
2741 
2742     Throw = MaybeCreateExprWithCleanups(Result.take());
2743     QualType ThrowType = Throw->getType();
2744     // Make sure the expression type is an ObjC pointer or "void *".
2745     if (!ThrowType->isDependentType() &&
2746         !ThrowType->isObjCObjectPointerType()) {
2747       const PointerType *PT = ThrowType->getAs<PointerType>();
2748       if (!PT || !PT->getPointeeType()->isVoidType())
2749         return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object)
2750                          << Throw->getType() << Throw->getSourceRange());
2751     }
2752   }
2753 
2754   return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw));
2755 }
2756 
2757 StmtResult
2758 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
2759                            Scope *CurScope) {
2760   if (!getLangOpts().ObjCExceptions)
2761     Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw";
2762 
2763   if (!Throw) {
2764     // @throw without an expression designates a rethrow (which much occur
2765     // in the context of an @catch clause).
2766     Scope *AtCatchParent = CurScope;
2767     while (AtCatchParent && !AtCatchParent->isAtCatchScope())
2768       AtCatchParent = AtCatchParent->getParent();
2769     if (!AtCatchParent)
2770       return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch));
2771   }
2772   return BuildObjCAtThrowStmt(AtLoc, Throw);
2773 }
2774 
2775 ExprResult
2776 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) {
2777   ExprResult result = DefaultLvalueConversion(operand);
2778   if (result.isInvalid())
2779     return ExprError();
2780   operand = result.take();
2781 
2782   // Make sure the expression type is an ObjC pointer or "void *".
2783   QualType type = operand->getType();
2784   if (!type->isDependentType() &&
2785       !type->isObjCObjectPointerType()) {
2786     const PointerType *pointerType = type->getAs<PointerType>();
2787     if (!pointerType || !pointerType->getPointeeType()->isVoidType())
2788       return Diag(atLoc, diag::error_objc_synchronized_expects_object)
2789                << type << operand->getSourceRange();
2790   }
2791 
2792   // The operand to @synchronized is a full-expression.
2793   return MaybeCreateExprWithCleanups(operand);
2794 }
2795 
2796 StmtResult
2797 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr,
2798                                   Stmt *SyncBody) {
2799   // We can't jump into or indirect-jump out of a @synchronized block.
2800   getCurFunction()->setHasBranchProtectedScope();
2801   return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody));
2802 }
2803 
2804 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block
2805 /// and creates a proper catch handler from them.
2806 StmtResult
2807 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl,
2808                          Stmt *HandlerBlock) {
2809   // There's nothing to test that ActOnExceptionDecl didn't already test.
2810   return Owned(new (Context) CXXCatchStmt(CatchLoc,
2811                                           cast_or_null<VarDecl>(ExDecl),
2812                                           HandlerBlock));
2813 }
2814 
2815 StmtResult
2816 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) {
2817   getCurFunction()->setHasBranchProtectedScope();
2818   return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body));
2819 }
2820 
2821 namespace {
2822 
2823 class TypeWithHandler {
2824   QualType t;
2825   CXXCatchStmt *stmt;
2826 public:
2827   TypeWithHandler(const QualType &type, CXXCatchStmt *statement)
2828   : t(type), stmt(statement) {}
2829 
2830   // An arbitrary order is fine as long as it places identical
2831   // types next to each other.
2832   bool operator<(const TypeWithHandler &y) const {
2833     if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr())
2834       return true;
2835     if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr())
2836       return false;
2837     else
2838       return getTypeSpecStartLoc() < y.getTypeSpecStartLoc();
2839   }
2840 
2841   bool operator==(const TypeWithHandler& other) const {
2842     return t == other.t;
2843   }
2844 
2845   CXXCatchStmt *getCatchStmt() const { return stmt; }
2846   SourceLocation getTypeSpecStartLoc() const {
2847     return stmt->getExceptionDecl()->getTypeSpecStartLoc();
2848   }
2849 };
2850 
2851 }
2852 
2853 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of
2854 /// handlers and creates a try statement from them.
2855 StmtResult
2856 Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
2857                        MultiStmtArg RawHandlers) {
2858   // Don't report an error if 'try' is used in system headers.
2859   if (!getLangOpts().CXXExceptions &&
2860       !getSourceManager().isInSystemHeader(TryLoc))
2861       Diag(TryLoc, diag::err_exceptions_disabled) << "try";
2862 
2863   unsigned NumHandlers = RawHandlers.size();
2864   assert(NumHandlers > 0 &&
2865          "The parser shouldn't call this if there are no handlers.");
2866   Stmt **Handlers = RawHandlers.get();
2867 
2868   SmallVector<TypeWithHandler, 8> TypesWithHandlers;
2869 
2870   for (unsigned i = 0; i < NumHandlers; ++i) {
2871     CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]);
2872     if (!Handler->getExceptionDecl()) {
2873       if (i < NumHandlers - 1)
2874         return StmtError(Diag(Handler->getLocStart(),
2875                               diag::err_early_catch_all));
2876 
2877       continue;
2878     }
2879 
2880     const QualType CaughtType = Handler->getCaughtType();
2881     const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType);
2882     TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler));
2883   }
2884 
2885   // Detect handlers for the same type as an earlier one.
2886   if (NumHandlers > 1) {
2887     llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end());
2888 
2889     TypeWithHandler prev = TypesWithHandlers[0];
2890     for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) {
2891       TypeWithHandler curr = TypesWithHandlers[i];
2892 
2893       if (curr == prev) {
2894         Diag(curr.getTypeSpecStartLoc(),
2895              diag::warn_exception_caught_by_earlier_handler)
2896           << curr.getCatchStmt()->getCaughtType().getAsString();
2897         Diag(prev.getTypeSpecStartLoc(),
2898              diag::note_previous_exception_handler)
2899           << prev.getCatchStmt()->getCaughtType().getAsString();
2900       }
2901 
2902       prev = curr;
2903     }
2904   }
2905 
2906   getCurFunction()->setHasBranchProtectedScope();
2907 
2908   // FIXME: We should detect handlers that cannot catch anything because an
2909   // earlier handler catches a superclass. Need to find a method that is not
2910   // quadratic for this.
2911   // Neither of these are explicitly forbidden, but every compiler detects them
2912   // and warns.
2913 
2914   return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock,
2915                                   Handlers, NumHandlers));
2916 }
2917 
2918 StmtResult
2919 Sema::ActOnSEHTryBlock(bool IsCXXTry,
2920                        SourceLocation TryLoc,
2921                        Stmt *TryBlock,
2922                        Stmt *Handler) {
2923   assert(TryBlock && Handler);
2924 
2925   getCurFunction()->setHasBranchProtectedScope();
2926 
2927   return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler));
2928 }
2929 
2930 StmtResult
2931 Sema::ActOnSEHExceptBlock(SourceLocation Loc,
2932                           Expr *FilterExpr,
2933                           Stmt *Block) {
2934   assert(FilterExpr && Block);
2935 
2936   if(!FilterExpr->getType()->isIntegerType()) {
2937     return StmtError(Diag(FilterExpr->getExprLoc(),
2938                      diag::err_filter_expression_integral)
2939                      << FilterExpr->getType());
2940   }
2941 
2942   return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block));
2943 }
2944 
2945 StmtResult
2946 Sema::ActOnSEHFinallyBlock(SourceLocation Loc,
2947                            Stmt *Block) {
2948   assert(Block);
2949   return Owned(SEHFinallyStmt::Create(Context,Loc,Block));
2950 }
2951 
2952 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2953                                             bool IsIfExists,
2954                                             NestedNameSpecifierLoc QualifierLoc,
2955                                             DeclarationNameInfo NameInfo,
2956                                             Stmt *Nested)
2957 {
2958   return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists,
2959                                              QualifierLoc, NameInfo,
2960                                              cast<CompoundStmt>(Nested));
2961 }
2962 
2963 
2964 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
2965                                             bool IsIfExists,
2966                                             CXXScopeSpec &SS,
2967                                             UnqualifiedId &Name,
2968                                             Stmt *Nested) {
2969   return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2970                                     SS.getWithLocInContext(Context),
2971                                     GetNameFromUnqualifiedId(Name),
2972                                     Nested);
2973 }
2974