SemaStmt.cpp revision 7e725bc7a099fefa5e0f03e2208838d3cdf064e3
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 "clang/Sema/SemaInternal.h" 15#include "clang/Sema/Scope.h" 16#include "clang/Sema/ScopeInfo.h" 17#include "clang/Sema/Initialization.h" 18#include "clang/Sema/Lookup.h" 19#include "clang/AST/ASTContext.h" 20#include "clang/AST/CharUnits.h" 21#include "clang/AST/DeclObjC.h" 22#include "clang/AST/ExprCXX.h" 23#include "clang/AST/ExprObjC.h" 24#include "clang/AST/StmtObjC.h" 25#include "clang/AST/StmtCXX.h" 26#include "clang/AST/TypeLoc.h" 27#include "clang/Lex/Preprocessor.h" 28#include "clang/Basic/TargetInfo.h" 29#include "llvm/ADT/ArrayRef.h" 30#include "llvm/ADT/STLExtras.h" 31#include "llvm/ADT/SmallVector.h" 32using namespace clang; 33using namespace sema; 34 35StmtResult Sema::ActOnExprStmt(FullExprArg expr) { 36 Expr *E = expr.get(); 37 if (!E) // FIXME: FullExprArg has no error state? 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 49StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc, 50 bool HasLeadingEmptyMacro) { 51 return Owned(new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro)); 52} 53 54StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, 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 VarDecl *var = cast<VarDecl>(DG.getSingleDecl()); 70 71 // suppress any potential 'unused variable' warning. 72 var->setUsed(); 73 74 // foreach variables are never actually initialized in the way that 75 // the parser came up with. 76 var->setInit(0); 77 78 // In ARC, we don't need to retain the iteration variable of a fast 79 // enumeration loop. Rather than actually trying to catch that 80 // during declaration processing, we remove the consequences here. 81 if (getLangOpts().ObjCAutoRefCount) { 82 QualType type = var->getType(); 83 84 // Only do this if we inferred the lifetime. Inferred lifetime 85 // will show up as a local qualifier because explicit lifetime 86 // should have shown up as an AttributedType instead. 87 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) { 88 // Add 'const' and mark the variable as pseudo-strong. 89 var->setType(type.withConst()); 90 var->setARCPseudoStrong(true); 91 } 92 } 93} 94 95/// \brief Diagnose unused '==' and '!=' as likely typos for '=' or '|='. 96/// 97/// Adding a cast to void (or other expression wrappers) will prevent the 98/// warning from firing. 99static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) { 100 SourceLocation Loc; 101 bool IsNotEqual, CanAssign; 102 103 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 104 if (Op->getOpcode() != BO_EQ && Op->getOpcode() != BO_NE) 105 return false; 106 107 Loc = Op->getOperatorLoc(); 108 IsNotEqual = Op->getOpcode() == BO_NE; 109 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue(); 110 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 111 if (Op->getOperator() != OO_EqualEqual && 112 Op->getOperator() != OO_ExclaimEqual) 113 return false; 114 115 Loc = Op->getOperatorLoc(); 116 IsNotEqual = Op->getOperator() == OO_ExclaimEqual; 117 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue(); 118 } else { 119 // Not a typo-prone comparison. 120 return false; 121 } 122 123 // Suppress warnings when the operator, suspicious as it may be, comes from 124 // a macro expansion. 125 if (Loc.isMacroID()) 126 return false; 127 128 S.Diag(Loc, diag::warn_unused_comparison) 129 << (unsigned)IsNotEqual << E->getSourceRange(); 130 131 // If the LHS is a plausible entity to assign to, provide a fixit hint to 132 // correct common typos. 133 if (CanAssign) { 134 if (IsNotEqual) 135 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign) 136 << FixItHint::CreateReplacement(Loc, "|="); 137 else 138 S.Diag(Loc, diag::note_equality_comparison_to_assign) 139 << FixItHint::CreateReplacement(Loc, "="); 140 } 141 142 return true; 143} 144 145void Sema::DiagnoseUnusedExprResult(const Stmt *S) { 146 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) 147 return DiagnoseUnusedExprResult(Label->getSubStmt()); 148 149 const Expr *E = dyn_cast_or_null<Expr>(S); 150 if (!E) 151 return; 152 153 SourceLocation Loc; 154 SourceRange R1, R2; 155 if (SourceMgr.isInSystemMacro(E->getExprLoc()) || 156 !E->isUnusedResultAWarning(Loc, R1, R2, Context)) 157 return; 158 159 // Okay, we have an unused result. Depending on what the base expression is, 160 // we might want to make a more specific diagnostic. Check for one of these 161 // cases now. 162 unsigned DiagID = diag::warn_unused_expr; 163 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E)) 164 E = Temps->getSubExpr(); 165 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E)) 166 E = TempExpr->getSubExpr(); 167 168 if (DiagnoseUnusedComparison(*this, E)) 169 return; 170 171 E = E->IgnoreParenImpCasts(); 172 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 173 if (E->getType()->isVoidType()) 174 return; 175 176 // If the callee has attribute pure, const, or warn_unused_result, warn with 177 // a more specific message to make it clear what is happening. 178 if (const Decl *FD = CE->getCalleeDecl()) { 179 if (FD->getAttr<WarnUnusedResultAttr>()) { 180 Diag(Loc, diag::warn_unused_result) << R1 << R2; 181 return; 182 } 183 if (FD->getAttr<PureAttr>()) { 184 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure"; 185 return; 186 } 187 if (FD->getAttr<ConstAttr>()) { 188 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const"; 189 return; 190 } 191 } 192 } else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) { 193 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) { 194 Diag(Loc, diag::err_arc_unused_init_message) << R1; 195 return; 196 } 197 const ObjCMethodDecl *MD = ME->getMethodDecl(); 198 if (MD && MD->getAttr<WarnUnusedResultAttr>()) { 199 Diag(Loc, diag::warn_unused_result) << R1 << R2; 200 return; 201 } 202 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 203 const Expr *Source = POE->getSyntacticForm(); 204 if (isa<ObjCSubscriptRefExpr>(Source)) 205 DiagID = diag::warn_unused_container_subscript_expr; 206 else 207 DiagID = diag::warn_unused_property_expr; 208 } else if (const CXXFunctionalCastExpr *FC 209 = dyn_cast<CXXFunctionalCastExpr>(E)) { 210 if (isa<CXXConstructExpr>(FC->getSubExpr()) || 211 isa<CXXTemporaryObjectExpr>(FC->getSubExpr())) 212 return; 213 } 214 // Diagnose "(void*) blah" as a typo for "(void) blah". 215 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) { 216 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 217 QualType T = TI->getType(); 218 219 // We really do want to use the non-canonical type here. 220 if (T == Context.VoidPtrTy) { 221 PointerTypeLoc TL = cast<PointerTypeLoc>(TI->getTypeLoc()); 222 223 Diag(Loc, diag::warn_unused_voidptr) 224 << FixItHint::CreateRemoval(TL.getStarLoc()); 225 return; 226 } 227 } 228 229 DiagRuntimeBehavior(Loc, 0, PDiag(DiagID) << R1 << R2); 230} 231 232void Sema::ActOnStartOfCompoundStmt() { 233 PushCompoundScope(); 234} 235 236void Sema::ActOnFinishOfCompoundStmt() { 237 PopCompoundScope(); 238} 239 240sema::CompoundScopeInfo &Sema::getCurCompoundScope() const { 241 return getCurFunction()->CompoundScopes.back(); 242} 243 244StmtResult 245Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R, 246 MultiStmtArg elts, bool isStmtExpr) { 247 unsigned NumElts = elts.size(); 248 Stmt **Elts = reinterpret_cast<Stmt**>(elts.release()); 249 // If we're in C89 mode, check that we don't have any decls after stmts. If 250 // so, emit an extension diagnostic. 251 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) { 252 // Note that __extension__ can be around a decl. 253 unsigned i = 0; 254 // Skip over all declarations. 255 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i) 256 /*empty*/; 257 258 // We found the end of the list or a statement. Scan for another declstmt. 259 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i) 260 /*empty*/; 261 262 if (i != NumElts) { 263 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin(); 264 Diag(D->getLocation(), diag::ext_mixed_decls_code); 265 } 266 } 267 // Warn about unused expressions in statements. 268 for (unsigned i = 0; i != NumElts; ++i) { 269 // Ignore statements that are last in a statement expression. 270 if (isStmtExpr && i == NumElts - 1) 271 continue; 272 273 DiagnoseUnusedExprResult(Elts[i]); 274 } 275 276 // Check for suspicious empty body (null statement) in `for' and `while' 277 // statements. Don't do anything for template instantiations, this just adds 278 // noise. 279 if (NumElts != 0 && !CurrentInstantiationScope && 280 getCurCompoundScope().HasEmptyLoopBodies) { 281 for (unsigned i = 0; i != NumElts - 1; ++i) 282 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]); 283 } 284 285 return Owned(new (Context) CompoundStmt(Context, Elts, NumElts, L, R)); 286} 287 288StmtResult 289Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal, 290 SourceLocation DotDotDotLoc, Expr *RHSVal, 291 SourceLocation ColonLoc) { 292 assert((LHSVal != 0) && "missing expression in case statement"); 293 294 if (getCurFunction()->SwitchStack.empty()) { 295 Diag(CaseLoc, diag::err_case_not_in_switch); 296 return StmtError(); 297 } 298 299 if (!getLangOpts().CPlusPlus0x) { 300 // C99 6.8.4.2p3: The expression shall be an integer constant. 301 // However, GCC allows any evaluatable integer expression. 302 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) { 303 LHSVal = VerifyIntegerConstantExpression(LHSVal).take(); 304 if (!LHSVal) 305 return StmtError(); 306 } 307 308 // GCC extension: The expression shall be an integer constant. 309 310 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) { 311 RHSVal = VerifyIntegerConstantExpression(RHSVal).take(); 312 // Recover from an error by just forgetting about it. 313 } 314 } 315 316 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc, 317 ColonLoc); 318 getCurFunction()->SwitchStack.back()->addSwitchCase(CS); 319 return Owned(CS); 320} 321 322/// ActOnCaseStmtBody - This installs a statement as the body of a case. 323void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) { 324 DiagnoseUnusedExprResult(SubStmt); 325 326 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt); 327 CS->setSubStmt(SubStmt); 328} 329 330StmtResult 331Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, 332 Stmt *SubStmt, Scope *CurScope) { 333 DiagnoseUnusedExprResult(SubStmt); 334 335 if (getCurFunction()->SwitchStack.empty()) { 336 Diag(DefaultLoc, diag::err_default_not_in_switch); 337 return Owned(SubStmt); 338 } 339 340 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt); 341 getCurFunction()->SwitchStack.back()->addSwitchCase(DS); 342 return Owned(DS); 343} 344 345StmtResult 346Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 347 SourceLocation ColonLoc, Stmt *SubStmt) { 348 349 // If the label was multiply defined, reject it now. 350 if (TheDecl->getStmt()) { 351 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName(); 352 Diag(TheDecl->getLocation(), diag::note_previous_definition); 353 return Owned(SubStmt); 354 } 355 356 // Otherwise, things are good. Fill in the declaration and return it. 357 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt); 358 TheDecl->setStmt(LS); 359 if (!TheDecl->isGnuLocal()) 360 TheDecl->setLocation(IdentLoc); 361 return Owned(LS); 362} 363 364StmtResult 365Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar, 366 Stmt *thenStmt, SourceLocation ElseLoc, 367 Stmt *elseStmt) { 368 ExprResult CondResult(CondVal.release()); 369 370 VarDecl *ConditionVar = 0; 371 if (CondVar) { 372 ConditionVar = cast<VarDecl>(CondVar); 373 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true); 374 if (CondResult.isInvalid()) 375 return StmtError(); 376 } 377 Expr *ConditionExpr = CondResult.takeAs<Expr>(); 378 if (!ConditionExpr) 379 return StmtError(); 380 381 DiagnoseUnusedExprResult(thenStmt); 382 383 if (!elseStmt) { 384 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt, 385 diag::warn_empty_if_body); 386 } 387 388 DiagnoseUnusedExprResult(elseStmt); 389 390 return Owned(new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr, 391 thenStmt, ElseLoc, elseStmt)); 392} 393 394/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 395/// the specified width and sign. If an overflow occurs, detect it and emit 396/// the specified diagnostic. 397void Sema::ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &Val, 398 unsigned NewWidth, bool NewSign, 399 SourceLocation Loc, 400 unsigned DiagID) { 401 // Perform a conversion to the promoted condition type if needed. 402 if (NewWidth > Val.getBitWidth()) { 403 // If this is an extension, just do it. 404 Val = Val.extend(NewWidth); 405 Val.setIsSigned(NewSign); 406 407 // If the input was signed and negative and the output is 408 // unsigned, don't bother to warn: this is implementation-defined 409 // behavior. 410 // FIXME: Introduce a second, default-ignored warning for this case? 411 } else if (NewWidth < Val.getBitWidth()) { 412 // If this is a truncation, check for overflow. 413 llvm::APSInt ConvVal(Val); 414 ConvVal = ConvVal.trunc(NewWidth); 415 ConvVal.setIsSigned(NewSign); 416 ConvVal = ConvVal.extend(Val.getBitWidth()); 417 ConvVal.setIsSigned(Val.isSigned()); 418 if (ConvVal != Val) 419 Diag(Loc, DiagID) << Val.toString(10) << ConvVal.toString(10); 420 421 // Regardless of whether a diagnostic was emitted, really do the 422 // truncation. 423 Val = Val.trunc(NewWidth); 424 Val.setIsSigned(NewSign); 425 } else if (NewSign != Val.isSigned()) { 426 // Convert the sign to match the sign of the condition. This can cause 427 // overflow as well: unsigned(INTMIN) 428 // We don't diagnose this overflow, because it is implementation-defined 429 // behavior. 430 // FIXME: Introduce a second, default-ignored warning for this case? 431 llvm::APSInt OldVal(Val); 432 Val.setIsSigned(NewSign); 433 } 434} 435 436namespace { 437 struct CaseCompareFunctor { 438 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 439 const llvm::APSInt &RHS) { 440 return LHS.first < RHS; 441 } 442 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 443 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 444 return LHS.first < RHS.first; 445 } 446 bool operator()(const llvm::APSInt &LHS, 447 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 448 return LHS < RHS.first; 449 } 450 }; 451} 452 453/// CmpCaseVals - Comparison predicate for sorting case values. 454/// 455static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs, 456 const std::pair<llvm::APSInt, CaseStmt*>& rhs) { 457 if (lhs.first < rhs.first) 458 return true; 459 460 if (lhs.first == rhs.first && 461 lhs.second->getCaseLoc().getRawEncoding() 462 < rhs.second->getCaseLoc().getRawEncoding()) 463 return true; 464 return false; 465} 466 467/// CmpEnumVals - Comparison predicate for sorting enumeration values. 468/// 469static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 470 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 471{ 472 return lhs.first < rhs.first; 473} 474 475/// EqEnumVals - Comparison preficate for uniqing enumeration values. 476/// 477static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 478 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 479{ 480 return lhs.first == rhs.first; 481} 482 483/// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of 484/// potentially integral-promoted expression @p expr. 485static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) { 486 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr)) 487 expr = cleanups->getSubExpr(); 488 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) { 489 if (impcast->getCastKind() != CK_IntegralCast) break; 490 expr = impcast->getSubExpr(); 491 } 492 return expr->getType(); 493} 494 495StmtResult 496Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond, 497 Decl *CondVar) { 498 ExprResult CondResult; 499 500 VarDecl *ConditionVar = 0; 501 if (CondVar) { 502 ConditionVar = cast<VarDecl>(CondVar); 503 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false); 504 if (CondResult.isInvalid()) 505 return StmtError(); 506 507 Cond = CondResult.release(); 508 } 509 510 if (!Cond) 511 return StmtError(); 512 513 CondResult 514 = ConvertToIntegralOrEnumerationType(SwitchLoc, Cond, 515 PDiag(diag::err_typecheck_statement_requires_integer), 516 PDiag(diag::err_switch_incomplete_class_type) 517 << Cond->getSourceRange(), 518 PDiag(diag::err_switch_explicit_conversion), 519 PDiag(diag::note_switch_conversion), 520 PDiag(diag::err_switch_multiple_conversions), 521 PDiag(diag::note_switch_conversion), 522 PDiag(0), 523 /*AllowScopedEnumerations*/ true); 524 if (CondResult.isInvalid()) return StmtError(); 525 Cond = CondResult.take(); 526 527 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr. 528 CondResult = UsualUnaryConversions(Cond); 529 if (CondResult.isInvalid()) return StmtError(); 530 Cond = CondResult.take(); 531 532 if (!CondVar) { 533 CheckImplicitConversions(Cond, SwitchLoc); 534 CondResult = MaybeCreateExprWithCleanups(Cond); 535 if (CondResult.isInvalid()) 536 return StmtError(); 537 Cond = CondResult.take(); 538 } 539 540 getCurFunction()->setHasBranchIntoScope(); 541 542 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond); 543 getCurFunction()->SwitchStack.push_back(SS); 544 return Owned(SS); 545} 546 547static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) { 548 if (Val.getBitWidth() < BitWidth) 549 Val = Val.extend(BitWidth); 550 else if (Val.getBitWidth() > BitWidth) 551 Val = Val.trunc(BitWidth); 552 Val.setIsSigned(IsSigned); 553} 554 555StmtResult 556Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, 557 Stmt *BodyStmt) { 558 SwitchStmt *SS = cast<SwitchStmt>(Switch); 559 assert(SS == getCurFunction()->SwitchStack.back() && 560 "switch stack missing push/pop!"); 561 562 SS->setBody(BodyStmt, SwitchLoc); 563 getCurFunction()->SwitchStack.pop_back(); 564 565 Expr *CondExpr = SS->getCond(); 566 if (!CondExpr) return StmtError(); 567 568 QualType CondType = CondExpr->getType(); 569 570 Expr *CondExprBeforePromotion = CondExpr; 571 QualType CondTypeBeforePromotion = 572 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion); 573 574 // C++ 6.4.2.p2: 575 // Integral promotions are performed (on the switch condition). 576 // 577 // A case value unrepresentable by the original switch condition 578 // type (before the promotion) doesn't make sense, even when it can 579 // be represented by the promoted type. Therefore we need to find 580 // the pre-promotion type of the switch condition. 581 if (!CondExpr->isTypeDependent()) { 582 // We have already converted the expression to an integral or enumeration 583 // type, when we started the switch statement. If we don't have an 584 // appropriate type now, just return an error. 585 if (!CondType->isIntegralOrEnumerationType()) 586 return StmtError(); 587 588 if (CondExpr->isKnownToHaveBooleanValue()) { 589 // switch(bool_expr) {...} is often a programmer error, e.g. 590 // switch(n && mask) { ... } // Doh - should be "n & mask". 591 // One can always use an if statement instead of switch(bool_expr). 592 Diag(SwitchLoc, diag::warn_bool_switch_condition) 593 << CondExpr->getSourceRange(); 594 } 595 } 596 597 // Get the bitwidth of the switched-on value before promotions. We must 598 // convert the integer case values to this width before comparison. 599 bool HasDependentValue 600 = CondExpr->isTypeDependent() || CondExpr->isValueDependent(); 601 unsigned CondWidth 602 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion); 603 bool CondIsSigned 604 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType(); 605 606 // Accumulate all of the case values in a vector so that we can sort them 607 // and detect duplicates. This vector contains the APInt for the case after 608 // it has been converted to the condition type. 609 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy; 610 CaseValsTy CaseVals; 611 612 // Keep track of any GNU case ranges we see. The APSInt is the low value. 613 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy; 614 CaseRangesTy CaseRanges; 615 616 DefaultStmt *TheDefaultStmt = 0; 617 618 bool CaseListIsErroneous = false; 619 620 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue; 621 SC = SC->getNextSwitchCase()) { 622 623 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) { 624 if (TheDefaultStmt) { 625 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined); 626 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev); 627 628 // FIXME: Remove the default statement from the switch block so that 629 // we'll return a valid AST. This requires recursing down the AST and 630 // finding it, not something we are set up to do right now. For now, 631 // just lop the entire switch stmt out of the AST. 632 CaseListIsErroneous = true; 633 } 634 TheDefaultStmt = DS; 635 636 } else { 637 CaseStmt *CS = cast<CaseStmt>(SC); 638 639 Expr *Lo = CS->getLHS(); 640 641 if (Lo->isTypeDependent() || Lo->isValueDependent()) { 642 HasDependentValue = true; 643 break; 644 } 645 646 llvm::APSInt LoVal; 647 648 if (getLangOpts().CPlusPlus0x) { 649 // C++11 [stmt.switch]p2: the constant-expression shall be a converted 650 // constant expression of the promoted type of the switch condition. 651 ExprResult ConvLo = 652 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue); 653 if (ConvLo.isInvalid()) { 654 CaseListIsErroneous = true; 655 continue; 656 } 657 Lo = ConvLo.take(); 658 } else { 659 // We already verified that the expression has a i-c-e value (C99 660 // 6.8.4.2p3) - get that value now. 661 LoVal = Lo->EvaluateKnownConstInt(Context); 662 663 // If the LHS is not the same type as the condition, insert an implicit 664 // cast. 665 Lo = DefaultLvalueConversion(Lo).take(); 666 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).take(); 667 } 668 669 // Convert the value to the same width/sign as the condition had prior to 670 // integral promotions. 671 // 672 // FIXME: This causes us to reject valid code: 673 // switch ((char)c) { case 256: case 0: return 0; } 674 // Here we claim there is a duplicated condition value, but there is not. 675 ConvertIntegerToTypeWarnOnOverflow(LoVal, CondWidth, CondIsSigned, 676 Lo->getLocStart(), 677 diag::warn_case_value_overflow); 678 679 CS->setLHS(Lo); 680 681 // If this is a case range, remember it in CaseRanges, otherwise CaseVals. 682 if (CS->getRHS()) { 683 if (CS->getRHS()->isTypeDependent() || 684 CS->getRHS()->isValueDependent()) { 685 HasDependentValue = true; 686 break; 687 } 688 CaseRanges.push_back(std::make_pair(LoVal, CS)); 689 } else 690 CaseVals.push_back(std::make_pair(LoVal, CS)); 691 } 692 } 693 694 if (!HasDependentValue) { 695 // If we don't have a default statement, check whether the 696 // condition is constant. 697 llvm::APSInt ConstantCondValue; 698 bool HasConstantCond = false; 699 if (!HasDependentValue && !TheDefaultStmt) { 700 HasConstantCond 701 = CondExprBeforePromotion->EvaluateAsInt(ConstantCondValue, Context, 702 Expr::SE_AllowSideEffects); 703 assert(!HasConstantCond || 704 (ConstantCondValue.getBitWidth() == CondWidth && 705 ConstantCondValue.isSigned() == CondIsSigned)); 706 } 707 bool ShouldCheckConstantCond = HasConstantCond; 708 709 // Sort all the scalar case values so we can easily detect duplicates. 710 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals); 711 712 if (!CaseVals.empty()) { 713 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) { 714 if (ShouldCheckConstantCond && 715 CaseVals[i].first == ConstantCondValue) 716 ShouldCheckConstantCond = false; 717 718 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) { 719 // If we have a duplicate, report it. 720 Diag(CaseVals[i].second->getLHS()->getLocStart(), 721 diag::err_duplicate_case) << CaseVals[i].first.toString(10); 722 Diag(CaseVals[i-1].second->getLHS()->getLocStart(), 723 diag::note_duplicate_case_prev); 724 // FIXME: We really want to remove the bogus case stmt from the 725 // substmt, but we have no way to do this right now. 726 CaseListIsErroneous = true; 727 } 728 } 729 } 730 731 // Detect duplicate case ranges, which usually don't exist at all in 732 // the first place. 733 if (!CaseRanges.empty()) { 734 // Sort all the case ranges by their low value so we can easily detect 735 // overlaps between ranges. 736 std::stable_sort(CaseRanges.begin(), CaseRanges.end()); 737 738 // Scan the ranges, computing the high values and removing empty ranges. 739 std::vector<llvm::APSInt> HiVals; 740 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 741 llvm::APSInt &LoVal = CaseRanges[i].first; 742 CaseStmt *CR = CaseRanges[i].second; 743 Expr *Hi = CR->getRHS(); 744 llvm::APSInt HiVal; 745 746 if (getLangOpts().CPlusPlus0x) { 747 // C++11 [stmt.switch]p2: the constant-expression shall be a converted 748 // constant expression of the promoted type of the switch condition. 749 ExprResult ConvHi = 750 CheckConvertedConstantExpression(Hi, CondType, HiVal, 751 CCEK_CaseValue); 752 if (ConvHi.isInvalid()) { 753 CaseListIsErroneous = true; 754 continue; 755 } 756 Hi = ConvHi.take(); 757 } else { 758 HiVal = Hi->EvaluateKnownConstInt(Context); 759 760 // If the RHS is not the same type as the condition, insert an 761 // implicit cast. 762 Hi = DefaultLvalueConversion(Hi).take(); 763 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).take(); 764 } 765 766 // Convert the value to the same width/sign as the condition. 767 ConvertIntegerToTypeWarnOnOverflow(HiVal, CondWidth, CondIsSigned, 768 Hi->getLocStart(), 769 diag::warn_case_value_overflow); 770 771 CR->setRHS(Hi); 772 773 // If the low value is bigger than the high value, the case is empty. 774 if (LoVal > HiVal) { 775 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range) 776 << SourceRange(CR->getLHS()->getLocStart(), 777 Hi->getLocEnd()); 778 CaseRanges.erase(CaseRanges.begin()+i); 779 --i, --e; 780 continue; 781 } 782 783 if (ShouldCheckConstantCond && 784 LoVal <= ConstantCondValue && 785 ConstantCondValue <= HiVal) 786 ShouldCheckConstantCond = false; 787 788 HiVals.push_back(HiVal); 789 } 790 791 // Rescan the ranges, looking for overlap with singleton values and other 792 // ranges. Since the range list is sorted, we only need to compare case 793 // ranges with their neighbors. 794 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 795 llvm::APSInt &CRLo = CaseRanges[i].first; 796 llvm::APSInt &CRHi = HiVals[i]; 797 CaseStmt *CR = CaseRanges[i].second; 798 799 // Check to see whether the case range overlaps with any 800 // singleton cases. 801 CaseStmt *OverlapStmt = 0; 802 llvm::APSInt OverlapVal(32); 803 804 // Find the smallest value >= the lower bound. If I is in the 805 // case range, then we have overlap. 806 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(), 807 CaseVals.end(), CRLo, 808 CaseCompareFunctor()); 809 if (I != CaseVals.end() && I->first < CRHi) { 810 OverlapVal = I->first; // Found overlap with scalar. 811 OverlapStmt = I->second; 812 } 813 814 // Find the smallest value bigger than the upper bound. 815 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor()); 816 if (I != CaseVals.begin() && (I-1)->first >= CRLo) { 817 OverlapVal = (I-1)->first; // Found overlap with scalar. 818 OverlapStmt = (I-1)->second; 819 } 820 821 // Check to see if this case stmt overlaps with the subsequent 822 // case range. 823 if (i && CRLo <= HiVals[i-1]) { 824 OverlapVal = HiVals[i-1]; // Found overlap with range. 825 OverlapStmt = CaseRanges[i-1].second; 826 } 827 828 if (OverlapStmt) { 829 // If we have a duplicate, report it. 830 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case) 831 << OverlapVal.toString(10); 832 Diag(OverlapStmt->getLHS()->getLocStart(), 833 diag::note_duplicate_case_prev); 834 // FIXME: We really want to remove the bogus case stmt from the 835 // substmt, but we have no way to do this right now. 836 CaseListIsErroneous = true; 837 } 838 } 839 } 840 841 // Complain if we have a constant condition and we didn't find a match. 842 if (!CaseListIsErroneous && ShouldCheckConstantCond) { 843 // TODO: it would be nice if we printed enums as enums, chars as 844 // chars, etc. 845 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition) 846 << ConstantCondValue.toString(10) 847 << CondExpr->getSourceRange(); 848 } 849 850 // Check to see if switch is over an Enum and handles all of its 851 // values. We only issue a warning if there is not 'default:', but 852 // we still do the analysis to preserve this information in the AST 853 // (which can be used by flow-based analyes). 854 // 855 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>(); 856 857 // If switch has default case, then ignore it. 858 if (!CaseListIsErroneous && !HasConstantCond && ET) { 859 const EnumDecl *ED = ET->getDecl(); 860 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> 861 EnumValsTy; 862 EnumValsTy EnumVals; 863 864 // Gather all enum values, set their type and sort them, 865 // allowing easier comparison with CaseVals. 866 for (EnumDecl::enumerator_iterator EDI = ED->enumerator_begin(); 867 EDI != ED->enumerator_end(); ++EDI) { 868 llvm::APSInt Val = EDI->getInitVal(); 869 AdjustAPSInt(Val, CondWidth, CondIsSigned); 870 EnumVals.push_back(std::make_pair(Val, *EDI)); 871 } 872 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals); 873 EnumValsTy::iterator EIend = 874 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals); 875 876 // See which case values aren't in enum. 877 EnumValsTy::const_iterator EI = EnumVals.begin(); 878 for (CaseValsTy::const_iterator CI = CaseVals.begin(); 879 CI != CaseVals.end(); CI++) { 880 while (EI != EIend && EI->first < CI->first) 881 EI++; 882 if (EI == EIend || EI->first > CI->first) 883 Diag(CI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum) 884 << ED->getDeclName(); 885 } 886 // See which of case ranges aren't in enum 887 EI = EnumVals.begin(); 888 for (CaseRangesTy::const_iterator RI = CaseRanges.begin(); 889 RI != CaseRanges.end() && EI != EIend; RI++) { 890 while (EI != EIend && EI->first < RI->first) 891 EI++; 892 893 if (EI == EIend || EI->first != RI->first) { 894 Diag(RI->second->getLHS()->getExprLoc(), diag::warn_not_in_enum) 895 << ED->getDeclName(); 896 } 897 898 llvm::APSInt Hi = 899 RI->second->getRHS()->EvaluateKnownConstInt(Context); 900 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 901 while (EI != EIend && EI->first < Hi) 902 EI++; 903 if (EI == EIend || EI->first != Hi) 904 Diag(RI->second->getRHS()->getExprLoc(), diag::warn_not_in_enum) 905 << ED->getDeclName(); 906 } 907 908 // Check which enum vals aren't in switch 909 CaseValsTy::const_iterator CI = CaseVals.begin(); 910 CaseRangesTy::const_iterator RI = CaseRanges.begin(); 911 bool hasCasesNotInSwitch = false; 912 913 SmallVector<DeclarationName,8> UnhandledNames; 914 915 for (EI = EnumVals.begin(); EI != EIend; EI++){ 916 // Drop unneeded case values 917 llvm::APSInt CIVal; 918 while (CI != CaseVals.end() && CI->first < EI->first) 919 CI++; 920 921 if (CI != CaseVals.end() && CI->first == EI->first) 922 continue; 923 924 // Drop unneeded case ranges 925 for (; RI != CaseRanges.end(); RI++) { 926 llvm::APSInt Hi = 927 RI->second->getRHS()->EvaluateKnownConstInt(Context); 928 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 929 if (EI->first <= Hi) 930 break; 931 } 932 933 if (RI == CaseRanges.end() || EI->first < RI->first) { 934 hasCasesNotInSwitch = true; 935 UnhandledNames.push_back(EI->second->getDeclName()); 936 } 937 } 938 939 if (TheDefaultStmt && UnhandledNames.empty()) 940 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default); 941 942 // Produce a nice diagnostic if multiple values aren't handled. 943 switch (UnhandledNames.size()) { 944 case 0: break; 945 case 1: 946 Diag(CondExpr->getExprLoc(), TheDefaultStmt 947 ? diag::warn_def_missing_case1 : diag::warn_missing_case1) 948 << UnhandledNames[0]; 949 break; 950 case 2: 951 Diag(CondExpr->getExprLoc(), TheDefaultStmt 952 ? diag::warn_def_missing_case2 : diag::warn_missing_case2) 953 << UnhandledNames[0] << UnhandledNames[1]; 954 break; 955 case 3: 956 Diag(CondExpr->getExprLoc(), TheDefaultStmt 957 ? diag::warn_def_missing_case3 : diag::warn_missing_case3) 958 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2]; 959 break; 960 default: 961 Diag(CondExpr->getExprLoc(), TheDefaultStmt 962 ? diag::warn_def_missing_cases : diag::warn_missing_cases) 963 << (unsigned)UnhandledNames.size() 964 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2]; 965 break; 966 } 967 968 if (!hasCasesNotInSwitch) 969 SS->setAllEnumCasesCovered(); 970 } 971 } 972 973 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt, 974 diag::warn_empty_switch_body); 975 976 // FIXME: If the case list was broken is some way, we don't have a good system 977 // to patch it up. Instead, just return the whole substmt as broken. 978 if (CaseListIsErroneous) 979 return StmtError(); 980 981 return Owned(SS); 982} 983 984StmtResult 985Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond, 986 Decl *CondVar, Stmt *Body) { 987 ExprResult CondResult(Cond.release()); 988 989 VarDecl *ConditionVar = 0; 990 if (CondVar) { 991 ConditionVar = cast<VarDecl>(CondVar); 992 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true); 993 if (CondResult.isInvalid()) 994 return StmtError(); 995 } 996 Expr *ConditionExpr = CondResult.take(); 997 if (!ConditionExpr) 998 return StmtError(); 999 1000 DiagnoseUnusedExprResult(Body); 1001 1002 if (isa<NullStmt>(Body)) 1003 getCurCompoundScope().setHasEmptyLoopBodies(); 1004 1005 return Owned(new (Context) WhileStmt(Context, ConditionVar, ConditionExpr, 1006 Body, WhileLoc)); 1007} 1008 1009StmtResult 1010Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 1011 SourceLocation WhileLoc, SourceLocation CondLParen, 1012 Expr *Cond, SourceLocation CondRParen) { 1013 assert(Cond && "ActOnDoStmt(): missing expression"); 1014 1015 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc); 1016 if (CondResult.isInvalid() || CondResult.isInvalid()) 1017 return StmtError(); 1018 Cond = CondResult.take(); 1019 1020 CheckImplicitConversions(Cond, DoLoc); 1021 CondResult = MaybeCreateExprWithCleanups(Cond); 1022 if (CondResult.isInvalid()) 1023 return StmtError(); 1024 Cond = CondResult.take(); 1025 1026 DiagnoseUnusedExprResult(Body); 1027 1028 return Owned(new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen)); 1029} 1030 1031StmtResult 1032Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 1033 Stmt *First, FullExprArg second, Decl *secondVar, 1034 FullExprArg third, 1035 SourceLocation RParenLoc, Stmt *Body) { 1036 if (!getLangOpts().CPlusPlus) { 1037 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) { 1038 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 1039 // declare identifiers for objects having storage class 'auto' or 1040 // 'register'. 1041 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end(); 1042 DI!=DE; ++DI) { 1043 VarDecl *VD = dyn_cast<VarDecl>(*DI); 1044 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage()) 1045 VD = 0; 1046 if (VD == 0) 1047 Diag((*DI)->getLocation(), diag::err_non_variable_decl_in_for); 1048 // FIXME: mark decl erroneous! 1049 } 1050 } 1051 } 1052 1053 ExprResult SecondResult(second.release()); 1054 VarDecl *ConditionVar = 0; 1055 if (secondVar) { 1056 ConditionVar = cast<VarDecl>(secondVar); 1057 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true); 1058 if (SecondResult.isInvalid()) 1059 return StmtError(); 1060 } 1061 1062 Expr *Third = third.release().takeAs<Expr>(); 1063 1064 DiagnoseUnusedExprResult(First); 1065 DiagnoseUnusedExprResult(Third); 1066 DiagnoseUnusedExprResult(Body); 1067 1068 if (isa<NullStmt>(Body)) 1069 getCurCompoundScope().setHasEmptyLoopBodies(); 1070 1071 return Owned(new (Context) ForStmt(Context, First, 1072 SecondResult.take(), ConditionVar, 1073 Third, Body, ForLoc, LParenLoc, 1074 RParenLoc)); 1075} 1076 1077/// In an Objective C collection iteration statement: 1078/// for (x in y) 1079/// x can be an arbitrary l-value expression. Bind it up as a 1080/// full-expression. 1081StmtResult Sema::ActOnForEachLValueExpr(Expr *E) { 1082 CheckImplicitConversions(E); 1083 ExprResult Result = MaybeCreateExprWithCleanups(E); 1084 if (Result.isInvalid()) return StmtError(); 1085 return Owned(static_cast<Stmt*>(Result.get())); 1086} 1087 1088ExprResult 1089Sema::ActOnObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) { 1090 assert(collection); 1091 1092 // Bail out early if we've got a type-dependent expression. 1093 if (collection->isTypeDependent()) return Owned(collection); 1094 1095 // Perform normal l-value conversion. 1096 ExprResult result = DefaultFunctionArrayLvalueConversion(collection); 1097 if (result.isInvalid()) 1098 return ExprError(); 1099 collection = result.take(); 1100 1101 // The operand needs to have object-pointer type. 1102 // TODO: should we do a contextual conversion? 1103 const ObjCObjectPointerType *pointerType = 1104 collection->getType()->getAs<ObjCObjectPointerType>(); 1105 if (!pointerType) 1106 return Diag(forLoc, diag::err_collection_expr_type) 1107 << collection->getType() << collection->getSourceRange(); 1108 1109 // Check that the operand provides 1110 // - countByEnumeratingWithState:objects:count: 1111 const ObjCObjectType *objectType = pointerType->getObjectType(); 1112 ObjCInterfaceDecl *iface = objectType->getInterface(); 1113 1114 // If we have a forward-declared type, we can't do this check. 1115 // Under ARC, it is an error not to have a forward-declared class. 1116 if (iface && 1117 RequireCompleteType(forLoc, QualType(objectType, 0), 1118 getLangOpts().ObjCAutoRefCount 1119 ? PDiag(diag::err_arc_collection_forward) 1120 << collection->getSourceRange() 1121 : PDiag(0))) { 1122 // Otherwise, if we have any useful type information, check that 1123 // the type declares the appropriate method. 1124 } else if (iface || !objectType->qual_empty()) { 1125 IdentifierInfo *selectorIdents[] = { 1126 &Context.Idents.get("countByEnumeratingWithState"), 1127 &Context.Idents.get("objects"), 1128 &Context.Idents.get("count") 1129 }; 1130 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]); 1131 1132 ObjCMethodDecl *method = 0; 1133 1134 // If there's an interface, look in both the public and private APIs. 1135 if (iface) { 1136 method = iface->lookupInstanceMethod(selector); 1137 if (!method) method = LookupPrivateInstanceMethod(selector, iface); 1138 } 1139 1140 // Also check protocol qualifiers. 1141 if (!method) 1142 method = LookupMethodInQualifiedType(selector, pointerType, 1143 /*instance*/ true); 1144 1145 // If we didn't find it anywhere, give up. 1146 if (!method) { 1147 Diag(forLoc, diag::warn_collection_expr_type) 1148 << collection->getType() << selector << collection->getSourceRange(); 1149 } 1150 1151 // TODO: check for an incompatible signature? 1152 } 1153 1154 // Wrap up any cleanups in the expression. 1155 return Owned(MaybeCreateExprWithCleanups(collection)); 1156} 1157 1158StmtResult 1159Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc, 1160 SourceLocation LParenLoc, 1161 Stmt *First, Expr *Second, 1162 SourceLocation RParenLoc, Stmt *Body) { 1163 if (First) { 1164 QualType FirstType; 1165 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) { 1166 if (!DS->isSingleDecl()) 1167 return StmtError(Diag((*DS->decl_begin())->getLocation(), 1168 diag::err_toomany_element_decls)); 1169 1170 VarDecl *D = cast<VarDecl>(DS->getSingleDecl()); 1171 FirstType = D->getType(); 1172 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 1173 // declare identifiers for objects having storage class 'auto' or 1174 // 'register'. 1175 if (!D->hasLocalStorage()) 1176 return StmtError(Diag(D->getLocation(), 1177 diag::err_non_variable_decl_in_for)); 1178 } else { 1179 Expr *FirstE = cast<Expr>(First); 1180 if (!FirstE->isTypeDependent() && !FirstE->isLValue()) 1181 return StmtError(Diag(First->getLocStart(), 1182 diag::err_selector_element_not_lvalue) 1183 << First->getSourceRange()); 1184 1185 FirstType = static_cast<Expr*>(First)->getType(); 1186 } 1187 if (!FirstType->isDependentType() && 1188 !FirstType->isObjCObjectPointerType() && 1189 !FirstType->isBlockPointerType()) 1190 Diag(ForLoc, diag::err_selector_element_type) 1191 << FirstType << First->getSourceRange(); 1192 } 1193 1194 return Owned(new (Context) ObjCForCollectionStmt(First, Second, Body, 1195 ForLoc, RParenLoc)); 1196} 1197 1198namespace { 1199 1200enum BeginEndFunction { 1201 BEF_begin, 1202 BEF_end 1203}; 1204 1205/// Build a variable declaration for a for-range statement. 1206static VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc, 1207 QualType Type, const char *Name) { 1208 DeclContext *DC = SemaRef.CurContext; 1209 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 1210 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 1211 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, 1212 TInfo, SC_Auto, SC_None); 1213 Decl->setImplicit(); 1214 return Decl; 1215} 1216 1217/// Finish building a variable declaration for a for-range statement. 1218/// \return true if an error occurs. 1219static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init, 1220 SourceLocation Loc, int diag) { 1221 // Deduce the type for the iterator variable now rather than leaving it to 1222 // AddInitializerToDecl, so we can produce a more suitable diagnostic. 1223 TypeSourceInfo *InitTSI = 0; 1224 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) || 1225 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitTSI) == 1226 Sema::DAR_Failed) 1227 SemaRef.Diag(Loc, diag) << Init->getType(); 1228 if (!InitTSI) { 1229 Decl->setInvalidDecl(); 1230 return true; 1231 } 1232 Decl->setTypeSourceInfo(InitTSI); 1233 Decl->setType(InitTSI->getType()); 1234 1235 // In ARC, infer lifetime. 1236 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if 1237 // we're doing the equivalent of fast iteration. 1238 if (SemaRef.getLangOpts().ObjCAutoRefCount && 1239 SemaRef.inferObjCARCLifetime(Decl)) 1240 Decl->setInvalidDecl(); 1241 1242 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false, 1243 /*TypeMayContainAuto=*/false); 1244 SemaRef.FinalizeDeclaration(Decl); 1245 SemaRef.CurContext->addHiddenDecl(Decl); 1246 return false; 1247} 1248 1249/// Produce a note indicating which begin/end function was implicitly called 1250/// by a C++0x for-range statement. This is often not obvious from the code, 1251/// nor from the diagnostics produced when analysing the implicit expressions 1252/// required in a for-range statement. 1253void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E, 1254 BeginEndFunction BEF) { 1255 CallExpr *CE = dyn_cast<CallExpr>(E); 1256 if (!CE) 1257 return; 1258 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl()); 1259 if (!D) 1260 return; 1261 SourceLocation Loc = D->getLocation(); 1262 1263 std::string Description; 1264 bool IsTemplate = false; 1265 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) { 1266 Description = SemaRef.getTemplateArgumentBindingsText( 1267 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs()); 1268 IsTemplate = true; 1269 } 1270 1271 SemaRef.Diag(Loc, diag::note_for_range_begin_end) 1272 << BEF << IsTemplate << Description << E->getType(); 1273} 1274 1275/// Build a call to 'begin' or 'end' for a C++0x for-range statement. If the 1276/// given LookupResult is non-empty, it is assumed to describe a member which 1277/// will be invoked. Otherwise, the function will be found via argument 1278/// dependent lookup. 1279static ExprResult BuildForRangeBeginEndCall(Sema &SemaRef, Scope *S, 1280 SourceLocation Loc, 1281 VarDecl *Decl, 1282 BeginEndFunction BEF, 1283 const DeclarationNameInfo &NameInfo, 1284 LookupResult &MemberLookup, 1285 Expr *Range) { 1286 ExprResult CallExpr; 1287 if (!MemberLookup.empty()) { 1288 ExprResult MemberRef = 1289 SemaRef.BuildMemberReferenceExpr(Range, Range->getType(), Loc, 1290 /*IsPtr=*/false, CXXScopeSpec(), 1291 /*TemplateKWLoc=*/SourceLocation(), 1292 /*FirstQualifierInScope=*/0, 1293 MemberLookup, 1294 /*TemplateArgs=*/0); 1295 if (MemberRef.isInvalid()) 1296 return ExprError(); 1297 CallExpr = SemaRef.ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), 1298 Loc, 0); 1299 if (CallExpr.isInvalid()) 1300 return ExprError(); 1301 } else { 1302 UnresolvedSet<0> FoundNames; 1303 // C++0x [stmt.ranged]p1: For the purposes of this name lookup, namespace 1304 // std is an associated namespace. 1305 UnresolvedLookupExpr *Fn = 1306 UnresolvedLookupExpr::Create(SemaRef.Context, /*NamingClass=*/0, 1307 NestedNameSpecifierLoc(), NameInfo, 1308 /*NeedsADL=*/true, /*Overloaded=*/false, 1309 FoundNames.begin(), FoundNames.end(), 1310 /*LookInStdNamespace=*/true); 1311 CallExpr = SemaRef.BuildOverloadedCallExpr(S, Fn, Fn, Loc, &Range, 1, Loc, 1312 0, /*AllowTypoCorrection=*/false); 1313 if (CallExpr.isInvalid()) { 1314 SemaRef.Diag(Range->getLocStart(), diag::note_for_range_type) 1315 << Range->getType(); 1316 return ExprError(); 1317 } 1318 } 1319 if (FinishForRangeVarDecl(SemaRef, Decl, CallExpr.get(), Loc, 1320 diag::err_for_range_iter_deduction_failure)) { 1321 NoteForRangeBeginEndFunction(SemaRef, CallExpr.get(), BEF); 1322 return ExprError(); 1323 } 1324 return CallExpr; 1325} 1326 1327} 1328 1329/// ActOnCXXForRangeStmt - Check and build a C++0x for-range statement. 1330/// 1331/// C++0x [stmt.ranged]: 1332/// A range-based for statement is equivalent to 1333/// 1334/// { 1335/// auto && __range = range-init; 1336/// for ( auto __begin = begin-expr, 1337/// __end = end-expr; 1338/// __begin != __end; 1339/// ++__begin ) { 1340/// for-range-declaration = *__begin; 1341/// statement 1342/// } 1343/// } 1344/// 1345/// The body of the loop is not available yet, since it cannot be analysed until 1346/// we have determined the type of the for-range-declaration. 1347StmtResult 1348Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 1349 Stmt *First, SourceLocation ColonLoc, Expr *Range, 1350 SourceLocation RParenLoc) { 1351 if (!First || !Range) 1352 return StmtError(); 1353 1354 DeclStmt *DS = dyn_cast<DeclStmt>(First); 1355 assert(DS && "first part of for range not a decl stmt"); 1356 1357 if (!DS->isSingleDecl()) { 1358 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range); 1359 return StmtError(); 1360 } 1361 if (DS->getSingleDecl()->isInvalidDecl()) 1362 return StmtError(); 1363 1364 if (DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) 1365 return StmtError(); 1366 1367 // Build auto && __range = range-init 1368 SourceLocation RangeLoc = Range->getLocStart(); 1369 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc, 1370 Context.getAutoRRefDeductType(), 1371 "__range"); 1372 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc, 1373 diag::err_for_range_deduction_failure)) 1374 return StmtError(); 1375 1376 // Claim the type doesn't contain auto: we've already done the checking. 1377 DeclGroupPtrTy RangeGroup = 1378 BuildDeclaratorGroup((Decl**)&RangeVar, 1, /*TypeMayContainAuto=*/false); 1379 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc); 1380 if (RangeDecl.isInvalid()) 1381 return StmtError(); 1382 1383 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(), 1384 /*BeginEndDecl=*/0, /*Cond=*/0, /*Inc=*/0, DS, 1385 RParenLoc); 1386} 1387 1388/// BuildCXXForRangeStmt - Build or instantiate a C++0x for-range statement. 1389StmtResult 1390Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc, 1391 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond, 1392 Expr *Inc, Stmt *LoopVarDecl, 1393 SourceLocation RParenLoc) { 1394 Scope *S = getCurScope(); 1395 1396 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl); 1397 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl()); 1398 QualType RangeVarType = RangeVar->getType(); 1399 1400 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl); 1401 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl()); 1402 1403 StmtResult BeginEndDecl = BeginEnd; 1404 ExprResult NotEqExpr = Cond, IncrExpr = Inc; 1405 1406 if (!BeginEndDecl.get() && !RangeVarType->isDependentType()) { 1407 SourceLocation RangeLoc = RangeVar->getLocation(); 1408 1409 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType(); 1410 1411 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType, 1412 VK_LValue, ColonLoc); 1413 if (BeginRangeRef.isInvalid()) 1414 return StmtError(); 1415 1416 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType, 1417 VK_LValue, ColonLoc); 1418 if (EndRangeRef.isInvalid()) 1419 return StmtError(); 1420 1421 QualType AutoType = Context.getAutoDeductType(); 1422 Expr *Range = RangeVar->getInit(); 1423 if (!Range) 1424 return StmtError(); 1425 QualType RangeType = Range->getType(); 1426 1427 if (RequireCompleteType(RangeLoc, RangeType, 1428 PDiag(diag::err_for_range_incomplete_type))) 1429 return StmtError(); 1430 1431 // Build auto __begin = begin-expr, __end = end-expr. 1432 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, 1433 "__begin"); 1434 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, 1435 "__end"); 1436 1437 // Build begin-expr and end-expr and attach to __begin and __end variables. 1438 ExprResult BeginExpr, EndExpr; 1439 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) { 1440 // - if _RangeT is an array type, begin-expr and end-expr are __range and 1441 // __range + __bound, respectively, where __bound is the array bound. If 1442 // _RangeT is an array of unknown size or an array of incomplete type, 1443 // the program is ill-formed; 1444 1445 // begin-expr is __range. 1446 BeginExpr = BeginRangeRef; 1447 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc, 1448 diag::err_for_range_iter_deduction_failure)) { 1449 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1450 return StmtError(); 1451 } 1452 1453 // Find the array bound. 1454 ExprResult BoundExpr; 1455 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT)) 1456 BoundExpr = Owned(IntegerLiteral::Create(Context, CAT->getSize(), 1457 Context.getPointerDiffType(), 1458 RangeLoc)); 1459 else if (const VariableArrayType *VAT = 1460 dyn_cast<VariableArrayType>(UnqAT)) 1461 BoundExpr = VAT->getSizeExpr(); 1462 else { 1463 // Can't be a DependentSizedArrayType or an IncompleteArrayType since 1464 // UnqAT is not incomplete and Range is not type-dependent. 1465 llvm_unreachable("Unexpected array type in for-range"); 1466 } 1467 1468 // end-expr is __range + __bound. 1469 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(), 1470 BoundExpr.get()); 1471 if (EndExpr.isInvalid()) 1472 return StmtError(); 1473 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc, 1474 diag::err_for_range_iter_deduction_failure)) { 1475 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 1476 return StmtError(); 1477 } 1478 } else { 1479 DeclarationNameInfo BeginNameInfo(&PP.getIdentifierTable().get("begin"), 1480 ColonLoc); 1481 DeclarationNameInfo EndNameInfo(&PP.getIdentifierTable().get("end"), 1482 ColonLoc); 1483 1484 LookupResult BeginMemberLookup(*this, BeginNameInfo, LookupMemberName); 1485 LookupResult EndMemberLookup(*this, EndNameInfo, LookupMemberName); 1486 1487 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) { 1488 // - if _RangeT is a class type, the unqualified-ids begin and end are 1489 // looked up in the scope of class _RangeT as if by class member access 1490 // lookup (3.4.5), and if either (or both) finds at least one 1491 // declaration, begin-expr and end-expr are __range.begin() and 1492 // __range.end(), respectively; 1493 LookupQualifiedName(BeginMemberLookup, D); 1494 LookupQualifiedName(EndMemberLookup, D); 1495 1496 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) { 1497 Diag(ColonLoc, diag::err_for_range_member_begin_end_mismatch) 1498 << RangeType << BeginMemberLookup.empty(); 1499 return StmtError(); 1500 } 1501 } else { 1502 // - otherwise, begin-expr and end-expr are begin(__range) and 1503 // end(__range), respectively, where begin and end are looked up with 1504 // argument-dependent lookup (3.4.2). For the purposes of this name 1505 // lookup, namespace std is an associated namespace. 1506 } 1507 1508 BeginExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, BeginVar, 1509 BEF_begin, BeginNameInfo, 1510 BeginMemberLookup, 1511 BeginRangeRef.get()); 1512 if (BeginExpr.isInvalid()) 1513 return StmtError(); 1514 1515 EndExpr = BuildForRangeBeginEndCall(*this, S, ColonLoc, EndVar, 1516 BEF_end, EndNameInfo, 1517 EndMemberLookup, EndRangeRef.get()); 1518 if (EndExpr.isInvalid()) 1519 return StmtError(); 1520 } 1521 1522 // C++0x [decl.spec.auto]p6: BeginType and EndType must be the same. 1523 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType(); 1524 if (!Context.hasSameType(BeginType, EndType)) { 1525 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ) 1526 << BeginType << EndType; 1527 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1528 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 1529 } 1530 1531 Decl *BeginEndDecls[] = { BeginVar, EndVar }; 1532 // Claim the type doesn't contain auto: we've already done the checking. 1533 DeclGroupPtrTy BeginEndGroup = 1534 BuildDeclaratorGroup(BeginEndDecls, 2, /*TypeMayContainAuto=*/false); 1535 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc); 1536 1537 const QualType BeginRefNonRefType = BeginType.getNonReferenceType(); 1538 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 1539 VK_LValue, ColonLoc); 1540 if (BeginRef.isInvalid()) 1541 return StmtError(); 1542 1543 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(), 1544 VK_LValue, ColonLoc); 1545 if (EndRef.isInvalid()) 1546 return StmtError(); 1547 1548 // Build and check __begin != __end expression. 1549 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal, 1550 BeginRef.get(), EndRef.get()); 1551 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get()); 1552 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get()); 1553 if (NotEqExpr.isInvalid()) { 1554 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1555 if (!Context.hasSameType(BeginType, EndType)) 1556 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 1557 return StmtError(); 1558 } 1559 1560 // Build and check ++__begin expression. 1561 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 1562 VK_LValue, ColonLoc); 1563 if (BeginRef.isInvalid()) 1564 return StmtError(); 1565 1566 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get()); 1567 IncrExpr = ActOnFinishFullExpr(IncrExpr.get()); 1568 if (IncrExpr.isInvalid()) { 1569 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1570 return StmtError(); 1571 } 1572 1573 // Build and check *__begin expression. 1574 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 1575 VK_LValue, ColonLoc); 1576 if (BeginRef.isInvalid()) 1577 return StmtError(); 1578 1579 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get()); 1580 if (DerefExpr.isInvalid()) { 1581 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1582 return StmtError(); 1583 } 1584 1585 // Attach *__begin as initializer for VD. 1586 if (!LoopVar->isInvalidDecl()) { 1587 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false, 1588 /*TypeMayContainAuto=*/true); 1589 if (LoopVar->isInvalidDecl()) 1590 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 1591 } 1592 } else { 1593 // The range is implicitly used as a placeholder when it is dependent. 1594 RangeVar->setUsed(); 1595 } 1596 1597 return Owned(new (Context) CXXForRangeStmt(RangeDS, 1598 cast_or_null<DeclStmt>(BeginEndDecl.get()), 1599 NotEqExpr.take(), IncrExpr.take(), 1600 LoopVarDS, /*Body=*/0, ForLoc, 1601 ColonLoc, RParenLoc)); 1602} 1603 1604/// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement. 1605/// This is a separate step from ActOnCXXForRangeStmt because analysis of the 1606/// body cannot be performed until after the type of the range variable is 1607/// determined. 1608StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) { 1609 if (!S || !B) 1610 return StmtError(); 1611 1612 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S); 1613 ForStmt->setBody(B); 1614 1615 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B, 1616 diag::warn_empty_range_based_for_body); 1617 1618 return S; 1619} 1620 1621StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc, 1622 SourceLocation LabelLoc, 1623 LabelDecl *TheDecl) { 1624 getCurFunction()->setHasBranchIntoScope(); 1625 TheDecl->setUsed(); 1626 return Owned(new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc)); 1627} 1628 1629StmtResult 1630Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, 1631 Expr *E) { 1632 // Convert operand to void* 1633 if (!E->isTypeDependent()) { 1634 QualType ETy = E->getType(); 1635 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst()); 1636 ExprResult ExprRes = Owned(E); 1637 AssignConvertType ConvTy = 1638 CheckSingleAssignmentConstraints(DestTy, ExprRes); 1639 if (ExprRes.isInvalid()) 1640 return StmtError(); 1641 E = ExprRes.take(); 1642 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing)) 1643 return StmtError(); 1644 E = MaybeCreateExprWithCleanups(E); 1645 } 1646 1647 getCurFunction()->setHasIndirectGoto(); 1648 1649 return Owned(new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E)); 1650} 1651 1652StmtResult 1653Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) { 1654 Scope *S = CurScope->getContinueParent(); 1655 if (!S) { 1656 // C99 6.8.6.2p1: A break shall appear only in or as a loop body. 1657 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop)); 1658 } 1659 1660 return Owned(new (Context) ContinueStmt(ContinueLoc)); 1661} 1662 1663StmtResult 1664Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) { 1665 Scope *S = CurScope->getBreakParent(); 1666 if (!S) { 1667 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body. 1668 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch)); 1669 } 1670 1671 return Owned(new (Context) BreakStmt(BreakLoc)); 1672} 1673 1674/// \brief Determine whether the given expression is a candidate for 1675/// copy elision in either a return statement or a throw expression. 1676/// 1677/// \param ReturnType If we're determining the copy elision candidate for 1678/// a return statement, this is the return type of the function. If we're 1679/// determining the copy elision candidate for a throw expression, this will 1680/// be a NULL type. 1681/// 1682/// \param E The expression being returned from the function or block, or 1683/// being thrown. 1684/// 1685/// \param AllowFunctionParameter Whether we allow function parameters to 1686/// be considered NRVO candidates. C++ prohibits this for NRVO itself, but 1687/// we re-use this logic to determine whether we should try to move as part of 1688/// a return or throw (which does allow function parameters). 1689/// 1690/// \returns The NRVO candidate variable, if the return statement may use the 1691/// NRVO, or NULL if there is no such candidate. 1692const VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, 1693 Expr *E, 1694 bool AllowFunctionParameter) { 1695 QualType ExprType = E->getType(); 1696 // - in a return statement in a function with ... 1697 // ... a class return type ... 1698 if (!ReturnType.isNull()) { 1699 if (!ReturnType->isRecordType()) 1700 return 0; 1701 // ... the same cv-unqualified type as the function return type ... 1702 if (!Context.hasSameUnqualifiedType(ReturnType, ExprType)) 1703 return 0; 1704 } 1705 1706 // ... the expression is the name of a non-volatile automatic object 1707 // (other than a function or catch-clause parameter)) ... 1708 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens()); 1709 if (!DR) 1710 return 0; 1711 const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()); 1712 if (!VD) 1713 return 0; 1714 1715 // ...object (other than a function or catch-clause parameter)... 1716 if (VD->getKind() != Decl::Var && 1717 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar)) 1718 return 0; 1719 if (VD->isExceptionVariable()) return 0; 1720 1721 // ...automatic... 1722 if (!VD->hasLocalStorage()) return 0; 1723 1724 // ...non-volatile... 1725 if (VD->getType().isVolatileQualified()) return 0; 1726 if (VD->getType()->isReferenceType()) return 0; 1727 1728 // __block variables can't be allocated in a way that permits NRVO. 1729 if (VD->hasAttr<BlocksAttr>()) return 0; 1730 1731 // Variables with higher required alignment than their type's ABI 1732 // alignment cannot use NRVO. 1733 if (VD->hasAttr<AlignedAttr>() && 1734 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType())) 1735 return 0; 1736 1737 return VD; 1738} 1739 1740/// \brief Perform the initialization of a potentially-movable value, which 1741/// is the result of return value. 1742/// 1743/// This routine implements C++0x [class.copy]p33, which attempts to treat 1744/// returned lvalues as rvalues in certain cases (to prefer move construction), 1745/// then falls back to treating them as lvalues if that failed. 1746ExprResult 1747Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 1748 const VarDecl *NRVOCandidate, 1749 QualType ResultType, 1750 Expr *Value, 1751 bool AllowNRVO) { 1752 // C++0x [class.copy]p33: 1753 // When the criteria for elision of a copy operation are met or would 1754 // be met save for the fact that the source object is a function 1755 // parameter, and the object to be copied is designated by an lvalue, 1756 // overload resolution to select the constructor for the copy is first 1757 // performed as if the object were designated by an rvalue. 1758 ExprResult Res = ExprError(); 1759 if (AllowNRVO && 1760 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) { 1761 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, 1762 Value->getType(), CK_LValueToRValue, 1763 Value, VK_XValue); 1764 1765 Expr *InitExpr = &AsRvalue; 1766 InitializationKind Kind 1767 = InitializationKind::CreateCopy(Value->getLocStart(), 1768 Value->getLocStart()); 1769 InitializationSequence Seq(*this, Entity, Kind, &InitExpr, 1); 1770 1771 // [...] If overload resolution fails, or if the type of the first 1772 // parameter of the selected constructor is not an rvalue reference 1773 // to the object's type (possibly cv-qualified), overload resolution 1774 // is performed again, considering the object as an lvalue. 1775 if (Seq) { 1776 for (InitializationSequence::step_iterator Step = Seq.step_begin(), 1777 StepEnd = Seq.step_end(); 1778 Step != StepEnd; ++Step) { 1779 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization) 1780 continue; 1781 1782 CXXConstructorDecl *Constructor 1783 = cast<CXXConstructorDecl>(Step->Function.Function); 1784 1785 const RValueReferenceType *RRefType 1786 = Constructor->getParamDecl(0)->getType() 1787 ->getAs<RValueReferenceType>(); 1788 1789 // If we don't meet the criteria, break out now. 1790 if (!RRefType || 1791 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(), 1792 Context.getTypeDeclType(Constructor->getParent()))) 1793 break; 1794 1795 // Promote "AsRvalue" to the heap, since we now need this 1796 // expression node to persist. 1797 Value = ImplicitCastExpr::Create(Context, Value->getType(), 1798 CK_LValueToRValue, Value, 0, 1799 VK_XValue); 1800 1801 // Complete type-checking the initialization of the return type 1802 // using the constructor we found. 1803 Res = Seq.Perform(*this, Entity, Kind, MultiExprArg(&Value, 1)); 1804 } 1805 } 1806 } 1807 1808 // Either we didn't meet the criteria for treating an lvalue as an rvalue, 1809 // above, or overload resolution failed. Either way, we need to try 1810 // (again) now with the return value expression as written. 1811 if (Res.isInvalid()) 1812 Res = PerformCopyInitialization(Entity, SourceLocation(), Value); 1813 1814 return Res; 1815} 1816 1817/// ActOnCapScopeReturnStmt - Utility routine to type-check return statements 1818/// for capturing scopes. 1819/// 1820StmtResult 1821Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 1822 // If this is the first return we've seen, infer the return type. 1823 // [expr.prim.lambda]p4 in C++11; block literals follow a superset of those 1824 // rules which allows multiple return statements. 1825 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction()); 1826 if (CurCap->HasImplicitReturnType) { 1827 QualType ReturnT; 1828 if (RetValExp && !isa<InitListExpr>(RetValExp)) { 1829 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp); 1830 if (Result.isInvalid()) 1831 return StmtError(); 1832 RetValExp = Result.take(); 1833 1834 if (!RetValExp->isTypeDependent()) 1835 ReturnT = RetValExp->getType(); 1836 else 1837 ReturnT = Context.DependentTy; 1838 } else { 1839 if (RetValExp) { 1840 // C++11 [expr.lambda.prim]p4 bans inferring the result from an 1841 // initializer list, because it is not an expression (even 1842 // though we represent it as one). We still deduce 'void'. 1843 Diag(ReturnLoc, diag::err_lambda_return_init_list) 1844 << RetValExp->getSourceRange(); 1845 } 1846 1847 ReturnT = Context.VoidTy; 1848 } 1849 // We require the return types to strictly match here. 1850 if (!CurCap->ReturnType.isNull() && 1851 !CurCap->ReturnType->isDependentType() && 1852 !ReturnT->isDependentType() && 1853 !Context.hasSameType(ReturnT, CurCap->ReturnType)) { 1854 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible) 1855 << ReturnT << CurCap->ReturnType 1856 << (getCurLambda() != 0); 1857 return StmtError(); 1858 } 1859 CurCap->ReturnType = ReturnT; 1860 } 1861 QualType FnRetType = CurCap->ReturnType; 1862 assert(!FnRetType.isNull()); 1863 1864 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) { 1865 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) { 1866 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr); 1867 return StmtError(); 1868 } 1869 } else { 1870 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CurCap); 1871 if (LSI->CallOperator->getType()->getAs<FunctionType>()->getNoReturnAttr()){ 1872 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr); 1873 return StmtError(); 1874 } 1875 } 1876 1877 // Otherwise, verify that this result type matches the previous one. We are 1878 // pickier with blocks than for normal functions because we don't have GCC 1879 // compatibility to worry about here. 1880 const VarDecl *NRVOCandidate = 0; 1881 if (FnRetType->isDependentType()) { 1882 // Delay processing for now. TODO: there are lots of dependent 1883 // types we can conclusively prove aren't void. 1884 } else if (FnRetType->isVoidType()) { 1885 if (RetValExp && !isa<InitListExpr>(RetValExp) && 1886 !(getLangOpts().CPlusPlus && 1887 (RetValExp->isTypeDependent() || 1888 RetValExp->getType()->isVoidType()))) { 1889 if (!getLangOpts().CPlusPlus && 1890 RetValExp->getType()->isVoidType()) 1891 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "" << 2; 1892 else { 1893 Diag(ReturnLoc, diag::err_return_block_has_expr); 1894 RetValExp = 0; 1895 } 1896 } 1897 } else if (!RetValExp) { 1898 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr)); 1899 } else if (!RetValExp->isTypeDependent()) { 1900 // we have a non-void block with an expression, continue checking 1901 1902 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 1903 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 1904 // function return. 1905 1906 // In C++ the return statement is handled via a copy initialization. 1907 // the C version of which boils down to CheckSingleAssignmentConstraints. 1908 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false); 1909 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, 1910 FnRetType, 1911 NRVOCandidate != 0); 1912 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, 1913 FnRetType, RetValExp); 1914 if (Res.isInvalid()) { 1915 // FIXME: Cleanup temporaries here, anyway? 1916 return StmtError(); 1917 } 1918 RetValExp = Res.take(); 1919 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 1920 } 1921 1922 if (RetValExp) { 1923 CheckImplicitConversions(RetValExp, ReturnLoc); 1924 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 1925 } 1926 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 1927 NRVOCandidate); 1928 1929 // If we need to check for the named return value optimization, save the 1930 // return statement in our scope for later processing. 1931 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() && 1932 !CurContext->isDependentContext()) 1933 FunctionScopes.back()->Returns.push_back(Result); 1934 1935 return Owned(Result); 1936} 1937 1938StmtResult 1939Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 1940 // Check for unexpanded parameter packs. 1941 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp)) 1942 return StmtError(); 1943 1944 if (isa<CapturingScopeInfo>(getCurFunction())) 1945 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp); 1946 1947 QualType FnRetType; 1948 QualType DeclaredRetType; 1949 if (const FunctionDecl *FD = getCurFunctionDecl()) { 1950 FnRetType = FD->getResultType(); 1951 DeclaredRetType = FnRetType; 1952 if (FD->hasAttr<NoReturnAttr>() || 1953 FD->getType()->getAs<FunctionType>()->getNoReturnAttr()) 1954 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) 1955 << FD->getDeclName(); 1956 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) { 1957 DeclaredRetType = MD->getResultType(); 1958 if (MD->hasRelatedResultType() && MD->getClassInterface()) { 1959 // In the implementation of a method with a related return type, the 1960 // type used to type-check the validity of return statements within the 1961 // method body is a pointer to the type of the class being implemented. 1962 FnRetType = Context.getObjCInterfaceType(MD->getClassInterface()); 1963 FnRetType = Context.getObjCObjectPointerType(FnRetType); 1964 } else { 1965 FnRetType = DeclaredRetType; 1966 } 1967 } else // If we don't have a function/method context, bail. 1968 return StmtError(); 1969 1970 ReturnStmt *Result = 0; 1971 if (FnRetType->isVoidType()) { 1972 if (RetValExp) { 1973 if (isa<InitListExpr>(RetValExp)) { 1974 // We simply never allow init lists as the return value of void 1975 // functions. This is compatible because this was never allowed before, 1976 // so there's no legacy code to deal with. 1977 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 1978 int FunctionKind = 0; 1979 if (isa<ObjCMethodDecl>(CurDecl)) 1980 FunctionKind = 1; 1981 else if (isa<CXXConstructorDecl>(CurDecl)) 1982 FunctionKind = 2; 1983 else if (isa<CXXDestructorDecl>(CurDecl)) 1984 FunctionKind = 3; 1985 1986 Diag(ReturnLoc, diag::err_return_init_list) 1987 << CurDecl->getDeclName() << FunctionKind 1988 << RetValExp->getSourceRange(); 1989 1990 // Drop the expression. 1991 RetValExp = 0; 1992 } else if (!RetValExp->isTypeDependent()) { 1993 // C99 6.8.6.4p1 (ext_ since GCC warns) 1994 unsigned D = diag::ext_return_has_expr; 1995 if (RetValExp->getType()->isVoidType()) 1996 D = diag::ext_return_has_void_expr; 1997 else { 1998 ExprResult Result = Owned(RetValExp); 1999 Result = IgnoredValueConversions(Result.take()); 2000 if (Result.isInvalid()) 2001 return StmtError(); 2002 RetValExp = Result.take(); 2003 RetValExp = ImpCastExprToType(RetValExp, 2004 Context.VoidTy, CK_ToVoid).take(); 2005 } 2006 2007 // return (some void expression); is legal in C++. 2008 if (D != diag::ext_return_has_void_expr || 2009 !getLangOpts().CPlusPlus) { 2010 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 2011 2012 int FunctionKind = 0; 2013 if (isa<ObjCMethodDecl>(CurDecl)) 2014 FunctionKind = 1; 2015 else if (isa<CXXConstructorDecl>(CurDecl)) 2016 FunctionKind = 2; 2017 else if (isa<CXXDestructorDecl>(CurDecl)) 2018 FunctionKind = 3; 2019 2020 Diag(ReturnLoc, D) 2021 << CurDecl->getDeclName() << FunctionKind 2022 << RetValExp->getSourceRange(); 2023 } 2024 } 2025 2026 if (RetValExp) { 2027 CheckImplicitConversions(RetValExp, ReturnLoc); 2028 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 2029 } 2030 } 2031 2032 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 0); 2033 } else if (!RetValExp && !FnRetType->isDependentType()) { 2034 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4 2035 // C99 6.8.6.4p1 (ext_ since GCC warns) 2036 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr; 2037 2038 if (FunctionDecl *FD = getCurFunctionDecl()) 2039 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/; 2040 else 2041 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/; 2042 Result = new (Context) ReturnStmt(ReturnLoc); 2043 } else { 2044 const VarDecl *NRVOCandidate = 0; 2045 if (!FnRetType->isDependentType() && !RetValExp->isTypeDependent()) { 2046 // we have a non-void function with an expression, continue checking 2047 2048 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 2049 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 2050 // function return. 2051 2052 // In C++ the return statement is handled via a copy initialization, 2053 // the C version of which boils down to CheckSingleAssignmentConstraints. 2054 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false); 2055 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, 2056 FnRetType, 2057 NRVOCandidate != 0); 2058 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, 2059 FnRetType, RetValExp); 2060 if (Res.isInvalid()) { 2061 // FIXME: Cleanup temporaries here, anyway? 2062 return StmtError(); 2063 } 2064 2065 RetValExp = Res.takeAs<Expr>(); 2066 if (RetValExp) 2067 CheckReturnStackAddr(RetValExp, FnRetType, ReturnLoc); 2068 } 2069 2070 if (RetValExp) { 2071 // If we type-checked an Objective-C method's return type based 2072 // on a related return type, we may need to adjust the return 2073 // type again. Do so now. 2074 if (DeclaredRetType != FnRetType) { 2075 ExprResult result = PerformImplicitConversion(RetValExp, 2076 DeclaredRetType, 2077 AA_Returning); 2078 if (result.isInvalid()) return StmtError(); 2079 RetValExp = result.take(); 2080 } 2081 2082 CheckImplicitConversions(RetValExp, ReturnLoc); 2083 RetValExp = MaybeCreateExprWithCleanups(RetValExp); 2084 } 2085 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate); 2086 } 2087 2088 // If we need to check for the named return value optimization, save the 2089 // return statement in our scope for later processing. 2090 if (getLangOpts().CPlusPlus && FnRetType->isRecordType() && 2091 !CurContext->isDependentContext()) 2092 FunctionScopes.back()->Returns.push_back(Result); 2093 2094 return Owned(Result); 2095} 2096 2097/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently 2098/// ignore "noop" casts in places where an lvalue is required by an inline asm. 2099/// We emulate this behavior when -fheinous-gnu-extensions is specified, but 2100/// provide a strong guidance to not use it. 2101/// 2102/// This method checks to see if the argument is an acceptable l-value and 2103/// returns false if it is a case we can handle. 2104static bool CheckAsmLValue(const Expr *E, Sema &S) { 2105 // Type dependent expressions will be checked during instantiation. 2106 if (E->isTypeDependent()) 2107 return false; 2108 2109 if (E->isLValue()) 2110 return false; // Cool, this is an lvalue. 2111 2112 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we 2113 // are supposed to allow. 2114 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context); 2115 if (E != E2 && E2->isLValue()) { 2116 if (!S.getLangOpts().HeinousExtensions) 2117 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue) 2118 << E->getSourceRange(); 2119 else 2120 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue) 2121 << E->getSourceRange(); 2122 // Accept, even if we emitted an error diagnostic. 2123 return false; 2124 } 2125 2126 // None of the above, just randomly invalid non-lvalue. 2127 return true; 2128} 2129 2130/// isOperandMentioned - Return true if the specified operand # is mentioned 2131/// anywhere in the decomposed asm string. 2132static bool isOperandMentioned(unsigned OpNo, 2133 ArrayRef<AsmStmt::AsmStringPiece> AsmStrPieces) { 2134 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) { 2135 const AsmStmt::AsmStringPiece &Piece = AsmStrPieces[p]; 2136 if (!Piece.isOperand()) continue; 2137 2138 // If this is a reference to the input and if the input was the smaller 2139 // one, then we have to reject this asm. 2140 if (Piece.getOperandNo() == OpNo) 2141 return true; 2142 } 2143 2144 return false; 2145} 2146 2147StmtResult Sema::ActOnAsmStmt(SourceLocation AsmLoc, bool IsSimple, 2148 bool IsVolatile, unsigned NumOutputs, 2149 unsigned NumInputs, IdentifierInfo **Names, 2150 MultiExprArg constraints, MultiExprArg exprs, 2151 Expr *asmString, MultiExprArg clobbers, 2152 SourceLocation RParenLoc, bool MSAsm) { 2153 unsigned NumClobbers = clobbers.size(); 2154 StringLiteral **Constraints = 2155 reinterpret_cast<StringLiteral**>(constraints.get()); 2156 Expr **Exprs = exprs.get(); 2157 StringLiteral *AsmString = cast<StringLiteral>(asmString); 2158 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.get()); 2159 2160 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; 2161 2162 // The parser verifies that there is a string literal here. 2163 if (!AsmString->isAscii()) 2164 return StmtError(Diag(AsmString->getLocStart(),diag::err_asm_wide_character) 2165 << AsmString->getSourceRange()); 2166 2167 for (unsigned i = 0; i != NumOutputs; i++) { 2168 StringLiteral *Literal = Constraints[i]; 2169 if (!Literal->isAscii()) 2170 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 2171 << Literal->getSourceRange()); 2172 2173 StringRef OutputName; 2174 if (Names[i]) 2175 OutputName = Names[i]->getName(); 2176 2177 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName); 2178 if (!Context.getTargetInfo().validateOutputConstraint(Info)) 2179 return StmtError(Diag(Literal->getLocStart(), 2180 diag::err_asm_invalid_output_constraint) 2181 << Info.getConstraintStr()); 2182 2183 // Check that the output exprs are valid lvalues. 2184 Expr *OutputExpr = Exprs[i]; 2185 if (CheckAsmLValue(OutputExpr, *this)) { 2186 return StmtError(Diag(OutputExpr->getLocStart(), 2187 diag::err_asm_invalid_lvalue_in_output) 2188 << OutputExpr->getSourceRange()); 2189 } 2190 2191 OutputConstraintInfos.push_back(Info); 2192 } 2193 2194 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos; 2195 2196 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) { 2197 StringLiteral *Literal = Constraints[i]; 2198 if (!Literal->isAscii()) 2199 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 2200 << Literal->getSourceRange()); 2201 2202 StringRef InputName; 2203 if (Names[i]) 2204 InputName = Names[i]->getName(); 2205 2206 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName); 2207 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(), 2208 NumOutputs, Info)) { 2209 return StmtError(Diag(Literal->getLocStart(), 2210 diag::err_asm_invalid_input_constraint) 2211 << Info.getConstraintStr()); 2212 } 2213 2214 Expr *InputExpr = Exprs[i]; 2215 2216 // Only allow void types for memory constraints. 2217 if (Info.allowsMemory() && !Info.allowsRegister()) { 2218 if (CheckAsmLValue(InputExpr, *this)) 2219 return StmtError(Diag(InputExpr->getLocStart(), 2220 diag::err_asm_invalid_lvalue_in_input) 2221 << Info.getConstraintStr() 2222 << InputExpr->getSourceRange()); 2223 } 2224 2225 if (Info.allowsRegister()) { 2226 if (InputExpr->getType()->isVoidType()) { 2227 return StmtError(Diag(InputExpr->getLocStart(), 2228 diag::err_asm_invalid_type_in_input) 2229 << InputExpr->getType() << Info.getConstraintStr() 2230 << InputExpr->getSourceRange()); 2231 } 2232 } 2233 2234 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]); 2235 if (Result.isInvalid()) 2236 return StmtError(); 2237 2238 Exprs[i] = Result.take(); 2239 InputConstraintInfos.push_back(Info); 2240 } 2241 2242 // Check that the clobbers are valid. 2243 for (unsigned i = 0; i != NumClobbers; i++) { 2244 StringLiteral *Literal = Clobbers[i]; 2245 if (!Literal->isAscii()) 2246 return StmtError(Diag(Literal->getLocStart(),diag::err_asm_wide_character) 2247 << Literal->getSourceRange()); 2248 2249 StringRef Clobber = Literal->getString(); 2250 2251 if (!Context.getTargetInfo().isValidClobber(Clobber)) 2252 return StmtError(Diag(Literal->getLocStart(), 2253 diag::err_asm_unknown_register_name) << Clobber); 2254 } 2255 2256 AsmStmt *NS = 2257 new (Context) AsmStmt(Context, AsmLoc, IsSimple, IsVolatile, MSAsm, 2258 NumOutputs, NumInputs, Names, Constraints, Exprs, 2259 AsmString, NumClobbers, Clobbers, RParenLoc); 2260 // Validate the asm string, ensuring it makes sense given the operands we 2261 // have. 2262 SmallVector<AsmStmt::AsmStringPiece, 8> Pieces; 2263 unsigned DiagOffs; 2264 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) { 2265 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID) 2266 << AsmString->getSourceRange(); 2267 return StmtError(); 2268 } 2269 2270 // Validate tied input operands for type mismatches. 2271 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) { 2272 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i]; 2273 2274 // If this is a tied constraint, verify that the output and input have 2275 // either exactly the same type, or that they are int/ptr operands with the 2276 // same size (int/long, int*/long, are ok etc). 2277 if (!Info.hasTiedOperand()) continue; 2278 2279 unsigned TiedTo = Info.getTiedOperand(); 2280 unsigned InputOpNo = i+NumOutputs; 2281 Expr *OutputExpr = Exprs[TiedTo]; 2282 Expr *InputExpr = Exprs[InputOpNo]; 2283 2284 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent()) 2285 continue; 2286 2287 QualType InTy = InputExpr->getType(); 2288 QualType OutTy = OutputExpr->getType(); 2289 if (Context.hasSameType(InTy, OutTy)) 2290 continue; // All types can be tied to themselves. 2291 2292 // Decide if the input and output are in the same domain (integer/ptr or 2293 // floating point. 2294 enum AsmDomain { 2295 AD_Int, AD_FP, AD_Other 2296 } InputDomain, OutputDomain; 2297 2298 if (InTy->isIntegerType() || InTy->isPointerType()) 2299 InputDomain = AD_Int; 2300 else if (InTy->isRealFloatingType()) 2301 InputDomain = AD_FP; 2302 else 2303 InputDomain = AD_Other; 2304 2305 if (OutTy->isIntegerType() || OutTy->isPointerType()) 2306 OutputDomain = AD_Int; 2307 else if (OutTy->isRealFloatingType()) 2308 OutputDomain = AD_FP; 2309 else 2310 OutputDomain = AD_Other; 2311 2312 // They are ok if they are the same size and in the same domain. This 2313 // allows tying things like: 2314 // void* to int* 2315 // void* to int if they are the same size. 2316 // double to long double if they are the same size. 2317 // 2318 uint64_t OutSize = Context.getTypeSize(OutTy); 2319 uint64_t InSize = Context.getTypeSize(InTy); 2320 if (OutSize == InSize && InputDomain == OutputDomain && 2321 InputDomain != AD_Other) 2322 continue; 2323 2324 // If the smaller input/output operand is not mentioned in the asm string, 2325 // then we can promote the smaller one to a larger input and the asm string 2326 // won't notice. 2327 bool SmallerValueMentioned = false; 2328 2329 // If this is a reference to the input and if the input was the smaller 2330 // one, then we have to reject this asm. 2331 if (isOperandMentioned(InputOpNo, Pieces)) { 2332 // This is a use in the asm string of the smaller operand. Since we 2333 // codegen this by promoting to a wider value, the asm will get printed 2334 // "wrong". 2335 SmallerValueMentioned |= InSize < OutSize; 2336 } 2337 if (isOperandMentioned(TiedTo, Pieces)) { 2338 // If this is a reference to the output, and if the output is the larger 2339 // value, then it's ok because we'll promote the input to the larger type. 2340 SmallerValueMentioned |= OutSize < InSize; 2341 } 2342 2343 // If the smaller value wasn't mentioned in the asm string, and if the 2344 // output was a register, just extend the shorter one to the size of the 2345 // larger one. 2346 if (!SmallerValueMentioned && InputDomain != AD_Other && 2347 OutputConstraintInfos[TiedTo].allowsRegister()) 2348 continue; 2349 2350 // Either both of the operands were mentioned or the smaller one was 2351 // mentioned. One more special case that we'll allow: if the tied input is 2352 // integer, unmentioned, and is a constant, then we'll allow truncating it 2353 // down to the size of the destination. 2354 if (InputDomain == AD_Int && OutputDomain == AD_Int && 2355 !isOperandMentioned(InputOpNo, Pieces) && 2356 InputExpr->isEvaluatable(Context)) { 2357 CastKind castKind = 2358 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast); 2359 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).take(); 2360 Exprs[InputOpNo] = InputExpr; 2361 NS->setInputExpr(i, InputExpr); 2362 continue; 2363 } 2364 2365 Diag(InputExpr->getLocStart(), 2366 diag::err_asm_tying_incompatible_types) 2367 << InTy << OutTy << OutputExpr->getSourceRange() 2368 << InputExpr->getSourceRange(); 2369 return StmtError(); 2370 } 2371 2372 return Owned(NS); 2373} 2374 2375StmtResult 2376Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc, 2377 SourceLocation RParen, Decl *Parm, 2378 Stmt *Body) { 2379 VarDecl *Var = cast_or_null<VarDecl>(Parm); 2380 if (Var && Var->isInvalidDecl()) 2381 return StmtError(); 2382 2383 return Owned(new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body)); 2384} 2385 2386StmtResult 2387Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) { 2388 return Owned(new (Context) ObjCAtFinallyStmt(AtLoc, Body)); 2389} 2390 2391StmtResult 2392Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 2393 MultiStmtArg CatchStmts, Stmt *Finally) { 2394 if (!getLangOpts().ObjCExceptions) 2395 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try"; 2396 2397 getCurFunction()->setHasBranchProtectedScope(); 2398 unsigned NumCatchStmts = CatchStmts.size(); 2399 return Owned(ObjCAtTryStmt::Create(Context, AtLoc, Try, 2400 CatchStmts.release(), 2401 NumCatchStmts, 2402 Finally)); 2403} 2404 2405StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, 2406 Expr *Throw) { 2407 if (Throw) { 2408 Throw = MaybeCreateExprWithCleanups(Throw); 2409 ExprResult Result = DefaultLvalueConversion(Throw); 2410 if (Result.isInvalid()) 2411 return StmtError(); 2412 2413 Throw = Result.take(); 2414 QualType ThrowType = Throw->getType(); 2415 // Make sure the expression type is an ObjC pointer or "void *". 2416 if (!ThrowType->isDependentType() && 2417 !ThrowType->isObjCObjectPointerType()) { 2418 const PointerType *PT = ThrowType->getAs<PointerType>(); 2419 if (!PT || !PT->getPointeeType()->isVoidType()) 2420 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object) 2421 << Throw->getType() << Throw->getSourceRange()); 2422 } 2423 } 2424 2425 return Owned(new (Context) ObjCAtThrowStmt(AtLoc, Throw)); 2426} 2427 2428StmtResult 2429Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 2430 Scope *CurScope) { 2431 if (!getLangOpts().ObjCExceptions) 2432 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw"; 2433 2434 if (!Throw) { 2435 // @throw without an expression designates a rethrow (which much occur 2436 // in the context of an @catch clause). 2437 Scope *AtCatchParent = CurScope; 2438 while (AtCatchParent && !AtCatchParent->isAtCatchScope()) 2439 AtCatchParent = AtCatchParent->getParent(); 2440 if (!AtCatchParent) 2441 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch)); 2442 } 2443 2444 return BuildObjCAtThrowStmt(AtLoc, Throw); 2445} 2446 2447ExprResult 2448Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) { 2449 ExprResult result = DefaultLvalueConversion(operand); 2450 if (result.isInvalid()) 2451 return ExprError(); 2452 operand = result.take(); 2453 2454 // Make sure the expression type is an ObjC pointer or "void *". 2455 QualType type = operand->getType(); 2456 if (!type->isDependentType() && 2457 !type->isObjCObjectPointerType()) { 2458 const PointerType *pointerType = type->getAs<PointerType>(); 2459 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) 2460 return Diag(atLoc, diag::error_objc_synchronized_expects_object) 2461 << type << operand->getSourceRange(); 2462 } 2463 2464 // The operand to @synchronized is a full-expression. 2465 return MaybeCreateExprWithCleanups(operand); 2466} 2467 2468StmtResult 2469Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr, 2470 Stmt *SyncBody) { 2471 // We can't jump into or indirect-jump out of a @synchronized block. 2472 getCurFunction()->setHasBranchProtectedScope(); 2473 return Owned(new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody)); 2474} 2475 2476/// ActOnCXXCatchBlock - Takes an exception declaration and a handler block 2477/// and creates a proper catch handler from them. 2478StmtResult 2479Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, 2480 Stmt *HandlerBlock) { 2481 // There's nothing to test that ActOnExceptionDecl didn't already test. 2482 return Owned(new (Context) CXXCatchStmt(CatchLoc, 2483 cast_or_null<VarDecl>(ExDecl), 2484 HandlerBlock)); 2485} 2486 2487StmtResult 2488Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) { 2489 getCurFunction()->setHasBranchProtectedScope(); 2490 return Owned(new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body)); 2491} 2492 2493namespace { 2494 2495class TypeWithHandler { 2496 QualType t; 2497 CXXCatchStmt *stmt; 2498public: 2499 TypeWithHandler(const QualType &type, CXXCatchStmt *statement) 2500 : t(type), stmt(statement) {} 2501 2502 // An arbitrary order is fine as long as it places identical 2503 // types next to each other. 2504 bool operator<(const TypeWithHandler &y) const { 2505 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr()) 2506 return true; 2507 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr()) 2508 return false; 2509 else 2510 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc(); 2511 } 2512 2513 bool operator==(const TypeWithHandler& other) const { 2514 return t == other.t; 2515 } 2516 2517 CXXCatchStmt *getCatchStmt() const { return stmt; } 2518 SourceLocation getTypeSpecStartLoc() const { 2519 return stmt->getExceptionDecl()->getTypeSpecStartLoc(); 2520 } 2521}; 2522 2523} 2524 2525/// ActOnCXXTryBlock - Takes a try compound-statement and a number of 2526/// handlers and creates a try statement from them. 2527StmtResult 2528Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 2529 MultiStmtArg RawHandlers) { 2530 // Don't report an error if 'try' is used in system headers. 2531 if (!getLangOpts().CXXExceptions && 2532 !getSourceManager().isInSystemHeader(TryLoc)) 2533 Diag(TryLoc, diag::err_exceptions_disabled) << "try"; 2534 2535 unsigned NumHandlers = RawHandlers.size(); 2536 assert(NumHandlers > 0 && 2537 "The parser shouldn't call this if there are no handlers."); 2538 Stmt **Handlers = RawHandlers.get(); 2539 2540 SmallVector<TypeWithHandler, 8> TypesWithHandlers; 2541 2542 for (unsigned i = 0; i < NumHandlers; ++i) { 2543 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]); 2544 if (!Handler->getExceptionDecl()) { 2545 if (i < NumHandlers - 1) 2546 return StmtError(Diag(Handler->getLocStart(), 2547 diag::err_early_catch_all)); 2548 2549 continue; 2550 } 2551 2552 const QualType CaughtType = Handler->getCaughtType(); 2553 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType); 2554 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler)); 2555 } 2556 2557 // Detect handlers for the same type as an earlier one. 2558 if (NumHandlers > 1) { 2559 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end()); 2560 2561 TypeWithHandler prev = TypesWithHandlers[0]; 2562 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) { 2563 TypeWithHandler curr = TypesWithHandlers[i]; 2564 2565 if (curr == prev) { 2566 Diag(curr.getTypeSpecStartLoc(), 2567 diag::warn_exception_caught_by_earlier_handler) 2568 << curr.getCatchStmt()->getCaughtType().getAsString(); 2569 Diag(prev.getTypeSpecStartLoc(), 2570 diag::note_previous_exception_handler) 2571 << prev.getCatchStmt()->getCaughtType().getAsString(); 2572 } 2573 2574 prev = curr; 2575 } 2576 } 2577 2578 getCurFunction()->setHasBranchProtectedScope(); 2579 2580 // FIXME: We should detect handlers that cannot catch anything because an 2581 // earlier handler catches a superclass. Need to find a method that is not 2582 // quadratic for this. 2583 // Neither of these are explicitly forbidden, but every compiler detects them 2584 // and warns. 2585 2586 return Owned(CXXTryStmt::Create(Context, TryLoc, TryBlock, 2587 Handlers, NumHandlers)); 2588} 2589 2590StmtResult 2591Sema::ActOnSEHTryBlock(bool IsCXXTry, 2592 SourceLocation TryLoc, 2593 Stmt *TryBlock, 2594 Stmt *Handler) { 2595 assert(TryBlock && Handler); 2596 2597 getCurFunction()->setHasBranchProtectedScope(); 2598 2599 return Owned(SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler)); 2600} 2601 2602StmtResult 2603Sema::ActOnSEHExceptBlock(SourceLocation Loc, 2604 Expr *FilterExpr, 2605 Stmt *Block) { 2606 assert(FilterExpr && Block); 2607 2608 if(!FilterExpr->getType()->isIntegerType()) { 2609 return StmtError(Diag(FilterExpr->getExprLoc(), 2610 diag::err_filter_expression_integral) 2611 << FilterExpr->getType()); 2612 } 2613 2614 return Owned(SEHExceptStmt::Create(Context,Loc,FilterExpr,Block)); 2615} 2616 2617StmtResult 2618Sema::ActOnSEHFinallyBlock(SourceLocation Loc, 2619 Stmt *Block) { 2620 assert(Block); 2621 return Owned(SEHFinallyStmt::Create(Context,Loc,Block)); 2622} 2623 2624StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc, 2625 bool IsIfExists, 2626 NestedNameSpecifierLoc QualifierLoc, 2627 DeclarationNameInfo NameInfo, 2628 Stmt *Nested) 2629{ 2630 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists, 2631 QualifierLoc, NameInfo, 2632 cast<CompoundStmt>(Nested)); 2633} 2634 2635 2636StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, 2637 bool IsIfExists, 2638 CXXScopeSpec &SS, 2639 UnqualifiedId &Name, 2640 Stmt *Nested) { 2641 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists, 2642 SS.getWithLocInContext(Context), 2643 GetNameFromUnqualifiedId(Name), 2644 Nested); 2645} 2646