SemaStmt.cpp revision 8cfe5a784133d90bf329fd20801824a6f71bb8ca
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/ExprCXX.h" 19#include "clang/AST/ExprObjC.h" 20#include "clang/AST/StmtObjC.h" 21#include "clang/AST/StmtCXX.h" 22#include "clang/Lex/Preprocessor.h" 23#include "clang/Basic/TargetInfo.h" 24#include "llvm/ADT/STLExtras.h" 25#include "llvm/ADT/SmallVector.h" 26using namespace clang; 27 28Sema::OwningStmtResult Sema::ActOnExprStmt(FullExprArg expr) { 29 Expr *E = expr->takeAs<Expr>(); 30 assert(E && "ActOnExprStmt(): missing expression"); 31 if (E->getType()->isObjCInterfaceType()) { 32 if (LangOpts.ObjCNonFragileABI) 33 Diag(E->getLocEnd(), diag::err_indirection_requires_nonfragile_object) 34 << E->getType(); 35 else 36 Diag(E->getLocEnd(), diag::err_direct_interface_unsupported) 37 << E->getType(); 38 return StmtError(); 39 } 40 // C99 6.8.3p2: The expression in an expression statement is evaluated as a 41 // void expression for its side effects. Conversion to void allows any 42 // operand, even incomplete types. 43 44 // Same thing in for stmt first clause (when expr) and third clause. 45 return Owned(static_cast<Stmt*>(E)); 46} 47 48 49Sema::OwningStmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc) { 50 return Owned(new (Context) NullStmt(SemiLoc)); 51} 52 53Sema::OwningStmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, 54 SourceLocation StartLoc, 55 SourceLocation EndLoc) { 56 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>(); 57 58 // If we have an invalid decl, just return an error. 59 if (DG.isNull()) return StmtError(); 60 61 return Owned(new (Context) DeclStmt(DG, StartLoc, EndLoc)); 62} 63 64void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) { 65 DeclGroupRef DG = dg.getAsVal<DeclGroupRef>(); 66 67 // If we have an invalid decl, just return. 68 if (DG.isNull() || !DG.isSingleDecl()) return; 69 // suppress any potential 'unused variable' warning. 70 DG.getSingleDecl()->setUsed(); 71} 72 73void Sema::DiagnoseUnusedExprResult(const Stmt *S) { 74 const Expr *E = dyn_cast_or_null<Expr>(S); 75 if (!E) 76 return; 77 78 // Ignore expressions that have void type. 79 if (E->getType()->isVoidType()) 80 return; 81 82 SourceLocation Loc; 83 SourceRange R1, R2; 84 if (!E->isUnusedResultAWarning(Loc, R1, R2, Context)) 85 return; 86 87 // Okay, we have an unused result. Depending on what the base expression is, 88 // we might want to make a more specific diagnostic. Check for one of these 89 // cases now. 90 unsigned DiagID = diag::warn_unused_expr; 91 E = E->IgnoreParens(); 92 if (isa<ObjCImplicitSetterGetterRefExpr>(E)) 93 DiagID = diag::warn_unused_property_expr; 94 95 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 96 // If the callee has attribute pure, const, or warn_unused_result, warn with 97 // a more specific message to make it clear what is happening. 98 if (const FunctionDecl *FD = CE->getDirectCallee()) { 99 if (FD->getAttr<WarnUnusedResultAttr>()) { 100 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "warn_unused_result"; 101 return; 102 } 103 if (FD->getAttr<PureAttr>()) { 104 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure"; 105 return; 106 } 107 if (FD->getAttr<ConstAttr>()) { 108 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const"; 109 return; 110 } 111 } 112 } 113 114 Diag(Loc, DiagID) << R1 << R2; 115} 116 117Action::OwningStmtResult 118Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R, 119 MultiStmtArg elts, bool isStmtExpr) { 120 unsigned NumElts = elts.size(); 121 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release()); 122 // If we're in C89 mode, check that we don't have any decls after stmts. If 123 // so, emit an extension diagnostic. 124 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus) { 125 // Note that __extension__ can be around a decl. 126 unsigned i = 0; 127 // Skip over all declarations. 128 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i) 129 /*empty*/; 130 131 // We found the end of the list or a statement. Scan for another declstmt. 132 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i) 133 /*empty*/; 134 135 if (i != NumElts) { 136 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin(); 137 Diag(D->getLocation(), diag::ext_mixed_decls_code); 138 } 139 } 140 // Warn about unused expressions in statements. 141 for (unsigned i = 0; i != NumElts; ++i) { 142 // Ignore statements that are last in a statement expression. 143 if (isStmtExpr && i == NumElts - 1) 144 continue; 145 146 DiagnoseUnusedExprResult(Elts[i]); 147 } 148 149 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R)); 150} 151 152Action::OwningStmtResult 153Sema::ActOnCaseStmt(SourceLocation CaseLoc, ExprArg lhsval, 154 SourceLocation DotDotDotLoc, ExprArg rhsval, 155 SourceLocation ColonLoc) { 156 assert((lhsval.get() != 0) && "missing expression in case statement"); 157 158 // C99 6.8.4.2p3: The expression shall be an integer constant. 159 // However, GCC allows any evaluatable integer expression. 160 Expr *LHSVal = static_cast<Expr*>(lhsval.get()); 161 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent() && 162 VerifyIntegerConstantExpression(LHSVal)) 163 return StmtError(); 164 165 // GCC extension: The expression shall be an integer constant. 166 167 Expr *RHSVal = static_cast<Expr*>(rhsval.get()); 168 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent() && 169 VerifyIntegerConstantExpression(RHSVal)) { 170 RHSVal = 0; // Recover by just forgetting about it. 171 rhsval = 0; 172 } 173 174 if (getSwitchStack().empty()) { 175 Diag(CaseLoc, diag::err_case_not_in_switch); 176 return StmtError(); 177 } 178 179 // Only now release the smart pointers. 180 lhsval.release(); 181 rhsval.release(); 182 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc, 183 ColonLoc); 184 getSwitchStack().back()->addSwitchCase(CS); 185 return Owned(CS); 186} 187 188/// ActOnCaseStmtBody - This installs a statement as the body of a case. 189void Sema::ActOnCaseStmtBody(StmtTy *caseStmt, StmtArg subStmt) { 190 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt); 191 Stmt *SubStmt = subStmt.takeAs<Stmt>(); 192 CS->setSubStmt(SubStmt); 193} 194 195Action::OwningStmtResult 196Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, 197 StmtArg subStmt, Scope *CurScope) { 198 Stmt *SubStmt = subStmt.takeAs<Stmt>(); 199 200 if (getSwitchStack().empty()) { 201 Diag(DefaultLoc, diag::err_default_not_in_switch); 202 return Owned(SubStmt); 203 } 204 205 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt); 206 getSwitchStack().back()->addSwitchCase(DS); 207 return Owned(DS); 208} 209 210Action::OwningStmtResult 211Sema::ActOnLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II, 212 SourceLocation ColonLoc, StmtArg subStmt) { 213 Stmt *SubStmt = subStmt.takeAs<Stmt>(); 214 // Look up the record for this label identifier. 215 LabelStmt *&LabelDecl = getLabelMap()[II]; 216 217 // If not forward referenced or defined already, just create a new LabelStmt. 218 if (LabelDecl == 0) 219 return Owned(LabelDecl = new (Context) LabelStmt(IdentLoc, II, SubStmt)); 220 221 assert(LabelDecl->getID() == II && "Label mismatch!"); 222 223 // Otherwise, this label was either forward reference or multiply defined. If 224 // multiply defined, reject it now. 225 if (LabelDecl->getSubStmt()) { 226 Diag(IdentLoc, diag::err_redefinition_of_label) << LabelDecl->getID(); 227 Diag(LabelDecl->getIdentLoc(), diag::note_previous_definition); 228 return Owned(SubStmt); 229 } 230 231 // Otherwise, this label was forward declared, and we just found its real 232 // definition. Fill in the forward definition and return it. 233 LabelDecl->setIdentLoc(IdentLoc); 234 LabelDecl->setSubStmt(SubStmt); 235 return Owned(LabelDecl); 236} 237 238Action::OwningStmtResult 239Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, 240 StmtArg ThenVal, SourceLocation ElseLoc, 241 StmtArg ElseVal) { 242 OwningExprResult CondResult(CondVal.release()); 243 244 Expr *condExpr = CondResult.takeAs<Expr>(); 245 assert(condExpr && "ActOnIfStmt(): missing expression"); 246 247 VarDecl *ConditionVar = 0; 248 if (CXXConditionDeclExpr *Cond = dyn_cast<CXXConditionDeclExpr>(condExpr)) { 249 ConditionVar = Cond->getVarDecl(); 250 condExpr = DeclRefExpr::Create(Context, 0, SourceRange(), ConditionVar, 251 ConditionVar->getLocation(), 252 ConditionVar->getType().getNonReferenceType()); 253 // FIXME: Leaks the old condExpr 254 } 255 256 if (CheckBooleanCondition(condExpr, IfLoc)) { 257 CondResult = condExpr; 258 return StmtError(); 259 } 260 261 Stmt *thenStmt = ThenVal.takeAs<Stmt>(); 262 DiagnoseUnusedExprResult(thenStmt); 263 264 // Warn if the if block has a null body without an else value. 265 // this helps prevent bugs due to typos, such as 266 // if (condition); 267 // do_stuff(); 268 if (!ElseVal.get()) { 269 if (NullStmt* stmt = dyn_cast<NullStmt>(thenStmt)) 270 Diag(stmt->getSemiLoc(), diag::warn_empty_if_body); 271 } 272 273 Stmt *elseStmt = ElseVal.takeAs<Stmt>(); 274 DiagnoseUnusedExprResult(elseStmt); 275 276 CondResult.release(); 277 return Owned(new (Context) IfStmt(IfLoc, ConditionVar, condExpr, thenStmt, 278 ElseLoc, elseStmt)); 279} 280 281Action::OwningStmtResult 282Sema::ActOnStartOfSwitchStmt(ExprArg cond) { 283 SwitchStmt *SS = new (Context) SwitchStmt(cond.takeAs<Expr>()); 284 getSwitchStack().push_back(SS); 285 return Owned(SS); 286} 287 288/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 289/// the specified width and sign. If an overflow occurs, detect it and emit 290/// the specified diagnostic. 291void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val, 292 unsigned NewWidth, bool NewSign, 293 SourceLocation Loc, 294 unsigned DiagID) { 295 // Perform a conversion to the promoted condition type if needed. 296 if (NewWidth > Val.getBitWidth()) { 297 // If this is an extension, just do it. 298 llvm::APSInt OldVal(Val); 299 Val.extend(NewWidth); 300 301 // If the input was signed and negative and the output is unsigned, 302 // warn. 303 if (!NewSign && OldVal.isSigned() && OldVal.isNegative()) 304 Diag(Loc, DiagID) << OldVal.toString(10) << Val.toString(10); 305 306 Val.setIsSigned(NewSign); 307 } else if (NewWidth < Val.getBitWidth()) { 308 // If this is a truncation, check for overflow. 309 llvm::APSInt ConvVal(Val); 310 ConvVal.trunc(NewWidth); 311 ConvVal.setIsSigned(NewSign); 312 ConvVal.extend(Val.getBitWidth()); 313 ConvVal.setIsSigned(Val.isSigned()); 314 if (ConvVal != Val) 315 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10); 316 317 // Regardless of whether a diagnostic was emitted, really do the 318 // truncation. 319 Val.trunc(NewWidth); 320 Val.setIsSigned(NewSign); 321 } else if (NewSign != Val.isSigned()) { 322 // Convert the sign to match the sign of the condition. This can cause 323 // overflow as well: unsigned(INTMIN) 324 llvm::APSInt OldVal(Val); 325 Val.setIsSigned(NewSign); 326 327 if (Val.isNegative()) // Sign bit changes meaning. 328 Diag(Loc, DiagID) << OldVal.toString(10) << Val.toString(10); 329 } 330} 331 332namespace { 333 struct CaseCompareFunctor { 334 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 335 const llvm::APSInt &RHS) { 336 return LHS.first < RHS; 337 } 338 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 339 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 340 return LHS.first < RHS.first; 341 } 342 bool operator()(const llvm::APSInt &LHS, 343 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 344 return LHS < RHS.first; 345 } 346 }; 347} 348 349/// CmpCaseVals - Comparison predicate for sorting case values. 350/// 351static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs, 352 const std::pair<llvm::APSInt, CaseStmt*>& rhs) { 353 if (lhs.first < rhs.first) 354 return true; 355 356 if (lhs.first == rhs.first && 357 lhs.second->getCaseLoc().getRawEncoding() 358 < rhs.second->getCaseLoc().getRawEncoding()) 359 return true; 360 return false; 361} 362 363/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of 364/// potentially integral-promoted expression @p expr. 365static QualType GetTypeBeforeIntegralPromotion(const Expr* expr) { 366 const ImplicitCastExpr *ImplicitCast = 367 dyn_cast_or_null<ImplicitCastExpr>(expr); 368 if (ImplicitCast != NULL) { 369 const Expr *ExprBeforePromotion = ImplicitCast->getSubExpr(); 370 QualType TypeBeforePromotion = ExprBeforePromotion->getType(); 371 if (TypeBeforePromotion->isIntegralType()) { 372 return TypeBeforePromotion; 373 } 374 } 375 return expr->getType(); 376} 377 378Action::OwningStmtResult 379Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, StmtArg Switch, 380 StmtArg Body) { 381 Stmt *BodyStmt = Body.takeAs<Stmt>(); 382 383 SwitchStmt *SS = getSwitchStack().back(); 384 assert(SS == (SwitchStmt*)Switch.get() && "switch stack missing push/pop!"); 385 386 SS->setBody(BodyStmt, SwitchLoc); 387 getSwitchStack().pop_back(); 388 389 Expr *CondExpr = SS->getCond(); 390 QualType CondTypeBeforePromotion = 391 GetTypeBeforeIntegralPromotion(CondExpr); 392 QualType CondType = CondExpr->getType(); 393 394 if (getLangOptions().CPlusPlus) { 395 // C++ 6.4.2.p2: 396 // The condition shall be of integral type, enumeration type, or of a class 397 // type for which a single conversion function to integral or enumeration 398 // type exists (12.3). If the condition is of class type, the condition is 399 // converted by calling that conversion function, and the result of the 400 // conversion is used in place of the original condition for the remainder 401 // of this section. Integral promotions are performed. 402 if (!CondExpr->isTypeDependent()) { 403 // Make sure that the condition expression has a complete type, 404 // otherwise we'll never find any conversions. 405 if (RequireCompleteType(SwitchLoc, CondType, 406 PDiag(diag::err_switch_incomplete_class_type) 407 << CondExpr->getSourceRange())) 408 return StmtError(); 409 410 llvm::SmallVector<CXXConversionDecl *, 4> ViableConversions; 411 llvm::SmallVector<CXXConversionDecl *, 4> ExplicitConversions; 412 if (const RecordType *RecordTy = CondType->getAs<RecordType>()) { 413 const UnresolvedSet *Conversions 414 = cast<CXXRecordDecl>(RecordTy->getDecl()) 415 ->getVisibleConversionFunctions(); 416 for (UnresolvedSet::iterator I = Conversions->begin(), 417 E = Conversions->end(); I != E; ++I) { 418 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(*I)) 419 if (Conversion->getConversionType().getNonReferenceType() 420 ->isIntegralType()) { 421 if (Conversion->isExplicit()) 422 ExplicitConversions.push_back(Conversion); 423 else 424 ViableConversions.push_back(Conversion); 425 } 426 } 427 428 switch (ViableConversions.size()) { 429 case 0: 430 if (ExplicitConversions.size() == 1) { 431 // The user probably meant to invoke the given explicit 432 // conversion; use it. 433 QualType ConvTy 434 = ExplicitConversions[0]->getConversionType() 435 .getNonReferenceType(); 436 std::string TypeStr; 437 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy); 438 439 440 Diag(SwitchLoc, diag::err_switch_explicit_conversion) 441 << CondType << ConvTy << CondExpr->getSourceRange() 442 << CodeModificationHint::CreateInsertion(CondExpr->getLocStart(), 443 "static_cast<" + TypeStr + ">(") 444 << CodeModificationHint::CreateInsertion( 445 PP.getLocForEndOfToken(CondExpr->getLocEnd()), 446 ")"); 447 Diag(ExplicitConversions[0]->getLocation(), 448 diag::note_switch_conversion) 449 << ConvTy->isEnumeralType() << ConvTy; 450 451 // If we aren't in a SFINAE context, build a call to the 452 // explicit conversion function. 453 if (!isSFINAEContext()) 454 CondExpr = BuildCXXMemberCallExpr(CondExpr, 455 ExplicitConversions[0]); 456 } 457 458 // We'll complain below about a non-integral condition type. 459 break; 460 461 case 1: 462 // Apply this conversion. 463 CondExpr = BuildCXXMemberCallExpr(CondExpr, ViableConversions[0]); 464 break; 465 466 default: 467 Diag(SwitchLoc, diag::err_switch_multiple_conversions) 468 << CondType << CondExpr->getSourceRange(); 469 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 470 QualType ConvTy 471 = ViableConversions[I]->getConversionType() 472 .getNonReferenceType(); 473 Diag(ViableConversions[I]->getLocation(), 474 diag::note_switch_conversion) 475 << ConvTy->isEnumeralType() << ConvTy; 476 } 477 return StmtError(); 478 } 479 } 480 CondType = CondExpr->getType(); 481 482 if (CondType->isIntegralType() || CondType->isEnumeralType()) { 483 // Integral promotions are performed. 484 UsualUnaryConversions(CondExpr); 485 } 486 } 487 } else { 488 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr. 489 UsualUnaryConversions(CondExpr); 490 } 491 CondType = CondExpr->getType(); 492 SS->setCond(CondExpr); 493 494 // C++ 6.4.2.p2: 495 // Integral promotions are performed (on the switch condition). 496 // 497 // A case value unrepresentable by the original switch condition 498 // type (before the promotion) doesn't make sense, even when it can 499 // be represented by the promoted type. Therefore we need to find 500 // the pre-promotion type of the switch condition. 501 if (!CondExpr->isTypeDependent()) { 502 if (!CondType->isIntegerType()) { // C99 6.8.4.2p1 503 Diag(SwitchLoc, diag::err_typecheck_statement_requires_integer) 504 << CondType << CondExpr->getSourceRange(); 505 return StmtError(); 506 } 507 508 if (CondTypeBeforePromotion->isBooleanType()) { 509 // switch(bool_expr) {...} is often a programmer error, e.g. 510 // switch(n && mask) { ... } // Doh - should be "n & mask". 511 // One can always use an if statement instead of switch(bool_expr). 512 Diag(SwitchLoc, diag::warn_bool_switch_condition) 513 << CondExpr->getSourceRange(); 514 } 515 } 516 517 // Get the bitwidth of the switched-on value before promotions. We must 518 // convert the integer case values to this width before comparison. 519 bool HasDependentValue 520 = CondExpr->isTypeDependent() || CondExpr->isValueDependent(); 521 unsigned CondWidth 522 = HasDependentValue? 0 523 : static_cast<unsigned>(Context.getTypeSize(CondTypeBeforePromotion)); 524 bool CondIsSigned = CondTypeBeforePromotion->isSignedIntegerType(); 525 526 // Accumulate all of the case values in a vector so that we can sort them 527 // and detect duplicates. This vector contains the APInt for the case after 528 // it has been converted to the condition type. 529 typedef llvm::SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy; 530 CaseValsTy CaseVals; 531 532 // Keep track of any GNU case ranges we see. The APSInt is the low value. 533 std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRanges; 534 535 DefaultStmt *TheDefaultStmt = 0; 536 537 bool CaseListIsErroneous = false; 538 539 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue; 540 SC = SC->getNextSwitchCase()) { 541 542 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) { 543 if (TheDefaultStmt) { 544 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined); 545 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev); 546 547 // FIXME: Remove the default statement from the switch block so that 548 // we'll return a valid AST. This requires recursing down the AST and 549 // finding it, not something we are set up to do right now. For now, 550 // just lop the entire switch stmt out of the AST. 551 CaseListIsErroneous = true; 552 } 553 TheDefaultStmt = DS; 554 555 } else { 556 CaseStmt *CS = cast<CaseStmt>(SC); 557 558 // We already verified that the expression has a i-c-e value (C99 559 // 6.8.4.2p3) - get that value now. 560 Expr *Lo = CS->getLHS(); 561 562 if (Lo->isTypeDependent() || Lo->isValueDependent()) { 563 HasDependentValue = true; 564 break; 565 } 566 567 llvm::APSInt LoVal = Lo->EvaluateAsInt(Context); 568 569 // Convert the value to the same width/sign as the condition. 570 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned, 571 CS->getLHS()->getLocStart(), 572 diag::warn_case_value_overflow); 573 574 // If the LHS is not the same type as the condition, insert an implicit 575 // cast. 576 ImpCastExprToType(Lo, CondType, CastExpr::CK_IntegralCast); 577 CS->setLHS(Lo); 578 579 // If this is a case range, remember it in CaseRanges, otherwise CaseVals. 580 if (CS->getRHS()) { 581 if (CS->getRHS()->isTypeDependent() || 582 CS->getRHS()->isValueDependent()) { 583 HasDependentValue = true; 584 break; 585 } 586 CaseRanges.push_back(std::make_pair(LoVal, CS)); 587 } else 588 CaseVals.push_back(std::make_pair(LoVal, CS)); 589 } 590 } 591 592 if (!HasDependentValue) { 593 // Sort all the scalar case values so we can easily detect duplicates. 594 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals); 595 596 if (!CaseVals.empty()) { 597 for (unsigned i = 0, e = CaseVals.size()-1; i != e; ++i) { 598 if (CaseVals[i].first == CaseVals[i+1].first) { 599 // If we have a duplicate, report it. 600 Diag(CaseVals[i+1].second->getLHS()->getLocStart(), 601 diag::err_duplicate_case) << CaseVals[i].first.toString(10); 602 Diag(CaseVals[i].second->getLHS()->getLocStart(), 603 diag::note_duplicate_case_prev); 604 // FIXME: We really want to remove the bogus case stmt from the 605 // substmt, but we have no way to do this right now. 606 CaseListIsErroneous = true; 607 } 608 } 609 } 610 611 // Detect duplicate case ranges, which usually don't exist at all in 612 // the first place. 613 if (!CaseRanges.empty()) { 614 // Sort all the case ranges by their low value so we can easily detect 615 // overlaps between ranges. 616 std::stable_sort(CaseRanges.begin(), CaseRanges.end()); 617 618 // Scan the ranges, computing the high values and removing empty ranges. 619 std::vector<llvm::APSInt> HiVals; 620 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 621 CaseStmt *CR = CaseRanges[i].second; 622 Expr *Hi = CR->getRHS(); 623 llvm::APSInt HiVal = Hi->EvaluateAsInt(Context); 624 625 // Convert the value to the same width/sign as the condition. 626 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned, 627 CR->getRHS()->getLocStart(), 628 diag::warn_case_value_overflow); 629 630 // If the LHS is not the same type as the condition, insert an implicit 631 // cast. 632 ImpCastExprToType(Hi, CondType, CastExpr::CK_IntegralCast); 633 CR->setRHS(Hi); 634 635 // If the low value is bigger than the high value, the case is empty. 636 if (CaseRanges[i].first > HiVal) { 637 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range) 638 << SourceRange(CR->getLHS()->getLocStart(), 639 CR->getRHS()->getLocEnd()); 640 CaseRanges.erase(CaseRanges.begin()+i); 641 --i, --e; 642 continue; 643 } 644 HiVals.push_back(HiVal); 645 } 646 647 // Rescan the ranges, looking for overlap with singleton values and other 648 // ranges. Since the range list is sorted, we only need to compare case 649 // ranges with their neighbors. 650 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 651 llvm::APSInt &CRLo = CaseRanges[i].first; 652 llvm::APSInt &CRHi = HiVals[i]; 653 CaseStmt *CR = CaseRanges[i].second; 654 655 // Check to see whether the case range overlaps with any 656 // singleton cases. 657 CaseStmt *OverlapStmt = 0; 658 llvm::APSInt OverlapVal(32); 659 660 // Find the smallest value >= the lower bound. If I is in the 661 // case range, then we have overlap. 662 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(), 663 CaseVals.end(), CRLo, 664 CaseCompareFunctor()); 665 if (I != CaseVals.end() && I->first < CRHi) { 666 OverlapVal = I->first; // Found overlap with scalar. 667 OverlapStmt = I->second; 668 } 669 670 // Find the smallest value bigger than the upper bound. 671 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor()); 672 if (I != CaseVals.begin() && (I-1)->first >= CRLo) { 673 OverlapVal = (I-1)->first; // Found overlap with scalar. 674 OverlapStmt = (I-1)->second; 675 } 676 677 // Check to see if this case stmt overlaps with the subsequent 678 // case range. 679 if (i && CRLo <= HiVals[i-1]) { 680 OverlapVal = HiVals[i-1]; // Found overlap with range. 681 OverlapStmt = CaseRanges[i-1].second; 682 } 683 684 if (OverlapStmt) { 685 // If we have a duplicate, report it. 686 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case) 687 << OverlapVal.toString(10); 688 Diag(OverlapStmt->getLHS()->getLocStart(), 689 diag::note_duplicate_case_prev); 690 // FIXME: We really want to remove the bogus case stmt from the 691 // substmt, but we have no way to do this right now. 692 CaseListIsErroneous = true; 693 } 694 } 695 } 696 } 697 698 // FIXME: If the case list was broken is some way, we don't have a good system 699 // to patch it up. Instead, just return the whole substmt as broken. 700 if (CaseListIsErroneous) 701 return StmtError(); 702 703 Switch.release(); 704 return Owned(SS); 705} 706 707Action::OwningStmtResult 708Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond, StmtArg Body) { 709 ExprArg CondArg(Cond.release()); 710 Expr *condExpr = CondArg.takeAs<Expr>(); 711 assert(condExpr && "ActOnWhileStmt(): missing expression"); 712 713 if (CheckBooleanCondition(condExpr, WhileLoc)) { 714 CondArg = condExpr; 715 return StmtError(); 716 } 717 718 Stmt *bodyStmt = Body.takeAs<Stmt>(); 719 DiagnoseUnusedExprResult(bodyStmt); 720 721 CondArg.release(); 722 return Owned(new (Context) WhileStmt(condExpr, bodyStmt, WhileLoc)); 723} 724 725Action::OwningStmtResult 726Sema::ActOnDoStmt(SourceLocation DoLoc, StmtArg Body, 727 SourceLocation WhileLoc, SourceLocation CondLParen, 728 ExprArg Cond, SourceLocation CondRParen) { 729 Expr *condExpr = Cond.takeAs<Expr>(); 730 assert(condExpr && "ActOnDoStmt(): missing expression"); 731 732 if (CheckBooleanCondition(condExpr, DoLoc)) { 733 Cond = condExpr; 734 return StmtError(); 735 } 736 737 Stmt *bodyStmt = Body.takeAs<Stmt>(); 738 DiagnoseUnusedExprResult(bodyStmt); 739 740 Cond.release(); 741 return Owned(new (Context) DoStmt(bodyStmt, condExpr, DoLoc, 742 WhileLoc, CondRParen)); 743} 744 745Action::OwningStmtResult 746Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 747 StmtArg first, ExprArg second, ExprArg third, 748 SourceLocation RParenLoc, StmtArg body) { 749 Stmt *First = static_cast<Stmt*>(first.get()); 750 Expr *Second = second.takeAs<Expr>(); 751 Expr *Third = static_cast<Expr*>(third.get()); 752 Stmt *Body = static_cast<Stmt*>(body.get()); 753 754 if (!getLangOptions().CPlusPlus) { 755 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) { 756 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 757 // declare identifiers for objects having storage class 'auto' or 758 // 'register'. 759 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end(); 760 DI!=DE; ++DI) { 761 VarDecl *VD = dyn_cast<VarDecl>(*DI); 762 if (VD && VD->isBlockVarDecl() && !VD->hasLocalStorage()) 763 VD = 0; 764 if (VD == 0) 765 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for); 766 // FIXME: mark decl erroneous! 767 } 768 } 769 } 770 if (Second && CheckBooleanCondition(Second, ForLoc)) { 771 second = Second; 772 return StmtError(); 773 } 774 775 DiagnoseUnusedExprResult(First); 776 DiagnoseUnusedExprResult(Third); 777 DiagnoseUnusedExprResult(Body); 778 779 first.release(); 780 third.release(); 781 body.release(); 782 return Owned(new (Context) ForStmt(First, Second, Third, Body, ForLoc, 783 LParenLoc, RParenLoc)); 784} 785 786Action::OwningStmtResult 787Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc, 788 SourceLocation LParenLoc, 789 StmtArg first, ExprArg second, 790 SourceLocation RParenLoc, StmtArg body) { 791 Stmt *First = static_cast<Stmt*>(first.get()); 792 Expr *Second = static_cast<Expr*>(second.get()); 793 Stmt *Body = static_cast<Stmt*>(body.get()); 794 if (First) { 795 QualType FirstType; 796 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) { 797 if (!DS->isSingleDecl()) 798 return StmtError(Diag((*DS->decl_begin())->getLocation(), 799 diag::err_toomany_element_decls)); 800 801 Decl *D = DS->getSingleDecl(); 802 FirstType = cast<ValueDecl>(D)->getType(); 803 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 804 // declare identifiers for objects having storage class 'auto' or 805 // 'register'. 806 VarDecl *VD = cast<VarDecl>(D); 807 if (VD->isBlockVarDecl() && !VD->hasLocalStorage()) 808 return StmtError(Diag(VD->getLocation(), 809 diag::err_non_variable_decl_in_for)); 810 } else { 811 if (cast<Expr>(First)->isLvalue(Context) != Expr::LV_Valid) 812 return StmtError(Diag(First->getLocStart(), 813 diag::err_selector_element_not_lvalue) 814 << First->getSourceRange()); 815 816 FirstType = static_cast<Expr*>(First)->getType(); 817 } 818 if (!FirstType->isObjCObjectPointerType() && 819 !FirstType->isBlockPointerType()) 820 Diag(ForLoc, diag::err_selector_element_type) 821 << FirstType << First->getSourceRange(); 822 } 823 if (Second) { 824 DefaultFunctionArrayConversion(Second); 825 QualType SecondType = Second->getType(); 826 if (!SecondType->isObjCObjectPointerType()) 827 Diag(ForLoc, diag::err_collection_expr_type) 828 << SecondType << Second->getSourceRange(); 829 } 830 first.release(); 831 second.release(); 832 body.release(); 833 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body, 834 ForLoc, RParenLoc)); 835} 836 837Action::OwningStmtResult 838Sema::ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, 839 IdentifierInfo *LabelII) { 840 // If we are in a block, reject all gotos for now. 841 if (CurBlock) 842 return StmtError(Diag(GotoLoc, diag::err_goto_in_block)); 843 844 // Look up the record for this label identifier. 845 LabelStmt *&LabelDecl = getLabelMap()[LabelII]; 846 847 // If we haven't seen this label yet, create a forward reference. 848 if (LabelDecl == 0) 849 LabelDecl = new (Context) LabelStmt(LabelLoc, LabelII, 0); 850 851 return Owned(new (Context) GotoStmt(LabelDecl, GotoLoc, LabelLoc)); 852} 853 854Action::OwningStmtResult 855Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, 856 ExprArg DestExp) { 857 // Convert operand to void* 858 Expr* E = DestExp.takeAs<Expr>(); 859 if (!E->isTypeDependent()) { 860 QualType ETy = E->getType(); 861 AssignConvertType ConvTy = 862 CheckSingleAssignmentConstraints(Context.VoidPtrTy, E); 863 if (DiagnoseAssignmentResult(ConvTy, StarLoc, Context.VoidPtrTy, ETy, 864 E, "passing")) 865 return StmtError(); 866 } 867 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E)); 868} 869 870Action::OwningStmtResult 871Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) { 872 Scope *S = CurScope->getContinueParent(); 873 if (!S) { 874 // C99 6.8.6.2p1: A break shall appear only in or as a loop body. 875 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop)); 876 } 877 878 return Owned(new (Context) ContinueStmt(ContinueLoc)); 879} 880 881Action::OwningStmtResult 882Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) { 883 Scope *S = CurScope->getBreakParent(); 884 if (!S) { 885 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body. 886 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch)); 887 } 888 889 return Owned(new (Context) BreakStmt(BreakLoc)); 890} 891 892/// ActOnBlockReturnStmt - Utility routine to figure out block's return type. 893/// 894Action::OwningStmtResult 895Sema::ActOnBlockReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 896 // If this is the first return we've seen in the block, infer the type of 897 // the block from it. 898 if (CurBlock->ReturnType.isNull()) { 899 if (RetValExp) { 900 // Don't call UsualUnaryConversions(), since we don't want to do 901 // integer promotions here. 902 DefaultFunctionArrayConversion(RetValExp); 903 CurBlock->ReturnType = RetValExp->getType(); 904 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(RetValExp)) { 905 // We have to remove a 'const' added to copied-in variable which was 906 // part of the implementation spec. and not the actual qualifier for 907 // the variable. 908 if (CDRE->isConstQualAdded()) 909 CurBlock->ReturnType.removeConst(); 910 } 911 } else 912 CurBlock->ReturnType = Context.VoidTy; 913 } 914 QualType FnRetType = CurBlock->ReturnType; 915 916 if (CurBlock->TheDecl->hasAttr<NoReturnAttr>()) { 917 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr) 918 << getCurFunctionOrMethodDecl()->getDeclName(); 919 return StmtError(); 920 } 921 922 // Otherwise, verify that this result type matches the previous one. We are 923 // pickier with blocks than for normal functions because we don't have GCC 924 // compatibility to worry about here. 925 if (CurBlock->ReturnType->isVoidType()) { 926 if (RetValExp) { 927 Diag(ReturnLoc, diag::err_return_block_has_expr); 928 RetValExp->Destroy(Context); 929 RetValExp = 0; 930 } 931 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp)); 932 } 933 934 if (!RetValExp) 935 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr)); 936 937 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 938 // we have a non-void block with an expression, continue checking 939 QualType RetValType = RetValExp->getType(); 940 941 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 942 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 943 // function return. 944 945 // In C++ the return statement is handled via a copy initialization. 946 // the C version of which boils down to CheckSingleAssignmentConstraints. 947 // FIXME: Leaks RetValExp. 948 if (PerformCopyInitialization(RetValExp, FnRetType, "returning")) 949 return StmtError(); 950 951 if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 952 } 953 954 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp)); 955} 956 957/// IsReturnCopyElidable - Whether returning @p RetExpr from a function that 958/// returns a @p RetType fulfills the criteria for copy elision (C++0x 12.8p15). 959static bool IsReturnCopyElidable(ASTContext &Ctx, QualType RetType, 960 Expr *RetExpr) { 961 QualType ExprType = RetExpr->getType(); 962 // - in a return statement in a function with ... 963 // ... a class return type ... 964 if (!RetType->isRecordType()) 965 return false; 966 // ... the same cv-unqualified type as the function return type ... 967 if (!Ctx.hasSameUnqualifiedType(RetType, ExprType)) 968 return false; 969 // ... the expression is the name of a non-volatile automatic object ... 970 // We ignore parentheses here. 971 // FIXME: Is this compliant? 972 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(RetExpr->IgnoreParens()); 973 if (!DR) 974 return false; 975 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()); 976 if (!VD) 977 return false; 978 return VD->hasLocalStorage() && !VD->getType()->isReferenceType() 979 && !VD->getType().isVolatileQualified(); 980} 981 982Action::OwningStmtResult 983Sema::ActOnReturnStmt(SourceLocation ReturnLoc, ExprArg rex) { 984 Expr *RetValExp = rex.takeAs<Expr>(); 985 if (CurBlock) 986 return ActOnBlockReturnStmt(ReturnLoc, RetValExp); 987 988 QualType FnRetType; 989 if (const FunctionDecl *FD = getCurFunctionDecl()) { 990 FnRetType = FD->getResultType(); 991 if (FD->hasAttr<NoReturnAttr>()) 992 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) 993 << getCurFunctionOrMethodDecl()->getDeclName(); 994 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) 995 FnRetType = MD->getResultType(); 996 else // If we don't have a function/method context, bail. 997 return StmtError(); 998 999 if (FnRetType->isVoidType()) { 1000 if (RetValExp && !RetValExp->isTypeDependent()) { 1001 // C99 6.8.6.4p1 (ext_ since GCC warns) 1002 unsigned D = diag::ext_return_has_expr; 1003 if (RetValExp->getType()->isVoidType()) 1004 D = diag::ext_return_has_void_expr; 1005 1006 // return (some void expression); is legal in C++. 1007 if (D != diag::ext_return_has_void_expr || 1008 !getLangOptions().CPlusPlus) { 1009 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 1010 Diag(ReturnLoc, D) 1011 << CurDecl->getDeclName() << isa<ObjCMethodDecl>(CurDecl) 1012 << RetValExp->getSourceRange(); 1013 } 1014 1015 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp, true); 1016 } 1017 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp)); 1018 } 1019 1020 if (!RetValExp && !FnRetType->isDependentType()) { 1021 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4 1022 // C99 6.8.6.4p1 (ext_ since GCC warns) 1023 if (getLangOptions().C99) DiagID = diag::ext_return_missing_expr; 1024 1025 if (FunctionDecl *FD = getCurFunctionDecl()) 1026 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/; 1027 else 1028 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/; 1029 return Owned(new (Context) ReturnStmt(ReturnLoc, (Expr*)0)); 1030 } 1031 1032 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 1033 // we have a non-void function with an expression, continue checking 1034 1035 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 1036 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 1037 // function return. 1038 1039 // C++0x 12.8p15: When certain criteria are met, an implementation is 1040 // allowed to omit the copy construction of a class object, [...] 1041 // - in a return statement in a function with a class return type, when 1042 // the expression is the name of a non-volatile automatic object with 1043 // the same cv-unqualified type as the function return type, the copy 1044 // operation can be omitted [...] 1045 // C++0x 12.8p16: When the criteria for elision of a copy operation are met 1046 // and the object to be copied is designated by an lvalue, overload 1047 // resolution to select the constructor for the copy is first performed 1048 // as if the object were designated by an rvalue. 1049 // Note that we only compute Elidable if we're in C++0x, since we don't 1050 // care otherwise. 1051 bool Elidable = getLangOptions().CPlusPlus0x ? 1052 IsReturnCopyElidable(Context, FnRetType, RetValExp) : 1053 false; 1054 1055 // In C++ the return statement is handled via a copy initialization. 1056 // the C version of which boils down to CheckSingleAssignmentConstraints. 1057 // FIXME: Leaks RetValExp on error. 1058 if (PerformCopyInitialization(RetValExp, FnRetType, "returning", Elidable)){ 1059 // We should still clean up our temporaries, even when we're failing! 1060 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp, true); 1061 return StmtError(); 1062 } 1063 1064 if (RetValExp) CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 1065 } 1066 1067 if (RetValExp) 1068 RetValExp = MaybeCreateCXXExprWithTemporaries(RetValExp, true); 1069 return Owned(new (Context) ReturnStmt(ReturnLoc, RetValExp)); 1070} 1071 1072/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently 1073/// ignore "noop" casts in places where an lvalue is required by an inline asm. 1074/// We emulate this behavior when -fheinous-gnu-extensions is specified, but 1075/// provide a strong guidance to not use it. 1076/// 1077/// This method checks to see if the argument is an acceptable l-value and 1078/// returns false if it is a case we can handle. 1079static bool CheckAsmLValue(const Expr *E, Sema &S) { 1080 if (E->isLvalue(S.Context) == Expr::LV_Valid) 1081 return false; // Cool, this is an lvalue. 1082 1083 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we 1084 // are supposed to allow. 1085 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context); 1086 if (E != E2 && E2->isLvalue(S.Context) == Expr::LV_Valid) { 1087 if (!S.getLangOptions().HeinousExtensions) 1088 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue) 1089 << E->getSourceRange(); 1090 else 1091 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue) 1092 << E->getSourceRange(); 1093 // Accept, even if we emitted an error diagnostic. 1094 return false; 1095 } 1096 1097 // None of the above, just randomly invalid non-lvalue. 1098 return true; 1099} 1100 1101 1102Sema::OwningStmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, 1103 bool IsSimple, 1104 bool IsVolatile, 1105 unsigned NumOutputs, 1106 unsigned NumInputs, 1107 std::string *Names, 1108 MultiExprArg constraints, 1109 MultiExprArg exprs, 1110 ExprArg asmString, 1111 MultiExprArg clobbers, 1112 SourceLocation RParenLoc) { 1113 unsigned NumClobbers = clobbers.size(); 1114 StringLiteral **Constraints = 1115 reinterpret_cast<StringLiteral**>(constraints.get()); 1116 Expr **Exprs = reinterpret_cast<Expr **>(exprs.get()); 1117 StringLiteral *AsmString = cast<StringLiteral>((Expr *)asmString.get()); 1118 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get()); 1119 1120 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; 1121 1122 // The parser verifies that there is a string literal here. 1123 if (AsmString->isWide()) 1124 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character) 1125 << AsmString->getSourceRange()); 1126 1127 for (unsigned i = 0; i != NumOutputs; i++) { 1128 StringLiteral *Literal = Constraints[i]; 1129 if (Literal->isWide()) 1130 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 1131 << Literal->getSourceRange()); 1132 1133 TargetInfo::ConstraintInfo Info(Literal->getStrData(), 1134 Literal->getByteLength(), 1135 Names[i]); 1136 if (!Context.Target.validateOutputConstraint(Info)) 1137 return StmtError(Diag(Literal->getLocStart(), 1138 diag::err_asm_invalid_output_constraint) 1139 << Info.getConstraintStr()); 1140 1141 // Check that the output exprs are valid lvalues. 1142 Expr *OutputExpr = Exprs[i]; 1143 if (CheckAsmLValue(OutputExpr, *this)) { 1144 return StmtError(Diag(OutputExpr->getLocStart(), 1145 diag::err_asm_invalid_lvalue_in_output) 1146 << OutputExpr->getSourceRange()); 1147 } 1148 1149 OutputConstraintInfos.push_back(Info); 1150 } 1151 1152 llvm::SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos; 1153 1154 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) { 1155 StringLiteral *Literal = Constraints[i]; 1156 if (Literal->isWide()) 1157 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 1158 << Literal->getSourceRange()); 1159 1160 TargetInfo::ConstraintInfo Info(Literal->getStrData(), 1161 Literal->getByteLength(), 1162 Names[i]); 1163 if (!Context.Target.validateInputConstraint(OutputConstraintInfos.data(), 1164 NumOutputs, Info)) { 1165 return StmtError(Diag(Literal->getLocStart(), 1166 diag::err_asm_invalid_input_constraint) 1167 << Info.getConstraintStr()); 1168 } 1169 1170 Expr *InputExpr = Exprs[i]; 1171 1172 // Only allow void types for memory constraints. 1173 if (Info.allowsMemory() && !Info.allowsRegister()) { 1174 if (CheckAsmLValue(InputExpr, *this)) 1175 return StmtError(Diag(InputExpr->getLocStart(), 1176 diag::err_asm_invalid_lvalue_in_input) 1177 << Info.getConstraintStr() 1178 << InputExpr->getSourceRange()); 1179 } 1180 1181 if (Info.allowsRegister()) { 1182 if (InputExpr->getType()->isVoidType()) { 1183 return StmtError(Diag(InputExpr->getLocStart(), 1184 diag::err_asm_invalid_type_in_input) 1185 << InputExpr->getType() << Info.getConstraintStr() 1186 << InputExpr->getSourceRange()); 1187 } 1188 } 1189 1190 DefaultFunctionArrayConversion(Exprs[i]); 1191 1192 InputConstraintInfos.push_back(Info); 1193 } 1194 1195 // Check that the clobbers are valid. 1196 for (unsigned i = 0; i != NumClobbers; i++) { 1197 StringLiteral *Literal = Clobbers[i]; 1198 if (Literal->isWide()) 1199 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 1200 << Literal->getSourceRange()); 1201 1202 std::string Clobber(Literal->getStrData(), 1203 Literal->getStrData() + 1204 Literal->getByteLength()); 1205 1206 if (!Context.Target.isValidGCCRegisterName(Clobber.c_str())) 1207 return StmtError(Diag(Literal->getLocStart(), 1208 diag::err_asm_unknown_register_name) << Clobber); 1209 } 1210 1211 constraints.release(); 1212 exprs.release(); 1213 asmString.release(); 1214 clobbers.release(); 1215 AsmStmt *NS = 1216 new (Context) AsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs, 1217 Names, Constraints, Exprs, AsmString, NumClobbers, 1218 Clobbers, RParenLoc); 1219 // Validate the asm string, ensuring it makes sense given the operands we 1220 // have. 1221 llvm::SmallVector<AsmStmt::AsmStringPiece, 8> Pieces; 1222 unsigned DiagOffs; 1223 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) { 1224 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID) 1225 << AsmString->getSourceRange(); 1226 DeleteStmt(NS); 1227 return StmtError(); 1228 } 1229 1230 // Validate tied input operands for type mismatches. 1231 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) { 1232 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i]; 1233 1234 // If this is a tied constraint, verify that the output and input have 1235 // either exactly the same type, or that they are int/ptr operands with the 1236 // same size (int/long, int*/long, are ok etc). 1237 if (!Info.hasTiedOperand()) continue; 1238 1239 unsigned TiedTo = Info.getTiedOperand(); 1240 Expr *OutputExpr = Exprs[TiedTo]; 1241 Expr *InputExpr = Exprs[i+NumOutputs]; 1242 QualType InTy = InputExpr->getType(); 1243 QualType OutTy = OutputExpr->getType(); 1244 if (Context.hasSameType(InTy, OutTy)) 1245 continue; // All types can be tied to themselves. 1246 1247 // Int/ptr operands have some special cases that we allow. 1248 if ((OutTy->isIntegerType() || OutTy->isPointerType()) && 1249 (InTy->isIntegerType() || InTy->isPointerType())) { 1250 1251 // They are ok if they are the same size. Tying void* to int is ok if 1252 // they are the same size, for example. This also allows tying void* to 1253 // int*. 1254 uint64_t OutSize = Context.getTypeSize(OutTy); 1255 uint64_t InSize = Context.getTypeSize(InTy); 1256 if (OutSize == InSize) 1257 continue; 1258 1259 // If the smaller input/output operand is not mentioned in the asm string, 1260 // then we can promote it and the asm string won't notice. Check this 1261 // case now. 1262 bool SmallerValueMentioned = false; 1263 for (unsigned p = 0, e = Pieces.size(); p != e; ++p) { 1264 AsmStmt::AsmStringPiece &Piece = Pieces[p]; 1265 if (!Piece.isOperand()) continue; 1266 1267 // If this is a reference to the input and if the input was the smaller 1268 // one, then we have to reject this asm. 1269 if (Piece.getOperandNo() == i+NumOutputs) { 1270 if (InSize < OutSize) { 1271 SmallerValueMentioned = true; 1272 break; 1273 } 1274 } 1275 1276 // If this is a reference to the input and if the input was the smaller 1277 // one, then we have to reject this asm. 1278 if (Piece.getOperandNo() == TiedTo) { 1279 if (InSize > OutSize) { 1280 SmallerValueMentioned = true; 1281 break; 1282 } 1283 } 1284 } 1285 1286 // If the smaller value wasn't mentioned in the asm string, and if the 1287 // output was a register, just extend the shorter one to the size of the 1288 // larger one. 1289 if (!SmallerValueMentioned && 1290 OutputConstraintInfos[TiedTo].allowsRegister()) 1291 continue; 1292 } 1293 1294 Diag(InputExpr->getLocStart(), 1295 diag::err_asm_tying_incompatible_types) 1296 << InTy << OutTy << OutputExpr->getSourceRange() 1297 << InputExpr->getSourceRange(); 1298 DeleteStmt(NS); 1299 return StmtError(); 1300 } 1301 1302 return Owned(NS); 1303} 1304 1305Action::OwningStmtResult 1306Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc, 1307 SourceLocation RParen, DeclPtrTy Parm, 1308 StmtArg Body, StmtArg catchList) { 1309 Stmt *CatchList = catchList.takeAs<Stmt>(); 1310 ParmVarDecl *PVD = cast_or_null<ParmVarDecl>(Parm.getAs<Decl>()); 1311 1312 // PVD == 0 implies @catch(...). 1313 if (PVD) { 1314 // If we already know the decl is invalid, reject it. 1315 if (PVD->isInvalidDecl()) 1316 return StmtError(); 1317 1318 if (!PVD->getType()->isObjCObjectPointerType()) 1319 return StmtError(Diag(PVD->getLocation(), 1320 diag::err_catch_param_not_objc_type)); 1321 if (PVD->getType()->isObjCQualifiedIdType()) 1322 return StmtError(Diag(PVD->getLocation(), 1323 diag::err_illegal_qualifiers_on_catch_parm)); 1324 } 1325 1326 ObjCAtCatchStmt *CS = new (Context) ObjCAtCatchStmt(AtLoc, RParen, 1327 PVD, Body.takeAs<Stmt>(), CatchList); 1328 return Owned(CatchList ? CatchList : CS); 1329} 1330 1331Action::OwningStmtResult 1332Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, StmtArg Body) { 1333 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, 1334 static_cast<Stmt*>(Body.release()))); 1335} 1336 1337Action::OwningStmtResult 1338Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, 1339 StmtArg Try, StmtArg Catch, StmtArg Finally) { 1340 CurFunctionNeedsScopeChecking = true; 1341 return Owned(new (Context) ObjCAtTryStmt(AtLoc, Try.takeAs<Stmt>(), 1342 Catch.takeAs<Stmt>(), 1343 Finally.takeAs<Stmt>())); 1344} 1345 1346Action::OwningStmtResult 1347Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, ExprArg expr,Scope *CurScope) { 1348 Expr *ThrowExpr = expr.takeAs<Expr>(); 1349 if (!ThrowExpr) { 1350 // @throw without an expression designates a rethrow (which much occur 1351 // in the context of an @catch clause). 1352 Scope *AtCatchParent = CurScope; 1353 while (AtCatchParent && !AtCatchParent->isAtCatchScope()) 1354 AtCatchParent = AtCatchParent->getParent(); 1355 if (!AtCatchParent) 1356 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch)); 1357 } else { 1358 QualType ThrowType = ThrowExpr->getType(); 1359 // Make sure the expression type is an ObjC pointer or "void *". 1360 if (!ThrowType->isObjCObjectPointerType()) { 1361 const PointerType *PT = ThrowType->getAs<PointerType>(); 1362 if (!PT || !PT->getPointeeType()->isVoidType()) 1363 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object) 1364 << ThrowExpr->getType() << ThrowExpr->getSourceRange()); 1365 } 1366 } 1367 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, ThrowExpr)); 1368} 1369 1370Action::OwningStmtResult 1371Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, ExprArg SynchExpr, 1372 StmtArg SynchBody) { 1373 CurFunctionNeedsScopeChecking = true; 1374 1375 // Make sure the expression type is an ObjC pointer or "void *". 1376 Expr *SyncExpr = static_cast<Expr*>(SynchExpr.get()); 1377 if (!SyncExpr->getType()->isObjCObjectPointerType()) { 1378 const PointerType *PT = SyncExpr->getType()->getAs<PointerType>(); 1379 if (!PT || !PT->getPointeeType()->isVoidType()) 1380 return StmtError(Diag(AtLoc, diag::error_objc_synchronized_expects_object) 1381 << SyncExpr->getType() << SyncExpr->getSourceRange()); 1382 } 1383 1384 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, 1385 SynchExpr.takeAs<Stmt>(), 1386 SynchBody.takeAs<Stmt>())); 1387} 1388 1389/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block 1390/// and creates a proper catch handler from them. 1391Action::OwningStmtResult 1392Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, DeclPtrTy ExDecl, 1393 StmtArg HandlerBlock) { 1394 // There's nothing to test that ActOnExceptionDecl didn't already test. 1395 return Owned(new (Context) CXXCatchStmt(CatchLoc, 1396 cast_or_null<VarDecl>(ExDecl.getAs<Decl>()), 1397 HandlerBlock.takeAs<Stmt>())); 1398} 1399 1400class TypeWithHandler { 1401 QualType t; 1402 CXXCatchStmt *stmt; 1403public: 1404 TypeWithHandler(const QualType &type, CXXCatchStmt *statement) 1405 : t(type), stmt(statement) {} 1406 1407 // An arbitrary order is fine as long as it places identical 1408 // types next to each other. 1409 bool operator<(const TypeWithHandler &y) const { 1410 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr()) 1411 return true; 1412 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr()) 1413 return false; 1414 else 1415 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc(); 1416 } 1417 1418 bool operator==(const TypeWithHandler& other) const { 1419 return t == other.t; 1420 } 1421 1422 QualType getQualType() const { return t; } 1423 CXXCatchStmt *getCatchStmt() const { return stmt; } 1424 SourceLocation getTypeSpecStartLoc() const { 1425 return stmt->getExceptionDecl()->getTypeSpecStartLoc(); 1426 } 1427}; 1428 1429/// ActOnCXXTryBlock - Takes a try compound-statement and a number of 1430/// handlers and creates a try statement from them. 1431Action::OwningStmtResult 1432Sema::ActOnCXXTryBlock(SourceLocation TryLoc, StmtArg TryBlock, 1433 MultiStmtArg RawHandlers) { 1434 unsigned NumHandlers = RawHandlers.size(); 1435 assert(NumHandlers > 0 && 1436 "The parser shouldn't call this if there are no handlers."); 1437 Stmt **Handlers = reinterpret_cast<Stmt**>(RawHandlers.get()); 1438 1439 llvm::SmallVector<TypeWithHandler, 8> TypesWithHandlers; 1440 1441 for (unsigned i = 0; i < NumHandlers; ++i) { 1442 CXXCatchStmt *Handler = llvm::cast<CXXCatchStmt>(Handlers[i]); 1443 if (!Handler->getExceptionDecl()) { 1444 if (i < NumHandlers - 1) 1445 return StmtError(Diag(Handler->getLocStart(), 1446 diag::err_early_catch_all)); 1447 1448 continue; 1449 } 1450 1451 const QualType CaughtType = Handler->getCaughtType(); 1452 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType); 1453 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler)); 1454 } 1455 1456 // Detect handlers for the same type as an earlier one. 1457 if (NumHandlers > 1) { 1458 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end()); 1459 1460 TypeWithHandler prev = TypesWithHandlers[0]; 1461 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) { 1462 TypeWithHandler curr = TypesWithHandlers[i]; 1463 1464 if (curr == prev) { 1465 Diag(curr.getTypeSpecStartLoc(), 1466 diag::warn_exception_caught_by_earlier_handler) 1467 << curr.getCatchStmt()->getCaughtType().getAsString(); 1468 Diag(prev.getTypeSpecStartLoc(), 1469 diag::note_previous_exception_handler) 1470 << prev.getCatchStmt()->getCaughtType().getAsString(); 1471 } 1472 1473 prev = curr; 1474 } 1475 } 1476 1477 // FIXME: We should detect handlers that cannot catch anything because an 1478 // earlier handler catches a superclass. Need to find a method that is not 1479 // quadratic for this. 1480 // Neither of these are explicitly forbidden, but every compiler detects them 1481 // and warns. 1482 1483 CurFunctionNeedsScopeChecking = true; 1484 RawHandlers.release(); 1485 return Owned(new (Context) CXXTryStmt(TryLoc, 1486 static_cast<Stmt*>(TryBlock.release()), 1487 Handlers, NumHandlers)); 1488} 1489