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