SemaStmt.cpp revision 49f4e1cbd839da27ff4814b4ea6d85a79f786cbd
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 ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E)) 93 E = Temps->getSubExpr(); 94 95 E = E->IgnoreParenImpCasts(); 96 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 97 if (E->getType()->isVoidType()) 98 return; 99 100 // If the callee has attribute pure, const, or warn_unused_result, warn with 101 // a more specific message to make it clear what is happening. 102 if (const Decl *FD = CE->getCalleeDecl()) { 103 if (FD->getAttr<WarnUnusedResultAttr>()) { 104 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result"; 105 return; 106 } 107 if (FD->getAttr<PureAttr>()) { 108 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure"; 109 return; 110 } 111 if (FD->getAttr<ConstAttr>()) { 112 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const"; 113 return; 114 } 115 } 116 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) { 117 const ObjCMethodDecl *MD = ME->getMethodDecl(); 118 if (MD && MD->getAttr<WarnUnusedResultAttr>()) { 119 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result"; 120 return; 121 } 122 } else if (isa<ObjCPropertyRefExpr>(E)) { 123 DiagID = diag::warn_unused_property_expr; 124 } else if (const CXXFunctionalCastExpr *FC 125 = dyn_cast<CXXFunctionalCastExpr>(E)) { 126 if (isa<CXXConstructExpr>(FC->getSubExpr()) || 127 isa<CXXTemporaryObjectExpr>(FC->getSubExpr())) 128 return; 129 } 130 // Diagnose "(void*) blah" as a typo for "(void) blah". 131 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) { 132 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 133 QualType T = TI->getType(); 134 135 // We really do want to use the non-canonical type here. 136 if (T == Context.VoidPtrTy) { 137 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc()); 138 139 Diag(Loc, diag::warn_unused_voidptr) 140 << FixItHint::CreateRemoval(TL.getStarLoc()); 141 return; 142 } 143 } 144 145 DiagRuntimeBehavior(Loc, 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 = 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 = ConvVal.trunc(NewWidth); 344 ConvVal.setIsSigned(NewSign); 345 ConvVal = 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 = 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 = MaybeCreateExprWithCleanups(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 = Val.extend(BitWidth); 474 else if (Val.getBitWidth() > BitWidth) 475 Val = 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 = MaybeCreateExprWithCleanups(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 955/// In an Objective C collection iteration statement: 956/// for (x in y) 957/// x can be an arbitrary l-value expression. Bind it up as a 958/// full-expression. 959StmtResult Sema::ActOnForEachLValueExpr(Expr *E) { 960 CheckImplicitConversions(E); 961 ExprResult Result = MaybeCreateExprWithCleanups(E); 962 if (Result.isInvalid()) return StmtError(); 963 return Owned(static_cast<Stmt*>(Result.get())); 964} 965 966StmtResult 967Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc, 968 SourceLocation LParenLoc, 969 Stmt *First, Expr *Second, 970 SourceLocation RParenLoc, Stmt *Body) { 971 if (First) { 972 QualType FirstType; 973 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) { 974 if (!DS->isSingleDecl()) 975 return StmtError(Diag((*DS->decl_begin())->getLocation(), 976 diag::err_toomany_element_decls)); 977 978 Decl *D = DS->getSingleDecl(); 979 FirstType = cast<ValueDecl>(D)->getType(); 980 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 981 // declare identifiers for objects having storage class 'auto' or 982 // 'register'. 983 VarDecl *VD = cast<VarDecl>(D); 984 if (VD->isLocalVarDecl() && !VD->hasLocalStorage()) 985 return StmtError(Diag(VD->getLocation(), 986 diag::err_non_variable_decl_in_for)); 987 } else { 988 Expr *FirstE = cast<Expr>(First); 989 if (!FirstE->isTypeDependent() && !FirstE->isLValue()) 990 return StmtError(Diag(First->getLocStart(), 991 diag::err_selector_element_not_lvalue) 992 << First->getSourceRange()); 993 994 FirstType = static_cast<Expr*>(First)->getType(); 995 } 996 if (!FirstType->isDependentType() && 997 !FirstType->isObjCObjectPointerType() && 998 !FirstType->isBlockPointerType()) 999 Diag(ForLoc, diag::err_selector_element_type) 1000 << FirstType << First->getSourceRange(); 1001 } 1002 if (Second && !Second->isTypeDependent()) { 1003 DefaultFunctionArrayLvalueConversion(Second); 1004 QualType SecondType = Second->getType(); 1005 if (!SecondType->isObjCObjectPointerType()) 1006 Diag(ForLoc, diag::err_collection_expr_type) 1007 << SecondType << Second->getSourceRange(); 1008 else if (const ObjCObjectPointerType *OPT = 1009 SecondType->getAsObjCInterfacePointerType()) { 1010 llvm::SmallVector<IdentifierInfo *, 4> KeyIdents; 1011 IdentifierInfo* selIdent = 1012 &Context.Idents.get("countByEnumeratingWithState"); 1013 KeyIdents.push_back(selIdent); 1014 selIdent = &Context.Idents.get("objects"); 1015 KeyIdents.push_back(selIdent); 1016 selIdent = &Context.Idents.get("count"); 1017 KeyIdents.push_back(selIdent); 1018 Selector CSelector = Context.Selectors.getSelector(3, &KeyIdents[0]); 1019 if (ObjCInterfaceDecl *IDecl = OPT->getInterfaceDecl()) { 1020 if (!IDecl->isForwardDecl() && 1021 !IDecl->lookupInstanceMethod(CSelector)) { 1022 // Must further look into private implementation methods. 1023 if (!LookupPrivateInstanceMethod(CSelector, IDecl)) 1024 Diag(ForLoc, diag::warn_collection_expr_type) 1025 << SecondType << CSelector << Second->getSourceRange(); 1026 } 1027 } 1028 } 1029 } 1030 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body, 1031 ForLoc, RParenLoc)); 1032} 1033 1034StmtResult 1035Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, 1036 IdentifierInfo *LabelII) { 1037 // Look up the record for this label identifier. 1038 LabelStmt *&LabelDecl = getCurFunction()->LabelMap[LabelII]; 1039 1040 getCurFunction()->setHasBranchIntoScope(); 1041 1042 // If we haven't seen this label yet, create a forward reference. 1043 if (LabelDecl == 0) 1044 LabelDecl = new (Context) LabelStmt(LabelLoc, LabelII, 0); 1045 1046 LabelDecl->setUsed(); 1047 return Owned(new (Context) GotoStmt(LabelDecl, GotoLoc, LabelLoc)); 1048} 1049 1050StmtResult 1051Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, 1052 Expr *E) { 1053 // Convert operand to void* 1054 if (!E->isTypeDependent()) { 1055 QualType ETy = E->getType(); 1056 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst()); 1057 AssignConvertType ConvTy = 1058 CheckSingleAssignmentConstraints(DestTy, E); 1059 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing)) 1060 return StmtError(); 1061 } 1062 1063 getCurFunction()->setHasIndirectGoto(); 1064 1065 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E)); 1066} 1067 1068StmtResult 1069Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) { 1070 Scope *S = CurScope->getContinueParent(); 1071 if (!S) { 1072 // C99 6.8.6.2p1: A break shall appear only in or as a loop body. 1073 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop)); 1074 } 1075 1076 return Owned(new (Context) ContinueStmt(ContinueLoc)); 1077} 1078 1079StmtResult 1080Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) { 1081 Scope *S = CurScope->getBreakParent(); 1082 if (!S) { 1083 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body. 1084 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch)); 1085 } 1086 1087 return Owned(new (Context) BreakStmt(BreakLoc)); 1088} 1089 1090/// \brief Determine whether a return statement is a candidate for the named 1091/// return value optimization (C++0x 12.8p34, bullet 1). 1092/// 1093/// \param Ctx The context in which the return expression and type occur. 1094/// 1095/// \param RetType The return type of the function or block. 1096/// 1097/// \param RetExpr The expression being returned from the function or block. 1098/// 1099/// \returns The NRVO candidate variable, if the return statement may use the 1100/// NRVO, or NULL if there is no such candidate. 1101static const VarDecl *getNRVOCandidate(ASTContext &Ctx, QualType RetType, 1102 Expr *RetExpr) { 1103 QualType ExprType = RetExpr->getType(); 1104 // - in a return statement in a function with ... 1105 // ... a class return type ... 1106 if (!RetType->isRecordType()) 1107 return 0; 1108 // ... the same cv-unqualified type as the function return type ... 1109 if (!Ctx.hasSameUnqualifiedType(RetType, ExprType)) 1110 return 0; 1111 // ... the expression is the name of a non-volatile automatic object ... 1112 // We ignore parentheses here. 1113 // FIXME: Is this compliant? (Everyone else does it) 1114 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetExpr->IgnoreParens()); 1115 if (!DR) 1116 return 0; 1117 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()); 1118 if (!VD) 1119 return 0; 1120 1121 if (VD->getKind() == Decl::Var && VD->hasLocalStorage() && 1122 !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() && 1123 !VD->getType().isVolatileQualified()) 1124 return VD; 1125 1126 return 0; 1127} 1128 1129/// ActOnBlockReturnStmt - Utility routine to figure out block's return type. 1130/// 1131StmtResult 1132Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 1133 // If this is the first return we've seen in the block, infer the type of 1134 // the block from it. 1135 BlockScopeInfo *CurBlock = getCurBlock(); 1136 if (CurBlock->ReturnType.isNull()) { 1137 if (RetValExp) { 1138 // Don't call UsualUnaryConversions(), since we don't want to do 1139 // integer promotions here. 1140 DefaultFunctionArrayLvalueConversion(RetValExp); 1141 CurBlock->ReturnType = RetValExp->getType(); 1142 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) { 1143 // We have to remove a 'const' added to copied-in variable which was 1144 // part of the implementation spec. and not the actual qualifier for 1145 // the variable. 1146 if (CDRE->isConstQualAdded()) 1147 CurBlock->ReturnType.removeLocalConst(); // FIXME: local??? 1148 } 1149 } else 1150 CurBlock->ReturnType = Context.VoidTy; 1151 } 1152 QualType FnRetType = CurBlock->ReturnType; 1153 1154 if (CurBlock->TheDecl->hasAttr<NoReturnAttr>()) { 1155 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr) 1156 << getCurFunctionOrMethodDecl()->getDeclName(); 1157 return StmtError(); 1158 } 1159 1160 // Otherwise, verify that this result type matches the previous one. We are 1161 // pickier with blocks than for normal functions because we don't have GCC 1162 // compatibility to worry about here. 1163 ReturnStmt *Result = 0; 1164 if (CurBlock->ReturnType->isVoidType()) { 1165 if (RetValExp) { 1166 Diag(ReturnLoc, diag::err_return_block_has_expr); 1167 RetValExp = 0; 1168 } 1169 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0); 1170 } else if (!RetValExp) { 1171 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr)); 1172 } else { 1173 const VarDecl *NRVOCandidate = 0; 1174 1175 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 1176 // we have a non-void block with an expression, continue checking 1177 1178 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 1179 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 1180 // function return. 1181 1182 // In C++ the return statement is handled via a copy initialization. 1183 // the C version of which boils down to CheckSingleAssignmentConstraints. 1184 NRVOCandidate = getNRVOCandidate(Context, FnRetType, RetValExp); 1185 ExprResult Res = PerformCopyInitialization( 1186 InitializedEntity::InitializeResult(ReturnLoc, 1187 FnRetType, 1188 NRVOCandidate != 0), 1189 SourceLocation(), 1190 Owned(RetValExp)); 1191 if (Res.isInvalid()) { 1192 // FIXME: Cleanup temporaries here, anyway? 1193 return StmtError(); 1194 } 1195 1196 if (RetValExp) { 1197 CheckImplicitConversions(RetValExp, ReturnLoc); 1198 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 1199 } 1200 1201 RetValExp = Res.takeAs<Expr>(); 1202 if (RetValExp) 1203 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 1204 } 1205 1206 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate); 1207 } 1208 1209 // If we need to check for the named return value optimization, save the 1210 // return statement in our scope for later processing. 1211 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() && 1212 !CurContext->isDependentContext()) 1213 FunctionScopes.back()->Returns.push_back(Result); 1214 1215 return Owned(Result); 1216} 1217 1218StmtResult 1219Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 1220 if (getCurBlock()) 1221 return ActOnBlockReturnStmt(ReturnLoc, RetValExp); 1222 1223 QualType FnRetType; 1224 if (const FunctionDecl *FD = getCurFunctionDecl()) { 1225 FnRetType = FD->getResultType(); 1226 if (FD->hasAttr<NoReturnAttr>() || 1227 FD->getType()->getAs<FunctionType>()->getNoReturnAttr()) 1228 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) 1229 << getCurFunctionOrMethodDecl()->getDeclName(); 1230 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) 1231 FnRetType = MD->getResultType(); 1232 else // If we don't have a function/method context, bail. 1233 return StmtError(); 1234 1235 ReturnStmt *Result = 0; 1236 if (FnRetType->isVoidType()) { 1237 if (RetValExp && !RetValExp->isTypeDependent()) { 1238 // C99 6.8.6.4p1 (ext_ since GCC warns) 1239 unsigned D = diag::ext_return_has_expr; 1240 if (RetValExp->getType()->isVoidType()) 1241 D = diag::ext_return_has_void_expr; 1242 else { 1243 IgnoredValueConversions(RetValExp); 1244 ImpCastExprToType(RetValExp, Context.VoidTy, CK_ToVoid); 1245 } 1246 1247 // return (some void expression); is legal in C++. 1248 if (D != diag::ext_return_has_void_expr || 1249 !getLangOptions().CPlusPlus) { 1250 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 1251 Diag(ReturnLoc, D) 1252 << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl) 1253 << RetValExp->getSourceRange(); 1254 } 1255 1256 CheckImplicitConversions(RetValExp, ReturnLoc); 1257 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 1258 } 1259 1260 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0); 1261 } else if (!RetValExp && !FnRetType->isDependentType()) { 1262 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4 1263 // C99 6.8.6.4p1 (ext_ since GCC warns) 1264 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr; 1265 1266 if (FunctionDecl *FD = getCurFunctionDecl()) 1267 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/; 1268 else 1269 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/; 1270 Result = new (Context) ReturnStmt(ReturnLoc); 1271 } else { 1272 const VarDecl *NRVOCandidate = 0; 1273 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 1274 // we have a non-void function with an expression, continue checking 1275 1276 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 1277 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 1278 // function return. 1279 1280 // In C++ the return statement is handled via a copy initialization. 1281 // the C version of which boils down to CheckSingleAssignmentConstraints. 1282 NRVOCandidate = getNRVOCandidate(Context, FnRetType, RetValExp); 1283 ExprResult Res = PerformCopyInitialization( 1284 InitializedEntity::InitializeResult(ReturnLoc, 1285 FnRetType, 1286 NRVOCandidate != 0), 1287 SourceLocation(), 1288 Owned(RetValExp)); 1289 if (Res.isInvalid()) { 1290 // FIXME: Cleanup temporaries here, anyway? 1291 return StmtError(); 1292 } 1293 1294 RetValExp = Res.takeAs<Expr>(); 1295 if (RetValExp) 1296 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 1297 } 1298 1299 if (RetValExp) { 1300 CheckImplicitConversions(RetValExp, ReturnLoc); 1301 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 1302 } 1303 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate); 1304 } 1305 1306 // If we need to check for the named return value optimization, save the 1307 // return statement in our scope for later processing. 1308 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() && 1309 !CurContext->isDependentContext()) 1310 FunctionScopes.back()->Returns.push_back(Result); 1311 1312 return Owned(Result); 1313} 1314 1315/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently 1316/// ignore "noop" casts in places where an lvalue is required by an inline asm. 1317/// We emulate this behavior when -fheinous-gnu-extensions is specified, but 1318/// provide a strong guidance to not use it. 1319/// 1320/// This method checks to see if the argument is an acceptable l-value and 1321/// returns false if it is a case we can handle. 1322static bool CheckAsmLValue(const Expr *E, Sema &S) { 1323 // Type dependent expressions will be checked during instantiation. 1324 if (E->isTypeDependent()) 1325 return false; 1326 1327 if (E->isLValue()) 1328 return false; // Cool, this is an lvalue. 1329 1330 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we 1331 // are supposed to allow. 1332 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context); 1333 if (E != E2 && E2->isLValue()) { 1334 if (!S.getLangOptions().HeinousExtensions) 1335 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue) 1336 << E->getSourceRange(); 1337 else 1338 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue) 1339 << E->getSourceRange(); 1340 // Accept, even if we emitted an error diagnostic. 1341 return false; 1342 } 1343 1344 // None of the above, just randomly invalid non-lvalue. 1345 return true; 1346} 1347 1348 1349StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, 1350 bool IsSimple, 1351 bool IsVolatile, 1352 unsigned NumOutputs, 1353 unsigned NumInputs, 1354 IdentifierInfo **Names, 1355 MultiExprArg constraints, 1356 MultiExprArg exprs, 1357 Expr *asmString, 1358 MultiExprArg clobbers, 1359 SourceLocation RParenLoc, 1360 bool MSAsm) { 1361 unsigned NumClobbers = clobbers.size(); 1362 StringLiteral **Constraints = 1363 reinterpret_cast<StringLiteral**>(constraints.get()); 1364 Expr **Exprs = exprs.get(); 1365 StringLiteral *AsmString = cast<StringLiteral>(asmString); 1366 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get()); 1367 1368 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; 1369 1370 // The parser verifies that there is a string literal here. 1371 if (AsmString->isWide()) 1372 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character) 1373 << AsmString->getSourceRange()); 1374 1375 for (unsigned i = 0; i != NumOutputs; i++) { 1376 StringLiteral *Literal = Constraints[i]; 1377 if (Literal->isWide()) 1378 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 1379 << Literal->getSourceRange()); 1380 1381 llvm::StringRef OutputName; 1382 if (Names[i]) 1383 OutputName = Names[i]->getName(); 1384 1385 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName); 1386 if (!Context.Target.validateOutputConstraint(Info)) 1387 return StmtError(Diag(Literal->getLocStart(), 1388 diag::err_asm_invalid_output_constraint) 1389 << Info.getConstraintStr()); 1390 1391 // Check that the output exprs are valid lvalues. 1392 Expr *OutputExpr = Exprs[i]; 1393 if (CheckAsmLValue(OutputExpr, *this)) { 1394 return StmtError(Diag(OutputExpr->getLocStart(), 1395 diag::err_asm_invalid_lvalue_in_output) 1396 << OutputExpr->getSourceRange()); 1397 } 1398 1399 OutputConstraintInfos.push_back(Info); 1400 } 1401 1402 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos; 1403 1404 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) { 1405 StringLiteral *Literal = Constraints[i]; 1406 if (Literal->isWide()) 1407 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 1408 << Literal->getSourceRange()); 1409 1410 llvm::StringRef InputName; 1411 if (Names[i]) 1412 InputName = Names[i]->getName(); 1413 1414 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName); 1415 if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(), 1416 NumOutputs, Info)) { 1417 return StmtError(Diag(Literal->getLocStart(), 1418 diag::err_asm_invalid_input_constraint) 1419 << Info.getConstraintStr()); 1420 } 1421 1422 Expr *InputExpr = Exprs[i]; 1423 1424 // Only allow void types for memory constraints. 1425 if (Info.allowsMemory() && !Info.allowsRegister()) { 1426 if (CheckAsmLValue(InputExpr, *this)) 1427 return StmtError(Diag(InputExpr->getLocStart(), 1428 diag::err_asm_invalid_lvalue_in_input) 1429 << Info.getConstraintStr() 1430 << InputExpr->getSourceRange()); 1431 } 1432 1433 if (Info.allowsRegister()) { 1434 if (InputExpr->getType()->isVoidType()) { 1435 return StmtError(Diag(InputExpr->getLocStart(), 1436 diag::err_asm_invalid_type_in_input) 1437 << InputExpr->getType() << Info.getConstraintStr() 1438 << InputExpr->getSourceRange()); 1439 } 1440 } 1441 1442 DefaultFunctionArrayLvalueConversion(Exprs[i]); 1443 1444 InputConstraintInfos.push_back(Info); 1445 } 1446 1447 // Check that the clobbers are valid. 1448 for (unsigned i = 0; i != NumClobbers; i++) { 1449 StringLiteral *Literal = Clobbers[i]; 1450 if (Literal->isWide()) 1451 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 1452 << Literal->getSourceRange()); 1453 1454 llvm::StringRef Clobber = Literal->getString(); 1455 1456 if (!Context.Target.isValidGCCRegisterName(Clobber)) 1457 return StmtError(Diag(Literal->getLocStart(), 1458 diag::err_asm_unknown_register_name) << Clobber); 1459 } 1460 1461 AsmStmt *NS = 1462 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm, 1463 NumOutputs, NumInputs, Names, Constraints, Exprs, 1464 AsmString, NumClobbers, Clobbers, RParenLoc); 1465 // Validate the asm string, ensuring it makes sense given the operands we 1466 // have. 1467 llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces; 1468 unsigned DiagOffs; 1469 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) { 1470 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID) 1471 << AsmString->getSourceRange(); 1472 return StmtError(); 1473 } 1474 1475 // Validate tied input operands for type mismatches. 1476 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) { 1477 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i]; 1478 1479 // If this is a tied constraint, verify that the output and input have 1480 // either exactly the same type, or that they are int/ptr operands with the 1481 // same size (int/long, int*/long, are ok etc). 1482 if (!Info.hasTiedOperand()) continue; 1483 1484 unsigned TiedTo = Info.getTiedOperand(); 1485 Expr *OutputExpr = Exprs[TiedTo]; 1486 Expr *InputExpr = Exprs[i+NumOutputs]; 1487 QualType InTy = InputExpr->getType(); 1488 QualType OutTy = OutputExpr->getType(); 1489 if (Context.hasSameType(InTy, OutTy)) 1490 continue; // All types can be tied to themselves. 1491 1492 // Decide if the input and output are in the same domain (integer/ptr or 1493 // floating point. 1494 enum AsmDomain { 1495 AD_Int, AD_FP, AD_Other 1496 } InputDomain, OutputDomain; 1497 1498 if (InTy->isIntegerType() || InTy->isPointerType()) 1499 InputDomain = AD_Int; 1500 else if (InTy->isRealFloatingType()) 1501 InputDomain = AD_FP; 1502 else 1503 InputDomain = AD_Other; 1504 1505 if (OutTy->isIntegerType() || OutTy->isPointerType()) 1506 OutputDomain = AD_Int; 1507 else if (OutTy->isRealFloatingType()) 1508 OutputDomain = AD_FP; 1509 else 1510 OutputDomain = AD_Other; 1511 1512 // They are ok if they are the same size and in the same domain. This 1513 // allows tying things like: 1514 // void* to int* 1515 // void* to int if they are the same size. 1516 // double to long double if they are the same size. 1517 // 1518 uint64_t OutSize = Context.getTypeSize(OutTy); 1519 uint64_t InSize = Context.getTypeSize(InTy); 1520 if (OutSize == InSize && InputDomain == OutputDomain && 1521 InputDomain != AD_Other) 1522 continue; 1523 1524 // If the smaller input/output operand is not mentioned in the asm string, 1525 // then we can promote it and the asm string won't notice. Check this 1526 // case now. 1527 bool SmallerValueMentioned = false; 1528 for (unsigned p = 0, e = Pieces.size(); p != e; ++p) { 1529 AsmStmt::AsmStringPiece &Piece = Pieces[p]; 1530 if (!Piece.isOperand()) continue; 1531 1532 // If this is a reference to the input and if the input was the smaller 1533 // one, then we have to reject this asm. 1534 if (Piece.getOperandNo() == i+NumOutputs) { 1535 if (InSize < OutSize) { 1536 SmallerValueMentioned = true; 1537 break; 1538 } 1539 } 1540 1541 // If this is a reference to the input and if the input was the smaller 1542 // one, then we have to reject this asm. 1543 if (Piece.getOperandNo() == TiedTo) { 1544 if (InSize > OutSize) { 1545 SmallerValueMentioned = true; 1546 break; 1547 } 1548 } 1549 } 1550 1551 // If the smaller value wasn't mentioned in the asm string, and if the 1552 // output was a register, just extend the shorter one to the size of the 1553 // larger one. 1554 if (!SmallerValueMentioned && InputDomain != AD_Other && 1555 OutputConstraintInfos[TiedTo].allowsRegister()) 1556 continue; 1557 1558 Diag(InputExpr->getLocStart(), 1559 diag::err_asm_tying_incompatible_types) 1560 << InTy << OutTy << OutputExpr->getSourceRange() 1561 << InputExpr->getSourceRange(); 1562 return StmtError(); 1563 } 1564 1565 return Owned(NS); 1566} 1567 1568StmtResult 1569Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc, 1570 SourceLocation RParen, Decl *Parm, 1571 Stmt *Body) { 1572 VarDecl *Var = cast_or_null<VarDecl>(Parm); 1573 if (Var && Var->isInvalidDecl()) 1574 return StmtError(); 1575 1576 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body)); 1577} 1578 1579StmtResult 1580Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) { 1581 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body)); 1582} 1583 1584StmtResult 1585Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 1586 MultiStmtArg CatchStmts, Stmt *Finally) { 1587 getCurFunction()->setHasBranchProtectedScope(); 1588 unsigned NumCatchStmts = CatchStmts.size(); 1589 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try, 1590 CatchStmts.release(), 1591 NumCatchStmts, 1592 Finally)); 1593} 1594 1595StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, 1596 Expr *Throw) { 1597 if (Throw) { 1598 QualType ThrowType = Throw->getType(); 1599 // Make sure the expression type is an ObjC pointer or "void *". 1600 if (!ThrowType->isDependentType() && 1601 !ThrowType->isObjCObjectPointerType()) { 1602 const PointerType *PT = ThrowType->getAs<PointerType>(); 1603 if (!PT || !PT->getPointeeType()->isVoidType()) 1604 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object) 1605 << Throw->getType() << Throw->getSourceRange()); 1606 } 1607 } 1608 1609 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw)); 1610} 1611 1612StmtResult 1613Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 1614 Scope *CurScope) { 1615 if (!Throw) { 1616 // @throw without an expression designates a rethrow (which much occur 1617 // in the context of an @catch clause). 1618 Scope *AtCatchParent = CurScope; 1619 while (AtCatchParent && !AtCatchParent->isAtCatchScope()) 1620 AtCatchParent = AtCatchParent->getParent(); 1621 if (!AtCatchParent) 1622 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch)); 1623 } 1624 1625 return BuildObjCAtThrowStmt(AtLoc, Throw); 1626} 1627 1628StmtResult 1629Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr, 1630 Stmt *SyncBody) { 1631 getCurFunction()->setHasBranchProtectedScope(); 1632 1633 // Make sure the expression type is an ObjC pointer or "void *". 1634 if (!SyncExpr->getType()->isDependentType() && 1635 !SyncExpr->getType()->isObjCObjectPointerType()) { 1636 const PointerType *PT = SyncExpr->getType()->getAs<PointerType>(); 1637 if (!PT || !PT->getPointeeType()->isVoidType()) 1638 return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object) 1639 << SyncExpr->getType() << SyncExpr->getSourceRange()); 1640 } 1641 1642 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody)); 1643} 1644 1645/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block 1646/// and creates a proper catch handler from them. 1647StmtResult 1648Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, 1649 Stmt *HandlerBlock) { 1650 // There's nothing to test that ActOnExceptionDecl didn't already test. 1651 return Owned(new (Context) CXXCatchStmt(CatchLoc, 1652 cast_or_null<VarDecl>(ExDecl), 1653 HandlerBlock)); 1654} 1655 1656namespace { 1657 1658class TypeWithHandler { 1659 QualType t; 1660 CXXCatchStmt *stmt; 1661public: 1662 TypeWithHandler(const QualType &type, CXXCatchStmt *statement) 1663 : t(type), stmt(statement) {} 1664 1665 // An arbitrary order is fine as long as it places identical 1666 // types next to each other. 1667 bool operator<(const TypeWithHandler &y) const { 1668 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr()) 1669 return true; 1670 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr()) 1671 return false; 1672 else 1673 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc(); 1674 } 1675 1676 bool operator==(const TypeWithHandler& other) const { 1677 return t == other.t; 1678 } 1679 1680 CXXCatchStmt *getCatchStmt() const { return stmt; } 1681 SourceLocation getTypeSpecStartLoc() const { 1682 return stmt->getExceptionDecl()->getTypeSpecStartLoc(); 1683 } 1684}; 1685 1686} 1687 1688/// ActOnCXXTryBlock - Takes a try compound-statement and a number of 1689/// handlers and creates a try statement from them. 1690StmtResult 1691Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 1692 MultiStmtArg RawHandlers) { 1693 unsigned NumHandlers = RawHandlers.size(); 1694 assert(NumHandlers > 0 && 1695 "The parser shouldn't call this if there are no handlers."); 1696 Stmt **Handlers = RawHandlers.get(); 1697 1698 llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers; 1699 1700 for (unsigned i = 0; i < NumHandlers; ++i) { 1701 CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]); 1702 if (!Handler->getExceptionDecl()) { 1703 if (i < NumHandlers - 1) 1704 return StmtError(Diag(Handler->getLocStart(), 1705 diag::err_early_catch_all)); 1706 1707 continue; 1708 } 1709 1710 const QualType CaughtType = Handler->getCaughtType(); 1711 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType); 1712 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler)); 1713 } 1714 1715 // Detect handlers for the same type as an earlier one. 1716 if (NumHandlers > 1) { 1717 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end()); 1718 1719 TypeWithHandler prev = TypesWithHandlers[0]; 1720 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) { 1721 TypeWithHandler curr = TypesWithHandlers[i]; 1722 1723 if (curr == prev) { 1724 Diag(curr.getTypeSpecStartLoc(), 1725 diag::warn_exception_caught_by_earlier_handler) 1726 << curr.getCatchStmt()->getCaughtType().getAsString(); 1727 Diag(prev.getTypeSpecStartLoc(), 1728 diag::note_previous_exception_handler) 1729 << prev.getCatchStmt()->getCaughtType().getAsString(); 1730 } 1731 1732 prev = curr; 1733 } 1734 } 1735 1736 getCurFunction()->setHasBranchProtectedScope(); 1737 1738 // FIXME: We should detect handlers that cannot catch anything because an 1739 // earlier handler catches a superclass. Need to find a method that is not 1740 // quadratic for this. 1741 // Neither of these are explicitly forbidden, but every compiler detects them 1742 // and warns. 1743 1744 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock, 1745 Handlers, NumHandlers)); 1746} 1747