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