SemaStmt.cpp revision d198abae5938262e501a409e833bf01ca8b8253e
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 DeclGroupRef DG(*decls.begin()); 62 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc)); 63 } 64 else { 65 DeclGroupRef 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 if they are non-void and if 99 // this not the last stmt in a stmt expr. 100 if (E->getType()->isVoidType() || (isStmtExpr && i == NumElts-1)) 101 continue; 102 103 SourceLocation Loc; 104 SourceRange R1, R2; 105 if (!E->isUnusedResultAWarning(Loc, R1, R2)) 106 continue; 107 108 Diag(Loc, diag::warn_unused_expr) << R1 << R2; 109 } 110 111 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R)); 112} 113 114Action::OwningStmtResult 115Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprArg lhsval, 116 SourceLocation DotDotDotLoc, ExprArg rhsval, 117 SourceLocation ColonLoc, StmtArg subStmt) { 118 Stmt *SubStmt = static_cast<Stmt*>(subStmt.release()); 119 assert((lhsval.get() != 0) && "missing expression in case statement"); 120 121 // C99 6.8.4.2p3: The expression shall be an integer constant. 122 // However, GCC allows any evaluatable integer expression. 123 124 Expr *LHSVal = static_cast<Expr*>(lhsval.get()); 125 if (VerifyIntegerConstantExpression(LHSVal)) 126 return Owned(SubStmt); 127 128 // GCC extension: The expression shall be an integer constant. 129 130 Expr *RHSVal = static_cast<Expr*>(rhsval.get()); 131 if (RHSVal && VerifyIntegerConstantExpression(RHSVal)) { 132 RHSVal = 0; // Recover by just forgetting about it. 133 rhsval = 0; 134 } 135 136 if (SwitchStack.empty()) { 137 Diag(CaseLoc, diag::err_case_not_in_switch); 138 return Owned(SubStmt); 139 } 140 141 // Only now release the smart pointers. 142 lhsval.release(); 143 rhsval.release(); 144 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, SubStmt, CaseLoc); 145 SwitchStack.back()->addSwitchCase(CS); 146 return Owned(CS); 147} 148 149Action::OwningStmtResult 150Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, 151 StmtArg subStmt, Scope *CurScope) { 152 Stmt *SubStmt = static_cast<Stmt*>(subStmt.release()); 153 154 if (SwitchStack.empty()) { 155 Diag(DefaultLoc, diag::err_default_not_in_switch); 156 return Owned(SubStmt); 157 } 158 159 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, SubStmt); 160 SwitchStack.back()->addSwitchCase(DS); 161 return Owned(DS); 162} 163 164Action::OwningStmtResult 165Sema::ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II, 166 SourceLocation ColonLoc, StmtArg subStmt) { 167 Stmt *SubStmt = static_cast<Stmt*>(subStmt.release()); 168 169 // Look up the record for this label identifier. 170 Scope::LabelMapTy::iterator I = ActiveScope->LabelMap.find(II); 171 172 LabelStmt *LabelDecl; 173 174 // If not forward referenced or defined already, just create a new LabelStmt. 175 if (I == ActiveScope->LabelMap.end()) { 176 LabelDecl = new (Context) LabelStmt(IdentLoc, II, SubStmt); 177 ActiveScope->LabelMap.insert(std::make_pair(II, LabelDecl)); 178 return Owned(LabelDecl); 179 } else 180 LabelDecl = static_cast<LabelStmt *>(I->second); 181 182 assert(LabelDecl->getID() == II && "Label mismatch!"); 183 184 // Otherwise, this label was either forward reference or multiply defined. If 185 // multiply defined, reject it now. 186 if (LabelDecl->getSubStmt()) { 187 Diag(IdentLoc, diag::err_redefinition_of_label) << LabelDecl->getID(); 188 Diag(LabelDecl->getIdentLoc(), diag::note_previous_definition); 189 return Owned(SubStmt); 190 } 191 192 // Otherwise, this label was forward declared, and we just found its real 193 // definition. Fill in the forward definition and return it. 194 LabelDecl->setIdentLoc(IdentLoc); 195 LabelDecl->setSubStmt(SubStmt); 196 return Owned(LabelDecl); 197} 198 199Action::OwningStmtResult 200Sema::ActOnIfStmt(SourceLocation IfLoc, ExprArg CondVal, 201 StmtArg ThenVal, SourceLocation ElseLoc, 202 StmtArg ElseVal) { 203 Expr *condExpr = (Expr *)CondVal.release(); 204 205 assert(condExpr && "ActOnIfStmt(): missing expression"); 206 207 DefaultFunctionArrayConversion(condExpr); 208 // Take ownership again until we're past the error checking. 209 CondVal = condExpr; 210 QualType condType = condExpr->getType(); 211 212 if (getLangOptions().CPlusPlus) { 213 if (CheckCXXBooleanCondition(condExpr)) // C++ 6.4p4 214 return StmtError(); 215 } else if (!condType->isScalarType()) // C99 6.8.4.1p1 216 return StmtError(Diag(IfLoc, diag::err_typecheck_statement_requires_scalar) 217 << condType << condExpr->getSourceRange()); 218 219 Stmt *thenStmt = (Stmt *)ThenVal.release(); 220 221 // Warn if the if block has a null body without an else value. 222 // this helps prevent bugs due to typos, such as 223 // if (condition); 224 // do_stuff(); 225 if (!ElseVal.get()) { 226 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt)) 227 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body); 228 } 229 230 CondVal.release(); 231 return Owned(new (Context) IfStmt(IfLoc, condExpr, thenStmt, 232 (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 (Context) 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 (Context) WhileStmt(condExpr, (Stmt*)Body.release(), 554 WhileLoc)); 555} 556 557Action::OwningStmtResult 558Sema::ActOnDoStmt(SourceLocation DoLoc, StmtArg Body, 559 SourceLocation WhileLoc, ExprArg Cond) { 560 Expr *condExpr = (Expr *)Cond.release(); 561 assert(condExpr && "ActOnDoStmt(): missing expression"); 562 563 DefaultFunctionArrayConversion(condExpr); 564 Cond = condExpr; 565 QualType condType = condExpr->getType(); 566 567 if (getLangOptions().CPlusPlus) { 568 if (CheckCXXBooleanCondition(condExpr)) // C++ 6.4p4 569 return StmtError(); 570 } else if (!condType->isScalarType()) // C99 6.8.5p2 571 return StmtError(Diag(DoLoc, diag::err_typecheck_statement_requires_scalar) 572 << condType << condExpr->getSourceRange()); 573 574 Cond.release(); 575 return Owned(new (Context) DoStmt((Stmt*)Body.release(), condExpr, DoLoc)); 576} 577 578Action::OwningStmtResult 579Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 580 StmtArg first, ExprArg second, ExprArg third, 581 SourceLocation RParenLoc, StmtArg body) { 582 Stmt *First = static_cast<Stmt*>(first.get()); 583 Expr *Second = static_cast<Expr*>(second.get()); 584 Expr *Third = static_cast<Expr*>(third.get()); 585 Stmt *Body = static_cast<Stmt*>(body.get()); 586 587 if (!getLangOptions().CPlusPlus) { 588 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) { 589 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 590 // declare identifiers for objects having storage class 'auto' or 591 // 'register'. 592 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end(); 593 DI!=DE; ++DI) { 594 VarDecl *VD = dyn_cast<VarDecl>(*DI); 595 if (VD && VD->isBlockVarDecl() && !VD->hasLocalStorage()) 596 VD = 0; 597 if (VD == 0) 598 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for); 599 // FIXME: mark decl erroneous! 600 } 601 } 602 } 603 if (Second) { 604 DefaultFunctionArrayConversion(Second); 605 QualType SecondType = Second->getType(); 606 607 if (getLangOptions().CPlusPlus) { 608 if (CheckCXXBooleanCondition(Second)) // C++ 6.4p4 609 return StmtError(); 610 } else if (!SecondType->isScalarType()) // C99 6.8.5p2 611 return StmtError(Diag(ForLoc, 612 diag::err_typecheck_statement_requires_scalar) 613 << SecondType << Second->getSourceRange()); 614 } 615 first.release(); 616 second.release(); 617 third.release(); 618 body.release(); 619 return Owned(new (Context) ForStmt(First, Second, Third, Body, ForLoc)); 620} 621 622Action::OwningStmtResult 623Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc, 624 SourceLocation LParenLoc, 625 StmtArg first, ExprArg second, 626 SourceLocation RParenLoc, StmtArg body) { 627 Stmt *First = static_cast<Stmt*>(first.get()); 628 Expr *Second = static_cast<Expr*>(second.get()); 629 Stmt *Body = static_cast<Stmt*>(body.get()); 630 if (First) { 631 QualType FirstType; 632 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) { 633 if (!DS->hasSolitaryDecl()) 634 return StmtError(Diag((*DS->decl_begin())->getLocation(), 635 diag::err_toomany_element_decls)); 636 637 Decl *D = DS->getSolitaryDecl(); 638 FirstType = cast<ValueDecl>(D)->getType(); 639 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 640 // declare identifiers for objects having storage class 'auto' or 641 // 'register'. 642 VarDecl *VD = cast<VarDecl>(D); 643 if (VD->isBlockVarDecl() && !VD->hasLocalStorage()) 644 return StmtError(Diag(VD->getLocation(), 645 diag::err_non_variable_decl_in_for)); 646 } else { 647 Expr::isLvalueResult lval = cast<Expr>(First)->isLvalue(Context); 648 649 if (lval != Expr::LV_Valid) 650 return StmtError(Diag(First->getLocStart(), 651 diag::err_selector_element_not_lvalue) 652 << First->getSourceRange()); 653 654 FirstType = static_cast<Expr*>(First)->getType(); 655 } 656 if (!Context.isObjCObjectPointerType(FirstType)) 657 Diag(ForLoc, diag::err_selector_element_type) 658 << FirstType << First->getSourceRange(); 659 } 660 if (Second) { 661 DefaultFunctionArrayConversion(Second); 662 QualType SecondType = Second->getType(); 663 if (!Context.isObjCObjectPointerType(SecondType)) 664 Diag(ForLoc, diag::err_collection_expr_type) 665 << SecondType << Second->getSourceRange(); 666 } 667 first.release(); 668 second.release(); 669 body.release(); 670 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body, 671 ForLoc, RParenLoc)); 672} 673 674Action::OwningStmtResult 675Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, 676 IdentifierInfo *LabelII) { 677 // If we are in a block, reject all gotos for now. 678 if (CurBlock) 679 return StmtError(Diag(GotoLoc, diag::err_goto_in_block)); 680 681 // Look up the record for this label identifier. 682 Scope::LabelMapTy::iterator I = ActiveScope->LabelMap.find(LabelII); 683 684 LabelStmt *LabelDecl; 685 686 // If not forward referenced or defined already, just create a new LabelStmt. 687 if (I == ActiveScope->LabelMap.end()) { 688 LabelDecl = new (Context) LabelStmt(LabelLoc, LabelII, 0); 689 ActiveScope->LabelMap.insert(std::make_pair(LabelII, LabelDecl)); 690 } else 691 LabelDecl = static_cast<LabelStmt *>(I->second); 692 693 return Owned(new (Context) GotoStmt(LabelDecl, GotoLoc, LabelLoc)); 694} 695 696Action::OwningStmtResult 697Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc,SourceLocation StarLoc, 698 ExprArg DestExp) { 699 // FIXME: Verify that the operand is convertible to void*. 700 701 return Owned(new (Context) IndirectGotoStmt((Expr*)DestExp.release())); 702} 703 704Action::OwningStmtResult 705Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) { 706 Scope *S = CurScope->getContinueParent(); 707 if (!S) { 708 // C99 6.8.6.2p1: A break shall appear only in or as a loop body. 709 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop)); 710 } 711 712 return Owned(new (Context) ContinueStmt(ContinueLoc)); 713} 714 715Action::OwningStmtResult 716Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) { 717 Scope *S = CurScope->getBreakParent(); 718 if (!S) { 719 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body. 720 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch)); 721 } 722 723 return Owned(new (Context) BreakStmt(BreakLoc)); 724} 725 726/// ActOnBlockReturnStmt - Utility routine to figure out block's return type. 727/// 728Action::OwningStmtResult 729Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 730 731 // If this is the first return we've seen in the block, infer the type of 732 // the block from it. 733 if (CurBlock->ReturnType == 0) { 734 if (RetValExp) { 735 // Don't call UsualUnaryConversions(), since we don't want to do 736 // integer promotions here. 737 DefaultFunctionArrayConversion(RetValExp); 738 CurBlock->ReturnType = RetValExp->getType().getTypePtr(); 739 } else 740 CurBlock->ReturnType = Context.VoidTy.getTypePtr(); 741 } 742 QualType FnRetType = QualType(CurBlock->ReturnType, 0); 743 744 // Otherwise, verify that this result type matches the previous one. We are 745 // pickier with blocks than for normal functions because we don't have GCC 746 // compatibility to worry about here. 747 if (CurBlock->ReturnType->isVoidType()) { 748 if (RetValExp) { 749 Diag(ReturnLoc, diag::err_return_block_has_expr); 750 RetValExp->Destroy(Context); 751 RetValExp = 0; 752 } 753 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp)); 754 } 755 756 if (!RetValExp) 757 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr)); 758 759 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 760 // we have a non-void block with an expression, continue checking 761 QualType RetValType = RetValExp->getType(); 762 763 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 764 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 765 // function return. 766 767 // In C++ the return statement is handled via a copy initialization. 768 // the C version of which boils down to CheckSingleAssignmentConstraints. 769 // FIXME: Leaks RetValExp. 770 if (PerformCopyInitialization(RetValExp, FnRetType, "returning")) 771 return StmtError(); 772 773 if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 774 } 775 776 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp)); 777} 778 779Action::OwningStmtResult 780Sema::ActOnReturnStmt(SourceLocation ReturnLoc, ExprArg rex) { 781 Expr *RetValExp = static_cast<Expr *>(rex.release()); 782 if (CurBlock) 783 return ActOnBlockReturnStmt(ReturnLoc, RetValExp); 784 785 QualType FnRetType; 786 if (FunctionDecl *FD = getCurFunctionDecl()) 787 FnRetType = FD->getResultType(); 788 else if (ObjCMethodDecl *MD = getCurMethodDecl()) 789 FnRetType = MD->getResultType(); 790 else // If we don't have a function/method context, bail. 791 return StmtError(); 792 793 if (FnRetType->isVoidType()) { 794 if (RetValExp) {// C99 6.8.6.4p1 (ext_ since GCC warns) 795 unsigned D = diag::ext_return_has_expr; 796 if (RetValExp->getType()->isVoidType()) 797 D = diag::ext_return_has_void_expr; 798 799 // return (some void expression); is legal in C++. 800 if (D != diag::ext_return_has_void_expr || 801 !getLangOptions().CPlusPlus) { 802 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 803 Diag(ReturnLoc, D) 804 << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl) 805 << RetValExp->getSourceRange(); 806 } 807 } 808 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp)); 809 } 810 811 if (!RetValExp) { 812 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4 813 // C99 6.8.6.4p1 (ext_ since GCC warns) 814 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr; 815 816 if (FunctionDecl *FD = getCurFunctionDecl()) 817 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/; 818 else 819 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/; 820 return Owned(new (Context) ReturnStmt(ReturnLoc, (Expr*)0)); 821 } 822 823 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 824 // we have a non-void function with an expression, continue checking 825 QualType RetValType = RetValExp->getType(); 826 827 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 828 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 829 // function return. 830 831 // In C++ the return statement is handled via a copy initialization. 832 // the C version of which boils down to CheckSingleAssignmentConstraints. 833 // FIXME: Leaks RetValExp. 834 if (PerformCopyInitialization(RetValExp, FnRetType, "returning")) 835 return StmtError(); 836 837 if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 838 } 839 840 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp)); 841} 842 843Sema::OwningStmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, 844 bool IsSimple, 845 bool IsVolatile, 846 unsigned NumOutputs, 847 unsigned NumInputs, 848 std::string *Names, 849 MultiExprArg constraints, 850 MultiExprArg exprs, 851 ExprArg asmString, 852 MultiExprArg clobbers, 853 SourceLocation RParenLoc) { 854 unsigned NumClobbers = clobbers.size(); 855 StringLiteral **Constraints = 856 reinterpret_cast<StringLiteral**>(constraints.get()); 857 Expr **Exprs = reinterpret_cast<Expr **>(exprs.get()); 858 StringLiteral *AsmString = cast<StringLiteral>((Expr *)asmString.get()); 859 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get()); 860 861 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; 862 863 // The parser verifies that there is a string literal here. 864 if (AsmString->isWide()) 865 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character) 866 << AsmString->getSourceRange()); 867 868 869 for (unsigned i = 0; i != NumOutputs; i++) { 870 StringLiteral *Literal = Constraints[i]; 871 if (Literal->isWide()) 872 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 873 << Literal->getSourceRange()); 874 875 std::string OutputConstraint(Literal->getStrData(), 876 Literal->getByteLength()); 877 878 TargetInfo::ConstraintInfo info; 879 if (!Context.Target.validateOutputConstraint(OutputConstraint.c_str(),info)) 880 return StmtError(Diag(Literal->getLocStart(), 881 diag::err_asm_invalid_output_constraint) << OutputConstraint); 882 883 // Check that the output exprs are valid lvalues. 884 ParenExpr *OutputExpr = cast<ParenExpr>(Exprs[i]); 885 Expr::isLvalueResult Result = OutputExpr->isLvalue(Context); 886 if (Result != Expr::LV_Valid) { 887 return StmtError(Diag(OutputExpr->getSubExpr()->getLocStart(), 888 diag::err_asm_invalid_lvalue_in_output) 889 << OutputExpr->getSubExpr()->getSourceRange()); 890 } 891 892 OutputConstraintInfos.push_back(info); 893 } 894 895 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) { 896 StringLiteral *Literal = Constraints[i]; 897 if (Literal->isWide()) 898 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 899 << Literal->getSourceRange()); 900 901 std::string InputConstraint(Literal->getStrData(), 902 Literal->getByteLength()); 903 904 TargetInfo::ConstraintInfo info; 905 if (!Context.Target.validateInputConstraint(InputConstraint.c_str(), 906 &Names[0], 907 &Names[0] + NumOutputs, 908 &OutputConstraintInfos[0], 909 info)) { 910 return StmtError(Diag(Literal->getLocStart(), 911 diag::err_asm_invalid_input_constraint) << InputConstraint); 912 } 913 914 ParenExpr *InputExpr = cast<ParenExpr>(Exprs[i]); 915 916 // Only allow void types for memory constraints. 917 if ((info & TargetInfo::CI_AllowsMemory) 918 && !(info & TargetInfo::CI_AllowsRegister)) { 919 if (InputExpr->isLvalue(Context) != Expr::LV_Valid) 920 return StmtError(Diag(InputExpr->getSubExpr()->getLocStart(), 921 diag::err_asm_invalid_lvalue_in_input) 922 << InputConstraint << InputExpr->getSubExpr()->getSourceRange()); 923 } 924 925 if (info & TargetInfo::CI_AllowsRegister) { 926 if (InputExpr->getType()->isVoidType()) { 927 return StmtError(Diag(InputExpr->getSubExpr()->getLocStart(), 928 diag::err_asm_invalid_type_in_input) 929 << InputExpr->getType() << InputConstraint 930 << InputExpr->getSubExpr()->getSourceRange()); 931 } 932 } 933 934 DefaultFunctionArrayConversion(Exprs[i]); 935 } 936 937 // Check that the clobbers are valid. 938 for (unsigned i = 0; i != NumClobbers; i++) { 939 StringLiteral *Literal = Clobbers[i]; 940 if (Literal->isWide()) 941 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 942 << Literal->getSourceRange()); 943 944 llvm::SmallString<16> Clobber(Literal->getStrData(), 945 Literal->getStrData() + 946 Literal->getByteLength()); 947 948 if (!Context.Target.isValidGCCRegisterName(Clobber.c_str())) 949 return StmtError(Diag(Literal->getLocStart(), 950 diag::err_asm_unknown_register_name) << Clobber.c_str()); 951 } 952 953 constraints.release(); 954 exprs.release(); 955 asmString.release(); 956 clobbers.release(); 957 return Owned(new (Context) AsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs, 958 NumInputs, Names, Constraints, Exprs, 959 AsmString, NumClobbers, 960 Clobbers, RParenLoc)); 961} 962 963Action::OwningStmtResult 964Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc, 965 SourceLocation RParen, DeclTy *Parm, 966 StmtArg Body, StmtArg catchList) { 967 Stmt *CatchList = static_cast<Stmt*>(catchList.release()); 968 ParmVarDecl *PVD = static_cast<ParmVarDecl*>(Parm); 969 970 // PVD == 0 implies @catch(...). 971 if (PVD) { 972 if (!Context.isObjCObjectPointerType(PVD->getType())) 973 return StmtError(Diag(PVD->getLocation(), 974 diag::err_catch_param_not_objc_type)); 975 if (PVD->getType()->isObjCQualifiedIdType()) 976 return StmtError(Diag(PVD->getLocation(), 977 diag::err_illegal_qualifiers_on_catch_parm)); 978 } 979 980 ObjCAtCatchStmt *CS = new (Context) ObjCAtCatchStmt(AtLoc, RParen, 981 PVD, static_cast<Stmt*>(Body.release()), CatchList); 982 return Owned(CatchList ? CatchList : CS); 983} 984 985Action::OwningStmtResult 986Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, StmtArg Body) { 987 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, 988 static_cast<Stmt*>(Body.release()))); 989} 990 991Action::OwningStmtResult 992Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, 993 StmtArg Try, StmtArg Catch, StmtArg Finally) { 994 return Owned(new (Context) ObjCAtTryStmt(AtLoc, 995 static_cast<Stmt*>(Try.release()), 996 static_cast<Stmt*>(Catch.release()), 997 static_cast<Stmt*>(Finally.release()))); 998} 999 1000Action::OwningStmtResult 1001Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, ExprArg expr,Scope *CurScope) { 1002 Expr *ThrowExpr = static_cast<Expr*>(expr.release()); 1003 if (!ThrowExpr) { 1004 // @throw without an expression designates a rethrow (which much occur 1005 // in the context of an @catch clause). 1006 Scope *AtCatchParent = CurScope; 1007 while (AtCatchParent && !AtCatchParent->isAtCatchScope()) 1008 AtCatchParent = AtCatchParent->getParent(); 1009 if (!AtCatchParent) 1010 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch)); 1011 } else { 1012 QualType ThrowType = ThrowExpr->getType(); 1013 // Make sure the expression type is an ObjC pointer or "void *". 1014 if (!Context.isObjCObjectPointerType(ThrowType)) { 1015 const PointerType *PT = ThrowType->getAsPointerType(); 1016 if (!PT || !PT->getPointeeType()->isVoidType()) 1017 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object) 1018 << ThrowExpr->getType() << ThrowExpr->getSourceRange()); 1019 } 1020 } 1021 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, ThrowExpr)); 1022} 1023 1024Action::OwningStmtResult 1025Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, ExprArg SynchExpr, 1026 StmtArg SynchBody) { 1027 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, 1028 static_cast<Stmt*>(SynchExpr.release()), 1029 static_cast<Stmt*>(SynchBody.release()))); 1030} 1031 1032/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block 1033/// and creates a proper catch handler from them. 1034Action::OwningStmtResult 1035Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, DeclTy *ExDecl, 1036 StmtArg HandlerBlock) { 1037 // There's nothing to test that ActOnExceptionDecl didn't already test. 1038 return Owned(new (Context) CXXCatchStmt(CatchLoc, 1039 static_cast<VarDecl*>(ExDecl), 1040 static_cast<Stmt*>(HandlerBlock.release()))); 1041} 1042 1043/// ActOnCXXTryBlock - Takes a try compound-statement and a number of 1044/// handlers and creates a try statement from them. 1045Action::OwningStmtResult 1046Sema::ActOnCXXTryBlock(SourceLocation TryLoc, StmtArg TryBlock, 1047 MultiStmtArg RawHandlers) { 1048 unsigned NumHandlers = RawHandlers.size(); 1049 assert(NumHandlers > 0 && 1050 "The parser shouldn't call this if there are no handlers."); 1051 Stmt **Handlers = reinterpret_cast<Stmt**>(RawHandlers.get()); 1052 1053 for(unsigned i = 0; i < NumHandlers - 1; ++i) { 1054 CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]); 1055 if (!Handler->getExceptionDecl()) 1056 return StmtError(Diag(Handler->getLocStart(), diag::err_early_catch_all)); 1057 } 1058 // FIXME: We should detect handlers for the same type as an earlier one. 1059 // This one is rather easy. 1060 // FIXME: We should detect handlers that cannot catch anything because an 1061 // earlier handler catches a superclass. Need to find a method that is not 1062 // quadratic for this. 1063 // Neither of these are explicitly forbidden, but every compiler detects them 1064 // and warns. 1065 1066 RawHandlers.release(); 1067 return Owned(new (Context) CXXTryStmt(TryLoc, 1068 static_cast<Stmt*>(TryBlock.release()), 1069 Handlers, NumHandlers)); 1070} 1071