SemaStmt.cpp revision 3dcfe10a6801eb52f4c20f1242bea0a3a98aa146
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/AST/ASTContext.h" 20#include "clang/Basic/TargetInfo.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 (Context) 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 (Context) DeclStmt(DG, StartLoc, EndLoc)); 63 } 64 else { 65 DeclGroupOwningRef DG(DeclGroup::Create(Context, decls.size(), &decls[0])); 66 return Owned(new (Context) 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 (Context) CompoundStmt(Context, 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 (Context) 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 (Context) 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 (Context) 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 (Context) IfStmt(IfLoc, condExpr, thenStmt, 233 (Stmt*)ElseVal.release())); 234} 235 236Action::OwningStmtResult 237Sema::ActOnStartOfSwitchStmt(ExprArg cond) { 238 Expr *Cond = static_cast<Expr*>(cond.release()); 239 240 if (getLangOptions().CPlusPlus) { 241 // C++ 6.4.2.p2: 242 // The condition shall be of integral type, enumeration type, or of a class 243 // type for which a single conversion function to integral or enumeration 244 // type exists (12.3). If the condition is of class type, the condition is 245 // converted by calling that conversion function, and the result of the 246 // conversion is used in place of the original condition for the remainder 247 // of this section. Integral promotions are performed. 248 249 QualType Ty = Cond->getType(); 250 251 // FIXME: Handle class types. 252 253 // If the type is wrong a diagnostic will be emitted later at 254 // ActOnFinishSwitchStmt. 255 if (Ty->isIntegralType() || Ty->isEnumeralType()) { 256 // Integral promotions are performed. 257 // FIXME: Integral promotions for C++ are not complete. 258 UsualUnaryConversions(Cond); 259 } 260 } else { 261 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr. 262 UsualUnaryConversions(Cond); 263 } 264 265 SwitchStmt *SS = new (Context) SwitchStmt(Cond); 266 SwitchStack.push_back(SS); 267 return Owned(SS); 268} 269 270/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 271/// the specified width and sign. If an overflow occurs, detect it and emit 272/// the specified diagnostic. 273void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val, 274 unsigned NewWidth, bool NewSign, 275 SourceLocation Loc, 276 unsigned DiagID) { 277 // Perform a conversion to the promoted condition type if needed. 278 if (NewWidth > Val.getBitWidth()) { 279 // If this is an extension, just do it. 280 llvm::APSInt OldVal(Val); 281 Val.extend(NewWidth); 282 283 // If the input was signed and negative and the output is unsigned, 284 // warn. 285 if (!NewSign && OldVal.isSigned() && OldVal.isNegative()) 286 Diag(Loc, DiagID) << OldVal.toString(10) << Val.toString(10); 287 288 Val.setIsSigned(NewSign); 289 } else if (NewWidth < Val.getBitWidth()) { 290 // If this is a truncation, check for overflow. 291 llvm::APSInt ConvVal(Val); 292 ConvVal.trunc(NewWidth); 293 ConvVal.setIsSigned(NewSign); 294 ConvVal.extend(Val.getBitWidth()); 295 ConvVal.setIsSigned(Val.isSigned()); 296 if (ConvVal != Val) 297 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10); 298 299 // Regardless of whether a diagnostic was emitted, really do the 300 // truncation. 301 Val.trunc(NewWidth); 302 Val.setIsSigned(NewSign); 303 } else if (NewSign != Val.isSigned()) { 304 // Convert the sign to match the sign of the condition. This can cause 305 // overflow as well: unsigned(INTMIN) 306 llvm::APSInt OldVal(Val); 307 Val.setIsSigned(NewSign); 308 309 if (Val.isNegative()) // Sign bit changes meaning. 310 Diag(Loc, DiagID) << OldVal.toString(10) << Val.toString(10); 311 } 312} 313 314namespace { 315 struct CaseCompareFunctor { 316 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 317 const llvm::APSInt &RHS) { 318 return LHS.first < RHS; 319 } 320 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 321 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 322 return LHS.first < RHS.first; 323 } 324 bool operator()(const llvm::APSInt &LHS, 325 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 326 return LHS < RHS.first; 327 } 328 }; 329} 330 331/// CmpCaseVals - Comparison predicate for sorting case values. 332/// 333static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs, 334 const std::pair<llvm::APSInt, CaseStmt*>& rhs) { 335 if (lhs.first < rhs.first) 336 return true; 337 338 if (lhs.first == rhs.first && 339 lhs.second->getCaseLoc().getRawEncoding() 340 < rhs.second->getCaseLoc().getRawEncoding()) 341 return true; 342 return false; 343} 344 345Action::OwningStmtResult 346Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, StmtArg Switch, 347 StmtArg Body) { 348 Stmt *BodyStmt = (Stmt*)Body.release(); 349 350 SwitchStmt *SS = SwitchStack.back(); 351 assert(SS == (SwitchStmt*)Switch.get() && "switch stack missing push/pop!"); 352 353 SS->setBody(BodyStmt, SwitchLoc); 354 SwitchStack.pop_back(); 355 356 Expr *CondExpr = SS->getCond(); 357 QualType CondType = CondExpr->getType(); 358 359 if (!CondType->isIntegerType()) { // C99 6.8.4.2p1 360 Diag(SwitchLoc, diag::err_typecheck_statement_requires_integer) 361 << CondType << CondExpr->getSourceRange(); 362 return StmtError(); 363 } 364 365 // Get the bitwidth of the switched-on value before promotions. We must 366 // convert the integer case values to this width before comparison. 367 unsigned CondWidth = static_cast<unsigned>(Context.getTypeSize(CondType)); 368 bool CondIsSigned = CondType->isSignedIntegerType(); 369 370 // Accumulate all of the case values in a vector so that we can sort them 371 // and detect duplicates. This vector contains the APInt for the case after 372 // it has been converted to the condition type. 373 typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy; 374 CaseValsTy CaseVals; 375 376 // Keep track of any GNU case ranges we see. The APSInt is the low value. 377 std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRanges; 378 379 DefaultStmt *TheDefaultStmt = 0; 380 381 bool CaseListIsErroneous = false; 382 383 for (SwitchCase *SC = SS->getSwitchCaseList(); SC; 384 SC = SC->getNextSwitchCase()) { 385 386 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) { 387 if (TheDefaultStmt) { 388 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined); 389 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev); 390 391 // FIXME: Remove the default statement from the switch block so that 392 // we'll return a valid AST. This requires recursing down the 393 // AST and finding it, not something we are set up to do right now. For 394 // now, just lop the entire switch stmt out of the AST. 395 CaseListIsErroneous = true; 396 } 397 TheDefaultStmt = DS; 398 399 } else { 400 CaseStmt *CS = cast<CaseStmt>(SC); 401 402 // We already verified that the expression has a i-c-e value (C99 403 // 6.8.4.2p3) - get that value now. 404 Expr *Lo = CS->getLHS(); 405 llvm::APSInt LoVal = Lo->EvaluateAsInt(Context); 406 407 // Convert the value to the same width/sign as the condition. 408 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned, 409 CS->getLHS()->getLocStart(), 410 diag::warn_case_value_overflow); 411 412 // If the LHS is not the same type as the condition, insert an implicit 413 // cast. 414 ImpCastExprToType(Lo, CondType); 415 CS->setLHS(Lo); 416 417 // If this is a case range, remember it in CaseRanges, otherwise CaseVals. 418 if (CS->getRHS()) 419 CaseRanges.push_back(std::make_pair(LoVal, CS)); 420 else 421 CaseVals.push_back(std::make_pair(LoVal, CS)); 422 } 423 } 424 425 // Sort all the scalar case values so we can easily detect duplicates. 426 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals); 427 428 if (!CaseVals.empty()) { 429 for (unsigned i = 0, e = CaseVals.size()-1; i != e; ++i) { 430 if (CaseVals[i].first == CaseVals[i+1].first) { 431 // If we have a duplicate, report it. 432 Diag(CaseVals[i+1].second->getLHS()->getLocStart(), 433 diag::err_duplicate_case) << CaseVals[i].first.toString(10); 434 Diag(CaseVals[i].second->getLHS()->getLocStart(), 435 diag::note_duplicate_case_prev); 436 // FIXME: We really want to remove the bogus case stmt from the substmt, 437 // but we have no way to do this right now. 438 CaseListIsErroneous = true; 439 } 440 } 441 } 442 443 // Detect duplicate case ranges, which usually don't exist at all in the first 444 // place. 445 if (!CaseRanges.empty()) { 446 // Sort all the case ranges by their low value so we can easily detect 447 // overlaps between ranges. 448 std::stable_sort(CaseRanges.begin(), CaseRanges.end()); 449 450 // Scan the ranges, computing the high values and removing empty ranges. 451 std::vector<llvm::APSInt> HiVals; 452 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 453 CaseStmt *CR = CaseRanges[i].second; 454 Expr *Hi = CR->getRHS(); 455 llvm::APSInt HiVal = Hi->EvaluateAsInt(Context); 456 457 // Convert the value to the same width/sign as the condition. 458 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned, 459 CR->getRHS()->getLocStart(), 460 diag::warn_case_value_overflow); 461 462 // If the LHS is not the same type as the condition, insert an implicit 463 // cast. 464 ImpCastExprToType(Hi, CondType); 465 CR->setRHS(Hi); 466 467 // If the low value is bigger than the high value, the case is empty. 468 if (CaseRanges[i].first > HiVal) { 469 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range) 470 << SourceRange(CR->getLHS()->getLocStart(), 471 CR->getRHS()->getLocEnd()); 472 CaseRanges.erase(CaseRanges.begin()+i); 473 --i, --e; 474 continue; 475 } 476 HiVals.push_back(HiVal); 477 } 478 479 // Rescan the ranges, looking for overlap with singleton values and other 480 // ranges. Since the range list is sorted, we only need to compare case 481 // ranges with their neighbors. 482 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 483 llvm::APSInt &CRLo = CaseRanges[i].first; 484 llvm::APSInt &CRHi = HiVals[i]; 485 CaseStmt *CR = CaseRanges[i].second; 486 487 // Check to see whether the case range overlaps with any singleton cases. 488 CaseStmt *OverlapStmt = 0; 489 llvm::APSInt OverlapVal(32); 490 491 // Find the smallest value >= the lower bound. If I is in the case range, 492 // then we have overlap. 493 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(), 494 CaseVals.end(), CRLo, 495 CaseCompareFunctor()); 496 if (I != CaseVals.end() && I->first < CRHi) { 497 OverlapVal = I->first; // Found overlap with scalar. 498 OverlapStmt = I->second; 499 } 500 501 // Find the smallest value bigger than the upper bound. 502 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor()); 503 if (I != CaseVals.begin() && (I-1)->first >= CRLo) { 504 OverlapVal = (I-1)->first; // Found overlap with scalar. 505 OverlapStmt = (I-1)->second; 506 } 507 508 // Check to see if this case stmt overlaps with the subsequent case range. 509 if (i && CRLo <= HiVals[i-1]) { 510 OverlapVal = HiVals[i-1]; // Found overlap with range. 511 OverlapStmt = CaseRanges[i-1].second; 512 } 513 514 if (OverlapStmt) { 515 // If we have a duplicate, report it. 516 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case) 517 << OverlapVal.toString(10); 518 Diag(OverlapStmt->getLHS()->getLocStart(), 519 diag::note_duplicate_case_prev); 520 // FIXME: We really want to remove the bogus case stmt from the substmt, 521 // but we have no way to do this right now. 522 CaseListIsErroneous = true; 523 } 524 } 525 } 526 527 // FIXME: If the case list was broken is some way, we don't have a good system 528 // to patch it up. Instead, just return the whole substmt as broken. 529 if (CaseListIsErroneous) 530 return StmtError(); 531 532 Switch.release(); 533 return Owned(SS); 534} 535 536Action::OwningStmtResult 537Sema::ActOnWhileStmt(SourceLocation WhileLoc, ExprArg Cond, StmtArg Body) { 538 Expr *condExpr = (Expr *)Cond.release(); 539 assert(condExpr && "ActOnWhileStmt(): missing expression"); 540 541 DefaultFunctionArrayConversion(condExpr); 542 Cond = condExpr; 543 QualType condType = condExpr->getType(); 544 545 if (getLangOptions().CPlusPlus) { 546 if (CheckCXXBooleanCondition(condExpr)) // C++ 6.4p4 547 return StmtError(); 548 } else if (!condType->isScalarType()) // C99 6.8.5p2 549 return StmtError(Diag(WhileLoc, 550 diag::err_typecheck_statement_requires_scalar) 551 << condType << condExpr->getSourceRange()); 552 553 Cond.release(); 554 return Owned(new (Context) WhileStmt(condExpr, (Stmt*)Body.release(), 555 WhileLoc)); 556} 557 558Action::OwningStmtResult 559Sema::ActOnDoStmt(SourceLocation DoLoc, StmtArg Body, 560 SourceLocation WhileLoc, ExprArg Cond) { 561 Expr *condExpr = (Expr *)Cond.release(); 562 assert(condExpr && "ActOnDoStmt(): missing expression"); 563 564 DefaultFunctionArrayConversion(condExpr); 565 Cond = condExpr; 566 QualType condType = condExpr->getType(); 567 568 if (getLangOptions().CPlusPlus) { 569 if (CheckCXXBooleanCondition(condExpr)) // C++ 6.4p4 570 return StmtError(); 571 } else if (!condType->isScalarType()) // C99 6.8.5p2 572 return StmtError(Diag(DoLoc, diag::err_typecheck_statement_requires_scalar) 573 << condType << condExpr->getSourceRange()); 574 575 Cond.release(); 576 return Owned(new (Context) DoStmt((Stmt*)Body.release(), condExpr, DoLoc)); 577} 578 579Action::OwningStmtResult 580Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 581 StmtArg first, ExprArg second, ExprArg third, 582 SourceLocation RParenLoc, StmtArg body) { 583 Stmt *First = static_cast<Stmt*>(first.get()); 584 Expr *Second = static_cast<Expr*>(second.get()); 585 Expr *Third = static_cast<Expr*>(third.get()); 586 Stmt *Body = static_cast<Stmt*>(body.get()); 587 588 if (!getLangOptions().CPlusPlus) { 589 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) { 590 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 591 // declare identifiers for objects having storage class 'auto' or 592 // 'register'. 593 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end(); 594 DI!=DE; ++DI) { 595 VarDecl *VD = dyn_cast<VarDecl>(*DI); 596 if (VD && VD->isBlockVarDecl() && !VD->hasLocalStorage()) 597 VD = 0; 598 if (VD == 0) 599 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for); 600 // FIXME: mark decl erroneous! 601 } 602 } 603 } 604 if (Second) { 605 DefaultFunctionArrayConversion(Second); 606 QualType SecondType = Second->getType(); 607 608 if (getLangOptions().CPlusPlus) { 609 if (CheckCXXBooleanCondition(Second)) // C++ 6.4p4 610 return StmtError(); 611 } else if (!SecondType->isScalarType()) // C99 6.8.5p2 612 return StmtError(Diag(ForLoc, 613 diag::err_typecheck_statement_requires_scalar) 614 << SecondType << Second->getSourceRange()); 615 } 616 first.release(); 617 second.release(); 618 third.release(); 619 body.release(); 620 return Owned(new (Context) ForStmt(First, Second, Third, Body, ForLoc)); 621} 622 623Action::OwningStmtResult 624Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc, 625 SourceLocation LParenLoc, 626 StmtArg first, ExprArg second, 627 SourceLocation RParenLoc, StmtArg body) { 628 Stmt *First = static_cast<Stmt*>(first.get()); 629 Expr *Second = static_cast<Expr*>(second.get()); 630 Stmt *Body = static_cast<Stmt*>(body.get()); 631 if (First) { 632 QualType FirstType; 633 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) { 634 if (!DS->hasSolitaryDecl()) 635 return StmtError(Diag((*DS->decl_begin())->getLocation(), 636 diag::err_toomany_element_decls)); 637 638 Decl *D = DS->getSolitaryDecl(); 639 FirstType = cast<ValueDecl>(D)->getType(); 640 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 641 // declare identifiers for objects having storage class 'auto' or 642 // 'register'. 643 VarDecl *VD = cast<VarDecl>(D); 644 if (VD->isBlockVarDecl() && !VD->hasLocalStorage()) 645 return StmtError(Diag(VD->getLocation(), 646 diag::err_non_variable_decl_in_for)); 647 } else { 648 Expr::isLvalueResult lval = cast<Expr>(First)->isLvalue(Context); 649 650 if (lval != Expr::LV_Valid) 651 return StmtError(Diag(First->getLocStart(), 652 diag::err_selector_element_not_lvalue) 653 << First->getSourceRange()); 654 655 FirstType = static_cast<Expr*>(First)->getType(); 656 } 657 if (!Context.isObjCObjectPointerType(FirstType)) 658 Diag(ForLoc, diag::err_selector_element_type) 659 << FirstType << First->getSourceRange(); 660 } 661 if (Second) { 662 DefaultFunctionArrayConversion(Second); 663 QualType SecondType = Second->getType(); 664 if (!Context.isObjCObjectPointerType(SecondType)) 665 Diag(ForLoc, diag::err_collection_expr_type) 666 << SecondType << Second->getSourceRange(); 667 } 668 first.release(); 669 second.release(); 670 body.release(); 671 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body, 672 ForLoc, RParenLoc)); 673} 674 675Action::OwningStmtResult 676Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, 677 IdentifierInfo *LabelII) { 678 // If we are in a block, reject all gotos for now. 679 if (CurBlock) 680 return StmtError(Diag(GotoLoc, diag::err_goto_in_block)); 681 682 // Look up the record for this label identifier. 683 LabelStmt *&LabelDecl = LabelMap[LabelII]; 684 685 // If we haven't seen this label yet, create a forward reference. 686 if (LabelDecl == 0) 687 LabelDecl = new (Context) LabelStmt(LabelLoc, LabelII, 0); 688 689 return Owned(new (Context) GotoStmt(LabelDecl, GotoLoc, LabelLoc)); 690} 691 692Action::OwningStmtResult 693Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc,SourceLocation StarLoc, 694 ExprArg DestExp) { 695 // FIXME: Verify that the operand is convertible to void*. 696 697 return Owned(new (Context) IndirectGotoStmt((Expr*)DestExp.release())); 698} 699 700Action::OwningStmtResult 701Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) { 702 Scope *S = CurScope->getContinueParent(); 703 if (!S) { 704 // C99 6.8.6.2p1: A break shall appear only in or as a loop body. 705 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop)); 706 } 707 708 return Owned(new (Context) ContinueStmt(ContinueLoc)); 709} 710 711Action::OwningStmtResult 712Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) { 713 Scope *S = CurScope->getBreakParent(); 714 if (!S) { 715 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body. 716 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch)); 717 } 718 719 return Owned(new (Context) BreakStmt(BreakLoc)); 720} 721 722/// ActOnBlockReturnStmt - Utility routine to figure out block's return type. 723/// 724Action::OwningStmtResult 725Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 726 727 // If this is the first return we've seen in the block, infer the type of 728 // the block from it. 729 if (CurBlock->ReturnType == 0) { 730 if (RetValExp) { 731 // Don't call UsualUnaryConversions(), since we don't want to do 732 // integer promotions here. 733 DefaultFunctionArrayConversion(RetValExp); 734 CurBlock->ReturnType = RetValExp->getType().getTypePtr(); 735 } else 736 CurBlock->ReturnType = Context.VoidTy.getTypePtr(); 737 } 738 QualType FnRetType = QualType(CurBlock->ReturnType, 0); 739 740 // Otherwise, verify that this result type matches the previous one. We are 741 // pickier with blocks than for normal functions because we don't have GCC 742 // compatibility to worry about here. 743 if (CurBlock->ReturnType->isVoidType()) { 744 if (RetValExp) { 745 Diag(ReturnLoc, diag::err_return_block_has_expr); 746 RetValExp->Destroy(Context); 747 RetValExp = 0; 748 } 749 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp)); 750 } 751 752 if (!RetValExp) 753 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr)); 754 755 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 756 // we have a non-void block with an expression, continue checking 757 QualType RetValType = RetValExp->getType(); 758 759 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 760 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 761 // function return. 762 763 // In C++ the return statement is handled via a copy initialization. 764 // the C version of which boils down to CheckSingleAssignmentConstraints. 765 // FIXME: Leaks RetValExp. 766 if (PerformCopyInitialization(RetValExp, FnRetType, "returning")) 767 return StmtError(); 768 769 if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 770 } 771 772 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp)); 773} 774 775Action::OwningStmtResult 776Sema::ActOnReturnStmt(SourceLocation ReturnLoc, ExprArg rex) { 777 Expr *RetValExp = static_cast<Expr *>(rex.release()); 778 if (CurBlock) 779 return ActOnBlockReturnStmt(ReturnLoc, RetValExp); 780 781 QualType FnRetType; 782 if (FunctionDecl *FD = getCurFunctionDecl()) 783 FnRetType = FD->getResultType(); 784 else 785 FnRetType = getCurMethodDecl()->getResultType(); 786 787 if (FnRetType->isVoidType()) { 788 if (RetValExp) {// C99 6.8.6.4p1 (ext_ since GCC warns) 789 unsigned D = diag::ext_return_has_expr; 790 if (RetValExp->getType()->isVoidType()) 791 D = diag::ext_return_has_void_expr; 792 793 // return (some void expression); is legal in C++. 794 if (D != diag::ext_return_has_void_expr || 795 !getLangOptions().CPlusPlus) { 796 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 797 Diag(ReturnLoc, D) 798 << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl) 799 << RetValExp->getSourceRange(); 800 } 801 } 802 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp)); 803 } 804 805 if (!RetValExp) { 806 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4 807 // C99 6.8.6.4p1 (ext_ since GCC warns) 808 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr; 809 810 if (FunctionDecl *FD = getCurFunctionDecl()) 811 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/; 812 else 813 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/; 814 return Owned(new (Context) ReturnStmt(ReturnLoc, (Expr*)0)); 815 } 816 817 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 818 // we have a non-void function with an expression, continue checking 819 QualType RetValType = RetValExp->getType(); 820 821 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 822 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 823 // function return. 824 825 // In C++ the return statement is handled via a copy initialization. 826 // the C version of which boils down to CheckSingleAssignmentConstraints. 827 // FIXME: Leaks RetValExp. 828 if (PerformCopyInitialization(RetValExp, FnRetType, "returning")) 829 return StmtError(); 830 831 if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 832 } 833 834 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp)); 835} 836 837Sema::OwningStmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, 838 bool IsSimple, 839 bool IsVolatile, 840 unsigned NumOutputs, 841 unsigned NumInputs, 842 std::string *Names, 843 MultiExprArg constraints, 844 MultiExprArg exprs, 845 ExprArg asmString, 846 MultiExprArg clobbers, 847 SourceLocation RParenLoc) { 848 unsigned NumClobbers = clobbers.size(); 849 StringLiteral **Constraints = 850 reinterpret_cast<StringLiteral**>(constraints.get()); 851 Expr **Exprs = reinterpret_cast<Expr **>(exprs.get()); 852 StringLiteral *AsmString = cast<StringLiteral>((Expr *)asmString.get()); 853 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get()); 854 855 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; 856 857 // The parser verifies that there is a string literal here. 858 if (AsmString->isWide()) 859 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character) 860 << AsmString->getSourceRange()); 861 862 863 for (unsigned i = 0; i != NumOutputs; i++) { 864 StringLiteral *Literal = Constraints[i]; 865 if (Literal->isWide()) 866 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 867 << Literal->getSourceRange()); 868 869 std::string OutputConstraint(Literal->getStrData(), 870 Literal->getByteLength()); 871 872 TargetInfo::ConstraintInfo info; 873 if (!Context.Target.validateOutputConstraint(OutputConstraint.c_str(),info)) 874 return StmtError(Diag(Literal->getLocStart(), 875 diag::err_asm_invalid_output_constraint) << OutputConstraint); 876 877 // Check that the output exprs are valid lvalues. 878 ParenExpr *OutputExpr = cast<ParenExpr>(Exprs[i]); 879 Expr::isLvalueResult Result = OutputExpr->isLvalue(Context); 880 if (Result != Expr::LV_Valid) { 881 return StmtError(Diag(OutputExpr->getSubExpr()->getLocStart(), 882 diag::err_asm_invalid_lvalue_in_output) 883 << OutputExpr->getSubExpr()->getSourceRange()); 884 } 885 886 OutputConstraintInfos.push_back(info); 887 } 888 889 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) { 890 StringLiteral *Literal = Constraints[i]; 891 if (Literal->isWide()) 892 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 893 << Literal->getSourceRange()); 894 895 std::string InputConstraint(Literal->getStrData(), 896 Literal->getByteLength()); 897 898 TargetInfo::ConstraintInfo info; 899 if (!Context.Target.validateInputConstraint(InputConstraint.c_str(), 900 &Names[0], 901 &Names[0] + NumOutputs, 902 &OutputConstraintInfos[0], 903 info)) { 904 return StmtError(Diag(Literal->getLocStart(), 905 diag::err_asm_invalid_input_constraint) << InputConstraint); 906 } 907 908 ParenExpr *InputExpr = cast<ParenExpr>(Exprs[i]); 909 910 // Only allow void types for memory constraints. 911 if ((info & TargetInfo::CI_AllowsMemory) 912 && !(info & TargetInfo::CI_AllowsRegister)) { 913 if (InputExpr->isLvalue(Context) != Expr::LV_Valid) 914 return StmtError(Diag(InputExpr->getSubExpr()->getLocStart(), 915 diag::err_asm_invalid_lvalue_in_input) 916 << InputConstraint << InputExpr->getSubExpr()->getSourceRange()); 917 } 918 919 if (info & TargetInfo::CI_AllowsRegister) { 920 if (InputExpr->getType()->isVoidType()) { 921 return StmtError(Diag(InputExpr->getSubExpr()->getLocStart(), 922 diag::err_asm_invalid_type_in_input) 923 << InputExpr->getType() << InputConstraint 924 << InputExpr->getSubExpr()->getSourceRange()); 925 } 926 927 DefaultFunctionArrayConversion(Exprs[i]); 928 } 929 } 930 931 // Check that the clobbers are valid. 932 for (unsigned i = 0; i != NumClobbers; i++) { 933 StringLiteral *Literal = Clobbers[i]; 934 if (Literal->isWide()) 935 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 936 << Literal->getSourceRange()); 937 938 llvm::SmallString<16> Clobber(Literal->getStrData(), 939 Literal->getStrData() + 940 Literal->getByteLength()); 941 942 if (!Context.Target.isValidGCCRegisterName(Clobber.c_str())) 943 return StmtError(Diag(Literal->getLocStart(), 944 diag::err_asm_unknown_register_name) << Clobber.c_str()); 945 } 946 947 constraints.release(); 948 exprs.release(); 949 asmString.release(); 950 clobbers.release(); 951 return Owned(new (Context) AsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs, 952 NumInputs, Names, Constraints, Exprs, 953 AsmString, NumClobbers, 954 Clobbers, RParenLoc)); 955} 956 957Action::OwningStmtResult 958Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc, 959 SourceLocation RParen, StmtArg Parm, 960 StmtArg Body, StmtArg catchList) { 961 Stmt *CatchList = static_cast<Stmt*>(catchList.release()); 962 ObjCAtCatchStmt *CS = new (Context) ObjCAtCatchStmt(AtLoc, RParen, 963 static_cast<Stmt*>(Parm.release()), static_cast<Stmt*>(Body.release()), 964 CatchList); 965 return Owned(CatchList ? CatchList : CS); 966} 967 968Action::OwningStmtResult 969Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, StmtArg Body) { 970 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, 971 static_cast<Stmt*>(Body.release()))); 972} 973 974Action::OwningStmtResult 975Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, 976 StmtArg Try, StmtArg Catch, StmtArg Finally) { 977 return Owned(new (Context) ObjCAtTryStmt(AtLoc, 978 static_cast<Stmt*>(Try.release()), 979 static_cast<Stmt*>(Catch.release()), 980 static_cast<Stmt*>(Finally.release()))); 981} 982 983Action::OwningStmtResult 984Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, ExprArg expr,Scope *CurScope) { 985 Expr *ThrowExpr = static_cast<Expr*>(expr.release()); 986 if (!ThrowExpr) { 987 // @throw without an expression designates a rethrow (which much occur 988 // in the context of an @catch clause). 989 Scope *AtCatchParent = CurScope; 990 while (AtCatchParent && !AtCatchParent->isAtCatchScope()) 991 AtCatchParent = AtCatchParent->getParent(); 992 if (!AtCatchParent) 993 Diag(AtLoc, diag::error_rethrow_used_outside_catch); 994 } else { 995 QualType ThrowType = ThrowExpr->getType(); 996 // Make sure the expression type is an ObjC pointer or "void *". 997 if (!Context.isObjCObjectPointerType(ThrowType)) { 998 const PointerType *PT = ThrowType->getAsPointerType(); 999 if (!PT || !PT->getPointeeType()->isVoidType()) 1000 Diag(AtLoc, diag::error_objc_throw_expects_object) 1001 << ThrowExpr->getType() << ThrowExpr->getSourceRange(); 1002 } 1003 } 1004 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, ThrowExpr)); 1005} 1006 1007Action::OwningStmtResult 1008Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, ExprArg SynchExpr, 1009 StmtArg SynchBody) { 1010 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, 1011 static_cast<Stmt*>(SynchExpr.release()), 1012 static_cast<Stmt*>(SynchBody.release()))); 1013} 1014 1015/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block 1016/// and creates a proper catch handler from them. 1017Action::OwningStmtResult 1018Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, DeclTy *ExDecl, 1019 StmtArg HandlerBlock) { 1020 // There's nothing to test that ActOnExceptionDecl didn't already test. 1021 return Owned(new (Context) CXXCatchStmt(CatchLoc, 1022 static_cast<VarDecl*>(ExDecl), 1023 static_cast<Stmt*>(HandlerBlock.release()))); 1024} 1025 1026/// ActOnCXXTryBlock - Takes a try compound-statement and a number of 1027/// handlers and creates a try statement from them. 1028Action::OwningStmtResult 1029Sema::ActOnCXXTryBlock(SourceLocation TryLoc, StmtArg TryBlock, 1030 MultiStmtArg RawHandlers) { 1031 unsigned NumHandlers = RawHandlers.size(); 1032 assert(NumHandlers > 0 && 1033 "The parser shouldn't call this if there are no handlers."); 1034 Stmt **Handlers = reinterpret_cast<Stmt**>(RawHandlers.get()); 1035 1036 for(unsigned i = 0; i < NumHandlers - 1; ++i) { 1037 CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]); 1038 if (!Handler->getExceptionDecl()) 1039 return StmtError(Diag(Handler->getLocStart(), diag::err_early_catch_all)); 1040 } 1041 // FIXME: We should detect handlers for the same type as an earlier one. 1042 // This one is rather easy. 1043 // FIXME: We should detect handlers that cannot catch anything because an 1044 // earlier handler catches a superclass. Need to find a method that is not 1045 // quadratic for this. 1046 // Neither of these are explicitly forbidden, but every compiler detects them 1047 // and warns. 1048 1049 RawHandlers.release(); 1050 return Owned(new (Context) CXXTryStmt(TryLoc, 1051 static_cast<Stmt*>(TryBlock.release()), 1052 Handlers, NumHandlers)); 1053} 1054