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