SemaStmt.cpp revision 4afa39deaa245592977136d367251ee2c173dd8d
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 "clang/AST/APValue.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/DeclObjC.h" 18#include "clang/AST/Expr.h" 19#include "clang/Basic/TargetInfo.h" 20#include "clang/Basic/Diagnostic.h" 21using namespace clang; 22 23Sema::OwningStmtResult Sema::ActOnExprStmt(ExprArg expr) { 24 Expr *E = static_cast<Expr*>(expr.release()); 25 assert(E && "ActOnExprStmt(): missing expression"); 26 27 // C99 6.8.3p2: The expression in an expression statement is evaluated as a 28 // void expression for its side effects. Conversion to void allows any 29 // operand, even incomplete types. 30 31 // Same thing in for stmt first clause (when expr) and third clause. 32 return Owned(static_cast<Stmt*>(E)); 33} 34 35 36Sema::OwningStmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc) { 37 return Owned(new NullStmt(SemiLoc)); 38} 39 40Sema::OwningStmtResult Sema::ActOnDeclStmt(DeclTy *decl, 41 SourceLocation StartLoc, 42 SourceLocation EndLoc) { 43 if (decl == 0) 44 return StmtError(); 45 46 Decl *D = static_cast<Decl *>(decl); 47 48 // This is a temporary hack until we are always passing around 49 // DeclGroupRefs. 50 llvm::SmallVector<Decl*, 10> decls; 51 while (D) { 52 Decl* d = D; 53 D = D->getNextDeclarator(); 54 d->setNextDeclarator(0); 55 decls.push_back(d); 56 } 57 58 assert (!decls.empty()); 59 60 if (decls.size() == 1) { 61 DeclGroupOwningRef DG(*decls.begin()); 62 return Owned(new DeclStmt(DG, StartLoc, EndLoc)); 63 } 64 else { 65 DeclGroupOwningRef DG(DeclGroup::Create(Context, decls.size(), &decls[0])); 66 return Owned(new DeclStmt(DG, StartLoc, EndLoc)); 67 } 68} 69 70Action::OwningStmtResult 71Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R, 72 MultiStmtArg elts, bool isStmtExpr) { 73 unsigned NumElts = elts.size(); 74 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release()); 75 // If we're in C89 mode, check that we don't have any decls after stmts. If 76 // so, emit an extension diagnostic. 77 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) { 78 // Note that __extension__ can be around a decl. 79 unsigned i = 0; 80 // Skip over all declarations. 81 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i) 82 /*empty*/; 83 84 // We found the end of the list or a statement. Scan for another declstmt. 85 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i) 86 /*empty*/; 87 88 if (i != NumElts) { 89 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin(); 90 Diag(D->getLocation(), diag::ext_mixed_decls_code); 91 } 92 } 93 // Warn about unused expressions in statements. 94 for (unsigned i = 0; i != NumElts; ++i) { 95 Expr *E = dyn_cast<Expr>(Elts[i]); 96 if (!E) continue; 97 98 // Warn about expressions with unused results. 99 if (E->hasLocalSideEffect() || E->getType()->isVoidType()) 100 continue; 101 102 // The last expr in a stmt expr really is used. 103 if (isStmtExpr && i == NumElts-1) 104 continue; 105 106 /// DiagnoseDeadExpr - This expression is side-effect free and evaluated in 107 /// a context where the result is unused. Emit a diagnostic to warn about 108 /// this. 109 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) 110 Diag(BO->getOperatorLoc(), diag::warn_unused_expr) 111 << BO->getLHS()->getSourceRange() << BO->getRHS()->getSourceRange(); 112 else if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) 113 Diag(UO->getOperatorLoc(), diag::warn_unused_expr) 114 << UO->getSubExpr()->getSourceRange(); 115 else 116 Diag(E->getExprLoc(), diag::warn_unused_expr) << E->getSourceRange(); 117 } 118 119 return Owned(new CompoundStmt(Elts, NumElts, L, R)); 120} 121 122Action::OwningStmtResult 123Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprArg lhsval, 124 SourceLocation DotDotDotLoc, ExprArg rhsval, 125 SourceLocation ColonLoc, StmtArg subStmt) { 126 Stmt *SubStmt = static_cast<Stmt*>(subStmt.release()); 127 assert((lhsval.get() != 0) && "missing expression in case statement"); 128 129 // C99 6.8.4.2p3: The expression shall be an integer constant. 130 // However, GCC allows any evaluatable integer expression. 131 132 Expr *LHSVal = static_cast<Expr*>(lhsval.get()); 133 if (VerifyIntegerConstantExpression(LHSVal)) 134 return Owned(SubStmt); 135 136 // GCC extension: The expression shall be an integer constant. 137 138 Expr *RHSVal = static_cast<Expr*>(rhsval.get()); 139 if (RHSVal && VerifyIntegerConstantExpression(RHSVal)) { 140 RHSVal = 0; // Recover by just forgetting about it. 141 rhsval = 0; 142 } 143 144 if (SwitchStack.empty()) { 145 Diag(CaseLoc, diag::err_case_not_in_switch); 146 return Owned(SubStmt); 147 } 148 149 // Only now release the smart pointers. 150 lhsval.release(); 151 rhsval.release(); 152 CaseStmt *CS = new CaseStmt(LHSVal, RHSVal, SubStmt, CaseLoc); 153 SwitchStack.back()->addSwitchCase(CS); 154 return Owned(CS); 155} 156 157Action::OwningStmtResult 158Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, 159 StmtArg subStmt, Scope *CurScope) { 160 Stmt *SubStmt = static_cast<Stmt*>(subStmt.release()); 161 162 if (SwitchStack.empty()) { 163 Diag(DefaultLoc, diag::err_default_not_in_switch); 164 return Owned(SubStmt); 165 } 166 167 DefaultStmt *DS = new DefaultStmt(DefaultLoc, SubStmt); 168 SwitchStack.back()->addSwitchCase(DS); 169 return Owned(DS); 170} 171 172Action::OwningStmtResult 173Sema::ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II, 174 SourceLocation ColonLoc, StmtArg subStmt) { 175 Stmt *SubStmt = static_cast<Stmt*>(subStmt.release()); 176 // Look up the record for this label identifier. 177 LabelStmt *&LabelDecl = LabelMap[II]; 178 179 // If not forward referenced or defined already, just create a new LabelStmt. 180 if (LabelDecl == 0) 181 return Owned(LabelDecl = new LabelStmt(IdentLoc, II, SubStmt)); 182 183 assert(LabelDecl->getID() == II && "Label mismatch!"); 184 185 // Otherwise, this label was either forward reference or multiply defined. If 186 // multiply defined, reject it now. 187 if (LabelDecl->getSubStmt()) { 188 Diag(IdentLoc, diag::err_redefinition_of_label) << LabelDecl->getID(); 189 Diag(LabelDecl->getIdentLoc(), diag::note_previous_definition); 190 return Owned(SubStmt); 191 } 192 193 // Otherwise, this label was forward declared, and we just found its real 194 // definition. Fill in the forward definition and return it. 195 LabelDecl->setIdentLoc(IdentLoc); 196 LabelDecl->setSubStmt(SubStmt); 197 return Owned(LabelDecl); 198} 199 200Action::OwningStmtResult 201Sema::ActOnIfStmt(SourceLocation IfLoc, ExprArg CondVal, 202 StmtArg ThenVal, SourceLocation ElseLoc, 203 StmtArg ElseVal) { 204 Expr *condExpr = (Expr *)CondVal.release(); 205 206 assert(condExpr && "ActOnIfStmt(): missing expression"); 207 208 DefaultFunctionArrayConversion(condExpr); 209 // Take ownership again until we're past the error checking. 210 CondVal = condExpr; 211 QualType condType = condExpr->getType(); 212 213 if (getLangOptions().CPlusPlus) { 214 if (CheckCXXBooleanCondition(condExpr)) // C++ 6.4p4 215 return StmtError(); 216 } else if (!condType->isScalarType()) // C99 6.8.4.1p1 217 return StmtError(Diag(IfLoc, diag::err_typecheck_statement_requires_scalar) 218 << condType << condExpr->getSourceRange()); 219 220 Stmt *thenStmt = (Stmt *)ThenVal.release(); 221 222 // Warn if the if block has a null body without an else value. 223 // this helps prevent bugs due to typos, such as 224 // if (condition); 225 // do_stuff(); 226 if (!ElseVal.get()) { 227 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt)) 228 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body); 229 } 230 231 CondVal.release(); 232 return Owned(new IfStmt(IfLoc, condExpr, thenStmt, (Stmt*)ElseVal.release())); 233} 234 235Action::OwningStmtResult 236Sema::ActOnStartOfSwitchStmt(ExprArg cond) { 237 Expr *Cond = static_cast<Expr*>(cond.release()); 238 239 if (getLangOptions().CPlusPlus) { 240 // C++ 6.4.2.p2: 241 // The condition shall be of integral type, enumeration type, or of a class 242 // type for which a single conversion function to integral or enumeration 243 // type exists (12.3). If the condition is of class type, the condition is 244 // converted by calling that conversion function, and the result of the 245 // conversion is used in place of the original condition for the remainder 246 // of this section. Integral promotions are performed. 247 248 QualType Ty = Cond->getType(); 249 250 // FIXME: Handle class types. 251 252 // If the type is wrong a diagnostic will be emitted later at 253 // ActOnFinishSwitchStmt. 254 if (Ty->isIntegralType() || Ty->isEnumeralType()) { 255 // Integral promotions are performed. 256 // FIXME: Integral promotions for C++ are not complete. 257 UsualUnaryConversions(Cond); 258 } 259 } else { 260 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr. 261 UsualUnaryConversions(Cond); 262 } 263 264 SwitchStmt *SS = new SwitchStmt(Cond); 265 SwitchStack.push_back(SS); 266 return Owned(SS); 267} 268 269/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 270/// the specified width and sign. If an overflow occurs, detect it and emit 271/// the specified diagnostic. 272void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val, 273 unsigned NewWidth, bool NewSign, 274 SourceLocation Loc, 275 unsigned DiagID) { 276 // Perform a conversion to the promoted condition type if needed. 277 if (NewWidth > Val.getBitWidth()) { 278 // If this is an extension, just do it. 279 llvm::APSInt OldVal(Val); 280 Val.extend(NewWidth); 281 282 // If the input was signed and negative and the output is unsigned, 283 // warn. 284 if (!NewSign && OldVal.isSigned() && OldVal.isNegative()) 285 Diag(Loc, DiagID) << OldVal.toString(10) << Val.toString(10); 286 287 Val.setIsSigned(NewSign); 288 } else if (NewWidth < Val.getBitWidth()) { 289 // If this is a truncation, check for overflow. 290 llvm::APSInt ConvVal(Val); 291 ConvVal.trunc(NewWidth); 292 ConvVal.setIsSigned(NewSign); 293 ConvVal.extend(Val.getBitWidth()); 294 ConvVal.setIsSigned(Val.isSigned()); 295 if (ConvVal != Val) 296 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10); 297 298 // Regardless of whether a diagnostic was emitted, really do the 299 // truncation. 300 Val.trunc(NewWidth); 301 Val.setIsSigned(NewSign); 302 } else if (NewSign != Val.isSigned()) { 303 // Convert the sign to match the sign of the condition. This can cause 304 // overflow as well: unsigned(INTMIN) 305 llvm::APSInt OldVal(Val); 306 Val.setIsSigned(NewSign); 307 308 if (Val.isNegative()) // Sign bit changes meaning. 309 Diag(Loc, DiagID) << OldVal.toString(10) << Val.toString(10); 310 } 311} 312 313namespace { 314 struct CaseCompareFunctor { 315 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 316 const llvm::APSInt &RHS) { 317 return LHS.first < RHS; 318 } 319 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 320 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 321 return LHS.first < RHS.first; 322 } 323 bool operator()(const llvm::APSInt &LHS, 324 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 325 return LHS < RHS.first; 326 } 327 }; 328} 329 330/// CmpCaseVals - Comparison predicate for sorting case values. 331/// 332static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs, 333 const std::pair<llvm::APSInt, CaseStmt*>& rhs) { 334 if (lhs.first < rhs.first) 335 return true; 336 337 if (lhs.first == rhs.first && 338 lhs.second->getCaseLoc().getRawEncoding() 339 < rhs.second->getCaseLoc().getRawEncoding()) 340 return true; 341 return false; 342} 343 344Action::OwningStmtResult 345Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, StmtArg Switch, 346 StmtArg Body) { 347 Stmt *BodyStmt = (Stmt*)Body.release(); 348 349 SwitchStmt *SS = SwitchStack.back(); 350 assert(SS == (SwitchStmt*)Switch.get() && "switch stack missing push/pop!"); 351 352 SS->setBody(BodyStmt, SwitchLoc); 353 SwitchStack.pop_back(); 354 355 Expr *CondExpr = SS->getCond(); 356 QualType CondType = CondExpr->getType(); 357 358 if (!CondType->isIntegerType()) { // C99 6.8.4.2p1 359 Diag(SwitchLoc, diag::err_typecheck_statement_requires_integer) 360 << CondType << CondExpr->getSourceRange(); 361 return StmtError(); 362 } 363 364 // Get the bitwidth of the switched-on value before promotions. We must 365 // convert the integer case values to this width before comparison. 366 unsigned CondWidth = static_cast<unsigned>(Context.getTypeSize(CondType)); 367 bool CondIsSigned = CondType->isSignedIntegerType(); 368 369 // Accumulate all of the case values in a vector so that we can sort them 370 // and detect duplicates. This vector contains the APInt for the case after 371 // it has been converted to the condition type. 372 typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy; 373 CaseValsTy CaseVals; 374 375 // Keep track of any GNU case ranges we see. The APSInt is the low value. 376 std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRanges; 377 378 DefaultStmt *TheDefaultStmt = 0; 379 380 bool CaseListIsErroneous = false; 381 382 for (SwitchCase *SC = SS->getSwitchCaseList(); SC; 383 SC = SC->getNextSwitchCase()) { 384 385 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) { 386 if (TheDefaultStmt) { 387 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined); 388 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev); 389 390 // FIXME: Remove the default statement from the switch block so that 391 // we'll return a valid AST. This requires recursing down the 392 // AST and finding it, not something we are set up to do right now. For 393 // now, just lop the entire switch stmt out of the AST. 394 CaseListIsErroneous = true; 395 } 396 TheDefaultStmt = DS; 397 398 } else { 399 CaseStmt *CS = cast<CaseStmt>(SC); 400 401 // We already verified that the expression has a i-c-e value (C99 402 // 6.8.4.2p3) - get that value now. 403 Expr *Lo = CS->getLHS(); 404 llvm::APSInt LoVal = Lo->EvaluateAsInt(Context); 405 406 // Convert the value to the same width/sign as the condition. 407 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned, 408 CS->getLHS()->getLocStart(), 409 diag::warn_case_value_overflow); 410 411 // If the LHS is not the same type as the condition, insert an implicit 412 // cast. 413 ImpCastExprToType(Lo, CondType); 414 CS->setLHS(Lo); 415 416 // If this is a case range, remember it in CaseRanges, otherwise CaseVals. 417 if (CS->getRHS()) 418 CaseRanges.push_back(std::make_pair(LoVal, CS)); 419 else 420 CaseVals.push_back(std::make_pair(LoVal, CS)); 421 } 422 } 423 424 // Sort all the scalar case values so we can easily detect duplicates. 425 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals); 426 427 if (!CaseVals.empty()) { 428 for (unsigned i = 0, e = CaseVals.size()-1; i != e; ++i) { 429 if (CaseVals[i].first == CaseVals[i+1].first) { 430 // If we have a duplicate, report it. 431 Diag(CaseVals[i+1].second->getLHS()->getLocStart(), 432 diag::err_duplicate_case) << CaseVals[i].first.toString(10); 433 Diag(CaseVals[i].second->getLHS()->getLocStart(), 434 diag::note_duplicate_case_prev); 435 // FIXME: We really want to remove the bogus case stmt from the substmt, 436 // but we have no way to do this right now. 437 CaseListIsErroneous = true; 438 } 439 } 440 } 441 442 // Detect duplicate case ranges, which usually don't exist at all in the first 443 // place. 444 if (!CaseRanges.empty()) { 445 // Sort all the case ranges by their low value so we can easily detect 446 // overlaps between ranges. 447 std::stable_sort(CaseRanges.begin(), CaseRanges.end()); 448 449 // Scan the ranges, computing the high values and removing empty ranges. 450 std::vector<llvm::APSInt> HiVals; 451 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 452 CaseStmt *CR = CaseRanges[i].second; 453 Expr *Hi = CR->getRHS(); 454 llvm::APSInt HiVal = Hi->EvaluateAsInt(Context); 455 456 // Convert the value to the same width/sign as the condition. 457 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned, 458 CR->getRHS()->getLocStart(), 459 diag::warn_case_value_overflow); 460 461 // If the LHS is not the same type as the condition, insert an implicit 462 // cast. 463 ImpCastExprToType(Hi, CondType); 464 CR->setRHS(Hi); 465 466 // If the low value is bigger than the high value, the case is empty. 467 if (CaseRanges[i].first > HiVal) { 468 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range) 469 << SourceRange(CR->getLHS()->getLocStart(), 470 CR->getRHS()->getLocEnd()); 471 CaseRanges.erase(CaseRanges.begin()+i); 472 --i, --e; 473 continue; 474 } 475 HiVals.push_back(HiVal); 476 } 477 478 // Rescan the ranges, looking for overlap with singleton values and other 479 // ranges. Since the range list is sorted, we only need to compare case 480 // ranges with their neighbors. 481 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 482 llvm::APSInt &CRLo = CaseRanges[i].first; 483 llvm::APSInt &CRHi = HiVals[i]; 484 CaseStmt *CR = CaseRanges[i].second; 485 486 // Check to see whether the case range overlaps with any singleton cases. 487 CaseStmt *OverlapStmt = 0; 488 llvm::APSInt OverlapVal(32); 489 490 // Find the smallest value >= the lower bound. If I is in the case range, 491 // then we have overlap. 492 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(), 493 CaseVals.end(), CRLo, 494 CaseCompareFunctor()); 495 if (I != CaseVals.end() && I->first < CRHi) { 496 OverlapVal = I->first; // Found overlap with scalar. 497 OverlapStmt = I->second; 498 } 499 500 // Find the smallest value bigger than the upper bound. 501 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor()); 502 if (I != CaseVals.begin() && (I-1)->first >= CRLo) { 503 OverlapVal = (I-1)->first; // Found overlap with scalar. 504 OverlapStmt = (I-1)->second; 505 } 506 507 // Check to see if this case stmt overlaps with the subsequent case range. 508 if (i && CRLo <= HiVals[i-1]) { 509 OverlapVal = HiVals[i-1]; // Found overlap with range. 510 OverlapStmt = CaseRanges[i-1].second; 511 } 512 513 if (OverlapStmt) { 514 // If we have a duplicate, report it. 515 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case) 516 << OverlapVal.toString(10); 517 Diag(OverlapStmt->getLHS()->getLocStart(), 518 diag::note_duplicate_case_prev); 519 // FIXME: We really want to remove the bogus case stmt from the substmt, 520 // but we have no way to do this right now. 521 CaseListIsErroneous = true; 522 } 523 } 524 } 525 526 // FIXME: If the case list was broken is some way, we don't have a good system 527 // to patch it up. Instead, just return the whole substmt as broken. 528 if (CaseListIsErroneous) 529 return StmtError(); 530 531 Switch.release(); 532 return Owned(SS); 533} 534 535Action::OwningStmtResult 536Sema::ActOnWhileStmt(SourceLocation WhileLoc, ExprArg Cond, StmtArg Body) { 537 Expr *condExpr = (Expr *)Cond.release(); 538 assert(condExpr && "ActOnWhileStmt(): missing expression"); 539 540 DefaultFunctionArrayConversion(condExpr); 541 Cond = condExpr; 542 QualType condType = condExpr->getType(); 543 544 if (getLangOptions().CPlusPlus) { 545 if (CheckCXXBooleanCondition(condExpr)) // C++ 6.4p4 546 return StmtError(); 547 } else if (!condType->isScalarType()) // C99 6.8.5p2 548 return StmtError(Diag(WhileLoc, 549 diag::err_typecheck_statement_requires_scalar) 550 << condType << condExpr->getSourceRange()); 551 552 Cond.release(); 553 return Owned(new WhileStmt(condExpr, (Stmt*)Body.release(), WhileLoc)); 554} 555 556Action::OwningStmtResult 557Sema::ActOnDoStmt(SourceLocation DoLoc, StmtArg Body, 558 SourceLocation WhileLoc, ExprArg Cond) { 559 Expr *condExpr = (Expr *)Cond.release(); 560 assert(condExpr && "ActOnDoStmt(): missing expression"); 561 562 DefaultFunctionArrayConversion(condExpr); 563 Cond = condExpr; 564 QualType condType = condExpr->getType(); 565 566 if (getLangOptions().CPlusPlus) { 567 if (CheckCXXBooleanCondition(condExpr)) // C++ 6.4p4 568 return StmtError(); 569 } else if (!condType->isScalarType()) // C99 6.8.5p2 570 return StmtError(Diag(DoLoc, diag::err_typecheck_statement_requires_scalar) 571 << condType << condExpr->getSourceRange()); 572 573 Cond.release(); 574 return Owned(new DoStmt((Stmt*)Body.release(), condExpr, DoLoc)); 575} 576 577Action::OwningStmtResult 578Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 579 StmtArg first, ExprArg second, ExprArg third, 580 SourceLocation RParenLoc, StmtArg body) { 581 Stmt *First = static_cast<Stmt*>(first.get()); 582 Expr *Second = static_cast<Expr*>(second.get()); 583 Expr *Third = static_cast<Expr*>(third.get()); 584 Stmt *Body = static_cast<Stmt*>(body.get()); 585 586 if (!getLangOptions().CPlusPlus) { 587 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) { 588 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 589 // declare identifiers for objects having storage class 'auto' or 590 // 'register'. 591 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end(); 592 DI!=DE; ++DI) { 593 VarDecl *VD = dyn_cast<VarDecl>(*DI); 594 if (VD && VD->isBlockVarDecl() && !VD->hasLocalStorage()) 595 VD = 0; 596 if (VD == 0) 597 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for); 598 // FIXME: mark decl erroneous! 599 } 600 } 601 } 602 if (Second) { 603 DefaultFunctionArrayConversion(Second); 604 QualType SecondType = Second->getType(); 605 606 if (getLangOptions().CPlusPlus) { 607 if (CheckCXXBooleanCondition(Second)) // C++ 6.4p4 608 return StmtError(); 609 } else if (!SecondType->isScalarType()) // C99 6.8.5p2 610 return StmtError(Diag(ForLoc, 611 diag::err_typecheck_statement_requires_scalar) 612 << SecondType << Second->getSourceRange()); 613 } 614 first.release(); 615 second.release(); 616 third.release(); 617 body.release(); 618 return Owned(new ForStmt(First, Second, Third, Body, ForLoc)); 619} 620 621Action::OwningStmtResult 622Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc, 623 SourceLocation LParenLoc, 624 StmtArg first, ExprArg second, 625 SourceLocation RParenLoc, StmtArg body) { 626 Stmt *First = static_cast<Stmt*>(first.get()); 627 Expr *Second = static_cast<Expr*>(second.get()); 628 Stmt *Body = static_cast<Stmt*>(body.get()); 629 if (First) { 630 QualType FirstType; 631 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) { 632 if (!DS->hasSolitaryDecl()) 633 return StmtError(Diag((*DS->decl_begin())->getLocation(), 634 diag::err_toomany_element_decls)); 635 636 Decl *D = DS->getSolitaryDecl(); 637 FirstType = cast<ValueDecl>(D)->getType(); 638 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 639 // declare identifiers for objects having storage class 'auto' or 640 // 'register'. 641 VarDecl *VD = cast<VarDecl>(D); 642 if (VD->isBlockVarDecl() && !VD->hasLocalStorage()) 643 return StmtError(Diag(VD->getLocation(), 644 diag::err_non_variable_decl_in_for)); 645 } else { 646 Expr::isLvalueResult lval = cast<Expr>(First)->isLvalue(Context); 647 648 if (lval != Expr::LV_Valid) 649 return StmtError(Diag(First->getLocStart(), 650 diag::err_selector_element_not_lvalue) 651 << First->getSourceRange()); 652 653 FirstType = static_cast<Expr*>(First)->getType(); 654 } 655 if (!Context.isObjCObjectPointerType(FirstType)) 656 Diag(ForLoc, diag::err_selector_element_type) 657 << FirstType << First->getSourceRange(); 658 } 659 if (Second) { 660 DefaultFunctionArrayConversion(Second); 661 QualType SecondType = Second->getType(); 662 if (!Context.isObjCObjectPointerType(SecondType)) 663 Diag(ForLoc, diag::err_collection_expr_type) 664 << SecondType << Second->getSourceRange(); 665 } 666 first.release(); 667 second.release(); 668 body.release(); 669 return Owned(new ObjCForCollectionStmt(First, Second, Body, 670 ForLoc, RParenLoc)); 671} 672 673Action::OwningStmtResult 674Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, 675 IdentifierInfo *LabelII) { 676 // If we are in a block, reject all gotos for now. 677 if (CurBlock) 678 return StmtError(Diag(GotoLoc, diag::err_goto_in_block)); 679 680 // Look up the record for this label identifier. 681 LabelStmt *&LabelDecl = LabelMap[LabelII]; 682 683 // If we haven't seen this label yet, create a forward reference. 684 if (LabelDecl == 0) 685 LabelDecl = new LabelStmt(LabelLoc, LabelII, 0); 686 687 return Owned(new GotoStmt(LabelDecl, GotoLoc, LabelLoc)); 688} 689 690Action::OwningStmtResult 691Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc,SourceLocation StarLoc, 692 ExprArg DestExp) { 693 // FIXME: Verify that the operand is convertible to void*. 694 695 return Owned(new IndirectGotoStmt((Expr*)DestExp.release())); 696} 697 698Action::OwningStmtResult 699Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) { 700 Scope *S = CurScope->getContinueParent(); 701 if (!S) { 702 // C99 6.8.6.2p1: A break shall appear only in or as a loop body. 703 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop)); 704 } 705 706 return Owned(new ContinueStmt(ContinueLoc)); 707} 708 709Action::OwningStmtResult 710Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) { 711 Scope *S = CurScope->getBreakParent(); 712 if (!S) { 713 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body. 714 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch)); 715 } 716 717 return Owned(new BreakStmt(BreakLoc)); 718} 719 720/// ActOnBlockReturnStmt - Utility routine to figure out block's return type. 721/// 722Action::OwningStmtResult 723Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 724 725 // If this is the first return we've seen in the block, infer the type of 726 // the block from it. 727 if (CurBlock->ReturnType == 0) { 728 if (RetValExp) { 729 // Don't call UsualUnaryConversions(), since we don't want to do 730 // integer promotions here. 731 DefaultFunctionArrayConversion(RetValExp); 732 CurBlock->ReturnType = RetValExp->getType().getTypePtr(); 733 } else 734 CurBlock->ReturnType = Context.VoidTy.getTypePtr(); 735 return Owned(new ReturnStmt(ReturnLoc, RetValExp)); 736 } 737 738 // Otherwise, verify that this result type matches the previous one. We are 739 // pickier with blocks than for normal functions because we don't have GCC 740 // compatibility to worry about here. 741 if (CurBlock->ReturnType->isVoidType()) { 742 if (RetValExp) { 743 Diag(ReturnLoc, diag::err_return_block_has_expr); 744 delete RetValExp; 745 RetValExp = 0; 746 } 747 return Owned(new ReturnStmt(ReturnLoc, RetValExp)); 748 } 749 750 if (!RetValExp) 751 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr)); 752 753 // we have a non-void block with an expression, continue checking 754 QualType RetValType = RetValExp->getType(); 755 756 // For now, restrict multiple return statements in a block to have 757 // strict compatible types only. 758 QualType BlockQT = QualType(CurBlock->ReturnType, 0); 759 if (Context.getCanonicalType(BlockQT).getTypePtr() 760 != Context.getCanonicalType(RetValType).getTypePtr()) { 761 // FIXME: non-localizable string in diagnostic 762 DiagnoseAssignmentResult(Incompatible, ReturnLoc, BlockQT, 763 RetValType, RetValExp, "returning"); 764 return StmtError(); 765 } 766 767 if (RetValExp) CheckReturnStackAddr(RetValExp, BlockQT, ReturnLoc); 768 769 return Owned(new ReturnStmt(ReturnLoc, RetValExp)); 770} 771 772Action::OwningStmtResult 773Sema::ActOnReturnStmt(SourceLocation ReturnLoc, ExprArg rex) { 774 Expr *RetValExp = static_cast<Expr *>(rex.release()); 775 if (CurBlock) 776 return ActOnBlockReturnStmt(ReturnLoc, RetValExp); 777 778 QualType FnRetType; 779 if (FunctionDecl *FD = getCurFunctionDecl()) 780 FnRetType = FD->getResultType(); 781 else 782 FnRetType = getCurMethodDecl()->getResultType(); 783 784 if (FnRetType->isVoidType()) { 785 if (RetValExp) {// C99 6.8.6.4p1 (ext_ since GCC warns) 786 unsigned D = diag::ext_return_has_expr; 787 if (RetValExp->getType()->isVoidType()) 788 D = diag::ext_return_has_void_expr; 789 790 // return (some void expression); is legal in C++. 791 if (D != diag::ext_return_has_void_expr || 792 !getLangOptions().CPlusPlus) { 793 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 794 Diag(ReturnLoc, D) 795 << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl) 796 << RetValExp->getSourceRange(); 797 } 798 } 799 return Owned(new ReturnStmt(ReturnLoc, RetValExp)); 800 } 801 802 if (!RetValExp) { 803 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4 804 // C99 6.8.6.4p1 (ext_ since GCC warns) 805 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr; 806 807 if (FunctionDecl *FD = getCurFunctionDecl()) 808 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/; 809 else 810 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/; 811 return Owned(new ReturnStmt(ReturnLoc, (Expr*)0)); 812 } 813 814 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 815 // we have a non-void function with an expression, continue checking 816 QualType RetValType = RetValExp->getType(); 817 818 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 819 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 820 // function return. 821 822 // In C++ the return statement is handled via a copy initialization. 823 // the C version of which boils down to CheckSingleAssignmentConstraints. 824 // FIXME: Leaks RetValExp. 825 if (PerformCopyInitialization(RetValExp, FnRetType, "returning")) 826 return StmtError(); 827 828 if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 829 } 830 831 return Owned(new ReturnStmt(ReturnLoc, RetValExp)); 832} 833 834Sema::OwningStmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, 835 bool IsSimple, 836 bool IsVolatile, 837 unsigned NumOutputs, 838 unsigned NumInputs, 839 std::string *Names, 840 MultiExprArg constraints, 841 MultiExprArg exprs, 842 ExprArg asmString, 843 MultiExprArg clobbers, 844 SourceLocation RParenLoc) { 845 unsigned NumClobbers = clobbers.size(); 846 StringLiteral **Constraints = 847 reinterpret_cast<StringLiteral**>(constraints.get()); 848 Expr **Exprs = reinterpret_cast<Expr **>(exprs.get()); 849 StringLiteral *AsmString = cast<StringLiteral>((Expr *)asmString.get()); 850 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get()); 851 852 // The parser verifies that there is a string literal here. 853 if (AsmString->isWide()) 854 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character) 855 << AsmString->getSourceRange()); 856 857 858 for (unsigned i = 0; i != NumOutputs; i++) { 859 StringLiteral *Literal = Constraints[i]; 860 if (Literal->isWide()) 861 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 862 << Literal->getSourceRange()); 863 864 std::string OutputConstraint(Literal->getStrData(), 865 Literal->getByteLength()); 866 867 TargetInfo::ConstraintInfo info; 868 if (!Context.Target.validateOutputConstraint(OutputConstraint.c_str(),info)) 869 return StmtError(Diag(Literal->getLocStart(), 870 diag::err_asm_invalid_output_constraint) << OutputConstraint); 871 872 // Check that the output exprs are valid lvalues. 873 ParenExpr *OutputExpr = cast<ParenExpr>(Exprs[i]); 874 Expr::isLvalueResult Result = OutputExpr->isLvalue(Context); 875 if (Result != Expr::LV_Valid) { 876 return StmtError(Diag(OutputExpr->getSubExpr()->getLocStart(), 877 diag::err_asm_invalid_lvalue_in_output) 878 << OutputExpr->getSubExpr()->getSourceRange()); 879 } 880 } 881 882 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) { 883 StringLiteral *Literal = Constraints[i]; 884 if (Literal->isWide()) 885 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 886 << Literal->getSourceRange()); 887 888 std::string InputConstraint(Literal->getStrData(), 889 Literal->getByteLength()); 890 891 TargetInfo::ConstraintInfo info; 892 if (!Context.Target.validateInputConstraint(InputConstraint.c_str(), 893 &Names[0], 894 &Names[0] + NumOutputs, info)) { 895 return StmtError(Diag(Literal->getLocStart(), 896 diag::err_asm_invalid_input_constraint) << InputConstraint); 897 } 898 899 // Check that the input exprs aren't of type void. 900 ParenExpr *InputExpr = cast<ParenExpr>(Exprs[i]); 901 if (InputExpr->getType()->isVoidType()) { 902 903 return StmtError(Diag(InputExpr->getSubExpr()->getLocStart(), 904 diag::err_asm_invalid_type_in_input) 905 << InputExpr->getType() << InputConstraint 906 << InputExpr->getSubExpr()->getSourceRange()); 907 } 908 909 if (info & TargetInfo::CI_AllowsRegister) 910 DefaultFunctionArrayConversion(Exprs[i]); 911 } 912 913 // Check that the clobbers are valid. 914 for (unsigned i = 0; i != NumClobbers; i++) { 915 StringLiteral *Literal = Clobbers[i]; 916 if (Literal->isWide()) 917 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 918 << Literal->getSourceRange()); 919 920 llvm::SmallString<16> Clobber(Literal->getStrData(), 921 Literal->getStrData() + 922 Literal->getByteLength()); 923 924 if (!Context.Target.isValidGCCRegisterName(Clobber.c_str())) 925 return StmtError(Diag(Literal->getLocStart(), 926 diag::err_asm_unknown_register_name) << Clobber.c_str()); 927 } 928 929 constraints.release(); 930 exprs.release(); 931 asmString.release(); 932 clobbers.release(); 933 return Owned(new AsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs, 934 Names, Constraints, Exprs, AsmString, NumClobbers, 935 Clobbers, RParenLoc)); 936} 937 938Action::OwningStmtResult 939Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc, 940 SourceLocation RParen, StmtArg Parm, 941 StmtArg Body, StmtArg catchList) { 942 Stmt *CatchList = static_cast<Stmt*>(catchList.release()); 943 ObjCAtCatchStmt *CS = new ObjCAtCatchStmt(AtLoc, RParen, 944 static_cast<Stmt*>(Parm.release()), static_cast<Stmt*>(Body.release()), 945 CatchList); 946 return Owned(CatchList ? CatchList : CS); 947} 948 949Action::OwningStmtResult 950Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, StmtArg Body) { 951 return Owned(new ObjCAtFinallyStmt(AtLoc, 952 static_cast<Stmt*>(Body.release()))); 953} 954 955Action::OwningStmtResult 956Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, 957 StmtArg Try, StmtArg Catch, StmtArg Finally) { 958 return Owned(new ObjCAtTryStmt(AtLoc, static_cast<Stmt*>(Try.release()), 959 static_cast<Stmt*>(Catch.release()), 960 static_cast<Stmt*>(Finally.release()))); 961} 962 963Action::OwningStmtResult 964Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, ExprArg Throw) { 965 return Owned(new ObjCAtThrowStmt(AtLoc, static_cast<Expr*>(Throw.release()))); 966} 967 968Action::OwningStmtResult 969Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, ExprArg SynchExpr, 970 StmtArg SynchBody) { 971 return Owned(new ObjCAtSynchronizedStmt(AtLoc, 972 static_cast<Stmt*>(SynchExpr.release()), 973 static_cast<Stmt*>(SynchBody.release()))); 974} 975 976/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block 977/// and creates a proper catch handler from them. 978Action::OwningStmtResult 979Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, DeclTy *ExDecl, 980 StmtArg HandlerBlock) { 981 // There's nothing to test that ActOnExceptionDecl didn't already test. 982 return Owned(new CXXCatchStmt(CatchLoc, static_cast<VarDecl*>(ExDecl), 983 static_cast<Stmt*>(HandlerBlock.release()))); 984} 985 986/// ActOnCXXTryBlock - Takes a try compound-statement and a number of 987/// handlers and creates a try statement from them. 988Action::OwningStmtResult 989Sema::ActOnCXXTryBlock(SourceLocation TryLoc, StmtArg TryBlock, 990 MultiStmtArg RawHandlers) { 991 unsigned NumHandlers = RawHandlers.size(); 992 assert(NumHandlers > 0 && 993 "The parser shouldn't call this if there are no handlers."); 994 Stmt **Handlers = reinterpret_cast<Stmt**>(RawHandlers.get()); 995 996 for(unsigned i = 0; i < NumHandlers - 1; ++i) { 997 CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]); 998 if (!Handler->getExceptionDecl()) 999 return StmtError(Diag(Handler->getLocStart(), diag::err_early_catch_all)); 1000 } 1001 // FIXME: We should detect handlers for the same type as an earlier one. 1002 // This one is rather easy. 1003 // FIXME: We should detect handlers that cannot catch anything because an 1004 // earlier handler catches a superclass. Need to find a method that is not 1005 // quadratic for this. 1006 // Neither of these are explicitly forbidden, but every compiler detects them 1007 // and warns. 1008 1009 RawHandlers.release(); 1010 return Owned(new CXXTryStmt(TryLoc, static_cast<Stmt*>(TryBlock.release()), 1011 Handlers, NumHandlers)); 1012} 1013