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