SemaStmt.cpp revision 12f78a6741a4cb3d904340f8d3d2714568b50e7a
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/AST/APValue.h" 19#include "clang/AST/ASTContext.h" 20#include "clang/AST/DeclObjC.h" 21#include "clang/AST/ExprCXX.h" 22#include "clang/AST/ExprObjC.h" 23#include "clang/AST/StmtObjC.h" 24#include "clang/AST/StmtCXX.h" 25#include "clang/AST/TypeLoc.h" 26#include "clang/Lex/Preprocessor.h" 27#include "clang/Basic/TargetInfo.h" 28#include "llvm/ADT/STLExtras.h" 29#include "llvm/ADT/SmallVector.h" 30using namespace clang; 31using namespace sema; 32 33StmtResult Sema::ActOnExprStmt(FullExprArg expr) { 34 Expr *E = expr.get(); 35 assert(E && "ActOnExprStmt(): missing expression"); 36 // C99 6.8.3p2: The expression in an expression statement is evaluated as a 37 // void expression for its side effects. Conversion to void allows any 38 // operand, even incomplete types. 39 40 // Same thing in for stmt first clause (when expr) and third clause. 41 return Owned(static_cast<Stmt*>(E)); 42} 43 44 45StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc, bool LeadingEmptyMacro) { 46 return Owned(new (Context) NullStmt(SemiLoc, LeadingEmptyMacro)); 47} 48 49StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, 50 SourceLocation StartLoc, 51 SourceLocation EndLoc) { 52 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>(); 53 54 // If we have an invalid decl, just return an error. 55 if (DG.isNull()) return StmtError(); 56 57 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc)); 58} 59 60void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) { 61 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>(); 62 63 // If we have an invalid decl, just return. 64 if (DG.isNull() || !DG.isSingleDecl()) return; 65 // suppress any potential 'unused variable' warning. 66 DG.getSingleDecl()->setUsed(); 67} 68 69void Sema::DiagnoseUnusedExprResult(const Stmt *S) { 70 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) 71 return DiagnoseUnusedExprResult(Label->getSubStmt()); 72 73 const Expr *E = dyn_cast_or_null<Expr>(S); 74 if (!E) 75 return; 76 77 if (E->isBoundMemberFunction(Context)) { 78 Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func) 79 << E->getSourceRange(); 80 return; 81 } 82 83 SourceLocation Loc; 84 SourceRange R1, R2; 85 if (!E->isUnusedResultAWarning(Loc, R1, R2, Context)) 86 return; 87 88 // Okay, we have an unused result. Depending on what the base expression is, 89 // we might want to make a more specific diagnostic. Check for one of these 90 // cases now. 91 unsigned DiagID = diag::warn_unused_expr; 92 if (const CXXExprWithTemporaries *Temps = dyn_cast<CXXExprWithTemporaries>(E)) 93 E = Temps->getSubExpr(); 94 95 E = E->IgnoreParens(); 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, 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, IdentifierInfo *II, 234 SourceLocation ColonLoc, Stmt *SubStmt, 235 const AttributeList *Attr) { 236 // According to GCC docs, "the only attribute that makes sense after a label 237 // is 'unused'". 238 bool HasUnusedAttr = false; 239 for ( ; Attr; Attr = Attr->getNext()) { 240 if (Attr->getKind() == AttributeList::AT_unused) { 241 HasUnusedAttr = true; 242 } else { 243 Diag(Attr->getLoc(), diag::warn_label_attribute_not_unused); 244 Attr->setInvalid(true); 245 } 246 } 247 248 return ActOnLabelStmt(IdentLoc, II, ColonLoc, SubStmt, HasUnusedAttr); 249} 250 251StmtResult 252Sema::ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II, 253 SourceLocation ColonLoc, Stmt *SubStmt, 254 bool HasUnusedAttr) { 255 // Look up the record for this label identifier. 256 LabelStmt *&LabelDecl = getCurFunction()->LabelMap[II]; 257 258 // If not forward referenced or defined already, just create a new LabelStmt. 259 if (LabelDecl == 0) 260 return Owned(LabelDecl = new (Context) LabelStmt(IdentLoc, II, SubStmt, 261 HasUnusedAttr)); 262 263 assert(LabelDecl->getID() == II && "Label mismatch!"); 264 265 // Otherwise, this label was either forward reference or multiply defined. If 266 // multiply defined, reject it now. 267 if (LabelDecl->getSubStmt()) { 268 Diag(IdentLoc, diag::err_redefinition_of_label) << LabelDecl->getID(); 269 Diag(LabelDecl->getIdentLoc(), diag::note_previous_definition); 270 return Owned(SubStmt); 271 } 272 273 // Otherwise, this label was forward declared, and we just found its real 274 // definition. Fill in the forward definition and return it. 275 LabelDecl->setIdentLoc(IdentLoc); 276 LabelDecl->setSubStmt(SubStmt); 277 LabelDecl->setUnusedAttribute(HasUnusedAttr); 278 return Owned(LabelDecl); 279} 280 281StmtResult 282Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar, 283 Stmt *thenStmt, SourceLocation ElseLoc, 284 Stmt *elseStmt) { 285 ExprResult CondResult(CondVal.release()); 286 287 VarDecl *ConditionVar = 0; 288 if (CondVar) { 289 ConditionVar = cast<VarDecl>(CondVar); 290 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true); 291 if (CondResult.isInvalid()) 292 return StmtError(); 293 } 294 Expr *ConditionExpr = CondResult.takeAs<Expr>(); 295 if (!ConditionExpr) 296 return StmtError(); 297 298 DiagnoseUnusedExprResult(thenStmt); 299 300 // Warn if the if block has a null body without an else value. 301 // this helps prevent bugs due to typos, such as 302 // if (condition); 303 // do_stuff(); 304 // 305 if (!elseStmt) { 306 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt)) 307 // But do not warn if the body is a macro that expands to nothing, e.g: 308 // 309 // #define CALL(x) 310 // if (condition) 311 // CALL(0); 312 // 313 if (!stmt->hasLeadingEmptyMacro()) 314 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body); 315 } 316 317 DiagnoseUnusedExprResult(elseStmt); 318 319 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr, 320 thenStmt, ElseLoc, elseStmt)); 321} 322 323/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 324/// the specified width and sign. If an overflow occurs, detect it and emit 325/// the specified diagnostic. 326void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val, 327 unsigned NewWidth, bool NewSign, 328 SourceLocation Loc, 329 unsigned DiagID) { 330 // Perform a conversion to the promoted condition type if needed. 331 if (NewWidth > Val.getBitWidth()) { 332 // If this is an extension, just do it. 333 Val.extend(NewWidth); 334 Val.setIsSigned(NewSign); 335 336 // If the input was signed and negative and the output is 337 // unsigned, don't bother to warn: this is implementation-defined 338 // behavior. 339 // FIXME: Introduce a second, default-ignored warning for this case? 340 } else if (NewWidth < Val.getBitWidth()) { 341 // If this is a truncation, check for overflow. 342 llvm::APSInt ConvVal(Val); 343 ConvVal.trunc(NewWidth); 344 ConvVal.setIsSigned(NewSign); 345 ConvVal.extend(Val.getBitWidth()); 346 ConvVal.setIsSigned(Val.isSigned()); 347 if (ConvVal != Val) 348 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10); 349 350 // Regardless of whether a diagnostic was emitted, really do the 351 // truncation. 352 Val.trunc(NewWidth); 353 Val.setIsSigned(NewSign); 354 } else if (NewSign != Val.isSigned()) { 355 // Convert the sign to match the sign of the condition. This can cause 356 // overflow as well: unsigned(INTMIN) 357 // We don't diagnose this overflow, because it is implementation-defined 358 // behavior. 359 // FIXME: Introduce a second, default-ignored warning for this case? 360 llvm::APSInt OldVal(Val); 361 Val.setIsSigned(NewSign); 362 } 363} 364 365namespace { 366 struct CaseCompareFunctor { 367 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 368 const llvm::APSInt &RHS) { 369 return LHS.first < RHS; 370 } 371 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 372 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 373 return LHS.first < RHS.first; 374 } 375 bool operator()(const llvm::APSInt &LHS, 376 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 377 return LHS < RHS.first; 378 } 379 }; 380} 381 382/// CmpCaseVals - Comparison predicate for sorting case values. 383/// 384static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs, 385 const std::pair<llvm::APSInt, CaseStmt*>& rhs) { 386 if (lhs.first < rhs.first) 387 return true; 388 389 if (lhs.first == rhs.first && 390 lhs.second->getCaseLoc().getRawEncoding() 391 < rhs.second->getCaseLoc().getRawEncoding()) 392 return true; 393 return false; 394} 395 396/// CmpEnumVals - Comparison predicate for sorting enumeration values. 397/// 398static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 399 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 400{ 401 return lhs.first < rhs.first; 402} 403 404/// EqEnumVals - Comparison preficate for uniqing enumeration values. 405/// 406static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 407 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 408{ 409 return lhs.first == rhs.first; 410} 411 412/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of 413/// potentially integral-promoted expression @p expr. 414static QualType GetTypeBeforeIntegralPromotion(const Expr* expr) { 415 if (const CastExpr *ImplicitCast = dyn_cast<ImplicitCastExpr>(expr)) { 416 const Expr *ExprBeforePromotion = ImplicitCast->getSubExpr(); 417 QualType TypeBeforePromotion = ExprBeforePromotion->getType(); 418 if (TypeBeforePromotion->isIntegralOrEnumerationType()) { 419 return TypeBeforePromotion; 420 } 421 } 422 return expr->getType(); 423} 424 425StmtResult 426Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond, 427 Decl *CondVar) { 428 ExprResult CondResult; 429 430 VarDecl *ConditionVar = 0; 431 if (CondVar) { 432 ConditionVar = cast<VarDecl>(CondVar); 433 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false); 434 if (CondResult.isInvalid()) 435 return StmtError(); 436 437 Cond = CondResult.release(); 438 } 439 440 if (!Cond) 441 return StmtError(); 442 443 CondResult 444 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, 445 PDiag(diag::err_typecheck_statement_requires_integer), 446 PDiag(diag::err_switch_incomplete_class_type) 447 << Cond->getSourceRange(), 448 PDiag(diag::err_switch_explicit_conversion), 449 PDiag(diag::note_switch_conversion), 450 PDiag(diag::err_switch_multiple_conversions), 451 PDiag(diag::note_switch_conversion), 452 PDiag(0)); 453 if (CondResult.isInvalid()) return StmtError(); 454 Cond = CondResult.take(); 455 456 if (!CondVar) { 457 CheckImplicitConversions(Cond, SwitchLoc); 458 CondResult = MaybeCreateCXXExprWithTemporaries(Cond); 459 if (CondResult.isInvalid()) 460 return StmtError(); 461 Cond = CondResult.take(); 462 } 463 464 getCurFunction()->setHasBranchIntoScope(); 465 466 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond); 467 getCurFunction()->SwitchStack.push_back(SS); 468 return Owned(SS); 469} 470 471static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) { 472 if (Val.getBitWidth() < BitWidth) 473 Val.extend(BitWidth); 474 else if (Val.getBitWidth() > BitWidth) 475 Val.trunc(BitWidth); 476 Val.setIsSigned(IsSigned); 477} 478 479StmtResult 480Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, 481 Stmt *BodyStmt) { 482 SwitchStmt *SS = cast<SwitchStmt>(Switch); 483 assert(SS == getCurFunction()->SwitchStack.back() && 484 "switch stack missing push/pop!"); 485 486 SS->setBody(BodyStmt, SwitchLoc); 487 getCurFunction()->SwitchStack.pop_back(); 488 489 if (SS->getCond() == 0) 490 return StmtError(); 491 492 Expr *CondExpr = SS->getCond(); 493 Expr *CondExprBeforePromotion = CondExpr; 494 QualType CondTypeBeforePromotion = 495 GetTypeBeforeIntegralPromotion(CondExpr); 496 497 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr. 498 UsualUnaryConversions(CondExpr); 499 QualType CondType = CondExpr->getType(); 500 SS->setCond(CondExpr); 501 502 // C++ 6.4.2.p2: 503 // Integral promotions are performed (on the switch condition). 504 // 505 // A case value unrepresentable by the original switch condition 506 // type (before the promotion) doesn't make sense, even when it can 507 // be represented by the promoted type. Therefore we need to find 508 // the pre-promotion type of the switch condition. 509 if (!CondExpr->isTypeDependent()) { 510 // We have already converted the expression to an integral or enumeration 511 // type, when we started the switch statement. If we don't have an 512 // appropriate type now, just return an error. 513 if (!CondType->isIntegralOrEnumerationType()) 514 return StmtError(); 515 516 if (CondExpr->isKnownToHaveBooleanValue()) { 517 // switch(bool_expr) {...} is often a programmer error, e.g. 518 // switch(n && mask) { ... } // Doh - should be "n & mask". 519 // One can always use an if statement instead of switch(bool_expr). 520 Diag(SwitchLoc, diag::warn_bool_switch_condition) 521 << CondExpr->getSourceRange(); 522 } 523 } 524 525 // Get the bitwidth of the switched-on value before promotions. We must 526 // convert the integer case values to this width before comparison. 527 bool HasDependentValue 528 = CondExpr->isTypeDependent() || CondExpr->isValueDependent(); 529 unsigned CondWidth 530 = HasDependentValue? 0 531 : static_cast<unsigned>(Context.getTypeSize(CondTypeBeforePromotion)); 532 bool CondIsSigned = CondTypeBeforePromotion->isSignedIntegerType(); 533 534 // Accumulate all of the case values in a vector so that we can sort them 535 // and detect duplicates. This vector contains the APInt for the case after 536 // it has been converted to the condition type. 537 typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy; 538 CaseValsTy CaseVals; 539 540 // Keep track of any GNU case ranges we see. The APSInt is the low value. 541 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy; 542 CaseRangesTy CaseRanges; 543 544 DefaultStmt *TheDefaultStmt = 0; 545 546 bool CaseListIsErroneous = false; 547 548 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue; 549 SC = SC->getNextSwitchCase()) { 550 551 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) { 552 if (TheDefaultStmt) { 553 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined); 554 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev); 555 556 // FIXME: Remove the default statement from the switch block so that 557 // we'll return a valid AST. This requires recursing down the AST and 558 // finding it, not something we are set up to do right now. For now, 559 // just lop the entire switch stmt out of the AST. 560 CaseListIsErroneous = true; 561 } 562 TheDefaultStmt = DS; 563 564 } else { 565 CaseStmt *CS = cast<CaseStmt>(SC); 566 567 // We already verified that the expression has a i-c-e value (C99 568 // 6.8.4.2p3) - get that value now. 569 Expr *Lo = CS->getLHS(); 570 571 if (Lo->isTypeDependent() || Lo->isValueDependent()) { 572 HasDependentValue = true; 573 break; 574 } 575 576 llvm::APSInt LoVal = Lo->EvaluateAsInt(Context); 577 578 // Convert the value to the same width/sign as the condition. 579 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned, 580 Lo->getLocStart(), 581 diag::warn_case_value_overflow); 582 583 // If the LHS is not the same type as the condition, insert an implicit 584 // cast. 585 ImpCastExprToType(Lo, CondType, CK_IntegralCast); 586 CS->setLHS(Lo); 587 588 // If this is a case range, remember it in CaseRanges, otherwise CaseVals. 589 if (CS->getRHS()) { 590 if (CS->getRHS()->isTypeDependent() || 591 CS->getRHS()->isValueDependent()) { 592 HasDependentValue = true; 593 break; 594 } 595 CaseRanges.push_back(std::make_pair(LoVal, CS)); 596 } else 597 CaseVals.push_back(std::make_pair(LoVal, CS)); 598 } 599 } 600 601 if (!HasDependentValue) { 602 // If we don't have a default statement, check whether the 603 // condition is constant. 604 llvm::APSInt ConstantCondValue; 605 bool HasConstantCond = false; 606 bool ShouldCheckConstantCond = false; 607 if (!HasDependentValue && !TheDefaultStmt) { 608 Expr::EvalResult Result; 609 HasConstantCond = CondExprBeforePromotion->Evaluate(Result, Context); 610 if (HasConstantCond) { 611 assert(Result.Val.isInt() && "switch condition evaluated to non-int"); 612 ConstantCondValue = Result.Val.getInt(); 613 ShouldCheckConstantCond = true; 614 615 assert(ConstantCondValue.getBitWidth() == CondWidth && 616 ConstantCondValue.isSigned() == CondIsSigned); 617 } 618 } 619 620 // Sort all the scalar case values so we can easily detect duplicates. 621 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals); 622 623 if (!CaseVals.empty()) { 624 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) { 625 if (ShouldCheckConstantCond && 626 CaseVals[i].first == ConstantCondValue) 627 ShouldCheckConstantCond = false; 628 629 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) { 630 // If we have a duplicate, report it. 631 Diag(CaseVals[i].second->getLHS()->getLocStart(), 632 diag::err_duplicate_case) << CaseVals[i].first.toString(10); 633 Diag(CaseVals[i-1].second->getLHS()->getLocStart(), 634 diag::note_duplicate_case_prev); 635 // FIXME: We really want to remove the bogus case stmt from the 636 // substmt, but we have no way to do this right now. 637 CaseListIsErroneous = true; 638 } 639 } 640 } 641 642 // Detect duplicate case ranges, which usually don't exist at all in 643 // the first place. 644 if (!CaseRanges.empty()) { 645 // Sort all the case ranges by their low value so we can easily detect 646 // overlaps between ranges. 647 std::stable_sort(CaseRanges.begin(), CaseRanges.end()); 648 649 // Scan the ranges, computing the high values and removing empty ranges. 650 std::vector<llvm::APSInt> HiVals; 651 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 652 llvm::APSInt &LoVal = CaseRanges[i].first; 653 CaseStmt *CR = CaseRanges[i].second; 654 Expr *Hi = CR->getRHS(); 655 llvm::APSInt HiVal = Hi->EvaluateAsInt(Context); 656 657 // Convert the value to the same width/sign as the condition. 658 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned, 659 Hi->getLocStart(), 660 diag::warn_case_value_overflow); 661 662 // If the LHS is not the same type as the condition, insert an implicit 663 // cast. 664 ImpCastExprToType(Hi, CondType, CK_IntegralCast); 665 CR->setRHS(Hi); 666 667 // If the low value is bigger than the high value, the case is empty. 668 if (LoVal > HiVal) { 669 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range) 670 << SourceRange(CR->getLHS()->getLocStart(), 671 Hi->getLocEnd()); 672 CaseRanges.erase(CaseRanges.begin()+i); 673 --i, --e; 674 continue; 675 } 676 677 if (ShouldCheckConstantCond && 678 LoVal <= ConstantCondValue && 679 ConstantCondValue <= HiVal) 680 ShouldCheckConstantCond = false; 681 682 HiVals.push_back(HiVal); 683 } 684 685 // Rescan the ranges, looking for overlap with singleton values and other 686 // ranges. Since the range list is sorted, we only need to compare case 687 // ranges with their neighbors. 688 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 689 llvm::APSInt &CRLo = CaseRanges[i].first; 690 llvm::APSInt &CRHi = HiVals[i]; 691 CaseStmt *CR = CaseRanges[i].second; 692 693 // Check to see whether the case range overlaps with any 694 // singleton cases. 695 CaseStmt *OverlapStmt = 0; 696 llvm::APSInt OverlapVal(32); 697 698 // Find the smallest value >= the lower bound. If I is in the 699 // case range, then we have overlap. 700 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(), 701 CaseVals.end(), CRLo, 702 CaseCompareFunctor()); 703 if (I != CaseVals.end() && I->first < CRHi) { 704 OverlapVal = I->first; // Found overlap with scalar. 705 OverlapStmt = I->second; 706 } 707 708 // Find the smallest value bigger than the upper bound. 709 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor()); 710 if (I != CaseVals.begin() && (I-1)->first >= CRLo) { 711 OverlapVal = (I-1)->first; // Found overlap with scalar. 712 OverlapStmt = (I-1)->second; 713 } 714 715 // Check to see if this case stmt overlaps with the subsequent 716 // case range. 717 if (i && CRLo <= HiVals[i-1]) { 718 OverlapVal = HiVals[i-1]; // Found overlap with range. 719 OverlapStmt = CaseRanges[i-1].second; 720 } 721 722 if (OverlapStmt) { 723 // If we have a duplicate, report it. 724 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case) 725 << OverlapVal.toString(10); 726 Diag(OverlapStmt->getLHS()->getLocStart(), 727 diag::note_duplicate_case_prev); 728 // FIXME: We really want to remove the bogus case stmt from the 729 // substmt, but we have no way to do this right now. 730 CaseListIsErroneous = true; 731 } 732 } 733 } 734 735 // Complain if we have a constant condition and we didn't find a match. 736 if (!CaseListIsErroneous && ShouldCheckConstantCond) { 737 // TODO: it would be nice if we printed enums as enums, chars as 738 // chars, etc. 739 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition) 740 << ConstantCondValue.toString(10) 741 << CondExpr->getSourceRange(); 742 } 743 744 // Check to see if switch is over an Enum and handles all of its 745 // values. We only issue a warning if there is not 'default:', but 746 // we still do the analysis to preserve this information in the AST 747 // (which can be used by flow-based analyes). 748 // 749 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>(); 750 751 // If switch has default case, then ignore it. 752 if (!CaseListIsErroneous && !HasConstantCond && ET) { 753 const EnumDecl *ED = ET->getDecl(); 754 typedef llvm::SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> EnumValsTy; 755 EnumValsTy EnumVals; 756 757 // Gather all enum values, set their type and sort them, 758 // allowing easier comparison with CaseVals. 759 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin(); 760 EDI != ED->enumerator_end(); ++EDI) { 761 llvm::APSInt Val = EDI->getInitVal(); 762 AdjustAPSInt(Val, CondWidth, CondIsSigned); 763 EnumVals.push_back(std::make_pair(Val, *EDI)); 764 } 765 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals); 766 EnumValsTy::iterator EIend = 767 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals); 768 769 // See which case values aren't in enum. 770 // TODO: we might want to check whether case values are out of the 771 // enum even if we don't want to check whether all cases are handled. 772 if (!TheDefaultStmt) { 773 EnumValsTy::const_iterator EI = EnumVals.begin(); 774 for (CaseValsTy::const_iterator CI = CaseVals.begin(); 775 CI != CaseVals.end(); CI++) { 776 while (EI != EIend && EI->first < CI->first) 777 EI++; 778 if (EI == EIend || EI->first > CI->first) 779 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum) 780 << ED->getDeclName(); 781 } 782 // See which of case ranges aren't in enum 783 EI = EnumVals.begin(); 784 for (CaseRangesTy::const_iterator RI = CaseRanges.begin(); 785 RI != CaseRanges.end() && EI != EIend; RI++) { 786 while (EI != EIend && EI->first < RI->first) 787 EI++; 788 789 if (EI == EIend || EI->first != RI->first) { 790 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum) 791 << ED->getDeclName(); 792 } 793 794 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context); 795 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 796 while (EI != EIend && EI->first < Hi) 797 EI++; 798 if (EI == EIend || EI->first != Hi) 799 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum) 800 << ED->getDeclName(); 801 } 802 } 803 804 // Check which enum vals aren't in switch 805 CaseValsTy::const_iterator CI = CaseVals.begin(); 806 CaseRangesTy::const_iterator RI = CaseRanges.begin(); 807 bool hasCasesNotInSwitch = false; 808 809 llvm::SmallVector<DeclarationName,8> UnhandledNames; 810 811 for (EnumValsTy::const_iterator EI = EnumVals.begin(); EI != EIend; EI++){ 812 // Drop unneeded case values 813 llvm::APSInt CIVal; 814 while (CI != CaseVals.end() && CI->first < EI->first) 815 CI++; 816 817 if (CI != CaseVals.end() && CI->first == EI->first) 818 continue; 819 820 // Drop unneeded case ranges 821 for (; RI != CaseRanges.end(); RI++) { 822 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context); 823 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 824 if (EI->first <= Hi) 825 break; 826 } 827 828 if (RI == CaseRanges.end() || EI->first < RI->first) { 829 hasCasesNotInSwitch = true; 830 if (!TheDefaultStmt) 831 UnhandledNames.push_back(EI->second->getDeclName()); 832 } 833 } 834 835 // Produce a nice diagnostic if multiple values aren't handled. 836 switch (UnhandledNames.size()) { 837 case 0: break; 838 case 1: 839 Diag(CondExpr->getExprLoc(), diag::warn_missing_case1) 840 << UnhandledNames[0]; 841 break; 842 case 2: 843 Diag(CondExpr->getExprLoc(), diag::warn_missing_case2) 844 << UnhandledNames[0] << UnhandledNames[1]; 845 break; 846 case 3: 847 Diag(CondExpr->getExprLoc(), diag::warn_missing_case3) 848 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2]; 849 break; 850 default: 851 Diag(CondExpr->getExprLoc(), diag::warn_missing_cases) 852 << (unsigned)UnhandledNames.size() 853 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2]; 854 break; 855 } 856 857 if (!hasCasesNotInSwitch) 858 SS->setAllEnumCasesCovered(); 859 } 860 } 861 862 // FIXME: If the case list was broken is some way, we don't have a good system 863 // to patch it up. Instead, just return the whole substmt as broken. 864 if (CaseListIsErroneous) 865 return StmtError(); 866 867 return Owned(SS); 868} 869 870StmtResult 871Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond, 872 Decl *CondVar, Stmt *Body) { 873 ExprResult CondResult(Cond.release()); 874 875 VarDecl *ConditionVar = 0; 876 if (CondVar) { 877 ConditionVar = cast<VarDecl>(CondVar); 878 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true); 879 if (CondResult.isInvalid()) 880 return StmtError(); 881 } 882 Expr *ConditionExpr = CondResult.take(); 883 if (!ConditionExpr) 884 return StmtError(); 885 886 DiagnoseUnusedExprResult(Body); 887 888 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr, 889 Body, WhileLoc)); 890} 891 892StmtResult 893Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 894 SourceLocation WhileLoc, SourceLocation CondLParen, 895 Expr *Cond, SourceLocation CondRParen) { 896 assert(Cond && "ActOnDoStmt(): missing expression"); 897 898 if (CheckBooleanCondition(Cond, DoLoc)) 899 return StmtError(); 900 901 CheckImplicitConversions(Cond, DoLoc); 902 ExprResult CondResult = MaybeCreateCXXExprWithTemporaries(Cond); 903 if (CondResult.isInvalid()) 904 return StmtError(); 905 Cond = CondResult.take(); 906 907 DiagnoseUnusedExprResult(Body); 908 909 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen)); 910} 911 912StmtResult 913Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 914 Stmt *First, FullExprArg second, Decl *secondVar, 915 FullExprArg third, 916 SourceLocation RParenLoc, Stmt *Body) { 917 if (!getLangOptions().CPlusPlus) { 918 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) { 919 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 920 // declare identifiers for objects having storage class 'auto' or 921 // 'register'. 922 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end(); 923 DI!=DE; ++DI) { 924 VarDecl *VD = dyn_cast<VarDecl>(*DI); 925 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage()) 926 VD = 0; 927 if (VD == 0) 928 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for); 929 // FIXME: mark decl erroneous! 930 } 931 } 932 } 933 934 ExprResult SecondResult(second.release()); 935 VarDecl *ConditionVar = 0; 936 if (secondVar) { 937 ConditionVar = cast<VarDecl>(secondVar); 938 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true); 939 if (SecondResult.isInvalid()) 940 return StmtError(); 941 } 942 943 Expr *Third = third.release().takeAs<Expr>(); 944 945 DiagnoseUnusedExprResult(First); 946 DiagnoseUnusedExprResult(Third); 947 DiagnoseUnusedExprResult(Body); 948 949 return Owned(new (Context) ForStmt(Context, First, 950 SecondResult.take(), ConditionVar, 951 Third, Body, ForLoc, LParenLoc, 952 RParenLoc)); 953} 954 955StmtResult 956Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc, 957 SourceLocation LParenLoc, 958 Stmt *First, Expr *Second, 959 SourceLocation RParenLoc, Stmt *Body) { 960 if (First) { 961 QualType FirstType; 962 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) { 963 if (!DS->isSingleDecl()) 964 return StmtError(Diag((*DS->decl_begin())->getLocation(), 965 diag::err_toomany_element_decls)); 966 967 Decl *D = DS->getSingleDecl(); 968 FirstType = cast<ValueDecl>(D)->getType(); 969 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 970 // declare identifiers for objects having storage class 'auto' or 971 // 'register'. 972 VarDecl *VD = cast<VarDecl>(D); 973 if (VD->isLocalVarDecl() && !VD->hasLocalStorage()) 974 return StmtError(Diag(VD->getLocation(), 975 diag::err_non_variable_decl_in_for)); 976 } else { 977 Expr *FirstE = cast<Expr>(First); 978 if (!FirstE->isTypeDependent() && !FirstE->isLValue()) 979 return StmtError(Diag(First->getLocStart(), 980 diag::err_selector_element_not_lvalue) 981 << First->getSourceRange()); 982 983 FirstType = static_cast<Expr*>(First)->getType(); 984 } 985 if (!FirstType->isDependentType() && 986 !FirstType->isObjCObjectPointerType() && 987 !FirstType->isBlockPointerType()) 988 Diag(ForLoc, diag::err_selector_element_type) 989 << FirstType << First->getSourceRange(); 990 } 991 if (Second && !Second->isTypeDependent()) { 992 DefaultFunctionArrayLvalueConversion(Second); 993 QualType SecondType = Second->getType(); 994 if (!SecondType->isObjCObjectPointerType()) 995 Diag(ForLoc, diag::err_collection_expr_type) 996 << SecondType << Second->getSourceRange(); 997 else if (const ObjCObjectPointerType *OPT = 998 SecondType->getAsObjCInterfacePointerType()) { 999 llvm::SmallVector<IdentifierInfo *, 4> KeyIdents; 1000 IdentifierInfo* selIdent = 1001 &Context.Idents.get("countByEnumeratingWithState"); 1002 KeyIdents.push_back(selIdent); 1003 selIdent = &Context.Idents.get("objects"); 1004 KeyIdents.push_back(selIdent); 1005 selIdent = &Context.Idents.get("count"); 1006 KeyIdents.push_back(selIdent); 1007 Selector CSelector = Context.Selectors.getSelector(3, &KeyIdents[0]); 1008 if (ObjCInterfaceDecl *IDecl = OPT->getInterfaceDecl()) { 1009 if (!IDecl->isForwardDecl() && 1010 !IDecl->lookupInstanceMethod(CSelector)) { 1011 // Must further look into private implementation methods. 1012 if (!LookupPrivateInstanceMethod(CSelector, IDecl)) 1013 Diag(ForLoc, diag::warn_collection_expr_type) 1014 << SecondType << CSelector << Second->getSourceRange(); 1015 } 1016 } 1017 } 1018 } 1019 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body, 1020 ForLoc, RParenLoc)); 1021} 1022 1023StmtResult 1024Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, 1025 IdentifierInfo *LabelII) { 1026 // Look up the record for this label identifier. 1027 LabelStmt *&LabelDecl = getCurFunction()->LabelMap[LabelII]; 1028 1029 getCurFunction()->setHasBranchIntoScope(); 1030 1031 // If we haven't seen this label yet, create a forward reference. 1032 if (LabelDecl == 0) 1033 LabelDecl = new (Context) LabelStmt(LabelLoc, LabelII, 0); 1034 1035 LabelDecl->setUsed(); 1036 return Owned(new (Context) GotoStmt(LabelDecl, GotoLoc, LabelLoc)); 1037} 1038 1039StmtResult 1040Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, 1041 Expr *E) { 1042 // Convert operand to void* 1043 if (!E->isTypeDependent()) { 1044 QualType ETy = E->getType(); 1045 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst()); 1046 AssignConvertType ConvTy = 1047 CheckSingleAssignmentConstraints(DestTy, E); 1048 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing)) 1049 return StmtError(); 1050 } 1051 1052 getCurFunction()->setHasIndirectGoto(); 1053 1054 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E)); 1055} 1056 1057StmtResult 1058Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) { 1059 Scope *S = CurScope->getContinueParent(); 1060 if (!S) { 1061 // C99 6.8.6.2p1: A break shall appear only in or as a loop body. 1062 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop)); 1063 } 1064 1065 return Owned(new (Context) ContinueStmt(ContinueLoc)); 1066} 1067 1068StmtResult 1069Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) { 1070 Scope *S = CurScope->getBreakParent(); 1071 if (!S) { 1072 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body. 1073 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch)); 1074 } 1075 1076 return Owned(new (Context) BreakStmt(BreakLoc)); 1077} 1078 1079/// \brief Determine whether a return statement is a candidate for the named 1080/// return value optimization (C++0x 12.8p34, bullet 1). 1081/// 1082/// \param Ctx The context in which the return expression and type occur. 1083/// 1084/// \param RetType The return type of the function or block. 1085/// 1086/// \param RetExpr The expression being returned from the function or block. 1087/// 1088/// \returns The NRVO candidate variable, if the return statement may use the 1089/// NRVO, or NULL if there is no such candidate. 1090static const VarDecl *getNRVOCandidate(ASTContext &Ctx, QualType RetType, 1091 Expr *RetExpr) { 1092 QualType ExprType = RetExpr->getType(); 1093 // - in a return statement in a function with ... 1094 // ... a class return type ... 1095 if (!RetType->isRecordType()) 1096 return 0; 1097 // ... the same cv-unqualified type as the function return type ... 1098 if (!Ctx.hasSameUnqualifiedType(RetType, ExprType)) 1099 return 0; 1100 // ... the expression is the name of a non-volatile automatic object ... 1101 // We ignore parentheses here. 1102 // FIXME: Is this compliant? (Everyone else does it) 1103 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetExpr->IgnoreParens()); 1104 if (!DR) 1105 return 0; 1106 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()); 1107 if (!VD) 1108 return 0; 1109 1110 if (VD->getKind() == Decl::Var && VD->hasLocalStorage() && 1111 !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() && 1112 !VD->getType().isVolatileQualified()) 1113 return VD; 1114 1115 return 0; 1116} 1117 1118/// ActOnBlockReturnStmt - Utility routine to figure out block's return type. 1119/// 1120StmtResult 1121Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 1122 // If this is the first return we've seen in the block, infer the type of 1123 // the block from it. 1124 BlockScopeInfo *CurBlock = getCurBlock(); 1125 if (CurBlock->ReturnType.isNull()) { 1126 if (RetValExp) { 1127 // Don't call UsualUnaryConversions(), since we don't want to do 1128 // integer promotions here. 1129 DefaultFunctionArrayLvalueConversion(RetValExp); 1130 CurBlock->ReturnType = RetValExp->getType(); 1131 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) { 1132 // We have to remove a 'const' added to copied-in variable which was 1133 // part of the implementation spec. and not the actual qualifier for 1134 // the variable. 1135 if (CDRE->isConstQualAdded()) 1136 CurBlock->ReturnType.removeConst(); 1137 } 1138 } else 1139 CurBlock->ReturnType = Context.VoidTy; 1140 } 1141 QualType FnRetType = CurBlock->ReturnType; 1142 1143 if (CurBlock->TheDecl->hasAttr<NoReturnAttr>()) { 1144 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr) 1145 << getCurFunctionOrMethodDecl()->getDeclName(); 1146 return StmtError(); 1147 } 1148 1149 // Otherwise, verify that this result type matches the previous one. We are 1150 // pickier with blocks than for normal functions because we don't have GCC 1151 // compatibility to worry about here. 1152 ReturnStmt *Result = 0; 1153 if (CurBlock->ReturnType->isVoidType()) { 1154 if (RetValExp) { 1155 Diag(ReturnLoc, diag::err_return_block_has_expr); 1156 RetValExp = 0; 1157 } 1158 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0); 1159 } else if (!RetValExp) { 1160 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr)); 1161 } else { 1162 const VarDecl *NRVOCandidate = 0; 1163 1164 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 1165 // we have a non-void block with an expression, continue checking 1166 1167 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 1168 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 1169 // function return. 1170 1171 // In C++ the return statement is handled via a copy initialization. 1172 // the C version of which boils down to CheckSingleAssignmentConstraints. 1173 NRVOCandidate = getNRVOCandidate(Context, FnRetType, RetValExp); 1174 ExprResult Res = PerformCopyInitialization( 1175 InitializedEntity::InitializeResult(ReturnLoc, 1176 FnRetType, 1177 NRVOCandidate != 0), 1178 SourceLocation(), 1179 Owned(RetValExp)); 1180 if (Res.isInvalid()) { 1181 // FIXME: Cleanup temporaries here, anyway? 1182 return StmtError(); 1183 } 1184 1185 if (RetValExp) { 1186 CheckImplicitConversions(RetValExp, ReturnLoc); 1187 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp); 1188 } 1189 1190 RetValExp = Res.takeAs<Expr>(); 1191 if (RetValExp) 1192 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 1193 } 1194 1195 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate); 1196 } 1197 1198 // If we need to check for the named return value optimization, save the 1199 // return statement in our scope for later processing. 1200 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() && 1201 !CurContext->isDependentContext()) 1202 FunctionScopes.back()->Returns.push_back(Result); 1203 1204 return Owned(Result); 1205} 1206 1207StmtResult 1208Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 1209 if (getCurBlock()) 1210 return ActOnBlockReturnStmt(ReturnLoc, RetValExp); 1211 1212 QualType FnRetType; 1213 if (const FunctionDecl *FD = getCurFunctionDecl()) { 1214 FnRetType = FD->getResultType(); 1215 if (FD->hasAttr<NoReturnAttr>() || 1216 FD->getType()->getAs<FunctionType>()->getNoReturnAttr()) 1217 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) 1218 << getCurFunctionOrMethodDecl()->getDeclName(); 1219 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) 1220 FnRetType = MD->getResultType(); 1221 else // If we don't have a function/method context, bail. 1222 return StmtError(); 1223 1224 ReturnStmt *Result = 0; 1225 if (FnRetType->isVoidType()) { 1226 if (RetValExp && !RetValExp->isTypeDependent()) { 1227 // C99 6.8.6.4p1 (ext_ since GCC warns) 1228 unsigned D = diag::ext_return_has_expr; 1229 if (RetValExp->getType()->isVoidType()) 1230 D = diag::ext_return_has_void_expr; 1231 1232 // return (some void expression); is legal in C++. 1233 if (D != diag::ext_return_has_void_expr || 1234 !getLangOptions().CPlusPlus) { 1235 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 1236 Diag(ReturnLoc, D) 1237 << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl) 1238 << RetValExp->getSourceRange(); 1239 } 1240 1241 CheckImplicitConversions(RetValExp, ReturnLoc); 1242 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp); 1243 } 1244 1245 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0); 1246 } else if (!RetValExp && !FnRetType->isDependentType()) { 1247 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4 1248 // C99 6.8.6.4p1 (ext_ since GCC warns) 1249 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr; 1250 1251 if (FunctionDecl *FD = getCurFunctionDecl()) 1252 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/; 1253 else 1254 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/; 1255 Result = new (Context) ReturnStmt(ReturnLoc); 1256 } else { 1257 const VarDecl *NRVOCandidate = 0; 1258 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 1259 // we have a non-void function with an expression, continue checking 1260 1261 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 1262 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 1263 // function return. 1264 1265 // In C++ the return statement is handled via a copy initialization. 1266 // the C version of which boils down to CheckSingleAssignmentConstraints. 1267 NRVOCandidate = getNRVOCandidate(Context, FnRetType, RetValExp); 1268 ExprResult Res = PerformCopyInitialization( 1269 InitializedEntity::InitializeResult(ReturnLoc, 1270 FnRetType, 1271 NRVOCandidate != 0), 1272 SourceLocation(), 1273 Owned(RetValExp)); 1274 if (Res.isInvalid()) { 1275 // FIXME: Cleanup temporaries here, anyway? 1276 return StmtError(); 1277 } 1278 1279 RetValExp = Res.takeAs<Expr>(); 1280 if (RetValExp) 1281 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 1282 } 1283 1284 if (RetValExp) { 1285 CheckImplicitConversions(RetValExp, ReturnLoc); 1286 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp); 1287 } 1288 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate); 1289 } 1290 1291 // If we need to check for the named return value optimization, save the 1292 // return statement in our scope for later processing. 1293 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() && 1294 !CurContext->isDependentContext()) 1295 FunctionScopes.back()->Returns.push_back(Result); 1296 1297 return Owned(Result); 1298} 1299 1300/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently 1301/// ignore "noop" casts in places where an lvalue is required by an inline asm. 1302/// We emulate this behavior when -fheinous-gnu-extensions is specified, but 1303/// provide a strong guidance to not use it. 1304/// 1305/// This method checks to see if the argument is an acceptable l-value and 1306/// returns false if it is a case we can handle. 1307static bool CheckAsmLValue(const Expr *E, Sema &S) { 1308 // Type dependent expressions will be checked during instantiation. 1309 if (E->isTypeDependent()) 1310 return false; 1311 1312 if (E->isLValue()) 1313 return false; // Cool, this is an lvalue. 1314 1315 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we 1316 // are supposed to allow. 1317 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context); 1318 if (E != E2 && E2->isLValue()) { 1319 if (!S.getLangOptions().HeinousExtensions) 1320 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue) 1321 << E->getSourceRange(); 1322 else 1323 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue) 1324 << E->getSourceRange(); 1325 // Accept, even if we emitted an error diagnostic. 1326 return false; 1327 } 1328 1329 // None of the above, just randomly invalid non-lvalue. 1330 return true; 1331} 1332 1333 1334StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, 1335 bool IsSimple, 1336 bool IsVolatile, 1337 unsigned NumOutputs, 1338 unsigned NumInputs, 1339 IdentifierInfo **Names, 1340 MultiExprArg constraints, 1341 MultiExprArg exprs, 1342 Expr *asmString, 1343 MultiExprArg clobbers, 1344 SourceLocation RParenLoc, 1345 bool MSAsm) { 1346 unsigned NumClobbers = clobbers.size(); 1347 StringLiteral **Constraints = 1348 reinterpret_cast<StringLiteral**>(constraints.get()); 1349 Expr **Exprs = exprs.get(); 1350 StringLiteral *AsmString = cast<StringLiteral>(asmString); 1351 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get()); 1352 1353 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; 1354 1355 // The parser verifies that there is a string literal here. 1356 if (AsmString->isWide()) 1357 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character) 1358 << AsmString->getSourceRange()); 1359 1360 for (unsigned i = 0; i != NumOutputs; i++) { 1361 StringLiteral *Literal = Constraints[i]; 1362 if (Literal->isWide()) 1363 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 1364 << Literal->getSourceRange()); 1365 1366 llvm::StringRef OutputName; 1367 if (Names[i]) 1368 OutputName = Names[i]->getName(); 1369 1370 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName); 1371 if (!Context.Target.validateOutputConstraint(Info)) 1372 return StmtError(Diag(Literal->getLocStart(), 1373 diag::err_asm_invalid_output_constraint) 1374 << Info.getConstraintStr()); 1375 1376 // Check that the output exprs are valid lvalues. 1377 Expr *OutputExpr = Exprs[i]; 1378 if (CheckAsmLValue(OutputExpr, *this)) { 1379 return StmtError(Diag(OutputExpr->getLocStart(), 1380 diag::err_asm_invalid_lvalue_in_output) 1381 << OutputExpr->getSourceRange()); 1382 } 1383 1384 OutputConstraintInfos.push_back(Info); 1385 } 1386 1387 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos; 1388 1389 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) { 1390 StringLiteral *Literal = Constraints[i]; 1391 if (Literal->isWide()) 1392 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 1393 << Literal->getSourceRange()); 1394 1395 llvm::StringRef InputName; 1396 if (Names[i]) 1397 InputName = Names[i]->getName(); 1398 1399 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName); 1400 if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(), 1401 NumOutputs, Info)) { 1402 return StmtError(Diag(Literal->getLocStart(), 1403 diag::err_asm_invalid_input_constraint) 1404 << Info.getConstraintStr()); 1405 } 1406 1407 Expr *InputExpr = Exprs[i]; 1408 1409 // Only allow void types for memory constraints. 1410 if (Info.allowsMemory() && !Info.allowsRegister()) { 1411 if (CheckAsmLValue(InputExpr, *this)) 1412 return StmtError(Diag(InputExpr->getLocStart(), 1413 diag::err_asm_invalid_lvalue_in_input) 1414 << Info.getConstraintStr() 1415 << InputExpr->getSourceRange()); 1416 } 1417 1418 if (Info.allowsRegister()) { 1419 if (InputExpr->getType()->isVoidType()) { 1420 return StmtError(Diag(InputExpr->getLocStart(), 1421 diag::err_asm_invalid_type_in_input) 1422 << InputExpr->getType() << Info.getConstraintStr() 1423 << InputExpr->getSourceRange()); 1424 } 1425 } 1426 1427 DefaultFunctionArrayLvalueConversion(Exprs[i]); 1428 1429 InputConstraintInfos.push_back(Info); 1430 } 1431 1432 // Check that the clobbers are valid. 1433 for (unsigned i = 0; i != NumClobbers; i++) { 1434 StringLiteral *Literal = Clobbers[i]; 1435 if (Literal->isWide()) 1436 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 1437 << Literal->getSourceRange()); 1438 1439 llvm::StringRef Clobber = Literal->getString(); 1440 1441 if (!Context.Target.isValidGCCRegisterName(Clobber)) 1442 return StmtError(Diag(Literal->getLocStart(), 1443 diag::err_asm_unknown_register_name) << Clobber); 1444 } 1445 1446 AsmStmt *NS = 1447 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm, 1448 NumOutputs, NumInputs, Names, Constraints, Exprs, 1449 AsmString, NumClobbers, Clobbers, RParenLoc); 1450 // Validate the asm string, ensuring it makes sense given the operands we 1451 // have. 1452 llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces; 1453 unsigned DiagOffs; 1454 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) { 1455 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID) 1456 << AsmString->getSourceRange(); 1457 return StmtError(); 1458 } 1459 1460 // Validate tied input operands for type mismatches. 1461 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) { 1462 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i]; 1463 1464 // If this is a tied constraint, verify that the output and input have 1465 // either exactly the same type, or that they are int/ptr operands with the 1466 // same size (int/long, int*/long, are ok etc). 1467 if (!Info.hasTiedOperand()) continue; 1468 1469 unsigned TiedTo = Info.getTiedOperand(); 1470 Expr *OutputExpr = Exprs[TiedTo]; 1471 Expr *InputExpr = Exprs[i+NumOutputs]; 1472 QualType InTy = InputExpr->getType(); 1473 QualType OutTy = OutputExpr->getType(); 1474 if (Context.hasSameType(InTy, OutTy)) 1475 continue; // All types can be tied to themselves. 1476 1477 // Decide if the input and output are in the same domain (integer/ptr or 1478 // floating point. 1479 enum AsmDomain { 1480 AD_Int, AD_FP, AD_Other 1481 } InputDomain, OutputDomain; 1482 1483 if (InTy->isIntegerType() || InTy->isPointerType()) 1484 InputDomain = AD_Int; 1485 else if (InTy->isRealFloatingType()) 1486 InputDomain = AD_FP; 1487 else 1488 InputDomain = AD_Other; 1489 1490 if (OutTy->isIntegerType() || OutTy->isPointerType()) 1491 OutputDomain = AD_Int; 1492 else if (OutTy->isRealFloatingType()) 1493 OutputDomain = AD_FP; 1494 else 1495 OutputDomain = AD_Other; 1496 1497 // They are ok if they are the same size and in the same domain. This 1498 // allows tying things like: 1499 // void* to int* 1500 // void* to int if they are the same size. 1501 // double to long double if they are the same size. 1502 // 1503 uint64_t OutSize = Context.getTypeSize(OutTy); 1504 uint64_t InSize = Context.getTypeSize(InTy); 1505 if (OutSize == InSize && InputDomain == OutputDomain && 1506 InputDomain != AD_Other) 1507 continue; 1508 1509 // If the smaller input/output operand is not mentioned in the asm string, 1510 // then we can promote it and the asm string won't notice. Check this 1511 // case now. 1512 bool SmallerValueMentioned = false; 1513 for (unsigned p = 0, e = Pieces.size(); p != e; ++p) { 1514 AsmStmt::AsmStringPiece &Piece = Pieces[p]; 1515 if (!Piece.isOperand()) continue; 1516 1517 // If this is a reference to the input and if the input was the smaller 1518 // one, then we have to reject this asm. 1519 if (Piece.getOperandNo() == i+NumOutputs) { 1520 if (InSize < OutSize) { 1521 SmallerValueMentioned = true; 1522 break; 1523 } 1524 } 1525 1526 // If this is a reference to the input and if the input was the smaller 1527 // one, then we have to reject this asm. 1528 if (Piece.getOperandNo() == TiedTo) { 1529 if (InSize > OutSize) { 1530 SmallerValueMentioned = true; 1531 break; 1532 } 1533 } 1534 } 1535 1536 // If the smaller value wasn't mentioned in the asm string, and if the 1537 // output was a register, just extend the shorter one to the size of the 1538 // larger one. 1539 if (!SmallerValueMentioned && InputDomain != AD_Other && 1540 OutputConstraintInfos[TiedTo].allowsRegister()) 1541 continue; 1542 1543 Diag(InputExpr->getLocStart(), 1544 diag::err_asm_tying_incompatible_types) 1545 << InTy << OutTy << OutputExpr->getSourceRange() 1546 << InputExpr->getSourceRange(); 1547 return StmtError(); 1548 } 1549 1550 return Owned(NS); 1551} 1552 1553StmtResult 1554Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc, 1555 SourceLocation RParen, Decl *Parm, 1556 Stmt *Body) { 1557 VarDecl *Var = cast_or_null<VarDecl>(Parm); 1558 if (Var && Var->isInvalidDecl()) 1559 return StmtError(); 1560 1561 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body)); 1562} 1563 1564StmtResult 1565Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) { 1566 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body)); 1567} 1568 1569StmtResult 1570Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 1571 MultiStmtArg CatchStmts, Stmt *Finally) { 1572 getCurFunction()->setHasBranchProtectedScope(); 1573 unsigned NumCatchStmts = CatchStmts.size(); 1574 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try, 1575 CatchStmts.release(), 1576 NumCatchStmts, 1577 Finally)); 1578} 1579 1580StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, 1581 Expr *Throw) { 1582 if (Throw) { 1583 QualType ThrowType = Throw->getType(); 1584 // Make sure the expression type is an ObjC pointer or "void *". 1585 if (!ThrowType->isDependentType() && 1586 !ThrowType->isObjCObjectPointerType()) { 1587 const PointerType *PT = ThrowType->getAs<PointerType>(); 1588 if (!PT || !PT->getPointeeType()->isVoidType()) 1589 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object) 1590 << Throw->getType() << Throw->getSourceRange()); 1591 } 1592 } 1593 1594 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw)); 1595} 1596 1597StmtResult 1598Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 1599 Scope *CurScope) { 1600 if (!Throw) { 1601 // @throw without an expression designates a rethrow (which much occur 1602 // in the context of an @catch clause). 1603 Scope *AtCatchParent = CurScope; 1604 while (AtCatchParent && !AtCatchParent->isAtCatchScope()) 1605 AtCatchParent = AtCatchParent->getParent(); 1606 if (!AtCatchParent) 1607 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch)); 1608 } 1609 1610 return BuildObjCAtThrowStmt(AtLoc, Throw); 1611} 1612 1613StmtResult 1614Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr, 1615 Stmt *SyncBody) { 1616 getCurFunction()->setHasBranchProtectedScope(); 1617 1618 // Make sure the expression type is an ObjC pointer or "void *". 1619 if (!SyncExpr->getType()->isDependentType() && 1620 !SyncExpr->getType()->isObjCObjectPointerType()) { 1621 const PointerType *PT = SyncExpr->getType()->getAs<PointerType>(); 1622 if (!PT || !PT->getPointeeType()->isVoidType()) 1623 return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object) 1624 << SyncExpr->getType() << SyncExpr->getSourceRange()); 1625 } 1626 1627 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody)); 1628} 1629 1630/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block 1631/// and creates a proper catch handler from them. 1632StmtResult 1633Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, 1634 Stmt *HandlerBlock) { 1635 // There's nothing to test that ActOnExceptionDecl didn't already test. 1636 return Owned(new (Context) CXXCatchStmt(CatchLoc, 1637 cast_or_null<VarDecl>(ExDecl), 1638 HandlerBlock)); 1639} 1640 1641namespace { 1642 1643class TypeWithHandler { 1644 QualType t; 1645 CXXCatchStmt *stmt; 1646public: 1647 TypeWithHandler(const QualType &type, CXXCatchStmt *statement) 1648 : t(type), stmt(statement) {} 1649 1650 // An arbitrary order is fine as long as it places identical 1651 // types next to each other. 1652 bool operator<(const TypeWithHandler &y) const { 1653 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr()) 1654 return true; 1655 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr()) 1656 return false; 1657 else 1658 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc(); 1659 } 1660 1661 bool operator==(const TypeWithHandler& other) const { 1662 return t == other.t; 1663 } 1664 1665 CXXCatchStmt *getCatchStmt() const { return stmt; } 1666 SourceLocation getTypeSpecStartLoc() const { 1667 return stmt->getExceptionDecl()->getTypeSpecStartLoc(); 1668 } 1669}; 1670 1671} 1672 1673/// ActOnCXXTryBlock - Takes a try compound-statement and a number of 1674/// handlers and creates a try statement from them. 1675StmtResult 1676Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 1677 MultiStmtArg RawHandlers) { 1678 unsigned NumHandlers = RawHandlers.size(); 1679 assert(NumHandlers > 0 && 1680 "The parser shouldn't call this if there are no handlers."); 1681 Stmt **Handlers = RawHandlers.get(); 1682 1683 llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers; 1684 1685 for (unsigned i = 0; i < NumHandlers; ++i) { 1686 CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]); 1687 if (!Handler->getExceptionDecl()) { 1688 if (i < NumHandlers - 1) 1689 return StmtError(Diag(Handler->getLocStart(), 1690 diag::err_early_catch_all)); 1691 1692 continue; 1693 } 1694 1695 const QualType CaughtType = Handler->getCaughtType(); 1696 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType); 1697 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler)); 1698 } 1699 1700 // Detect handlers for the same type as an earlier one. 1701 if (NumHandlers > 1) { 1702 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end()); 1703 1704 TypeWithHandler prev = TypesWithHandlers[0]; 1705 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) { 1706 TypeWithHandler curr = TypesWithHandlers[i]; 1707 1708 if (curr == prev) { 1709 Diag(curr.getTypeSpecStartLoc(), 1710 diag::warn_exception_caught_by_earlier_handler) 1711 << curr.getCatchStmt()->getCaughtType().getAsString(); 1712 Diag(prev.getTypeSpecStartLoc(), 1713 diag::note_previous_exception_handler) 1714 << prev.getCatchStmt()->getCaughtType().getAsString(); 1715 } 1716 1717 prev = curr; 1718 } 1719 } 1720 1721 getCurFunction()->setHasBranchProtectedScope(); 1722 1723 // FIXME: We should detect handlers that cannot catch anything because an 1724 // earlier handler catches a superclass. Need to find a method that is not 1725 // quadratic for this. 1726 // Neither of these are explicitly forbidden, but every compiler detects them 1727 // and warns. 1728 1729 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock, 1730 Handlers, NumHandlers)); 1731} 1732