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