SemaStmt.cpp revision 35e12c90c1b107a75c5615aa76fdbd403661aaa6
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 "Sema.h" 15#include "SemaInit.h" 16#include "clang/AST/APValue.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/DeclObjC.h" 19#include "clang/AST/ExprCXX.h" 20#include "clang/AST/ExprObjC.h" 21#include "clang/AST/StmtObjC.h" 22#include "clang/AST/StmtCXX.h" 23#include "clang/AST/TypeLoc.h" 24#include "clang/Lex/Preprocessor.h" 25#include "clang/Basic/TargetInfo.h" 26#include "llvm/ADT/STLExtras.h" 27#include "llvm/ADT/SmallVector.h" 28using namespace clang; 29 30Sema::OwningStmtResult Sema::ActOnExprStmt(FullExprArg expr) { 31 Expr *E = expr->takeAs<Expr>(); 32 assert(E && "ActOnExprStmt(): missing expression"); 33 if (E->getType()->isObjCObjectType()) { 34 if (LangOpts.ObjCNonFragileABI) 35 Diag(E->getLocEnd(), diag::err_indirection_requires_nonfragile_object) 36 << E->getType(); 37 else 38 Diag(E->getLocEnd(), diag::err_direct_interface_unsupported) 39 << E->getType(); 40 return StmtError(); 41 } 42 // C99 6.8.3p2: The expression in an expression statement is evaluated as a 43 // void expression for its side effects. Conversion to void allows any 44 // operand, even incomplete types. 45 46 // Same thing in for stmt first clause (when expr) and third clause. 47 return Owned(static_cast<Stmt*>(E)); 48} 49 50 51Sema::OwningStmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc) { 52 return Owned(new (Context) NullStmt(SemiLoc)); 53} 54 55Sema::OwningStmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, 56 SourceLocation StartLoc, 57 SourceLocation EndLoc) { 58 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>(); 59 60 // If we have an invalid decl, just return an error. 61 if (DG.isNull()) return StmtError(); 62 63 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc)); 64} 65 66void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) { 67 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>(); 68 69 // If we have an invalid decl, just return. 70 if (DG.isNull() || !DG.isSingleDecl()) return; 71 // suppress any potential 'unused variable' warning. 72 DG.getSingleDecl()->setUsed(); 73} 74 75void Sema::DiagnoseUnusedExprResult(const Stmt *S) { 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 E = E->IgnoreParens(); 90 if (isa<ObjCImplicitSetterGetterRefExpr>(E)) 91 DiagID = diag::warn_unused_property_expr; 92 93 if (const CXXExprWithTemporaries *Temps = dyn_cast<CXXExprWithTemporaries>(E)) 94 E = Temps->getSubExpr(); 95 96 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 97 if (E->getType()->isVoidType()) 98 return; 99 100 // If the callee has attribute pure, const, or warn_unused_result, warn with 101 // a more specific message to make it clear what is happening. 102 if (const Decl *FD = CE->getCalleeDecl()) { 103 if (FD->getAttr<WarnUnusedResultAttr>()) { 104 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result"; 105 return; 106 } 107 if (FD->getAttr<PureAttr>()) { 108 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure"; 109 return; 110 } 111 if (FD->getAttr<ConstAttr>()) { 112 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const"; 113 return; 114 } 115 } 116 } 117 else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) { 118 const ObjCMethodDecl *MD = ME->getMethodDecl(); 119 if (MD && MD->getAttr<WarnUnusedResultAttr>()) { 120 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result"; 121 return; 122 } 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, PDiag(DiagID) << R1 << R2); 145} 146 147Action::OwningStmtResult 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 182Action::OwningStmtResult 183Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprArg lhsval, 184 SourceLocation DotDotDotLoc, ExprArg rhsval, 185 SourceLocation ColonLoc) { 186 assert((lhsval.get() != 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 Expr *LHSVal = static_cast<Expr*>(lhsval.get()); 191 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() && 192 VerifyIntegerConstantExpression(LHSVal)) 193 return StmtError(); 194 195 // GCC extension: The expression shall be an integer constant. 196 197 Expr *RHSVal = static_cast<Expr*>(rhsval.get()); 198 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() && 199 VerifyIntegerConstantExpression(RHSVal)) { 200 RHSVal = 0; // Recover by just forgetting about it. 201 rhsval = 0; 202 } 203 204 if (getSwitchStack().empty()) { 205 Diag(CaseLoc, diag::err_case_not_in_switch); 206 return StmtError(); 207 } 208 209 // Only now release the smart pointers. 210 lhsval.release(); 211 rhsval.release(); 212 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc, 213 ColonLoc); 214 getSwitchStack().back()->addSwitchCase(CS); 215 return Owned(CS); 216} 217 218/// ActOnCaseStmtBody - This installs a statement as the body of a case. 219void Sema::ActOnCaseStmtBody(StmtTy *caseStmt, StmtArg subStmt) { 220 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt); 221 Stmt *SubStmt = subStmt.takeAs<Stmt>(); 222 CS->setSubStmt(SubStmt); 223} 224 225Action::OwningStmtResult 226Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, 227 StmtArg subStmt, Scope *CurScope) { 228 Stmt *SubStmt = subStmt.takeAs<Stmt>(); 229 230 if (getSwitchStack().empty()) { 231 Diag(DefaultLoc, diag::err_default_not_in_switch); 232 return Owned(SubStmt); 233 } 234 235 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt); 236 getSwitchStack().back()->addSwitchCase(DS); 237 return Owned(DS); 238} 239 240Action::OwningStmtResult 241Sema::ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II, 242 SourceLocation ColonLoc, StmtArg subStmt) { 243 Stmt *SubStmt = subStmt.takeAs<Stmt>(); 244 // Look up the record for this label identifier. 245 LabelStmt *&LabelDecl = getLabelMap()[II]; 246 247 // If not forward referenced or defined already, just create a new LabelStmt. 248 if (LabelDecl == 0) 249 return Owned(LabelDecl = new (Context) LabelStmt(IdentLoc, II, SubStmt)); 250 251 assert(LabelDecl->getID() == II && "Label mismatch!"); 252 253 // Otherwise, this label was either forward reference or multiply defined. If 254 // multiply defined, reject it now. 255 if (LabelDecl->getSubStmt()) { 256 Diag(IdentLoc, diag::err_redefinition_of_label) << LabelDecl->getID(); 257 Diag(LabelDecl->getIdentLoc(), diag::note_previous_definition); 258 return Owned(SubStmt); 259 } 260 261 // Otherwise, this label was forward declared, and we just found its real 262 // definition. Fill in the forward definition and return it. 263 LabelDecl->setIdentLoc(IdentLoc); 264 LabelDecl->setSubStmt(SubStmt); 265 return Owned(LabelDecl); 266} 267 268Action::OwningStmtResult 269Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, DeclPtrTy CondVar, 270 StmtArg ThenVal, SourceLocation ElseLoc, 271 StmtArg ElseVal) { 272 OwningExprResult CondResult(CondVal.release()); 273 274 VarDecl *ConditionVar = 0; 275 if (CondVar.get()) { 276 ConditionVar = CondVar.getAs<VarDecl>(); 277 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true); 278 if (CondResult.isInvalid()) 279 return StmtError(); 280 } 281 Expr *ConditionExpr = CondResult.takeAs<Expr>(); 282 if (!ConditionExpr) 283 return StmtError(); 284 285 Stmt *thenStmt = ThenVal.takeAs<Stmt>(); 286 DiagnoseUnusedExprResult(thenStmt); 287 288 // Warn if the if block has a null body without an else value. 289 // this helps prevent bugs due to typos, such as 290 // if (condition); 291 // do_stuff(); 292 if (!ElseVal.get()) { 293 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt)) 294 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body); 295 } 296 297 Stmt *elseStmt = ElseVal.takeAs<Stmt>(); 298 DiagnoseUnusedExprResult(elseStmt); 299 300 CondResult.release(); 301 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr, 302 thenStmt, ElseLoc, elseStmt)); 303} 304 305/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 306/// the specified width and sign. If an overflow occurs, detect it and emit 307/// the specified diagnostic. 308void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val, 309 unsigned NewWidth, bool NewSign, 310 SourceLocation Loc, 311 unsigned DiagID) { 312 // Perform a conversion to the promoted condition type if needed. 313 if (NewWidth > Val.getBitWidth()) { 314 // If this is an extension, just do it. 315 Val.extend(NewWidth); 316 Val.setIsSigned(NewSign); 317 318 // If the input was signed and negative and the output is 319 // unsigned, don't bother to warn: this is implementation-defined 320 // behavior. 321 // FIXME: Introduce a second, default-ignored warning for this case? 322 } else if (NewWidth < Val.getBitWidth()) { 323 // If this is a truncation, check for overflow. 324 llvm::APSInt ConvVal(Val); 325 ConvVal.trunc(NewWidth); 326 ConvVal.setIsSigned(NewSign); 327 ConvVal.extend(Val.getBitWidth()); 328 ConvVal.setIsSigned(Val.isSigned()); 329 if (ConvVal != Val) 330 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10); 331 332 // Regardless of whether a diagnostic was emitted, really do the 333 // truncation. 334 Val.trunc(NewWidth); 335 Val.setIsSigned(NewSign); 336 } else if (NewSign != Val.isSigned()) { 337 // Convert the sign to match the sign of the condition. This can cause 338 // overflow as well: unsigned(INTMIN) 339 // We don't diagnose this overflow, because it is implementation-defined 340 // behavior. 341 // FIXME: Introduce a second, default-ignored warning for this case? 342 llvm::APSInt OldVal(Val); 343 Val.setIsSigned(NewSign); 344 } 345} 346 347namespace { 348 struct CaseCompareFunctor { 349 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 350 const llvm::APSInt &RHS) { 351 return LHS.first < RHS; 352 } 353 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 354 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 355 return LHS.first < RHS.first; 356 } 357 bool operator()(const llvm::APSInt &LHS, 358 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 359 return LHS < RHS.first; 360 } 361 }; 362} 363 364/// CmpCaseVals - Comparison predicate for sorting case values. 365/// 366static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs, 367 const std::pair<llvm::APSInt, CaseStmt*>& rhs) { 368 if (lhs.first < rhs.first) 369 return true; 370 371 if (lhs.first == rhs.first && 372 lhs.second->getCaseLoc().getRawEncoding() 373 < rhs.second->getCaseLoc().getRawEncoding()) 374 return true; 375 return false; 376} 377 378/// CmpEnumVals - Comparison predicate for sorting enumeration values. 379/// 380static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 381 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 382{ 383 return lhs.first < rhs.first; 384} 385 386/// EqEnumVals - Comparison preficate for uniqing enumeration values. 387/// 388static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 389 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 390{ 391 return lhs.first == rhs.first; 392} 393 394/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of 395/// potentially integral-promoted expression @p expr. 396static QualType GetTypeBeforeIntegralPromotion(const Expr* expr) { 397 if (const CastExpr *ImplicitCast = dyn_cast<ImplicitCastExpr>(expr)) { 398 const Expr *ExprBeforePromotion = ImplicitCast->getSubExpr(); 399 QualType TypeBeforePromotion = ExprBeforePromotion->getType(); 400 if (TypeBeforePromotion->isIntegralOrEnumerationType()) { 401 return TypeBeforePromotion; 402 } 403 } 404 return expr->getType(); 405} 406 407Action::OwningStmtResult 408Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, ExprArg Cond, 409 DeclPtrTy CondVar) { 410 VarDecl *ConditionVar = 0; 411 if (CondVar.get()) { 412 ConditionVar = CondVar.getAs<VarDecl>(); 413 OwningExprResult CondE = CheckConditionVariable(ConditionVar, SourceLocation(), false); 414 if (CondE.isInvalid()) 415 return StmtError(); 416 417 Cond = move(CondE); 418 } 419 420 if (!Cond.get()) 421 return StmtError(); 422 423 Expr *CondExpr = static_cast<Expr *>(Cond.get()); 424 OwningExprResult ConvertedCond 425 = ConvertToIntegralOrEnumerationType(SwitchLoc, move(Cond), 426 PDiag(diag::err_typecheck_statement_requires_integer), 427 PDiag(diag::err_switch_incomplete_class_type) 428 << CondExpr->getSourceRange(), 429 PDiag(diag::err_switch_explicit_conversion), 430 PDiag(diag::note_switch_conversion), 431 PDiag(diag::err_switch_multiple_conversions), 432 PDiag(diag::note_switch_conversion), 433 PDiag(0)); 434 if (ConvertedCond.isInvalid()) 435 return StmtError(); 436 437 CondExpr = ConvertedCond.takeAs<Expr>(); 438 439 if (!CondVar.get()) { 440 CondExpr = MaybeCreateCXXExprWithTemporaries(CondExpr); 441 if (!CondExpr) 442 return StmtError(); 443 } 444 445 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, CondExpr); 446 getSwitchStack().push_back(SS); 447 return Owned(SS); 448} 449 450Action::OwningStmtResult 451Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, StmtArg Switch, 452 StmtArg Body) { 453 Stmt *BodyStmt = Body.takeAs<Stmt>(); 454 455 SwitchStmt *SS = getSwitchStack().back(); 456 assert(SS == (SwitchStmt*)Switch.get() && "switch stack missing push/pop!"); 457 458 SS->setBody(BodyStmt, SwitchLoc); 459 getSwitchStack().pop_back(); 460 461 if (SS->getCond() == 0) { 462 SS->Destroy(Context); 463 return StmtError(); 464 } 465 466 Expr *CondExpr = SS->getCond(); 467 Expr *CondExprBeforePromotion = CondExpr; 468 QualType CondTypeBeforePromotion = 469 GetTypeBeforeIntegralPromotion(CondExpr); 470 471 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr. 472 UsualUnaryConversions(CondExpr); 473 QualType CondType = CondExpr->getType(); 474 SS->setCond(CondExpr); 475 476 // C++ 6.4.2.p2: 477 // Integral promotions are performed (on the switch condition). 478 // 479 // A case value unrepresentable by the original switch condition 480 // type (before the promotion) doesn't make sense, even when it can 481 // be represented by the promoted type. Therefore we need to find 482 // the pre-promotion type of the switch condition. 483 if (!CondExpr->isTypeDependent()) { 484 // We have already converted the expression to an integral or enumeration 485 // type, when we started the switch statement. If we don't have an 486 // appropriate type now, just return an error. 487 if (!CondType->isIntegralOrEnumerationType()) 488 return StmtError(); 489 490 if (CondExpr->isKnownToHaveBooleanValue()) { 491 // switch(bool_expr) {...} is often a programmer error, e.g. 492 // switch(n && mask) { ... } // Doh - should be "n & mask". 493 // One can always use an if statement instead of switch(bool_expr). 494 Diag(SwitchLoc, diag::warn_bool_switch_condition) 495 << CondExpr->getSourceRange(); 496 } 497 } 498 499 // Get the bitwidth of the switched-on value before promotions. We must 500 // convert the integer case values to this width before comparison. 501 bool HasDependentValue 502 = CondExpr->isTypeDependent() || CondExpr->isValueDependent(); 503 unsigned CondWidth 504 = HasDependentValue? 0 505 : static_cast<unsigned>(Context.getTypeSize(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 CS->getLHS()->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, CastExpr::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 CR->getRHS()->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, CastExpr::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 CR->getRHS()->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 don't need to do this if there's a default 720 // statement or if we have a constant condition. 721 // 722 // TODO: we might want to check whether case values are out of the 723 // enum even if we don't want to check whether all cases are handled. 724 const EnumType* ET = CondTypeBeforePromotion->getAs<EnumType>(); 725 // If switch has default case, then ignore it. 726 if (!CaseListIsErroneous && !TheDefaultStmt && !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 if(Val.getBitWidth() < CondWidth) 737 Val.extend(CondWidth); 738 else if (Val.getBitWidth() > CondWidth) 739 Val.trunc(CondWidth); 740 Val.setIsSigned(CondIsSigned); 741 EnumVals.push_back(std::make_pair(Val, (*EDI))); 742 } 743 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals); 744 EnumValsTy::iterator EIend = 745 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals); 746 // See which case values aren't in enum 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 while (EI != EIend && EI->first < Hi) 770 EI++; 771 if (EI == EIend || EI->first != Hi) 772 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum) 773 << ED->getDeclName(); 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 EI = EnumVals.begin(); 779 for (; EI != EIend; EI++) { 780 //Drop unneeded case values 781 llvm::APSInt CIVal; 782 while (CI != CaseVals.end() && CI->first < EI->first) 783 CI++; 784 785 if (CI != CaseVals.end() && CI->first == EI->first) 786 continue; 787 788 //Drop unneeded case ranges 789 for (; RI != CaseRanges.end(); RI++) { 790 llvm::APSInt Hi = RI->second->getRHS()->EvaluateAsInt(Context); 791 if (EI->first <= Hi) 792 break; 793 } 794 795 if (RI == CaseRanges.end() || EI->first < RI->first) 796 Diag(CondExpr->getExprLoc(), diag::warn_missing_cases) 797 << EI->second->getDeclName(); 798 } 799 } 800 } 801 802 // FIXME: If the case list was broken is some way, we don't have a good system 803 // to patch it up. Instead, just return the whole substmt as broken. 804 if (CaseListIsErroneous) 805 return StmtError(); 806 807 Switch.release(); 808 return Owned(SS); 809} 810 811Action::OwningStmtResult 812Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond, 813 DeclPtrTy CondVar, StmtArg Body) { 814 OwningExprResult CondResult(Cond.release()); 815 816 VarDecl *ConditionVar = 0; 817 if (CondVar.get()) { 818 ConditionVar = CondVar.getAs<VarDecl>(); 819 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true); 820 if (CondResult.isInvalid()) 821 return StmtError(); 822 } 823 Expr *ConditionExpr = CondResult.takeAs<Expr>(); 824 if (!ConditionExpr) 825 return StmtError(); 826 827 Stmt *bodyStmt = Body.takeAs<Stmt>(); 828 DiagnoseUnusedExprResult(bodyStmt); 829 830 CondResult.release(); 831 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr, 832 bodyStmt, WhileLoc)); 833} 834 835Action::OwningStmtResult 836Sema::ActOnDoStmt(SourceLocation DoLoc, StmtArg Body, 837 SourceLocation WhileLoc, SourceLocation CondLParen, 838 ExprArg Cond, SourceLocation CondRParen) { 839 Expr *condExpr = Cond.takeAs<Expr>(); 840 assert(condExpr && "ActOnDoStmt(): missing expression"); 841 842 if (CheckBooleanCondition(condExpr, DoLoc)) { 843 Cond = condExpr; 844 return StmtError(); 845 } 846 847 condExpr = MaybeCreateCXXExprWithTemporaries(condExpr); 848 if (!condExpr) 849 return StmtError(); 850 851 Stmt *bodyStmt = Body.takeAs<Stmt>(); 852 DiagnoseUnusedExprResult(bodyStmt); 853 854 Cond.release(); 855 return Owned(new (Context) DoStmt(bodyStmt, condExpr, DoLoc, 856 WhileLoc, CondRParen)); 857} 858 859Action::OwningStmtResult 860Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 861 StmtArg first, FullExprArg second, DeclPtrTy secondVar, 862 FullExprArg third, 863 SourceLocation RParenLoc, StmtArg body) { 864 Stmt *First = static_cast<Stmt*>(first.get()); 865 866 if (!getLangOptions().CPlusPlus) { 867 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) { 868 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 869 // declare identifiers for objects having storage class 'auto' or 870 // 'register'. 871 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end(); 872 DI!=DE; ++DI) { 873 VarDecl *VD = dyn_cast<VarDecl>(*DI); 874 if (VD && VD->isBlockVarDecl() && !VD->hasLocalStorage()) 875 VD = 0; 876 if (VD == 0) 877 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for); 878 // FIXME: mark decl erroneous! 879 } 880 } 881 } 882 883 OwningExprResult SecondResult(second.release()); 884 VarDecl *ConditionVar = 0; 885 if (secondVar.get()) { 886 ConditionVar = secondVar.getAs<VarDecl>(); 887 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true); 888 if (SecondResult.isInvalid()) 889 return StmtError(); 890 } 891 892 Expr *Third = third.release().takeAs<Expr>(); 893 Stmt *Body = static_cast<Stmt*>(body.get()); 894 895 DiagnoseUnusedExprResult(First); 896 DiagnoseUnusedExprResult(Third); 897 DiagnoseUnusedExprResult(Body); 898 899 first.release(); 900 body.release(); 901 return Owned(new (Context) ForStmt(Context, First, 902 SecondResult.takeAs<Expr>(), ConditionVar, 903 Third, Body, ForLoc, LParenLoc, 904 RParenLoc)); 905} 906 907Action::OwningStmtResult 908Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc, 909 SourceLocation LParenLoc, 910 StmtArg first, ExprArg second, 911 SourceLocation RParenLoc, StmtArg body) { 912 Stmt *First = static_cast<Stmt*>(first.get()); 913 Expr *Second = static_cast<Expr*>(second.get()); 914 Stmt *Body = static_cast<Stmt*>(body.get()); 915 if (First) { 916 QualType FirstType; 917 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) { 918 if (!DS->isSingleDecl()) 919 return StmtError(Diag((*DS->decl_begin())->getLocation(), 920 diag::err_toomany_element_decls)); 921 922 Decl *D = DS->getSingleDecl(); 923 FirstType = cast<ValueDecl>(D)->getType(); 924 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 925 // declare identifiers for objects having storage class 'auto' or 926 // 'register'. 927 VarDecl *VD = cast<VarDecl>(D); 928 if (VD->isBlockVarDecl() && !VD->hasLocalStorage()) 929 return StmtError(Diag(VD->getLocation(), 930 diag::err_non_variable_decl_in_for)); 931 } else { 932 Expr *FirstE = cast<Expr>(First); 933 if (!FirstE->isTypeDependent() && 934 FirstE->isLvalue(Context) != Expr::LV_Valid) 935 return StmtError(Diag(First->getLocStart(), 936 diag::err_selector_element_not_lvalue) 937 << First->getSourceRange()); 938 939 FirstType = static_cast<Expr*>(First)->getType(); 940 } 941 if (!FirstType->isDependentType() && 942 !FirstType->isObjCObjectPointerType() && 943 !FirstType->isBlockPointerType()) 944 Diag(ForLoc, diag::err_selector_element_type) 945 << FirstType << First->getSourceRange(); 946 } 947 if (Second && !Second->isTypeDependent()) { 948 DefaultFunctionArrayLvalueConversion(Second); 949 QualType SecondType = Second->getType(); 950 if (!SecondType->isObjCObjectPointerType()) 951 Diag(ForLoc, diag::err_collection_expr_type) 952 << SecondType << Second->getSourceRange(); 953 } 954 first.release(); 955 second.release(); 956 body.release(); 957 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body, 958 ForLoc, RParenLoc)); 959} 960 961Action::OwningStmtResult 962Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, 963 IdentifierInfo *LabelII) { 964 // Look up the record for this label identifier. 965 LabelStmt *&LabelDecl = getLabelMap()[LabelII]; 966 967 // If we haven't seen this label yet, create a forward reference. 968 if (LabelDecl == 0) 969 LabelDecl = new (Context) LabelStmt(LabelLoc, LabelII, 0); 970 971 return Owned(new (Context) GotoStmt(LabelDecl, GotoLoc, LabelLoc)); 972} 973 974Action::OwningStmtResult 975Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, 976 ExprArg DestExp) { 977 // Convert operand to void* 978 Expr* E = DestExp.takeAs<Expr>(); 979 if (!E->isTypeDependent()) { 980 QualType ETy = E->getType(); 981 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst()); 982 AssignConvertType ConvTy = 983 CheckSingleAssignmentConstraints(DestTy, E); 984 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing)) 985 return StmtError(); 986 } 987 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E)); 988} 989 990Action::OwningStmtResult 991Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) { 992 Scope *S = CurScope->getContinueParent(); 993 if (!S) { 994 // C99 6.8.6.2p1: A break shall appear only in or as a loop body. 995 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop)); 996 } 997 998 return Owned(new (Context) ContinueStmt(ContinueLoc)); 999} 1000 1001Action::OwningStmtResult 1002Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) { 1003 Scope *S = CurScope->getBreakParent(); 1004 if (!S) { 1005 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body. 1006 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch)); 1007 } 1008 1009 return Owned(new (Context) BreakStmt(BreakLoc)); 1010} 1011 1012/// \brief Determine whether a return statement is a candidate for the named 1013/// return value optimization (C++0x 12.8p34, bullet 1). 1014/// 1015/// \param Ctx The context in which the return expression and type occur. 1016/// 1017/// \param RetType The return type of the function or block. 1018/// 1019/// \param RetExpr The expression being returned from the function or block. 1020/// 1021/// \returns The NRVO candidate variable, if the return statement may use the 1022/// NRVO, or NULL if there is no such candidate. 1023static const VarDecl *getNRVOCandidate(ASTContext &Ctx, QualType RetType, 1024 Expr *RetExpr) { 1025 QualType ExprType = RetExpr->getType(); 1026 // - in a return statement in a function with ... 1027 // ... a class return type ... 1028 if (!RetType->isRecordType()) 1029 return 0; 1030 // ... the same cv-unqualified type as the function return type ... 1031 if (!Ctx.hasSameUnqualifiedType(RetType, ExprType)) 1032 return 0; 1033 // ... the expression is the name of a non-volatile automatic object ... 1034 // We ignore parentheses here. 1035 // FIXME: Is this compliant? (Everyone else does it) 1036 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetExpr->IgnoreParens()); 1037 if (!DR) 1038 return 0; 1039 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()); 1040 if (!VD) 1041 return 0; 1042 1043 if (VD->getKind() == Decl::Var && VD->hasLocalStorage() && 1044 !VD->getType()->isReferenceType() && !VD->hasAttr<BlocksAttr>() && 1045 !VD->getType().isVolatileQualified()) 1046 return VD; 1047 1048 return 0; 1049} 1050 1051/// ActOnBlockReturnStmt - Utility routine to figure out block's return type. 1052/// 1053Action::OwningStmtResult 1054Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 1055 // If this is the first return we've seen in the block, infer the type of 1056 // the block from it. 1057 BlockScopeInfo *CurBlock = getCurBlock(); 1058 if (CurBlock->ReturnType.isNull()) { 1059 if (RetValExp) { 1060 // Don't call UsualUnaryConversions(), since we don't want to do 1061 // integer promotions here. 1062 DefaultFunctionArrayLvalueConversion(RetValExp); 1063 CurBlock->ReturnType = RetValExp->getType(); 1064 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) { 1065 // We have to remove a 'const' added to copied-in variable which was 1066 // part of the implementation spec. and not the actual qualifier for 1067 // the variable. 1068 if (CDRE->isConstQualAdded()) 1069 CurBlock->ReturnType.removeConst(); 1070 } 1071 } else 1072 CurBlock->ReturnType = Context.VoidTy; 1073 } 1074 QualType FnRetType = CurBlock->ReturnType; 1075 1076 if (CurBlock->TheDecl->hasAttr<NoReturnAttr>()) { 1077 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr) 1078 << getCurFunctionOrMethodDecl()->getDeclName(); 1079 return StmtError(); 1080 } 1081 1082 // Otherwise, verify that this result type matches the previous one. We are 1083 // pickier with blocks than for normal functions because we don't have GCC 1084 // compatibility to worry about here. 1085 ReturnStmt *Result = 0; 1086 if (CurBlock->ReturnType->isVoidType()) { 1087 if (RetValExp) { 1088 Diag(ReturnLoc, diag::err_return_block_has_expr); 1089 RetValExp->Destroy(Context); 1090 RetValExp = 0; 1091 } 1092 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0); 1093 } else if (!RetValExp) { 1094 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr)); 1095 } else { 1096 const VarDecl *NRVOCandidate = 0; 1097 1098 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 1099 // we have a non-void block with an expression, continue checking 1100 1101 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 1102 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 1103 // function return. 1104 1105 // In C++ the return statement is handled via a copy initialization. 1106 // the C version of which boils down to CheckSingleAssignmentConstraints. 1107 NRVOCandidate = getNRVOCandidate(Context, FnRetType, RetValExp); 1108 OwningExprResult Res = PerformCopyInitialization( 1109 InitializedEntity::InitializeResult(ReturnLoc, 1110 FnRetType, 1111 NRVOCandidate != 0), 1112 SourceLocation(), 1113 Owned(RetValExp)); 1114 if (Res.isInvalid()) { 1115 // FIXME: Cleanup temporaries here, anyway? 1116 return StmtError(); 1117 } 1118 1119 if (RetValExp) 1120 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp); 1121 1122 RetValExp = Res.takeAs<Expr>(); 1123 if (RetValExp) 1124 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 1125 } 1126 1127 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate); 1128 } 1129 1130 // If we need to check for the named return value optimization, save the 1131 // return statement in our scope for later processing. 1132 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() && 1133 !CurContext->isDependentContext()) 1134 FunctionScopes.back()->Returns.push_back(Result); 1135 1136 return Owned(Result); 1137} 1138 1139Action::OwningStmtResult 1140Sema::ActOnReturnStmt(SourceLocation ReturnLoc, ExprArg rex) { 1141 Expr *RetValExp = rex.takeAs<Expr>(); 1142 if (getCurBlock()) 1143 return ActOnBlockReturnStmt(ReturnLoc, RetValExp); 1144 1145 QualType FnRetType; 1146 if (const FunctionDecl *FD = getCurFunctionDecl()) { 1147 FnRetType = FD->getResultType(); 1148 if (FD->hasAttr<NoReturnAttr>() || 1149 FD->getType()->getAs<FunctionType>()->getNoReturnAttr()) 1150 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) 1151 << getCurFunctionOrMethodDecl()->getDeclName(); 1152 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) 1153 FnRetType = MD->getResultType(); 1154 else // If we don't have a function/method context, bail. 1155 return StmtError(); 1156 1157 ReturnStmt *Result = 0; 1158 if (FnRetType->isVoidType()) { 1159 if (RetValExp && !RetValExp->isTypeDependent()) { 1160 // C99 6.8.6.4p1 (ext_ since GCC warns) 1161 unsigned D = diag::ext_return_has_expr; 1162 if (RetValExp->getType()->isVoidType()) 1163 D = diag::ext_return_has_void_expr; 1164 1165 // return (some void expression); is legal in C++. 1166 if (D != diag::ext_return_has_void_expr || 1167 !getLangOptions().CPlusPlus) { 1168 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 1169 Diag(ReturnLoc, D) 1170 << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl) 1171 << RetValExp->getSourceRange(); 1172 } 1173 1174 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp); 1175 } 1176 1177 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0); 1178 } else if (!RetValExp && !FnRetType->isDependentType()) { 1179 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4 1180 // C99 6.8.6.4p1 (ext_ since GCC warns) 1181 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr; 1182 1183 if (FunctionDecl *FD = getCurFunctionDecl()) 1184 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/; 1185 else 1186 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/; 1187 Result = new (Context) ReturnStmt(ReturnLoc); 1188 } else { 1189 const VarDecl *NRVOCandidate = 0; 1190 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 1191 // we have a non-void function with an expression, continue checking 1192 1193 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 1194 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 1195 // function return. 1196 1197 // In C++ the return statement is handled via a copy initialization. 1198 // the C version of which boils down to CheckSingleAssignmentConstraints. 1199 NRVOCandidate = getNRVOCandidate(Context, FnRetType, RetValExp); 1200 OwningExprResult Res = PerformCopyInitialization( 1201 InitializedEntity::InitializeResult(ReturnLoc, 1202 FnRetType, 1203 NRVOCandidate != 0), 1204 SourceLocation(), 1205 Owned(RetValExp)); 1206 if (Res.isInvalid()) { 1207 // FIXME: Cleanup temporaries here, anyway? 1208 return StmtError(); 1209 } 1210 1211 RetValExp = Res.takeAs<Expr>(); 1212 if (RetValExp) 1213 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 1214 } 1215 1216 if (RetValExp) 1217 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp); 1218 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate); 1219 } 1220 1221 // If we need to check for the named return value optimization, save the 1222 // return statement in our scope for later processing. 1223 if (getLangOptions().CPlusPlus && FnRetType->isRecordType() && 1224 !CurContext->isDependentContext()) 1225 FunctionScopes.back()->Returns.push_back(Result); 1226 1227 return Owned(Result); 1228} 1229 1230/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently 1231/// ignore "noop" casts in places where an lvalue is required by an inline asm. 1232/// We emulate this behavior when -fheinous-gnu-extensions is specified, but 1233/// provide a strong guidance to not use it. 1234/// 1235/// This method checks to see if the argument is an acceptable l-value and 1236/// returns false if it is a case we can handle. 1237static bool CheckAsmLValue(const Expr *E, Sema &S) { 1238 // Type dependent expressions will be checked during instantiation. 1239 if (E->isTypeDependent()) 1240 return false; 1241 1242 if (E->isLvalue(S.Context) == Expr::LV_Valid) 1243 return false; // Cool, this is an lvalue. 1244 1245 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we 1246 // are supposed to allow. 1247 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context); 1248 if (E != E2 && E2->isLvalue(S.Context) == Expr::LV_Valid) { 1249 if (!S.getLangOptions().HeinousExtensions) 1250 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue) 1251 << E->getSourceRange(); 1252 else 1253 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue) 1254 << E->getSourceRange(); 1255 // Accept, even if we emitted an error diagnostic. 1256 return false; 1257 } 1258 1259 // None of the above, just randomly invalid non-lvalue. 1260 return true; 1261} 1262 1263 1264Sema::OwningStmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, 1265 bool IsSimple, 1266 bool IsVolatile, 1267 unsigned NumOutputs, 1268 unsigned NumInputs, 1269 IdentifierInfo **Names, 1270 MultiExprArg constraints, 1271 MultiExprArg exprs, 1272 ExprArg asmString, 1273 MultiExprArg clobbers, 1274 SourceLocation RParenLoc, 1275 bool MSAsm) { 1276 unsigned NumClobbers = clobbers.size(); 1277 StringLiteral **Constraints = 1278 reinterpret_cast<StringLiteral**>(constraints.get()); 1279 Expr **Exprs = reinterpret_cast<Expr **>(exprs.get()); 1280 StringLiteral *AsmString = cast<StringLiteral>((Expr *)asmString.get()); 1281 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get()); 1282 1283 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; 1284 1285 // The parser verifies that there is a string literal here. 1286 if (AsmString->isWide()) 1287 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character) 1288 << AsmString->getSourceRange()); 1289 1290 for (unsigned i = 0; i != NumOutputs; i++) { 1291 StringLiteral *Literal = Constraints[i]; 1292 if (Literal->isWide()) 1293 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 1294 << Literal->getSourceRange()); 1295 1296 llvm::StringRef OutputName; 1297 if (Names[i]) 1298 OutputName = Names[i]->getName(); 1299 1300 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName); 1301 if (!Context.Target.validateOutputConstraint(Info)) 1302 return StmtError(Diag(Literal->getLocStart(), 1303 diag::err_asm_invalid_output_constraint) 1304 << Info.getConstraintStr()); 1305 1306 // Check that the output exprs are valid lvalues. 1307 Expr *OutputExpr = Exprs[i]; 1308 if (CheckAsmLValue(OutputExpr, *this)) { 1309 return StmtError(Diag(OutputExpr->getLocStart(), 1310 diag::err_asm_invalid_lvalue_in_output) 1311 << OutputExpr->getSourceRange()); 1312 } 1313 1314 OutputConstraintInfos.push_back(Info); 1315 } 1316 1317 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos; 1318 1319 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) { 1320 StringLiteral *Literal = Constraints[i]; 1321 if (Literal->isWide()) 1322 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 1323 << Literal->getSourceRange()); 1324 1325 llvm::StringRef InputName; 1326 if (Names[i]) 1327 InputName = Names[i]->getName(); 1328 1329 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName); 1330 if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(), 1331 NumOutputs, Info)) { 1332 return StmtError(Diag(Literal->getLocStart(), 1333 diag::err_asm_invalid_input_constraint) 1334 << Info.getConstraintStr()); 1335 } 1336 1337 Expr *InputExpr = Exprs[i]; 1338 1339 // Only allow void types for memory constraints. 1340 if (Info.allowsMemory() && !Info.allowsRegister()) { 1341 if (CheckAsmLValue(InputExpr, *this)) 1342 return StmtError(Diag(InputExpr->getLocStart(), 1343 diag::err_asm_invalid_lvalue_in_input) 1344 << Info.getConstraintStr() 1345 << InputExpr->getSourceRange()); 1346 } 1347 1348 if (Info.allowsRegister()) { 1349 if (InputExpr->getType()->isVoidType()) { 1350 return StmtError(Diag(InputExpr->getLocStart(), 1351 diag::err_asm_invalid_type_in_input) 1352 << InputExpr->getType() << Info.getConstraintStr() 1353 << InputExpr->getSourceRange()); 1354 } 1355 } 1356 1357 DefaultFunctionArrayLvalueConversion(Exprs[i]); 1358 1359 InputConstraintInfos.push_back(Info); 1360 } 1361 1362 // Check that the clobbers are valid. 1363 for (unsigned i = 0; i != NumClobbers; i++) { 1364 StringLiteral *Literal = Clobbers[i]; 1365 if (Literal->isWide()) 1366 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 1367 << Literal->getSourceRange()); 1368 1369 llvm::StringRef Clobber = Literal->getString(); 1370 1371 if (!Context.Target.isValidGCCRegisterName(Clobber)) 1372 return StmtError(Diag(Literal->getLocStart(), 1373 diag::err_asm_unknown_register_name) << Clobber); 1374 } 1375 1376 constraints.release(); 1377 exprs.release(); 1378 asmString.release(); 1379 clobbers.release(); 1380 AsmStmt *NS = 1381 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm, 1382 NumOutputs, NumInputs, Names, Constraints, Exprs, 1383 AsmString, NumClobbers, Clobbers, RParenLoc); 1384 // Validate the asm string, ensuring it makes sense given the operands we 1385 // have. 1386 llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces; 1387 unsigned DiagOffs; 1388 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) { 1389 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID) 1390 << AsmString->getSourceRange(); 1391 DeleteStmt(NS); 1392 return StmtError(); 1393 } 1394 1395 // Validate tied input operands for type mismatches. 1396 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) { 1397 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i]; 1398 1399 // If this is a tied constraint, verify that the output and input have 1400 // either exactly the same type, or that they are int/ptr operands with the 1401 // same size (int/long, int*/long, are ok etc). 1402 if (!Info.hasTiedOperand()) continue; 1403 1404 unsigned TiedTo = Info.getTiedOperand(); 1405 Expr *OutputExpr = Exprs[TiedTo]; 1406 Expr *InputExpr = Exprs[i+NumOutputs]; 1407 QualType InTy = InputExpr->getType(); 1408 QualType OutTy = OutputExpr->getType(); 1409 if (Context.hasSameType(InTy, OutTy)) 1410 continue; // All types can be tied to themselves. 1411 1412 // Decide if the input and output are in the same domain (integer/ptr or 1413 // floating point. 1414 enum AsmDomain { 1415 AD_Int, AD_FP, AD_Other 1416 } InputDomain, OutputDomain; 1417 1418 if (InTy->isIntegerType() || InTy->isPointerType()) 1419 InputDomain = AD_Int; 1420 else if (InTy->isRealFloatingType()) 1421 InputDomain = AD_FP; 1422 else 1423 InputDomain = AD_Other; 1424 1425 if (OutTy->isIntegerType() || OutTy->isPointerType()) 1426 OutputDomain = AD_Int; 1427 else if (OutTy->isRealFloatingType()) 1428 OutputDomain = AD_FP; 1429 else 1430 OutputDomain = AD_Other; 1431 1432 // They are ok if they are the same size and in the same domain. This 1433 // allows tying things like: 1434 // void* to int* 1435 // void* to int if they are the same size. 1436 // double to long double if they are the same size. 1437 // 1438 uint64_t OutSize = Context.getTypeSize(OutTy); 1439 uint64_t InSize = Context.getTypeSize(InTy); 1440 if (OutSize == InSize && InputDomain == OutputDomain && 1441 InputDomain != AD_Other) 1442 continue; 1443 1444 // If the smaller input/output operand is not mentioned in the asm string, 1445 // then we can promote it and the asm string won't notice. Check this 1446 // case now. 1447 bool SmallerValueMentioned = false; 1448 for (unsigned p = 0, e = Pieces.size(); p != e; ++p) { 1449 AsmStmt::AsmStringPiece &Piece = Pieces[p]; 1450 if (!Piece.isOperand()) continue; 1451 1452 // If this is a reference to the input and if the input was the smaller 1453 // one, then we have to reject this asm. 1454 if (Piece.getOperandNo() == i+NumOutputs) { 1455 if (InSize < OutSize) { 1456 SmallerValueMentioned = true; 1457 break; 1458 } 1459 } 1460 1461 // If this is a reference to the input and if the input was the smaller 1462 // one, then we have to reject this asm. 1463 if (Piece.getOperandNo() == TiedTo) { 1464 if (InSize > OutSize) { 1465 SmallerValueMentioned = true; 1466 break; 1467 } 1468 } 1469 } 1470 1471 // If the smaller value wasn't mentioned in the asm string, and if the 1472 // output was a register, just extend the shorter one to the size of the 1473 // larger one. 1474 if (!SmallerValueMentioned && InputDomain != AD_Other && 1475 OutputConstraintInfos[TiedTo].allowsRegister()) 1476 continue; 1477 1478 Diag(InputExpr->getLocStart(), 1479 diag::err_asm_tying_incompatible_types) 1480 << InTy << OutTy << OutputExpr->getSourceRange() 1481 << InputExpr->getSourceRange(); 1482 DeleteStmt(NS); 1483 return StmtError(); 1484 } 1485 1486 return Owned(NS); 1487} 1488 1489Action::OwningStmtResult 1490Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc, 1491 SourceLocation RParen, DeclPtrTy Parm, 1492 StmtArg Body) { 1493 VarDecl *Var = cast_or_null<VarDecl>(Parm.getAs<Decl>()); 1494 if (Var && Var->isInvalidDecl()) 1495 return StmtError(); 1496 1497 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, 1498 Body.takeAs<Stmt>())); 1499} 1500 1501Action::OwningStmtResult 1502Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, StmtArg Body) { 1503 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, 1504 static_cast<Stmt*>(Body.release()))); 1505} 1506 1507Action::OwningStmtResult 1508Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, StmtArg Try, 1509 MultiStmtArg CatchStmts, StmtArg Finally) { 1510 FunctionNeedsScopeChecking() = true; 1511 unsigned NumCatchStmts = CatchStmts.size(); 1512 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try.takeAs<Stmt>(), 1513 (Stmt **)CatchStmts.release(), 1514 NumCatchStmts, 1515 Finally.takeAs<Stmt>())); 1516} 1517 1518Sema::OwningStmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, 1519 ExprArg ThrowE) { 1520 Expr *Throw = static_cast<Expr *>(ThrowE.get()); 1521 if (Throw) { 1522 QualType ThrowType = Throw->getType(); 1523 // Make sure the expression type is an ObjC pointer or "void *". 1524 if (!ThrowType->isDependentType() && 1525 !ThrowType->isObjCObjectPointerType()) { 1526 const PointerType *PT = ThrowType->getAs<PointerType>(); 1527 if (!PT || !PT->getPointeeType()->isVoidType()) 1528 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object) 1529 << Throw->getType() << Throw->getSourceRange()); 1530 } 1531 } 1532 1533 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, ThrowE.takeAs<Expr>())); 1534} 1535 1536Action::OwningStmtResult 1537Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, ExprArg Throw, 1538 Scope *CurScope) { 1539 if (!Throw.get()) { 1540 // @throw without an expression designates a rethrow (which much occur 1541 // in the context of an @catch clause). 1542 Scope *AtCatchParent = CurScope; 1543 while (AtCatchParent && !AtCatchParent->isAtCatchScope()) 1544 AtCatchParent = AtCatchParent->getParent(); 1545 if (!AtCatchParent) 1546 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch)); 1547 } 1548 1549 return BuildObjCAtThrowStmt(AtLoc, move(Throw)); 1550} 1551 1552Action::OwningStmtResult 1553Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, ExprArg SynchExpr, 1554 StmtArg SynchBody) { 1555 FunctionNeedsScopeChecking() = true; 1556 1557 // Make sure the expression type is an ObjC pointer or "void *". 1558 Expr *SyncExpr = static_cast<Expr*>(SynchExpr.get()); 1559 if (!SyncExpr->getType()->isDependentType() && 1560 !SyncExpr->getType()->isObjCObjectPointerType()) { 1561 const PointerType *PT = SyncExpr->getType()->getAs<PointerType>(); 1562 if (!PT || !PT->getPointeeType()->isVoidType()) 1563 return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object) 1564 << SyncExpr->getType() << SyncExpr->getSourceRange()); 1565 } 1566 1567 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, 1568 SynchExpr.takeAs<Stmt>(), 1569 SynchBody.takeAs<Stmt>())); 1570} 1571 1572/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block 1573/// and creates a proper catch handler from them. 1574Action::OwningStmtResult 1575Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, DeclPtrTy ExDecl, 1576 StmtArg HandlerBlock) { 1577 // There's nothing to test that ActOnExceptionDecl didn't already test. 1578 return Owned(new (Context) CXXCatchStmt(CatchLoc, 1579 cast_or_null<VarDecl>(ExDecl.getAs<Decl>()), 1580 HandlerBlock.takeAs<Stmt>())); 1581} 1582 1583class TypeWithHandler { 1584 QualType t; 1585 CXXCatchStmt *stmt; 1586public: 1587 TypeWithHandler(const QualType &type, CXXCatchStmt *statement) 1588 : t(type), stmt(statement) {} 1589 1590 // An arbitrary order is fine as long as it places identical 1591 // types next to each other. 1592 bool operator<(const TypeWithHandler &y) const { 1593 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr()) 1594 return true; 1595 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr()) 1596 return false; 1597 else 1598 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc(); 1599 } 1600 1601 bool operator==(const TypeWithHandler& other) const { 1602 return t == other.t; 1603 } 1604 1605 QualType getQualType() const { return t; } 1606 CXXCatchStmt *getCatchStmt() const { return stmt; } 1607 SourceLocation getTypeSpecStartLoc() const { 1608 return stmt->getExceptionDecl()->getTypeSpecStartLoc(); 1609 } 1610}; 1611 1612/// ActOnCXXTryBlock - Takes a try compound-statement and a number of 1613/// handlers and creates a try statement from them. 1614Action::OwningStmtResult 1615Sema::ActOnCXXTryBlock(SourceLocation TryLoc, StmtArg TryBlock, 1616 MultiStmtArg RawHandlers) { 1617 unsigned NumHandlers = RawHandlers.size(); 1618 assert(NumHandlers > 0 && 1619 "The parser shouldn't call this if there are no handlers."); 1620 Stmt **Handlers = reinterpret_cast<Stmt**>(RawHandlers.get()); 1621 1622 llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers; 1623 1624 for (unsigned i = 0; i < NumHandlers; ++i) { 1625 CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]); 1626 if (!Handler->getExceptionDecl()) { 1627 if (i < NumHandlers - 1) 1628 return StmtError(Diag(Handler->getLocStart(), 1629 diag::err_early_catch_all)); 1630 1631 continue; 1632 } 1633 1634 const QualType CaughtType = Handler->getCaughtType(); 1635 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType); 1636 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler)); 1637 } 1638 1639 // Detect handlers for the same type as an earlier one. 1640 if (NumHandlers > 1) { 1641 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end()); 1642 1643 TypeWithHandler prev = TypesWithHandlers[0]; 1644 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) { 1645 TypeWithHandler curr = TypesWithHandlers[i]; 1646 1647 if (curr == prev) { 1648 Diag(curr.getTypeSpecStartLoc(), 1649 diag::warn_exception_caught_by_earlier_handler) 1650 << curr.getCatchStmt()->getCaughtType().getAsString(); 1651 Diag(prev.getTypeSpecStartLoc(), 1652 diag::note_previous_exception_handler) 1653 << prev.getCatchStmt()->getCaughtType().getAsString(); 1654 } 1655 1656 prev = curr; 1657 } 1658 } 1659 1660 // FIXME: We should detect handlers that cannot catch anything because an 1661 // earlier handler catches a superclass. Need to find a method that is not 1662 // quadratic for this. 1663 // Neither of these are explicitly forbidden, but every compiler detects them 1664 // and warns. 1665 1666 FunctionNeedsScopeChecking() = true; 1667 RawHandlers.release(); 1668 return Owned(CXXTryStmt::Create(Context, TryLoc, 1669 static_cast<Stmt*>(TryBlock.release()), 1670 Handlers, NumHandlers)); 1671} 1672