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