SemaStmt.cpp revision 8d7946151cd15c0e7c34250c122d59b2f5027999
1//===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements semantic analysis for statements. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Sema/SemaInternal.h" 15#include "clang/Sema/Scope.h" 16#include "clang/Sema/ScopeInfo.h" 17#include "clang/Sema/Initialization.h" 18#include "clang/Sema/Lookup.h" 19#include "clang/AST/APValue.h" 20#include "clang/AST/ASTContext.h" 21#include "clang/AST/DeclObjC.h" 22#include "clang/AST/ExprCXX.h" 23#include "clang/AST/ExprObjC.h" 24#include "clang/AST/StmtObjC.h" 25#include "clang/AST/StmtCXX.h" 26#include "clang/AST/TypeLoc.h" 27#include "clang/Lex/Preprocessor.h" 28#include "clang/Basic/TargetInfo.h" 29#include "llvm/ADT/ArrayRef.h" 30#include "llvm/ADT/STLExtras.h" 31#include "llvm/ADT/SmallVector.h" 32using namespace clang; 33using namespace sema; 34 35StmtResult Sema::ActOnExprStmt(FullExprArg expr) { 36 Expr *E = expr.get(); 37 if (!E) // FIXME: FullExprArg has no error state? 38 return StmtError(); 39 40 // C99 6.8.3p2: The expression in an expression statement is evaluated as a 41 // void expression for its side effects. Conversion to void allows any 42 // operand, even incomplete types. 43 44 // Same thing in for stmt first clause (when expr) and third clause. 45 return Owned(static_cast<Stmt*>(E)); 46} 47 48 49StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc, 50 SourceLocation LeadingEmptyMacroLoc) { 51 return Owned(new (Context) NullStmt(SemiLoc, LeadingEmptyMacroLoc)); 52} 53 54StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc, 55 SourceLocation EndLoc) { 56 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>(); 57 58 // If we have an invalid decl, just return an error. 59 if (DG.isNull()) return StmtError(); 60 61 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc)); 62} 63 64void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) { 65 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>(); 66 67 // If we have an invalid decl, just return. 68 if (DG.isNull() || !DG.isSingleDecl()) return; 69 // suppress any potential 'unused variable' warning. 70 DG.getSingleDecl()->setUsed(); 71} 72 73void Sema::DiagnoseUnusedExprResult(const Stmt *S) { 74 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) 75 return DiagnoseUnusedExprResult(Label->getSubStmt()); 76 77 const Expr *E = dyn_cast_or_null<Expr>(S); 78 if (!E) 79 return; 80 81 SourceLocation Loc; 82 SourceRange R1, R2; 83 if (!E->isUnusedResultAWarning(Loc, R1, R2, Context)) 84 return; 85 86 // Okay, we have an unused result. Depending on what the base expression is, 87 // we might want to make a more specific diagnostic. Check for one of these 88 // cases now. 89 unsigned DiagID = diag::warn_unused_expr; 90 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E)) 91 E = Temps->getSubExpr(); 92 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E)) 93 E = TempExpr->getSubExpr(); 94 95 E = E->IgnoreParenImpCasts(); 96 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 97 if (E->getType()->isVoidType()) 98 return; 99 100 // If the callee has attribute pure, const, or warn_unused_result, warn with 101 // a more specific message to make it clear what is happening. 102 if (const Decl *FD = CE->getCalleeDecl()) { 103 if (FD->getAttr<WarnUnusedResultAttr>()) { 104 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result"; 105 return; 106 } 107 if (FD->getAttr<PureAttr>()) { 108 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure"; 109 return; 110 } 111 if (FD->getAttr<ConstAttr>()) { 112 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const"; 113 return; 114 } 115 } 116 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) { 117 const ObjCMethodDecl *MD = ME->getMethodDecl(); 118 if (MD && MD->getAttr<WarnUnusedResultAttr>()) { 119 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result"; 120 return; 121 } 122 } else if (isa<ObjCPropertyRefExpr>(E)) { 123 DiagID = diag::warn_unused_property_expr; 124 } else if (const CXXFunctionalCastExpr *FC 125 = dyn_cast<CXXFunctionalCastExpr>(E)) { 126 if (isa<CXXConstructExpr>(FC->getSubExpr()) || 127 isa<CXXTemporaryObjectExpr>(FC->getSubExpr())) 128 return; 129 } 130 // Diagnose "(void*) blah" as a typo for "(void) blah". 131 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) { 132 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 133 QualType T = TI->getType(); 134 135 // We really do want to use the non-canonical type here. 136 if (T == Context.VoidPtrTy) { 137 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc()); 138 139 Diag(Loc, diag::warn_unused_voidptr) 140 << FixItHint::CreateRemoval(TL.getStarLoc()); 141 return; 142 } 143 } 144 145 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2); 146} 147 148StmtResult 149Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R, 150 MultiStmtArg elts, bool isStmtExpr) { 151 unsigned NumElts = elts.size(); 152 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release()); 153 // If we're in C89 mode, check that we don't have any decls after stmts. If 154 // so, emit an extension diagnostic. 155 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) { 156 // Note that __extension__ can be around a decl. 157 unsigned i = 0; 158 // Skip over all declarations. 159 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i) 160 /*empty*/; 161 162 // We found the end of the list or a statement. Scan for another declstmt. 163 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i) 164 /*empty*/; 165 166 if (i != NumElts) { 167 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin(); 168 Diag(D->getLocation(), diag::ext_mixed_decls_code); 169 } 170 } 171 // Warn about unused expressions in statements. 172 for (unsigned i = 0; i != NumElts; ++i) { 173 // Ignore statements that are last in a statement expression. 174 if (isStmtExpr && i == NumElts - 1) 175 continue; 176 177 DiagnoseUnusedExprResult(Elts[i]); 178 } 179 180 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R)); 181} 182 183StmtResult 184Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal, 185 SourceLocation DotDotDotLoc, Expr *RHSVal, 186 SourceLocation ColonLoc) { 187 assert((LHSVal != 0) && "missing expression in case statement"); 188 189 // C99 6.8.4.2p3: The expression shall be an integer constant. 190 // However, GCC allows any evaluatable integer expression. 191 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() && 192 VerifyIntegerConstantExpression(LHSVal)) 193 return StmtError(); 194 195 // GCC extension: The expression shall be an integer constant. 196 197 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() && 198 VerifyIntegerConstantExpression(RHSVal)) { 199 RHSVal = 0; // Recover by just forgetting about it. 200 } 201 202 if (getCurFunction()->SwitchStack.empty()) { 203 Diag(CaseLoc, diag::err_case_not_in_switch); 204 return StmtError(); 205 } 206 207 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc, 208 ColonLoc); 209 getCurFunction()->SwitchStack.back()->addSwitchCase(CS); 210 return Owned(CS); 211} 212 213/// ActOnCaseStmtBody - This installs a statement as the body of a case. 214void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) { 215 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt); 216 CS->setSubStmt(SubStmt); 217} 218 219StmtResult 220Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, 221 Stmt *SubStmt, Scope *CurScope) { 222 if (getCurFunction()->SwitchStack.empty()) { 223 Diag(DefaultLoc, diag::err_default_not_in_switch); 224 return Owned(SubStmt); 225 } 226 227 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt); 228 getCurFunction()->SwitchStack.back()->addSwitchCase(DS); 229 return Owned(DS); 230} 231 232StmtResult 233Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 234 SourceLocation ColonLoc, Stmt *SubStmt) { 235 236 // If the label was multiply defined, reject it now. 237 if (TheDecl->getStmt()) { 238 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName(); 239 Diag(TheDecl->getLocation(), diag::note_previous_definition); 240 return Owned(SubStmt); 241 } 242 243 // Otherwise, things are good. Fill in the declaration and return it. 244 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt); 245 TheDecl->setStmt(LS); 246 if (!TheDecl->isGnuLocal()) 247 TheDecl->setLocation(IdentLoc); 248 return Owned(LS); 249} 250 251StmtResult 252Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar, 253 Stmt *thenStmt, SourceLocation ElseLoc, 254 Stmt *elseStmt) { 255 ExprResult CondResult(CondVal.release()); 256 257 VarDecl *ConditionVar = 0; 258 if (CondVar) { 259 ConditionVar = cast<VarDecl>(CondVar); 260 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true); 261 if (CondResult.isInvalid()) 262 return StmtError(); 263 } 264 Expr *ConditionExpr = CondResult.takeAs<Expr>(); 265 if (!ConditionExpr) 266 return StmtError(); 267 268 DiagnoseUnusedExprResult(thenStmt); 269 270 // Warn if the if block has a null body without an else value. 271 // this helps prevent bugs due to typos, such as 272 // if (condition); 273 // do_stuff(); 274 // 275 if (!elseStmt) { 276 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt)) 277 // But do not warn if the body is a macro that expands to nothing, e.g: 278 // 279 // #define CALL(x) 280 // if (condition) 281 // CALL(0); 282 // 283 if (!stmt->hasLeadingEmptyMacro()) 284 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body); 285 } 286 287 DiagnoseUnusedExprResult(elseStmt); 288 289 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr, 290 thenStmt, ElseLoc, elseStmt)); 291} 292 293/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 294/// the specified width and sign. If an overflow occurs, detect it and emit 295/// the specified diagnostic. 296void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val, 297 unsigned NewWidth, bool NewSign, 298 SourceLocation Loc, 299 unsigned DiagID) { 300 // Perform a conversion to the promoted condition type if needed. 301 if (NewWidth > Val.getBitWidth()) { 302 // If this is an extension, just do it. 303 Val = Val.extend(NewWidth); 304 Val.setIsSigned(NewSign); 305 306 // If the input was signed and negative and the output is 307 // unsigned, don't bother to warn: this is implementation-defined 308 // behavior. 309 // FIXME: Introduce a second, default-ignored warning for this case? 310 } else if (NewWidth < Val.getBitWidth()) { 311 // If this is a truncation, check for overflow. 312 llvm::APSInt ConvVal(Val); 313 ConvVal = ConvVal.trunc(NewWidth); 314 ConvVal.setIsSigned(NewSign); 315 ConvVal = ConvVal.extend(Val.getBitWidth()); 316 ConvVal.setIsSigned(Val.isSigned()); 317 if (ConvVal != Val) 318 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10); 319 320 // Regardless of whether a diagnostic was emitted, really do the 321 // truncation. 322 Val = Val.trunc(NewWidth); 323 Val.setIsSigned(NewSign); 324 } else if (NewSign != Val.isSigned()) { 325 // Convert the sign to match the sign of the condition. This can cause 326 // overflow as well: unsigned(INTMIN) 327 // We don't diagnose this overflow, because it is implementation-defined 328 // behavior. 329 // FIXME: Introduce a second, default-ignored warning for this case? 330 llvm::APSInt OldVal(Val); 331 Val.setIsSigned(NewSign); 332 } 333} 334 335namespace { 336 struct CaseCompareFunctor { 337 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 338 const llvm::APSInt &RHS) { 339 return LHS.first < RHS; 340 } 341 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 342 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 343 return LHS.first < RHS.first; 344 } 345 bool operator()(const llvm::APSInt &LHS, 346 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 347 return LHS < RHS.first; 348 } 349 }; 350} 351 352/// CmpCaseVals - Comparison predicate for sorting case values. 353/// 354static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs, 355 const std::pair<llvm::APSInt, CaseStmt*>& rhs) { 356 if (lhs.first < rhs.first) 357 return true; 358 359 if (lhs.first == rhs.first && 360 lhs.second->getCaseLoc().getRawEncoding() 361 < rhs.second->getCaseLoc().getRawEncoding()) 362 return true; 363 return false; 364} 365 366/// CmpEnumVals - Comparison predicate for sorting enumeration values. 367/// 368static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 369 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 370{ 371 return lhs.first < rhs.first; 372} 373 374/// EqEnumVals - Comparison preficate for uniqing enumeration values. 375/// 376static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 377 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 378{ 379 return lhs.first == rhs.first; 380} 381 382/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of 383/// potentially integral-promoted expression @p expr. 384static QualType GetTypeBeforeIntegralPromotion(const Expr* expr) { 385 if (const CastExpr *ImplicitCast = dyn_cast<ImplicitCastExpr>(expr)) { 386 const Expr *ExprBeforePromotion = ImplicitCast->getSubExpr(); 387 QualType TypeBeforePromotion = ExprBeforePromotion->getType(); 388 if (TypeBeforePromotion->isIntegralOrEnumerationType()) { 389 return TypeBeforePromotion; 390 } 391 } 392 return expr->getType(); 393} 394 395StmtResult 396Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond, 397 Decl *CondVar) { 398 ExprResult CondResult; 399 400 VarDecl *ConditionVar = 0; 401 if (CondVar) { 402 ConditionVar = cast<VarDecl>(CondVar); 403 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false); 404 if (CondResult.isInvalid()) 405 return StmtError(); 406 407 Cond = CondResult.release(); 408 } 409 410 if (!Cond) 411 return StmtError(); 412 413 CondResult 414 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, 415 PDiag(diag::err_typecheck_statement_requires_integer), 416 PDiag(diag::err_switch_incomplete_class_type) 417 << Cond->getSourceRange(), 418 PDiag(diag::err_switch_explicit_conversion), 419 PDiag(diag::note_switch_conversion), 420 PDiag(diag::err_switch_multiple_conversions), 421 PDiag(diag::note_switch_conversion), 422 PDiag(0)); 423 if (CondResult.isInvalid()) return StmtError(); 424 Cond = CondResult.take(); 425 426 if (!CondVar) { 427 CheckImplicitConversions(Cond, SwitchLoc); 428 CondResult = MaybeCreateExprWithCleanups(Cond); 429 if (CondResult.isInvalid()) 430 return StmtError(); 431 Cond = CondResult.take(); 432 } 433 434 getCurFunction()->setHasBranchIntoScope(); 435 436 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond); 437 getCurFunction()->SwitchStack.push_back(SS); 438 return Owned(SS); 439} 440 441static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) { 442 if (Val.getBitWidth() < BitWidth) 443 Val = Val.extend(BitWidth); 444 else if (Val.getBitWidth() > BitWidth) 445 Val = Val.trunc(BitWidth); 446 Val.setIsSigned(IsSigned); 447} 448 449StmtResult 450Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, 451 Stmt *BodyStmt) { 452 SwitchStmt *SS = cast<SwitchStmt>(Switch); 453 assert(SS == getCurFunction()->SwitchStack.back() && 454 "switch stack missing push/pop!"); 455 456 SS->setBody(BodyStmt, SwitchLoc); 457 getCurFunction()->SwitchStack.pop_back(); 458 459 if (SS->getCond() == 0) 460 return StmtError(); 461 462 Expr *CondExpr = SS->getCond(); 463 Expr *CondExprBeforePromotion = CondExpr; 464 QualType CondTypeBeforePromotion = 465 GetTypeBeforeIntegralPromotion(CondExpr); 466 467 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr. 468 ExprResult CondResult = UsualUnaryConversions(CondExpr); 469 if (CondResult.isInvalid()) 470 return StmtError(); 471 CondExpr = CondResult.take(); 472 QualType CondType = CondExpr->getType(); 473 SS->setCond(CondExpr); 474 475 // C++ 6.4.2.p2: 476 // Integral promotions are performed (on the switch condition). 477 // 478 // A case value unrepresentable by the original switch condition 479 // type (before the promotion) doesn't make sense, even when it can 480 // be represented by the promoted type. Therefore we need to find 481 // the pre-promotion type of the switch condition. 482 if (!CondExpr->isTypeDependent()) { 483 // We have already converted the expression to an integral or enumeration 484 // type, when we started the switch statement. If we don't have an 485 // appropriate type now, just return an error. 486 if (!CondType->isIntegralOrEnumerationType()) 487 return StmtError(); 488 489 if (CondExpr->isKnownToHaveBooleanValue()) { 490 // switch(bool_expr) {...} is often a programmer error, e.g. 491 // switch(n && mask) { ... } // Doh - should be "n & mask". 492 // One can always use an if statement instead of switch(bool_expr). 493 Diag(SwitchLoc, diag::warn_bool_switch_condition) 494 << CondExpr->getSourceRange(); 495 } 496 } 497 498 // Get the bitwidth of the switched-on value before promotions. We must 499 // convert the integer case values to this width before comparison. 500 bool HasDependentValue 501 = CondExpr->isTypeDependent() || CondExpr->isValueDependent(); 502 unsigned CondWidth 503 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion); 504 bool CondIsSigned 505 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType(); 506 507 // Accumulate all of the case values in a vector so that we can sort them 508 // and detect duplicates. This vector contains the APInt for the case after 509 // it has been converted to the condition type. 510 typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy; 511 CaseValsTy CaseVals; 512 513 // Keep track of any GNU case ranges we see. The APSInt is the low value. 514 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy; 515 CaseRangesTy CaseRanges; 516 517 DefaultStmt *TheDefaultStmt = 0; 518 519 bool CaseListIsErroneous = false; 520 521 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue; 522 SC = SC->getNextSwitchCase()) { 523 524 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) { 525 if (TheDefaultStmt) { 526 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined); 527 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev); 528 529 // FIXME: Remove the default statement from the switch block so that 530 // we'll return a valid AST. This requires recursing down the AST and 531 // finding it, not something we are set up to do right now. For now, 532 // just lop the entire switch stmt out of the AST. 533 CaseListIsErroneous = true; 534 } 535 TheDefaultStmt = DS; 536 537 } else { 538 CaseStmt *CS = cast<CaseStmt>(SC); 539 540 // We already verified that the expression has a i-c-e value (C99 541 // 6.8.4.2p3) - get that value now. 542 Expr *Lo = CS->getLHS(); 543 544 if (Lo->isTypeDependent() || Lo->isValueDependent()) { 545 HasDependentValue = true; 546 break; 547 } 548 549 llvm::APSInt LoVal = Lo->EvaluateAsInt(Context); 550 551 // Convert the value to the same width/sign as the condition. 552 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned, 553 Lo->getLocStart(), 554 diag::warn_case_value_overflow); 555 556 // If the LHS is not the same type as the condition, insert an implicit 557 // cast. 558 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take(); 559 CS->setLHS(Lo); 560 561 // If this is a case range, remember it in CaseRanges, otherwise CaseVals. 562 if (CS->getRHS()) { 563 if (CS->getRHS()->isTypeDependent() || 564 CS->getRHS()->isValueDependent()) { 565 HasDependentValue = true; 566 break; 567 } 568 CaseRanges.push_back(std::make_pair(LoVal, CS)); 569 } else 570 CaseVals.push_back(std::make_pair(LoVal, CS)); 571 } 572 } 573 574 if (!HasDependentValue) { 575 // If we don't have a default statement, check whether the 576 // condition is constant. 577 llvm::APSInt ConstantCondValue; 578 bool HasConstantCond = false; 579 bool ShouldCheckConstantCond = false; 580 if (!HasDependentValue && !TheDefaultStmt) { 581 Expr::EvalResult Result; 582 HasConstantCond = CondExprBeforePromotion->Evaluate(Result, Context); 583 if (HasConstantCond) { 584 assert(Result.Val.isInt() && "switch condition evaluated to non-int"); 585 ConstantCondValue = Result.Val.getInt(); 586 ShouldCheckConstantCond = true; 587 588 assert(ConstantCondValue.getBitWidth() == CondWidth && 589 ConstantCondValue.isSigned() == CondIsSigned); 590 } 591 } 592 593 // Sort all the scalar case values so we can easily detect duplicates. 594 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals); 595 596 if (!CaseVals.empty()) { 597 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) { 598 if (ShouldCheckConstantCond && 599 CaseVals[i].first == ConstantCondValue) 600 ShouldCheckConstantCond = false; 601 602 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) { 603 // If we have a duplicate, report it. 604 Diag(CaseVals[i].second->getLHS()->getLocStart(), 605 diag::err_duplicate_case) << CaseVals[i].first.toString(10); 606 Diag(CaseVals[i-1].second->getLHS()->getLocStart(), 607 diag::note_duplicate_case_prev); 608 // FIXME: We really want to remove the bogus case stmt from the 609 // substmt, but we have no way to do this right now. 610 CaseListIsErroneous = true; 611 } 612 } 613 } 614 615 // Detect duplicate case ranges, which usually don't exist at all in 616 // the first place. 617 if (!CaseRanges.empty()) { 618 // Sort all the case ranges by their low value so we can easily detect 619 // overlaps between ranges. 620 std::stable_sort(CaseRanges.begin(), CaseRanges.end()); 621 622 // Scan the ranges, computing the high values and removing empty ranges. 623 std::vector<llvm::APSInt> HiVals; 624 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 625 llvm::APSInt &LoVal = CaseRanges[i].first; 626 CaseStmt *CR = CaseRanges[i].second; 627 Expr *Hi = CR->getRHS(); 628 llvm::APSInt HiVal = Hi->EvaluateAsInt(Context); 629 630 // Convert the value to the same width/sign as the condition. 631 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned, 632 Hi->getLocStart(), 633 diag::warn_case_value_overflow); 634 635 // If the LHS is not the same type as the condition, insert an implicit 636 // cast. 637 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take(); 638 CR->setRHS(Hi); 639 640 // If the low value is bigger than the high value, the case is empty. 641 if (LoVal > HiVal) { 642 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range) 643 << SourceRange(CR->getLHS()->getLocStart(), 644 Hi->getLocEnd()); 645 CaseRanges.erase(CaseRanges.begin()+i); 646 --i, --e; 647 continue; 648 } 649 650 if (ShouldCheckConstantCond && 651 LoVal <= ConstantCondValue && 652 ConstantCondValue <= HiVal) 653 ShouldCheckConstantCond = false; 654 655 HiVals.push_back(HiVal); 656 } 657 658 // Rescan the ranges, looking for overlap with singleton values and other 659 // ranges. Since the range list is sorted, we only need to compare case 660 // ranges with their neighbors. 661 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 662 llvm::APSInt &CRLo = CaseRanges[i].first; 663 llvm::APSInt &CRHi = HiVals[i]; 664 CaseStmt *CR = CaseRanges[i].second; 665 666 // Check to see whether the case range overlaps with any 667 // singleton cases. 668 CaseStmt *OverlapStmt = 0; 669 llvm::APSInt OverlapVal(32); 670 671 // Find the smallest value >= the lower bound. If I is in the 672 // case range, then we have overlap. 673 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(), 674 CaseVals.end(), CRLo, 675 CaseCompareFunctor()); 676 if (I != CaseVals.end() && I->first < CRHi) { 677 OverlapVal = I->first; // Found overlap with scalar. 678 OverlapStmt = I->second; 679 } 680 681 // Find the smallest value bigger than the upper bound. 682 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor()); 683 if (I != CaseVals.begin() && (I-1)->first >= CRLo) { 684 OverlapVal = (I-1)->first; // Found overlap with scalar. 685 OverlapStmt = (I-1)->second; 686 } 687 688 // Check to see if this case stmt overlaps with the subsequent 689 // case range. 690 if (i && CRLo <= HiVals[i-1]) { 691 OverlapVal = HiVals[i-1]; // Found overlap with range. 692 OverlapStmt = CaseRanges[i-1].second; 693 } 694 695 if (OverlapStmt) { 696 // If we have a duplicate, report it. 697 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case) 698 << OverlapVal.toString(10); 699 Diag(OverlapStmt->getLHS()->getLocStart(), 700 diag::note_duplicate_case_prev); 701 // FIXME: We really want to remove the bogus case stmt from the 702 // substmt, but we have no way to do this right now. 703 CaseListIsErroneous = true; 704 } 705 } 706 } 707 708 // Complain if we have a constant condition and we didn't find a match. 709 if (!CaseListIsErroneous && ShouldCheckConstantCond) { 710 // TODO: it would be nice if we printed enums as enums, chars as 711 // chars, etc. 712 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition) 713 << ConstantCondValue.toString(10) 714 << CondExpr->getSourceRange(); 715 } 716 717 // Check to see if switch is over an Enum and handles all of its 718 // values. We only issue a warning if there is not 'default:', but 719 // we still do the analysis to preserve this information in the AST 720 // (which can be used by flow-based analyes). 721 // 722 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>(); 723 724 // If switch has default case, then ignore it. 725 if (!CaseListIsErroneous && !HasConstantCond && ET) { 726 const EnumDecl *ED = ET->getDecl(); 727 typedef llvm::SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy; 728 EnumValsTy EnumVals; 729 730 // Gather all enum values, set their type and sort them, 731 // allowing easier comparison with CaseVals. 732 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin(); 733 EDI != ED->enumerator_end(); ++EDI) { 734 llvm::APSInt Val = EDI->getInitVal(); 735 AdjustAPSInt(Val, CondWidth, CondIsSigned); 736 EnumVals.push_back(std::make_pair(Val, *EDI)); 737 } 738 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals); 739 EnumValsTy::iterator EIend = 740 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals); 741 742 // See which case values aren't in enum. 743 // TODO: we might want to check whether case values are out of the 744 // enum even if we don't want to check whether all cases are handled. 745 if (!TheDefaultStmt) { 746 EnumValsTy::const_iterator EI = EnumVals.begin(); 747 for (CaseValsTy::const_iterator CI = CaseVals.begin(); 748 CI != CaseVals.end(); CI++) { 749 while (EI != EIend && EI->first < CI->first) 750 EI++; 751 if (EI == EIend || EI->first > CI->first) 752 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum) 753 << ED->getDeclName(); 754 } 755 // See which of case ranges aren't in enum 756 EI = EnumVals.begin(); 757 for (CaseRangesTy::const_iterator RI = CaseRanges.begin(); 758 RI != CaseRanges.end() && EI != EIend; RI++) { 759 while (EI != EIend && EI->first < RI->first) 760 EI++; 761 762 if (EI == EIend || EI->first != RI->first) { 763 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum) 764 << ED->getDeclName(); 765 } 766 767 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context); 768 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 769 while (EI != EIend && EI->first < Hi) 770 EI++; 771 if (EI == EIend || EI->first != Hi) 772 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum) 773 << ED->getDeclName(); 774 } 775 } 776 777 // Check which enum vals aren't in switch 778 CaseValsTy::const_iterator CI = CaseVals.begin(); 779 CaseRangesTy::const_iterator RI = CaseRanges.begin(); 780 bool hasCasesNotInSwitch = false; 781 782 llvm::SmallVector<DeclarationName,8> UnhandledNames; 783 784 for (EnumValsTy::const_iterator EI = EnumVals.begin(); EI != EIend; EI++){ 785 // Drop unneeded case values 786 llvm::APSInt CIVal; 787 while (CI != CaseVals.end() && CI->first < EI->first) 788 CI++; 789 790 if (CI != CaseVals.end() && CI->first == EI->first) 791 continue; 792 793 // Drop unneeded case ranges 794 for (; RI != CaseRanges.end(); RI++) { 795 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context); 796 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 797 if (EI->first <= Hi) 798 break; 799 } 800 801 if (RI == CaseRanges.end() || EI->first < RI->first) { 802 hasCasesNotInSwitch = true; 803 if (!TheDefaultStmt) 804 UnhandledNames.push_back(EI->second->getDeclName()); 805 } 806 } 807 808 // Produce a nice diagnostic if multiple values aren't handled. 809 switch (UnhandledNames.size()) { 810 case 0: break; 811 case 1: 812 Diag(CondExpr->getExprLoc(), diag::warn_missing_case1) 813 << UnhandledNames[0]; 814 break; 815 case 2: 816 Diag(CondExpr->getExprLoc(), diag::warn_missing_case2) 817 << UnhandledNames[0] << UnhandledNames[1]; 818 break; 819 case 3: 820 Diag(CondExpr->getExprLoc(), diag::warn_missing_case3) 821 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2]; 822 break; 823 default: 824 Diag(CondExpr->getExprLoc(), diag::warn_missing_cases) 825 << (unsigned)UnhandledNames.size() 826 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2]; 827 break; 828 } 829 830 if (!hasCasesNotInSwitch) 831 SS->setAllEnumCasesCovered(); 832 } 833 } 834 835 // FIXME: If the case list was broken is some way, we don't have a good system 836 // to patch it up. Instead, just return the whole substmt as broken. 837 if (CaseListIsErroneous) 838 return StmtError(); 839 840 return Owned(SS); 841} 842 843StmtResult 844Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond, 845 Decl *CondVar, Stmt *Body) { 846 ExprResult CondResult(Cond.release()); 847 848 VarDecl *ConditionVar = 0; 849 if (CondVar) { 850 ConditionVar = cast<VarDecl>(CondVar); 851 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true); 852 if (CondResult.isInvalid()) 853 return StmtError(); 854 } 855 Expr *ConditionExpr = CondResult.take(); 856 if (!ConditionExpr) 857 return StmtError(); 858 859 DiagnoseUnusedExprResult(Body); 860 861 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr, 862 Body, WhileLoc)); 863} 864 865StmtResult 866Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 867 SourceLocation WhileLoc, SourceLocation CondLParen, 868 Expr *Cond, SourceLocation CondRParen) { 869 assert(Cond && "ActOnDoStmt(): missing expression"); 870 871 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc); 872 if (CondResult.isInvalid() || CondResult.isInvalid()) 873 return StmtError(); 874 Cond = CondResult.take(); 875 876 CheckImplicitConversions(Cond, DoLoc); 877 CondResult = MaybeCreateExprWithCleanups(Cond); 878 if (CondResult.isInvalid()) 879 return StmtError(); 880 Cond = CondResult.take(); 881 882 DiagnoseUnusedExprResult(Body); 883 884 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen)); 885} 886 887StmtResult 888Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 889 Stmt *First, FullExprArg second, Decl *secondVar, 890 FullExprArg third, 891 SourceLocation RParenLoc, Stmt *Body) { 892 if (!getLangOptions().CPlusPlus) { 893 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) { 894 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 895 // declare identifiers for objects having storage class 'auto' or 896 // 'register'. 897 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end(); 898 DI!=DE; ++DI) { 899 VarDecl *VD = dyn_cast<VarDecl>(*DI); 900 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage()) 901 VD = 0; 902 if (VD == 0) 903 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for); 904 // FIXME: mark decl erroneous! 905 } 906 } 907 } 908 909 ExprResult SecondResult(second.release()); 910 VarDecl *ConditionVar = 0; 911 if (secondVar) { 912 ConditionVar = cast<VarDecl>(secondVar); 913 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true); 914 if (SecondResult.isInvalid()) 915 return StmtError(); 916 } 917 918 Expr *Third = third.release().takeAs<Expr>(); 919 920 DiagnoseUnusedExprResult(First); 921 DiagnoseUnusedExprResult(Third); 922 DiagnoseUnusedExprResult(Body); 923 924 return Owned(new (Context) ForStmt(Context, First, 925 SecondResult.take(), ConditionVar, 926 Third, Body, ForLoc, LParenLoc, 927 RParenLoc)); 928} 929 930/// In an Objective C collection iteration statement: 931/// for (x in y) 932/// x can be an arbitrary l-value expression. Bind it up as a 933/// full-expression. 934StmtResult Sema::ActOnForEachLValueExpr(Expr *E) { 935 CheckImplicitConversions(E); 936 ExprResult Result = MaybeCreateExprWithCleanups(E); 937 if (Result.isInvalid()) return StmtError(); 938 return Owned(static_cast<Stmt*>(Result.get())); 939} 940 941StmtResult 942Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc, 943 SourceLocation LParenLoc, 944 Stmt *First, Expr *Second, 945 SourceLocation RParenLoc, Stmt *Body) { 946 if (First) { 947 QualType FirstType; 948 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) { 949 if (!DS->isSingleDecl()) 950 return StmtError(Diag((*DS->decl_begin())->getLocation(), 951 diag::err_toomany_element_decls)); 952 953 Decl *D = DS->getSingleDecl(); 954 FirstType = cast<ValueDecl>(D)->getType(); 955 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 956 // declare identifiers for objects having storage class 'auto' or 957 // 'register'. 958 VarDecl *VD = cast<VarDecl>(D); 959 if (VD->isLocalVarDecl() && !VD->hasLocalStorage()) 960 return StmtError(Diag(VD->getLocation(), 961 diag::err_non_variable_decl_in_for)); 962 } else { 963 Expr *FirstE = cast<Expr>(First); 964 if (!FirstE->isTypeDependent() && !FirstE->isLValue()) 965 return StmtError(Diag(First->getLocStart(), 966 diag::err_selector_element_not_lvalue) 967 << First->getSourceRange()); 968 969 FirstType = static_cast<Expr*>(First)->getType(); 970 } 971 if (!FirstType->isDependentType() && 972 !FirstType->isObjCObjectPointerType() && 973 !FirstType->isBlockPointerType()) 974 Diag(ForLoc, diag::err_selector_element_type) 975 << FirstType << First->getSourceRange(); 976 } 977 if (Second && !Second->isTypeDependent()) { 978 ExprResult Result = DefaultFunctionArrayLvalueConversion(Second); 979 if (Result.isInvalid()) 980 return StmtError(); 981 Second = Result.take(); 982 QualType SecondType = Second->getType(); 983 if (!SecondType->isObjCObjectPointerType()) 984 Diag(ForLoc, diag::err_collection_expr_type) 985 << SecondType << Second->getSourceRange(); 986 else if (const ObjCObjectPointerType *OPT = 987 SecondType->getAsObjCInterfacePointerType()) { 988 llvm::SmallVector<IdentifierInfo *, 4> KeyIdents; 989 IdentifierInfo* selIdent = 990 &Context.Idents.get("countByEnumeratingWithState"); 991 KeyIdents.push_back(selIdent); 992 selIdent = &Context.Idents.get("objects"); 993 KeyIdents.push_back(selIdent); 994 selIdent = &Context.Idents.get("count"); 995 KeyIdents.push_back(selIdent); 996 Selector CSelector = Context.Selectors.getSelector(3, &KeyIdents[0]); 997 if (ObjCInterfaceDecl *IDecl = OPT->getInterfaceDecl()) { 998 if (!IDecl->isForwardDecl() && 999 !IDecl->lookupInstanceMethod(CSelector) && 1000 !LookupMethodInQualifiedType(CSelector, OPT, true)) { 1001 // Must further look into private implementation methods. 1002 if (!LookupPrivateInstanceMethod(CSelector, IDecl)) 1003 Diag(ForLoc, diag::warn_collection_expr_type) 1004 << SecondType << CSelector << Second->getSourceRange(); 1005 } 1006 } 1007 } 1008 } 1009 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body, 1010 ForLoc, RParenLoc)); 1011} 1012 1013namespace { 1014 1015enum BeginEndFunction { 1016 BEF_begin, 1017 BEF_end 1018}; 1019 1020/// Build a variable declaration for a for-range statement. 1021static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc, 1022 QualType Type, const char *Name) { 1023 DeclContext *DC = SemaRef.CurContext; 1024 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 1025 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 1026 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, 1027 TInfo, SC_Auto, SC_None); 1028 Decl->setImplicit(); 1029 return Decl; 1030} 1031 1032/// Finish building a variable declaration for a for-range statement. 1033/// \return true if an error occurs. 1034static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init, 1035 SourceLocation Loc, int diag) { 1036 // Deduce the type for the iterator variable now rather than leaving it to 1037 // AddInitializerToDecl, so we can produce a more suitable diagnostic. 1038 TypeSourceInfo *InitTSI = 0; 1039 if (Init->getType()->isVoidType() || 1040 !SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI)) 1041 SemaRef.Diag(Loc, diag) << Init->getType(); 1042 if (!InitTSI) { 1043 Decl->setInvalidDecl(); 1044 return true; 1045 } 1046 Decl->setTypeSourceInfo(InitTSI); 1047 Decl->setType(InitTSI->getType()); 1048 1049 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false, 1050 /*TypeMayContainAuto=*/false); 1051 SemaRef.FinalizeDeclaration(Decl); 1052 SemaRef.CurContext->addHiddenDecl(Decl); 1053 return false; 1054} 1055 1056/// Produce a note indicating which begin/end function was implicitly called 1057/// by a C++0x for-range statement. This is often not obvious from the code, 1058/// nor from the diagnostics produced when analysing the implicit expressions 1059/// required in a for-range statement. 1060void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E, 1061 BeginEndFunction BEF) { 1062 CallExpr *CE = dyn_cast<CallExpr>(E); 1063 if (!CE) 1064 return; 1065 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl()); 1066 if (!D) 1067 return; 1068 SourceLocation Loc = D->getLocation(); 1069 1070 std::string Description; 1071 bool IsTemplate = false; 1072 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) { 1073 Description = SemaRef.getTemplateArgumentBindingsText( 1074 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs()); 1075 IsTemplate = true; 1076 } 1077 1078 SemaRef.Diag(Loc, diag::note_for_range_begin_end) 1079 << BEF << IsTemplate << Description << E->getType(); 1080} 1081 1082/// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the 1083/// given LookupResult is non-empty, it is assumed to describe a member which 1084/// will be invoked. Otherwise, the function will be found via argument 1085/// dependent lookup. 1086static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S, 1087 SourceLocation Loc, 1088 VarDecl *Decl, 1089 BeginEndFunction BEF, 1090 const DeclarationNameInfo &NameInfo, 1091 LookupResult &MemberLookup, 1092 Expr *Range) { 1093 ExprResult CallExpr; 1094 if (!MemberLookup.empty()) { 1095 ExprResult MemberRef = 1096 SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc, 1097 /*IsPtr=*/false, CXXScopeSpec(), 1098 /*Qualifier=*/0, MemberLookup, 1099 /*TemplateArgs=*/0); 1100 if (MemberRef.isInvalid()) 1101 return ExprError(); 1102 CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), 1103 Loc, 0); 1104 if (CallExpr.isInvalid()) 1105 return ExprError(); 1106 } else { 1107 UnresolvedSet<0> FoundNames; 1108 // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace 1109 // std is an associated namespace. 1110 UnresolvedLookupExpr *Fn = 1111 UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0, 1112 NestedNameSpecifierLoc(), NameInfo, 1113 /*NeedsADL=*/true, /*Overloaded=*/false, 1114 FoundNames.begin(), FoundNames.end(), 1115 /*LookInStdNamespace=*/true); 1116 CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc, 1117 0); 1118 if (CallExpr.isInvalid()) { 1119 SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type) 1120 << Range->getType(); 1121 return ExprError(); 1122 } 1123 } 1124 if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc, 1125 diag::err_for_range_iter_deduction_failure)) { 1126 NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF); 1127 return ExprError(); 1128 } 1129 return CallExpr; 1130} 1131 1132} 1133 1134/// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement. 1135/// 1136/// C++0x [stmt.ranged]: 1137/// A range-based for statement is equivalent to 1138/// 1139/// { 1140/// auto && __range = range-init; 1141/// for ( auto __begin = begin-expr, 1142/// __end = end-expr; 1143/// __begin != __end; 1144/// ++__begin ) { 1145/// for-range-declaration = *__begin; 1146/// statement 1147/// } 1148/// } 1149/// 1150/// The body of the loop is not available yet, since it cannot be analysed until 1151/// we have determined the type of the for-range-declaration. 1152StmtResult 1153Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 1154 Stmt *First, SourceLocation ColonLoc, Expr *Range, 1155 SourceLocation RParenLoc) { 1156 if (!First || !Range) 1157 return StmtError(); 1158 1159 DeclStmt *DS = dyn_cast<DeclStmt>(First); 1160 assert(DS && "first part of for range not a decl stmt"); 1161 1162 if (!DS->isSingleDecl()) { 1163 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range); 1164 return StmtError(); 1165 } 1166 if (DS->getSingleDecl()->isInvalidDecl()) 1167 return StmtError(); 1168 1169 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) 1170 return StmtError(); 1171 1172 // Build auto && __range = range-init 1173 SourceLocation RangeLoc = Range->getLocStart(); 1174 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc, 1175 Context.getAutoRRefDeductType(), 1176 "__range"); 1177 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc, 1178 diag::err_for_range_deduction_failure)) 1179 return StmtError(); 1180 1181 // Claim the type doesn't contain auto: we've already done the checking. 1182 DeclGroupPtrTy RangeGroup = 1183 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false); 1184 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc); 1185 if (RangeDecl.isInvalid()) 1186 return StmtError(); 1187 1188 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(), 1189 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS, 1190 RParenLoc); 1191} 1192 1193/// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement. 1194StmtResult 1195Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc, 1196 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond, 1197 Expr *Inc, Stmt *LoopVarDecl, 1198 SourceLocation RParenLoc) { 1199 Scope *S = getCurScope(); 1200 1201 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl); 1202 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl()); 1203 QualType RangeVarType = RangeVar->getType(); 1204 1205 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl); 1206 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl()); 1207 1208 StmtResult BeginEndDecl = BeginEnd; 1209 ExprResult NotEqExpr = Cond, IncrExpr = Inc; 1210 1211 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) { 1212 SourceLocation RangeLoc = RangeVar->getLocation(); 1213 1214 ExprResult RangeRef = BuildDeclRefExpr(RangeVar, 1215 RangeVarType.getNonReferenceType(), 1216 VK_LValue, ColonLoc); 1217 if (RangeRef.isInvalid()) 1218 return StmtError(); 1219 1220 QualType AutoType = Context.getAutoDeductType(); 1221 Expr *Range = RangeVar->getInit(); 1222 if (!Range) 1223 return StmtError(); 1224 QualType RangeType = Range->getType(); 1225 1226 if (RequireCompleteType(RangeLoc, RangeType, 1227 PDiag(diag::err_for_range_incomplete_type))) 1228 return StmtError(); 1229 1230 // Build auto __begin = begin-expr, __end = end-expr. 1231 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, 1232 "__begin"); 1233 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, 1234 "__end"); 1235 1236 // Build begin-expr and end-expr and attach to __begin and __end variables. 1237 ExprResult BeginExpr, EndExpr; 1238 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) { 1239 // - if _RangeT is an array type, begin-expr and end-expr are __range and 1240 // __range + __bound, respectively, where __bound is the array bound. If 1241 // _RangeT is an array of unknown size or an array of incomplete type, 1242 // the program is ill-formed; 1243 1244 // begin-expr is __range. 1245 BeginExpr = RangeRef; 1246 if (FinishForRangeVarDecl(*this, BeginVar, RangeRef.get(), ColonLoc, 1247 diag::err_for_range_iter_deduction_failure)) { 1248 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1249 return StmtError(); 1250 } 1251 1252 // Find the array bound. 1253 ExprResult BoundExpr; 1254 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT)) 1255 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(), 1256 Context.getPointerDiffType(), 1257 RangeLoc)); 1258 else if (const VariableArrayType *VAT = 1259 dyn_cast<VariableArrayType>(UnqAT)) 1260 BoundExpr = VAT->getSizeExpr(); 1261 else { 1262 // Can't be a DependentSizedArrayType or an IncompleteArrayType since 1263 // UnqAT is not incomplete and Range is not type-dependent. 1264 assert(0 && "Unexpected array type in for-range"); 1265 return StmtError(); 1266 } 1267 1268 // end-expr is __range + __bound. 1269 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, RangeRef.get(), 1270 BoundExpr.get()); 1271 if (EndExpr.isInvalid()) 1272 return StmtError(); 1273 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc, 1274 diag::err_for_range_iter_deduction_failure)) { 1275 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 1276 return StmtError(); 1277 } 1278 } else { 1279 DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"), 1280 ColonLoc); 1281 DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"), 1282 ColonLoc); 1283 1284 LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName); 1285 LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName); 1286 1287 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) { 1288 // - if _RangeT is a class type, the unqualified-ids begin and end are 1289 // looked up in the scope of class _RangeT as if by class member access 1290 // lookup (3.4.5), and if either (or both) finds at least one 1291 // declaration, begin-expr and end-expr are __range.begin() and 1292 // __range.end(), respectively; 1293 LookupQualifiedName(BeginMemberLookup, D); 1294 LookupQualifiedName(EndMemberLookup, D); 1295 1296 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) { 1297 Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch) 1298 << RangeType << BeginMemberLookup.empty(); 1299 return StmtError(); 1300 } 1301 } else { 1302 // - otherwise, begin-expr and end-expr are begin(__range) and 1303 // end(__range), respectively, where begin and end are looked up with 1304 // argument-dependent lookup (3.4.2). For the purposes of this name 1305 // lookup, namespace std is an associated namespace. 1306 } 1307 1308 BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar, 1309 BEF_begin, BeginNameInfo, 1310 BeginMemberLookup, RangeRef.get()); 1311 if (BeginExpr.isInvalid()) 1312 return StmtError(); 1313 1314 EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar, 1315 BEF_end, EndNameInfo, 1316 EndMemberLookup, RangeRef.get()); 1317 if (EndExpr.isInvalid()) 1318 return StmtError(); 1319 } 1320 1321 // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same. 1322 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType(); 1323 if (!Context.hasSameType(BeginType, EndType)) { 1324 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ) 1325 << BeginType << EndType; 1326 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1327 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 1328 } 1329 1330 Decl *BeginEndDecls[] = { BeginVar, EndVar }; 1331 // Claim the type doesn't contain auto: we've already done the checking. 1332 DeclGroupPtrTy BeginEndGroup = 1333 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false); 1334 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc); 1335 1336 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, 1337 BeginType.getNonReferenceType(), 1338 VK_LValue, ColonLoc); 1339 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(), 1340 VK_LValue, ColonLoc); 1341 1342 // Build and check __begin != __end expression. 1343 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal, 1344 BeginRef.get(), EndRef.get()); 1345 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get()); 1346 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get()); 1347 if (NotEqExpr.isInvalid()) { 1348 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1349 if (!Context.hasSameType(BeginType, EndType)) 1350 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 1351 return StmtError(); 1352 } 1353 1354 // Build and check ++__begin expression. 1355 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get()); 1356 IncrExpr = ActOnFinishFullExpr(IncrExpr.get()); 1357 if (IncrExpr.isInvalid()) { 1358 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1359 return StmtError(); 1360 } 1361 1362 // Build and check *__begin expression. 1363 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get()); 1364 if (DerefExpr.isInvalid()) { 1365 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1366 return StmtError(); 1367 } 1368 1369 // Attach *__begin as initializer for VD. 1370 if (!LoopVar->isInvalidDecl()) { 1371 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false, 1372 /*TypeMayContainAuto=*/true); 1373 if (LoopVar->isInvalidDecl()) 1374 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1375 } 1376 } 1377 1378 return Owned(new (Context) CXXForRangeStmt(RangeDS, 1379 cast_or_null<DeclStmt>(BeginEndDecl.get()), 1380 NotEqExpr.take(), IncrExpr.take(), 1381 LoopVarDS, /*Body=*/0, ForLoc, 1382 ColonLoc, RParenLoc)); 1383} 1384 1385/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement. 1386/// This is a separate step from ActOnCXXForRangeStmt because analysis of the 1387/// body cannot be performed until after the type of the range variable is 1388/// determined. 1389StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) { 1390 if (!S || !B) 1391 return StmtError(); 1392 1393 cast<CXXForRangeStmt>(S)->setBody(B); 1394 return S; 1395} 1396 1397StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc, 1398 SourceLocation LabelLoc, 1399 LabelDecl *TheDecl) { 1400 getCurFunction()->setHasBranchIntoScope(); 1401 TheDecl->setUsed(); 1402 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc)); 1403} 1404 1405StmtResult 1406Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, 1407 Expr *E) { 1408 // Convert operand to void* 1409 if (!E->isTypeDependent()) { 1410 QualType ETy = E->getType(); 1411 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst()); 1412 ExprResult ExprRes = Owned(E); 1413 AssignConvertType ConvTy = 1414 CheckSingleAssignmentConstraints(DestTy, ExprRes); 1415 if (ExprRes.isInvalid()) 1416 return StmtError(); 1417 E = ExprRes.take(); 1418 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing)) 1419 return StmtError(); 1420 } 1421 1422 getCurFunction()->setHasIndirectGoto(); 1423 1424 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E)); 1425} 1426 1427StmtResult 1428Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) { 1429 Scope *S = CurScope->getContinueParent(); 1430 if (!S) { 1431 // C99 6.8.6.2p1: A break shall appear only in or as a loop body. 1432 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop)); 1433 } 1434 1435 return Owned(new (Context) ContinueStmt(ContinueLoc)); 1436} 1437 1438StmtResult 1439Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) { 1440 Scope *S = CurScope->getBreakParent(); 1441 if (!S) { 1442 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body. 1443 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch)); 1444 } 1445 1446 return Owned(new (Context) BreakStmt(BreakLoc)); 1447} 1448 1449/// \brief Determine whether the given expression is a candidate for 1450/// copy elision in either a return statement or a throw expression. 1451/// 1452/// \param ReturnType If we're determining the copy elision candidate for 1453/// a return statement, this is the return type of the function. If we're 1454/// determining the copy elision candidate for a throw expression, this will 1455/// be a NULL type. 1456/// 1457/// \param E The expression being returned from the function or block, or 1458/// being thrown. 1459/// 1460/// \param AllowFunctionParameter Whether we allow function parameters to 1461/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but 1462/// we re-use this logic to determine whether we should try to move as part of 1463/// a return or throw (which does allow function parameters). 1464/// 1465/// \returns The NRVO candidate variable, if the return statement may use the 1466/// NRVO, or NULL if there is no such candidate. 1467const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, 1468 Expr *E, 1469 bool AllowFunctionParameter) { 1470 QualType ExprType = E->getType(); 1471 // - in a return statement in a function with ... 1472 // ... a class return type ... 1473 if (!ReturnType.isNull()) { 1474 if (!ReturnType->isRecordType()) 1475 return 0; 1476 // ... the same cv-unqualified type as the function return type ... 1477 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType)) 1478 return 0; 1479 } 1480 1481 // ... the expression is the name of a non-volatile automatic object 1482 // (other than a function or catch-clause parameter)) ... 1483 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens()); 1484 if (!DR) 1485 return 0; 1486 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()); 1487 if (!VD) 1488 return 0; 1489 1490 if (VD->hasLocalStorage() && !VD->isExceptionVariable() && 1491 !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() && 1492 !VD->getType().isVolatileQualified() && 1493 ((VD->getKind() == Decl::Var) || 1494 (AllowFunctionParameter && VD->getKind() == Decl::ParmVar))) 1495 return VD; 1496 1497 return 0; 1498} 1499 1500/// \brief Perform the initialization of a potentially-movable value, which 1501/// is the result of return value. 1502/// 1503/// This routine implements C++0x [class.copy]p33, which attempts to treat 1504/// returned lvalues as rvalues in certain cases (to prefer move construction), 1505/// then falls back to treating them as lvalues if that failed. 1506ExprResult 1507Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 1508 const VarDecl *NRVOCandidate, 1509 QualType ResultType, 1510 Expr *Value) { 1511 // C++0x [class.copy]p33: 1512 // When the criteria for elision of a copy operation are met or would 1513 // be met save for the fact that the source object is a function 1514 // parameter, and the object to be copied is designated by an lvalue, 1515 // overload resolution to select the constructor for the copy is first 1516 // performed as if the object were designated by an rvalue. 1517 ExprResult Res = ExprError(); 1518 if (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true)) { 1519 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, 1520 Value->getType(), CK_LValueToRValue, 1521 Value, VK_XValue); 1522 1523 Expr *InitExpr = &AsRvalue; 1524 InitializationKind Kind 1525 = InitializationKind::CreateCopy(Value->getLocStart(), 1526 Value->getLocStart()); 1527 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1); 1528 1529 // [...] If overload resolution fails, or if the type of the first 1530 // parameter of the selected constructor is not an rvalue reference 1531 // to the object's type (possibly cv-qualified), overload resolution 1532 // is performed again, considering the object as an lvalue. 1533 if (Seq.getKind() != InitializationSequence::FailedSequence) { 1534 for (InitializationSequence::step_iterator Step = Seq.step_begin(), 1535 StepEnd = Seq.step_end(); 1536 Step != StepEnd; ++Step) { 1537 if (Step->Kind 1538 != InitializationSequence::SK_ConstructorInitialization) 1539 continue; 1540 1541 CXXConstructorDecl *Constructor 1542 = cast<CXXConstructorDecl>(Step->Function.Function); 1543 1544 const RValueReferenceType *RRefType 1545 = Constructor->getParamDecl(0)->getType() 1546 ->getAs<RValueReferenceType>(); 1547 1548 // If we don't meet the criteria, break out now. 1549 if (!RRefType || 1550 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(), 1551 Context.getTypeDeclType(Constructor->getParent()))) 1552 break; 1553 1554 // Promote "AsRvalue" to the heap, since we now need this 1555 // expression node to persist. 1556 Value = ImplicitCastExpr::Create(Context, Value->getType(), 1557 CK_LValueToRValue, Value, 0, 1558 VK_XValue); 1559 1560 // Complete type-checking the initialization of the return type 1561 // using the constructor we found. 1562 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1)); 1563 } 1564 } 1565 } 1566 1567 // Either we didn't meet the criteria for treating an lvalue as an rvalue, 1568 // above, or overload resolution failed. Either way, we need to try 1569 // (again) now with the return value expression as written. 1570 if (Res.isInvalid()) 1571 Res = PerformCopyInitialization(Entity, SourceLocation(), Value); 1572 1573 return Res; 1574} 1575 1576/// ActOnBlockReturnStmt - Utility routine to figure out block's return type. 1577/// 1578StmtResult 1579Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 1580 // If this is the first return we've seen in the block, infer the type of 1581 // the block from it. 1582 BlockScopeInfo *CurBlock = getCurBlock(); 1583 if (CurBlock->ReturnType.isNull()) { 1584 if (RetValExp) { 1585 // Don't call UsualUnaryConversions(), since we don't want to do 1586 // integer promotions here. 1587 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp); 1588 if (Result.isInvalid()) 1589 return StmtError(); 1590 RetValExp = Result.take(); 1591 CurBlock->ReturnType = RetValExp->getType(); 1592 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) { 1593 // We have to remove a 'const' added to copied-in variable which was 1594 // part of the implementation spec. and not the actual qualifier for 1595 // the variable. 1596 if (CDRE->isConstQualAdded()) 1597 CurBlock->ReturnType.removeLocalConst(); // FIXME: local??? 1598 } 1599 } else 1600 CurBlock->ReturnType = Context.VoidTy; 1601 } 1602 QualType FnRetType = CurBlock->ReturnType; 1603 1604 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) { 1605 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr) 1606 << getCurFunctionOrMethodDecl()->getDeclName(); 1607 return StmtError(); 1608 } 1609 1610 // Otherwise, verify that this result type matches the previous one. We are 1611 // pickier with blocks than for normal functions because we don't have GCC 1612 // compatibility to worry about here. 1613 ReturnStmt *Result = 0; 1614 if (CurBlock->ReturnType->isVoidType()) { 1615 if (RetValExp) { 1616 Diag(ReturnLoc, diag::err_return_block_has_expr); 1617 RetValExp = 0; 1618 } 1619 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0); 1620 } else if (!RetValExp) { 1621 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr)); 1622 } else { 1623 const VarDecl *NRVOCandidate = 0; 1624 1625 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 1626 // we have a non-void block with an expression, continue checking 1627 1628 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 1629 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 1630 // function return. 1631 1632 // In C++ the return statement is handled via a copy initialization. 1633 // the C version of which boils down to CheckSingleAssignmentConstraints. 1634 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false); 1635 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, 1636 FnRetType, 1637 NRVOCandidate != 0); 1638 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, 1639 FnRetType, RetValExp); 1640 if (Res.isInvalid()) { 1641 // FIXME: Cleanup temporaries here, anyway? 1642 return StmtError(); 1643 } 1644 1645 if (RetValExp) { 1646 CheckImplicitConversions(RetValExp, ReturnLoc); 1647 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 1648 } 1649 1650 RetValExp = Res.takeAs<Expr>(); 1651 if (RetValExp) 1652 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 1653 } 1654 1655 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate); 1656 } 1657 1658 // If we need to check for the named return value optimization, save the 1659 // return statement in our scope for later processing. 1660 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() && 1661 !CurContext->isDependentContext()) 1662 FunctionScopes.back()->Returns.push_back(Result); 1663 1664 return Owned(Result); 1665} 1666 1667StmtResult 1668Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 1669 // Check for unexpanded parameter packs. 1670 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp)) 1671 return StmtError(); 1672 1673 if (getCurBlock()) 1674 return ActOnBlockReturnStmt(ReturnLoc, RetValExp); 1675 1676 QualType FnRetType; 1677 if (const FunctionDecl *FD = getCurFunctionDecl()) { 1678 FnRetType = FD->getResultType(); 1679 if (FD->hasAttr<NoReturnAttr>() || 1680 FD->getType()->getAs<FunctionType>()->getNoReturnAttr()) 1681 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) 1682 << getCurFunctionOrMethodDecl()->getDeclName(); 1683 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) 1684 FnRetType = MD->getResultType(); 1685 else // If we don't have a function/method context, bail. 1686 return StmtError(); 1687 1688 ReturnStmt *Result = 0; 1689 if (FnRetType->isVoidType()) { 1690 if (RetValExp) { 1691 if (!RetValExp->isTypeDependent()) { 1692 // C99 6.8.6.4p1 (ext_ since GCC warns) 1693 unsigned D = diag::ext_return_has_expr; 1694 if (RetValExp->getType()->isVoidType()) 1695 D = diag::ext_return_has_void_expr; 1696 else { 1697 ExprResult Result = Owned(RetValExp); 1698 Result = IgnoredValueConversions(Result.take()); 1699 if (Result.isInvalid()) 1700 return StmtError(); 1701 RetValExp = Result.take(); 1702 RetValExp = ImpCastExprToType(RetValExp, 1703 Context.VoidTy, CK_ToVoid).take(); 1704 } 1705 1706 // return (some void expression); is legal in C++. 1707 if (D != diag::ext_return_has_void_expr || 1708 !getLangOptions().CPlusPlus) { 1709 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 1710 Diag(ReturnLoc, D) 1711 << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl) 1712 << RetValExp->getSourceRange(); 1713 } 1714 } 1715 1716 CheckImplicitConversions(RetValExp, ReturnLoc); 1717 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 1718 } 1719 1720 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0); 1721 } else if (!RetValExp && !FnRetType->isDependentType()) { 1722 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4 1723 // C99 6.8.6.4p1 (ext_ since GCC warns) 1724 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr; 1725 1726 if (FunctionDecl *FD = getCurFunctionDecl()) 1727 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/; 1728 else 1729 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/; 1730 Result = new (Context) ReturnStmt(ReturnLoc); 1731 } else { 1732 const VarDecl *NRVOCandidate = 0; 1733 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 1734 // we have a non-void function with an expression, continue checking 1735 1736 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 1737 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 1738 // function return. 1739 1740 // In C++ the return statement is handled via a copy initialization. 1741 // the C version of which boils down to CheckSingleAssignmentConstraints. 1742 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false); 1743 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, 1744 FnRetType, 1745 NRVOCandidate != 0); 1746 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, 1747 FnRetType, RetValExp); 1748 if (Res.isInvalid()) { 1749 // FIXME: Cleanup temporaries here, anyway? 1750 return StmtError(); 1751 } 1752 1753 RetValExp = Res.takeAs<Expr>(); 1754 if (RetValExp) 1755 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 1756 } 1757 1758 if (RetValExp) { 1759 CheckImplicitConversions(RetValExp, ReturnLoc); 1760 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 1761 } 1762 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate); 1763 } 1764 1765 // If we need to check for the named return value optimization, save the 1766 // return statement in our scope for later processing. 1767 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() && 1768 !CurContext->isDependentContext()) 1769 FunctionScopes.back()->Returns.push_back(Result); 1770 1771 return Owned(Result); 1772} 1773 1774/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently 1775/// ignore "noop" casts in places where an lvalue is required by an inline asm. 1776/// We emulate this behavior when -fheinous-gnu-extensions is specified, but 1777/// provide a strong guidance to not use it. 1778/// 1779/// This method checks to see if the argument is an acceptable l-value and 1780/// returns false if it is a case we can handle. 1781static bool CheckAsmLValue(const Expr *E, Sema &S) { 1782 // Type dependent expressions will be checked during instantiation. 1783 if (E->isTypeDependent()) 1784 return false; 1785 1786 if (E->isLValue()) 1787 return false; // Cool, this is an lvalue. 1788 1789 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we 1790 // are supposed to allow. 1791 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context); 1792 if (E != E2 && E2->isLValue()) { 1793 if (!S.getLangOptions().HeinousExtensions) 1794 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue) 1795 << E->getSourceRange(); 1796 else 1797 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue) 1798 << E->getSourceRange(); 1799 // Accept, even if we emitted an error diagnostic. 1800 return false; 1801 } 1802 1803 // None of the above, just randomly invalid non-lvalue. 1804 return true; 1805} 1806 1807/// isOperandMentioned - Return true if the specified operand # is mentioned 1808/// anywhere in the decomposed asm string. 1809static bool isOperandMentioned(unsigned OpNo, 1810 llvm::ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) { 1811 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) { 1812 const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p]; 1813 if (!Piece.isOperand()) continue; 1814 1815 // If this is a reference to the input and if the input was the smaller 1816 // one, then we have to reject this asm. 1817 if (Piece.getOperandNo() == OpNo) 1818 return true; 1819 } 1820 1821 return false; 1822} 1823 1824StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple, 1825 bool IsVolatile, unsigned NumOutputs, 1826 unsigned NumInputs, IdentifierInfo **Names, 1827 MultiExprArg constraints, MultiExprArg exprs, 1828 Expr *asmString, MultiExprArg clobbers, 1829 SourceLocation RParenLoc, bool MSAsm) { 1830 unsigned NumClobbers = clobbers.size(); 1831 StringLiteral **Constraints = 1832 reinterpret_cast<StringLiteral**>(constraints.get()); 1833 Expr **Exprs = exprs.get(); 1834 StringLiteral *AsmString = cast<StringLiteral>(asmString); 1835 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get()); 1836 1837 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; 1838 1839 // The parser verifies that there is a string literal here. 1840 if (AsmString->isWide()) 1841 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character) 1842 << AsmString->getSourceRange()); 1843 1844 for (unsigned i = 0; i != NumOutputs; i++) { 1845 StringLiteral *Literal = Constraints[i]; 1846 if (Literal->isWide()) 1847 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 1848 << Literal->getSourceRange()); 1849 1850 llvm::StringRef OutputName; 1851 if (Names[i]) 1852 OutputName = Names[i]->getName(); 1853 1854 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName); 1855 if (!Context.Target.validateOutputConstraint(Info)) 1856 return StmtError(Diag(Literal->getLocStart(), 1857 diag::err_asm_invalid_output_constraint) 1858 << Info.getConstraintStr()); 1859 1860 // Check that the output exprs are valid lvalues. 1861 Expr *OutputExpr = Exprs[i]; 1862 if (CheckAsmLValue(OutputExpr, *this)) { 1863 return StmtError(Diag(OutputExpr->getLocStart(), 1864 diag::err_asm_invalid_lvalue_in_output) 1865 << OutputExpr->getSourceRange()); 1866 } 1867 1868 OutputConstraintInfos.push_back(Info); 1869 } 1870 1871 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos; 1872 1873 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) { 1874 StringLiteral *Literal = Constraints[i]; 1875 if (Literal->isWide()) 1876 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 1877 << Literal->getSourceRange()); 1878 1879 llvm::StringRef InputName; 1880 if (Names[i]) 1881 InputName = Names[i]->getName(); 1882 1883 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName); 1884 if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(), 1885 NumOutputs, Info)) { 1886 return StmtError(Diag(Literal->getLocStart(), 1887 diag::err_asm_invalid_input_constraint) 1888 << Info.getConstraintStr()); 1889 } 1890 1891 Expr *InputExpr = Exprs[i]; 1892 1893 // Only allow void types for memory constraints. 1894 if (Info.allowsMemory() && !Info.allowsRegister()) { 1895 if (CheckAsmLValue(InputExpr, *this)) 1896 return StmtError(Diag(InputExpr->getLocStart(), 1897 diag::err_asm_invalid_lvalue_in_input) 1898 << Info.getConstraintStr() 1899 << InputExpr->getSourceRange()); 1900 } 1901 1902 if (Info.allowsRegister()) { 1903 if (InputExpr->getType()->isVoidType()) { 1904 return StmtError(Diag(InputExpr->getLocStart(), 1905 diag::err_asm_invalid_type_in_input) 1906 << InputExpr->getType() << Info.getConstraintStr() 1907 << InputExpr->getSourceRange()); 1908 } 1909 } 1910 1911 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]); 1912 if (Result.isInvalid()) 1913 return StmtError(); 1914 1915 Exprs[i] = Result.take(); 1916 InputConstraintInfos.push_back(Info); 1917 } 1918 1919 // Check that the clobbers are valid. 1920 for (unsigned i = 0; i != NumClobbers; i++) { 1921 StringLiteral *Literal = Clobbers[i]; 1922 if (Literal->isWide()) 1923 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 1924 << Literal->getSourceRange()); 1925 1926 llvm::StringRef Clobber = Literal->getString(); 1927 1928 if (!Context.Target.isValidGCCRegisterName(Clobber)) 1929 return StmtError(Diag(Literal->getLocStart(), 1930 diag::err_asm_unknown_register_name) << Clobber); 1931 } 1932 1933 AsmStmt *NS = 1934 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm, 1935 NumOutputs, NumInputs, Names, Constraints, Exprs, 1936 AsmString, NumClobbers, Clobbers, RParenLoc); 1937 // Validate the asm string, ensuring it makes sense given the operands we 1938 // have. 1939 llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces; 1940 unsigned DiagOffs; 1941 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) { 1942 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID) 1943 << AsmString->getSourceRange(); 1944 return StmtError(); 1945 } 1946 1947 // Validate tied input operands for type mismatches. 1948 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) { 1949 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i]; 1950 1951 // If this is a tied constraint, verify that the output and input have 1952 // either exactly the same type, or that they are int/ptr operands with the 1953 // same size (int/long, int*/long, are ok etc). 1954 if (!Info.hasTiedOperand()) continue; 1955 1956 unsigned TiedTo = Info.getTiedOperand(); 1957 unsigned InputOpNo = i+NumOutputs; 1958 Expr *OutputExpr = Exprs[TiedTo]; 1959 Expr *InputExpr = Exprs[InputOpNo]; 1960 QualType InTy = InputExpr->getType(); 1961 QualType OutTy = OutputExpr->getType(); 1962 if (Context.hasSameType(InTy, OutTy)) 1963 continue; // All types can be tied to themselves. 1964 1965 // Decide if the input and output are in the same domain (integer/ptr or 1966 // floating point. 1967 enum AsmDomain { 1968 AD_Int, AD_FP, AD_Other 1969 } InputDomain, OutputDomain; 1970 1971 if (InTy->isIntegerType() || InTy->isPointerType()) 1972 InputDomain = AD_Int; 1973 else if (InTy->isRealFloatingType()) 1974 InputDomain = AD_FP; 1975 else 1976 InputDomain = AD_Other; 1977 1978 if (OutTy->isIntegerType() || OutTy->isPointerType()) 1979 OutputDomain = AD_Int; 1980 else if (OutTy->isRealFloatingType()) 1981 OutputDomain = AD_FP; 1982 else 1983 OutputDomain = AD_Other; 1984 1985 // They are ok if they are the same size and in the same domain. This 1986 // allows tying things like: 1987 // void* to int* 1988 // void* to int if they are the same size. 1989 // double to long double if they are the same size. 1990 // 1991 uint64_t OutSize = Context.getTypeSize(OutTy); 1992 uint64_t InSize = Context.getTypeSize(InTy); 1993 if (OutSize == InSize && InputDomain == OutputDomain && 1994 InputDomain != AD_Other) 1995 continue; 1996 1997 // If the smaller input/output operand is not mentioned in the asm string, 1998 // then we can promote the smaller one to a larger input and the asm string 1999 // won't notice. 2000 bool SmallerValueMentioned = false; 2001 2002 // If this is a reference to the input and if the input was the smaller 2003 // one, then we have to reject this asm. 2004 if (isOperandMentioned(InputOpNo, Pieces)) { 2005 // This is a use in the asm string of the smaller operand. Since we 2006 // codegen this by promoting to a wider value, the asm will get printed 2007 // "wrong". 2008 SmallerValueMentioned |= InSize < OutSize; 2009 } 2010 if (isOperandMentioned(TiedTo, Pieces)) { 2011 // If this is a reference to the output, and if the output is the larger 2012 // value, then it's ok because we'll promote the input to the larger type. 2013 SmallerValueMentioned |= OutSize < InSize; 2014 } 2015 2016 // If the smaller value wasn't mentioned in the asm string, and if the 2017 // output was a register, just extend the shorter one to the size of the 2018 // larger one. 2019 if (!SmallerValueMentioned && InputDomain != AD_Other && 2020 OutputConstraintInfos[TiedTo].allowsRegister()) 2021 continue; 2022 2023 // Either both of the operands were mentioned or the smaller one was 2024 // mentioned. One more special case that we'll allow: if the tied input is 2025 // integer, unmentioned, and is a constant, then we'll allow truncating it 2026 // down to the size of the destination. 2027 if (InputDomain == AD_Int && OutputDomain == AD_Int && 2028 !isOperandMentioned(InputOpNo, Pieces) && 2029 InputExpr->isEvaluatable(Context)) { 2030 CastKind castKind = 2031 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast); 2032 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take(); 2033 Exprs[InputOpNo] = InputExpr; 2034 NS->setInputExpr(i, InputExpr); 2035 continue; 2036 } 2037 2038 Diag(InputExpr->getLocStart(), 2039 diag::err_asm_tying_incompatible_types) 2040 << InTy << OutTy << OutputExpr->getSourceRange() 2041 << InputExpr->getSourceRange(); 2042 return StmtError(); 2043 } 2044 2045 return Owned(NS); 2046} 2047 2048StmtResult 2049Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc, 2050 SourceLocation RParen, Decl *Parm, 2051 Stmt *Body) { 2052 VarDecl *Var = cast_or_null<VarDecl>(Parm); 2053 if (Var && Var->isInvalidDecl()) 2054 return StmtError(); 2055 2056 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body)); 2057} 2058 2059StmtResult 2060Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) { 2061 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body)); 2062} 2063 2064StmtResult 2065Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 2066 MultiStmtArg CatchStmts, Stmt *Finally) { 2067 if (!getLangOptions().ObjCExceptions) 2068 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try"; 2069 2070 getCurFunction()->setHasBranchProtectedScope(); 2071 unsigned NumCatchStmts = CatchStmts.size(); 2072 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try, 2073 CatchStmts.release(), 2074 NumCatchStmts, 2075 Finally)); 2076} 2077 2078StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, 2079 Expr *Throw) { 2080 if (Throw) { 2081 ExprResult Result = DefaultLvalueConversion(Throw); 2082 if (Result.isInvalid()) 2083 return StmtError(); 2084 2085 Throw = Result.take(); 2086 QualType ThrowType = Throw->getType(); 2087 // Make sure the expression type is an ObjC pointer or "void *". 2088 if (!ThrowType->isDependentType() && 2089 !ThrowType->isObjCObjectPointerType()) { 2090 const PointerType *PT = ThrowType->getAs<PointerType>(); 2091 if (!PT || !PT->getPointeeType()->isVoidType()) 2092 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object) 2093 << Throw->getType() << Throw->getSourceRange()); 2094 } 2095 } 2096 2097 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw)); 2098} 2099 2100StmtResult 2101Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 2102 Scope *CurScope) { 2103 if (!getLangOptions().ObjCExceptions) 2104 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw"; 2105 2106 if (!Throw) { 2107 // @throw without an expression designates a rethrow (which much occur 2108 // in the context of an @catch clause). 2109 Scope *AtCatchParent = CurScope; 2110 while (AtCatchParent && !AtCatchParent->isAtCatchScope()) 2111 AtCatchParent = AtCatchParent->getParent(); 2112 if (!AtCatchParent) 2113 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch)); 2114 } 2115 2116 return BuildObjCAtThrowStmt(AtLoc, Throw); 2117} 2118 2119StmtResult 2120Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr, 2121 Stmt *SyncBody) { 2122 getCurFunction()->setHasBranchProtectedScope(); 2123 2124 ExprResult Result = DefaultLvalueConversion(SyncExpr); 2125 if (Result.isInvalid()) 2126 return StmtError(); 2127 2128 SyncExpr = Result.take(); 2129 // Make sure the expression type is an ObjC pointer or "void *". 2130 if (!SyncExpr->getType()->isDependentType() && 2131 !SyncExpr->getType()->isObjCObjectPointerType()) { 2132 const PointerType *PT = SyncExpr->getType()->getAs<PointerType>(); 2133 if (!PT || !PT->getPointeeType()->isVoidType()) 2134 return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object) 2135 << SyncExpr->getType() << SyncExpr->getSourceRange()); 2136 } 2137 2138 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody)); 2139} 2140 2141/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block 2142/// and creates a proper catch handler from them. 2143StmtResult 2144Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, 2145 Stmt *HandlerBlock) { 2146 // There's nothing to test that ActOnExceptionDecl didn't already test. 2147 return Owned(new (Context) CXXCatchStmt(CatchLoc, 2148 cast_or_null<VarDecl>(ExDecl), 2149 HandlerBlock)); 2150} 2151 2152namespace { 2153 2154class TypeWithHandler { 2155 QualType t; 2156 CXXCatchStmt *stmt; 2157public: 2158 TypeWithHandler(const QualType &type, CXXCatchStmt *statement) 2159 : t(type), stmt(statement) {} 2160 2161 // An arbitrary order is fine as long as it places identical 2162 // types next to each other. 2163 bool operator<(const TypeWithHandler &y) const { 2164 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr()) 2165 return true; 2166 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr()) 2167 return false; 2168 else 2169 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc(); 2170 } 2171 2172 bool operator==(const TypeWithHandler& other) const { 2173 return t == other.t; 2174 } 2175 2176 CXXCatchStmt *getCatchStmt() const { return stmt; } 2177 SourceLocation getTypeSpecStartLoc() const { 2178 return stmt->getExceptionDecl()->getTypeSpecStartLoc(); 2179 } 2180}; 2181 2182} 2183 2184/// ActOnCXXTryBlock - Takes a try compound-statement and a number of 2185/// handlers and creates a try statement from them. 2186StmtResult 2187Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 2188 MultiStmtArg RawHandlers) { 2189 // Don't report an error if 'try' is used in system headers. 2190 if (!getLangOptions().CXXExceptions && 2191 !getSourceManager().isInSystemHeader(TryLoc)) 2192 Diag(TryLoc, diag::err_exceptions_disabled) << "try"; 2193 2194 unsigned NumHandlers = RawHandlers.size(); 2195 assert(NumHandlers > 0 && 2196 "The parser shouldn't call this if there are no handlers."); 2197 Stmt **Handlers = RawHandlers.get(); 2198 2199 llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers; 2200 2201 for (unsigned i = 0; i < NumHandlers; ++i) { 2202 CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]); 2203 if (!Handler->getExceptionDecl()) { 2204 if (i < NumHandlers - 1) 2205 return StmtError(Diag(Handler->getLocStart(), 2206 diag::err_early_catch_all)); 2207 2208 continue; 2209 } 2210 2211 const QualType CaughtType = Handler->getCaughtType(); 2212 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType); 2213 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler)); 2214 } 2215 2216 // Detect handlers for the same type as an earlier one. 2217 if (NumHandlers > 1) { 2218 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end()); 2219 2220 TypeWithHandler prev = TypesWithHandlers[0]; 2221 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) { 2222 TypeWithHandler curr = TypesWithHandlers[i]; 2223 2224 if (curr == prev) { 2225 Diag(curr.getTypeSpecStartLoc(), 2226 diag::warn_exception_caught_by_earlier_handler) 2227 << curr.getCatchStmt()->getCaughtType().getAsString(); 2228 Diag(prev.getTypeSpecStartLoc(), 2229 diag::note_previous_exception_handler) 2230 << prev.getCatchStmt()->getCaughtType().getAsString(); 2231 } 2232 2233 prev = curr; 2234 } 2235 } 2236 2237 getCurFunction()->setHasBranchProtectedScope(); 2238 2239 // FIXME: We should detect handlers that cannot catch anything because an 2240 // earlier handler catches a superclass. Need to find a method that is not 2241 // quadratic for this. 2242 // Neither of these are explicitly forbidden, but every compiler detects them 2243 // and warns. 2244 2245 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock, 2246 Handlers, NumHandlers)); 2247} 2248 2249StmtResult 2250Sema::ActOnSEHTryBlock(bool IsCXXTry, 2251 SourceLocation TryLoc, 2252 Stmt *TryBlock, 2253 Stmt *Handler) { 2254 assert(TryBlock && Handler); 2255 2256 getCurFunction()->setHasBranchProtectedScope(); 2257 2258 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler)); 2259} 2260 2261StmtResult 2262Sema::ActOnSEHExceptBlock(SourceLocation Loc, 2263 Expr *FilterExpr, 2264 Stmt *Block) { 2265 assert(FilterExpr && Block); 2266 2267 if(!FilterExpr->getType()->isIntegerType()) { 2268 return StmtError(Diag(FilterExpr->getExprLoc(), diag::err_filter_expression_integral) << FilterExpr->getType()); 2269 } 2270 2271 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block)); 2272} 2273 2274StmtResult 2275Sema::ActOnSEHFinallyBlock(SourceLocation Loc, 2276 Stmt *Block) { 2277 assert(Block); 2278 return Owned(SEHFinallyStmt::Create(Context,Loc,Block)); 2279} 2280 2281