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