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