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