clang API Documentation
00001 //===--- SemaStmt.cpp - Semantic Analysis for Statements ------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements semantic analysis for statements. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "clang/Sema/SemaInternal.h" 00015 #include "clang/AST/ASTContext.h" 00016 #include "clang/AST/ASTDiagnostic.h" 00017 #include "clang/AST/CharUnits.h" 00018 #include "clang/AST/DeclObjC.h" 00019 #include "clang/AST/EvaluatedExprVisitor.h" 00020 #include "clang/AST/ExprCXX.h" 00021 #include "clang/AST/ExprObjC.h" 00022 #include "clang/AST/RecursiveASTVisitor.h" 00023 #include "clang/AST/StmtCXX.h" 00024 #include "clang/AST/StmtObjC.h" 00025 #include "clang/AST/TypeLoc.h" 00026 #include "clang/Lex/Preprocessor.h" 00027 #include "clang/Sema/Initialization.h" 00028 #include "clang/Sema/Lookup.h" 00029 #include "clang/Sema/Scope.h" 00030 #include "clang/Sema/ScopeInfo.h" 00031 #include "llvm/ADT/ArrayRef.h" 00032 #include "llvm/ADT/STLExtras.h" 00033 #include "llvm/ADT/SmallPtrSet.h" 00034 #include "llvm/ADT/SmallString.h" 00035 #include "llvm/ADT/SmallVector.h" 00036 using namespace clang; 00037 using namespace sema; 00038 00039 StmtResult Sema::ActOnExprStmt(ExprResult FE) { 00040 if (FE.isInvalid()) 00041 return StmtError(); 00042 00043 FE = ActOnFinishFullExpr(FE.get(), FE.get()->getExprLoc(), 00044 /*DiscardedValue*/ true); 00045 if (FE.isInvalid()) 00046 return StmtError(); 00047 00048 // C99 6.8.3p2: The expression in an expression statement is evaluated as a 00049 // void expression for its side effects. Conversion to void allows any 00050 // operand, even incomplete types. 00051 00052 // Same thing in for stmt first clause (when expr) and third clause. 00053 return StmtResult(FE.getAs<Stmt>()); 00054 } 00055 00056 00057 StmtResult Sema::ActOnExprStmtError() { 00058 DiscardCleanupsInEvaluationContext(); 00059 return StmtError(); 00060 } 00061 00062 StmtResult Sema::ActOnNullStmt(SourceLocation SemiLoc, 00063 bool HasLeadingEmptyMacro) { 00064 return new (Context) NullStmt(SemiLoc, HasLeadingEmptyMacro); 00065 } 00066 00067 StmtResult Sema::ActOnDeclStmt(DeclGroupPtrTy dg, SourceLocation StartLoc, 00068 SourceLocation EndLoc) { 00069 DeclGroupRef DG = dg.get(); 00070 00071 // If we have an invalid decl, just return an error. 00072 if (DG.isNull()) return StmtError(); 00073 00074 return new (Context) DeclStmt(DG, StartLoc, EndLoc); 00075 } 00076 00077 void Sema::ActOnForEachDeclStmt(DeclGroupPtrTy dg) { 00078 DeclGroupRef DG = dg.get(); 00079 00080 // If we don't have a declaration, or we have an invalid declaration, 00081 // just return. 00082 if (DG.isNull() || !DG.isSingleDecl()) 00083 return; 00084 00085 Decl *decl = DG.getSingleDecl(); 00086 if (!decl || decl->isInvalidDecl()) 00087 return; 00088 00089 // Only variable declarations are permitted. 00090 VarDecl *var = dyn_cast<VarDecl>(decl); 00091 if (!var) { 00092 Diag(decl->getLocation(), diag::err_non_variable_decl_in_for); 00093 decl->setInvalidDecl(); 00094 return; 00095 } 00096 00097 // foreach variables are never actually initialized in the way that 00098 // the parser came up with. 00099 var->setInit(nullptr); 00100 00101 // In ARC, we don't need to retain the iteration variable of a fast 00102 // enumeration loop. Rather than actually trying to catch that 00103 // during declaration processing, we remove the consequences here. 00104 if (getLangOpts().ObjCAutoRefCount) { 00105 QualType type = var->getType(); 00106 00107 // Only do this if we inferred the lifetime. Inferred lifetime 00108 // will show up as a local qualifier because explicit lifetime 00109 // should have shown up as an AttributedType instead. 00110 if (type.getLocalQualifiers().getObjCLifetime() == Qualifiers::OCL_Strong) { 00111 // Add 'const' and mark the variable as pseudo-strong. 00112 var->setType(type.withConst()); 00113 var->setARCPseudoStrong(true); 00114 } 00115 } 00116 } 00117 00118 /// \brief Diagnose unused comparisons, both builtin and overloaded operators. 00119 /// For '==' and '!=', suggest fixits for '=' or '|='. 00120 /// 00121 /// Adding a cast to void (or other expression wrappers) will prevent the 00122 /// warning from firing. 00123 static bool DiagnoseUnusedComparison(Sema &S, const Expr *E) { 00124 SourceLocation Loc; 00125 bool IsNotEqual, CanAssign, IsRelational; 00126 00127 if (const BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) { 00128 if (!Op->isComparisonOp()) 00129 return false; 00130 00131 IsRelational = Op->isRelationalOp(); 00132 Loc = Op->getOperatorLoc(); 00133 IsNotEqual = Op->getOpcode() == BO_NE; 00134 CanAssign = Op->getLHS()->IgnoreParenImpCasts()->isLValue(); 00135 } else if (const CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) { 00136 switch (Op->getOperator()) { 00137 default: 00138 return false; 00139 case OO_EqualEqual: 00140 case OO_ExclaimEqual: 00141 IsRelational = false; 00142 break; 00143 case OO_Less: 00144 case OO_Greater: 00145 case OO_GreaterEqual: 00146 case OO_LessEqual: 00147 IsRelational = true; 00148 break; 00149 } 00150 00151 Loc = Op->getOperatorLoc(); 00152 IsNotEqual = Op->getOperator() == OO_ExclaimEqual; 00153 CanAssign = Op->getArg(0)->IgnoreParenImpCasts()->isLValue(); 00154 } else { 00155 // Not a typo-prone comparison. 00156 return false; 00157 } 00158 00159 // Suppress warnings when the operator, suspicious as it may be, comes from 00160 // a macro expansion. 00161 if (S.SourceMgr.isMacroBodyExpansion(Loc)) 00162 return false; 00163 00164 S.Diag(Loc, diag::warn_unused_comparison) 00165 << (unsigned)IsRelational << (unsigned)IsNotEqual << E->getSourceRange(); 00166 00167 // If the LHS is a plausible entity to assign to, provide a fixit hint to 00168 // correct common typos. 00169 if (!IsRelational && CanAssign) { 00170 if (IsNotEqual) 00171 S.Diag(Loc, diag::note_inequality_comparison_to_or_assign) 00172 << FixItHint::CreateReplacement(Loc, "|="); 00173 else 00174 S.Diag(Loc, diag::note_equality_comparison_to_assign) 00175 << FixItHint::CreateReplacement(Loc, "="); 00176 } 00177 00178 return true; 00179 } 00180 00181 void Sema::DiagnoseUnusedExprResult(const Stmt *S) { 00182 if (const LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S)) 00183 return DiagnoseUnusedExprResult(Label->getSubStmt()); 00184 00185 const Expr *E = dyn_cast_or_null<Expr>(S); 00186 if (!E) 00187 return; 00188 00189 // If we are in an unevaluated expression context, then there can be no unused 00190 // results because the results aren't expected to be used in the first place. 00191 if (isUnevaluatedContext()) 00192 return; 00193 00194 SourceLocation ExprLoc = E->IgnoreParens()->getExprLoc(); 00195 // In most cases, we don't want to warn if the expression is written in a 00196 // macro body, or if the macro comes from a system header. If the offending 00197 // expression is a call to a function with the warn_unused_result attribute, 00198 // we warn no matter the location. Because of the order in which the various 00199 // checks need to happen, we factor out the macro-related test here. 00200 bool ShouldSuppress = 00201 SourceMgr.isMacroBodyExpansion(ExprLoc) || 00202 SourceMgr.isInSystemMacro(ExprLoc); 00203 00204 const Expr *WarnExpr; 00205 SourceLocation Loc; 00206 SourceRange R1, R2; 00207 if (!E->isUnusedResultAWarning(WarnExpr, Loc, R1, R2, Context)) 00208 return; 00209 00210 // If this is a GNU statement expression expanded from a macro, it is probably 00211 // unused because it is a function-like macro that can be used as either an 00212 // expression or statement. Don't warn, because it is almost certainly a 00213 // false positive. 00214 if (isa<StmtExpr>(E) && Loc.isMacroID()) 00215 return; 00216 00217 // Okay, we have an unused result. Depending on what the base expression is, 00218 // we might want to make a more specific diagnostic. Check for one of these 00219 // cases now. 00220 unsigned DiagID = diag::warn_unused_expr; 00221 if (const ExprWithCleanups *Temps = dyn_cast<ExprWithCleanups>(E)) 00222 E = Temps->getSubExpr(); 00223 if (const CXXBindTemporaryExpr *TempExpr = dyn_cast<CXXBindTemporaryExpr>(E)) 00224 E = TempExpr->getSubExpr(); 00225 00226 if (DiagnoseUnusedComparison(*this, E)) 00227 return; 00228 00229 E = WarnExpr; 00230 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 00231 if (E->getType()->isVoidType()) 00232 return; 00233 00234 // If the callee has attribute pure, const, or warn_unused_result, warn with 00235 // a more specific message to make it clear what is happening. If the call 00236 // is written in a macro body, only warn if it has the warn_unused_result 00237 // attribute. 00238 if (const Decl *FD = CE->getCalleeDecl()) { 00239 if (FD->hasAttr<WarnUnusedResultAttr>()) { 00240 Diag(Loc, diag::warn_unused_result) << R1 << R2; 00241 return; 00242 } 00243 if (ShouldSuppress) 00244 return; 00245 if (FD->hasAttr<PureAttr>()) { 00246 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "pure"; 00247 return; 00248 } 00249 if (FD->hasAttr<ConstAttr>()) { 00250 Diag(Loc, diag::warn_unused_call) << R1 << R2 << "const"; 00251 return; 00252 } 00253 } 00254 } else if (ShouldSuppress) 00255 return; 00256 00257 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(E)) { 00258 if (getLangOpts().ObjCAutoRefCount && ME->isDelegateInitCall()) { 00259 Diag(Loc, diag::err_arc_unused_init_message) << R1; 00260 return; 00261 } 00262 const ObjCMethodDecl *MD = ME->getMethodDecl(); 00263 if (MD) { 00264 if (MD->hasAttr<WarnUnusedResultAttr>()) { 00265 Diag(Loc, diag::warn_unused_result) << R1 << R2; 00266 return; 00267 } 00268 if (MD->isPropertyAccessor()) { 00269 Diag(Loc, diag::warn_unused_property_expr); 00270 return; 00271 } 00272 } 00273 } else if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 00274 const Expr *Source = POE->getSyntacticForm(); 00275 if (isa<ObjCSubscriptRefExpr>(Source)) 00276 DiagID = diag::warn_unused_container_subscript_expr; 00277 else 00278 DiagID = diag::warn_unused_property_expr; 00279 } else if (const CXXFunctionalCastExpr *FC 00280 = dyn_cast<CXXFunctionalCastExpr>(E)) { 00281 if (isa<CXXConstructExpr>(FC->getSubExpr()) || 00282 isa<CXXTemporaryObjectExpr>(FC->getSubExpr())) 00283 return; 00284 } 00285 // Diagnose "(void*) blah" as a typo for "(void) blah". 00286 else if (const CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(E)) { 00287 TypeSourceInfo *TI = CE->getTypeInfoAsWritten(); 00288 QualType T = TI->getType(); 00289 00290 // We really do want to use the non-canonical type here. 00291 if (T == Context.VoidPtrTy) { 00292 PointerTypeLoc TL = TI->getTypeLoc().castAs<PointerTypeLoc>(); 00293 00294 Diag(Loc, diag::warn_unused_voidptr) 00295 << FixItHint::CreateRemoval(TL.getStarLoc()); 00296 return; 00297 } 00298 } 00299 00300 if (E->isGLValue() && E->getType().isVolatileQualified()) { 00301 Diag(Loc, diag::warn_unused_volatile) << R1 << R2; 00302 return; 00303 } 00304 00305 DiagRuntimeBehavior(Loc, nullptr, PDiag(DiagID) << R1 << R2); 00306 } 00307 00308 void Sema::ActOnStartOfCompoundStmt() { 00309 PushCompoundScope(); 00310 } 00311 00312 void Sema::ActOnFinishOfCompoundStmt() { 00313 PopCompoundScope(); 00314 } 00315 00316 sema::CompoundScopeInfo &Sema::getCurCompoundScope() const { 00317 return getCurFunction()->CompoundScopes.back(); 00318 } 00319 00320 StmtResult Sema::ActOnCompoundStmt(SourceLocation L, SourceLocation R, 00321 ArrayRef<Stmt *> Elts, bool isStmtExpr) { 00322 const unsigned NumElts = Elts.size(); 00323 00324 // If we're in C89 mode, check that we don't have any decls after stmts. If 00325 // so, emit an extension diagnostic. 00326 if (!getLangOpts().C99 && !getLangOpts().CPlusPlus) { 00327 // Note that __extension__ can be around a decl. 00328 unsigned i = 0; 00329 // Skip over all declarations. 00330 for (; i != NumElts && isa<DeclStmt>(Elts[i]); ++i) 00331 /*empty*/; 00332 00333 // We found the end of the list or a statement. Scan for another declstmt. 00334 for (; i != NumElts && !isa<DeclStmt>(Elts[i]); ++i) 00335 /*empty*/; 00336 00337 if (i != NumElts) { 00338 Decl *D = *cast<DeclStmt>(Elts[i])->decl_begin(); 00339 Diag(D->getLocation(), diag::ext_mixed_decls_code); 00340 } 00341 } 00342 // Warn about unused expressions in statements. 00343 for (unsigned i = 0; i != NumElts; ++i) { 00344 // Ignore statements that are last in a statement expression. 00345 if (isStmtExpr && i == NumElts - 1) 00346 continue; 00347 00348 DiagnoseUnusedExprResult(Elts[i]); 00349 } 00350 00351 // Check for suspicious empty body (null statement) in `for' and `while' 00352 // statements. Don't do anything for template instantiations, this just adds 00353 // noise. 00354 if (NumElts != 0 && !CurrentInstantiationScope && 00355 getCurCompoundScope().HasEmptyLoopBodies) { 00356 for (unsigned i = 0; i != NumElts - 1; ++i) 00357 DiagnoseEmptyLoopBody(Elts[i], Elts[i + 1]); 00358 } 00359 00360 return new (Context) CompoundStmt(Context, Elts, L, R); 00361 } 00362 00363 StmtResult 00364 Sema::ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal, 00365 SourceLocation DotDotDotLoc, Expr *RHSVal, 00366 SourceLocation ColonLoc) { 00367 assert(LHSVal && "missing expression in case statement"); 00368 00369 if (getCurFunction()->SwitchStack.empty()) { 00370 Diag(CaseLoc, diag::err_case_not_in_switch); 00371 return StmtError(); 00372 } 00373 00374 if (!getLangOpts().CPlusPlus11) { 00375 // C99 6.8.4.2p3: The expression shall be an integer constant. 00376 // However, GCC allows any evaluatable integer expression. 00377 if (!LHSVal->isTypeDependent() && !LHSVal->isValueDependent()) { 00378 LHSVal = VerifyIntegerConstantExpression(LHSVal).get(); 00379 if (!LHSVal) 00380 return StmtError(); 00381 } 00382 00383 // GCC extension: The expression shall be an integer constant. 00384 00385 if (RHSVal && !RHSVal->isTypeDependent() && !RHSVal->isValueDependent()) { 00386 RHSVal = VerifyIntegerConstantExpression(RHSVal).get(); 00387 // Recover from an error by just forgetting about it. 00388 } 00389 } 00390 00391 LHSVal = ActOnFinishFullExpr(LHSVal, LHSVal->getExprLoc(), false, 00392 getLangOpts().CPlusPlus11).get(); 00393 if (RHSVal) 00394 RHSVal = ActOnFinishFullExpr(RHSVal, RHSVal->getExprLoc(), false, 00395 getLangOpts().CPlusPlus11).get(); 00396 00397 CaseStmt *CS = new (Context) CaseStmt(LHSVal, RHSVal, CaseLoc, DotDotDotLoc, 00398 ColonLoc); 00399 getCurFunction()->SwitchStack.back()->addSwitchCase(CS); 00400 return CS; 00401 } 00402 00403 /// ActOnCaseStmtBody - This installs a statement as the body of a case. 00404 void Sema::ActOnCaseStmtBody(Stmt *caseStmt, Stmt *SubStmt) { 00405 DiagnoseUnusedExprResult(SubStmt); 00406 00407 CaseStmt *CS = static_cast<CaseStmt*>(caseStmt); 00408 CS->setSubStmt(SubStmt); 00409 } 00410 00411 StmtResult 00412 Sema::ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, 00413 Stmt *SubStmt, Scope *CurScope) { 00414 DiagnoseUnusedExprResult(SubStmt); 00415 00416 if (getCurFunction()->SwitchStack.empty()) { 00417 Diag(DefaultLoc, diag::err_default_not_in_switch); 00418 return SubStmt; 00419 } 00420 00421 DefaultStmt *DS = new (Context) DefaultStmt(DefaultLoc, ColonLoc, SubStmt); 00422 getCurFunction()->SwitchStack.back()->addSwitchCase(DS); 00423 return DS; 00424 } 00425 00426 StmtResult 00427 Sema::ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 00428 SourceLocation ColonLoc, Stmt *SubStmt) { 00429 // If the label was multiply defined, reject it now. 00430 if (TheDecl->getStmt()) { 00431 Diag(IdentLoc, diag::err_redefinition_of_label) << TheDecl->getDeclName(); 00432 Diag(TheDecl->getLocation(), diag::note_previous_definition); 00433 return SubStmt; 00434 } 00435 00436 // Otherwise, things are good. Fill in the declaration and return it. 00437 LabelStmt *LS = new (Context) LabelStmt(IdentLoc, TheDecl, SubStmt); 00438 TheDecl->setStmt(LS); 00439 if (!TheDecl->isGnuLocal()) { 00440 TheDecl->setLocStart(IdentLoc); 00441 if (!TheDecl->isMSAsmLabel()) { 00442 // Don't update the location of MS ASM labels. These will result in 00443 // a diagnostic, and changing the location here will mess that up. 00444 TheDecl->setLocation(IdentLoc); 00445 } 00446 } 00447 return LS; 00448 } 00449 00450 StmtResult Sema::ActOnAttributedStmt(SourceLocation AttrLoc, 00451 ArrayRef<const Attr*> Attrs, 00452 Stmt *SubStmt) { 00453 // Fill in the declaration and return it. 00454 AttributedStmt *LS = AttributedStmt::Create(Context, AttrLoc, Attrs, SubStmt); 00455 return LS; 00456 } 00457 00458 StmtResult 00459 Sema::ActOnIfStmt(SourceLocation IfLoc, FullExprArg CondVal, Decl *CondVar, 00460 Stmt *thenStmt, SourceLocation ElseLoc, 00461 Stmt *elseStmt) { 00462 // If the condition was invalid, discard the if statement. We could recover 00463 // better by replacing it with a valid expr, but don't do that yet. 00464 if (!CondVal.get() && !CondVar) { 00465 getCurFunction()->setHasDroppedStmt(); 00466 return StmtError(); 00467 } 00468 00469 ExprResult CondResult(CondVal.release()); 00470 00471 VarDecl *ConditionVar = nullptr; 00472 if (CondVar) { 00473 ConditionVar = cast<VarDecl>(CondVar); 00474 CondResult = CheckConditionVariable(ConditionVar, IfLoc, true); 00475 if (CondResult.isInvalid()) 00476 return StmtError(); 00477 } 00478 Expr *ConditionExpr = CondResult.getAs<Expr>(); 00479 if (!ConditionExpr) 00480 return StmtError(); 00481 00482 DiagnoseUnusedExprResult(thenStmt); 00483 00484 if (!elseStmt) { 00485 DiagnoseEmptyStmtBody(ConditionExpr->getLocEnd(), thenStmt, 00486 diag::warn_empty_if_body); 00487 } 00488 00489 DiagnoseUnusedExprResult(elseStmt); 00490 00491 return new (Context) IfStmt(Context, IfLoc, ConditionVar, ConditionExpr, 00492 thenStmt, ElseLoc, elseStmt); 00493 } 00494 00495 namespace { 00496 struct CaseCompareFunctor { 00497 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 00498 const llvm::APSInt &RHS) { 00499 return LHS.first < RHS; 00500 } 00501 bool operator()(const std::pair<llvm::APSInt, CaseStmt*> &LHS, 00502 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 00503 return LHS.first < RHS.first; 00504 } 00505 bool operator()(const llvm::APSInt &LHS, 00506 const std::pair<llvm::APSInt, CaseStmt*> &RHS) { 00507 return LHS < RHS.first; 00508 } 00509 }; 00510 } 00511 00512 /// CmpCaseVals - Comparison predicate for sorting case values. 00513 /// 00514 static bool CmpCaseVals(const std::pair<llvm::APSInt, CaseStmt*>& lhs, 00515 const std::pair<llvm::APSInt, CaseStmt*>& rhs) { 00516 if (lhs.first < rhs.first) 00517 return true; 00518 00519 if (lhs.first == rhs.first && 00520 lhs.second->getCaseLoc().getRawEncoding() 00521 < rhs.second->getCaseLoc().getRawEncoding()) 00522 return true; 00523 return false; 00524 } 00525 00526 /// CmpEnumVals - Comparison predicate for sorting enumeration values. 00527 /// 00528 static bool CmpEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 00529 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 00530 { 00531 return lhs.first < rhs.first; 00532 } 00533 00534 /// EqEnumVals - Comparison preficate for uniqing enumeration values. 00535 /// 00536 static bool EqEnumVals(const std::pair<llvm::APSInt, EnumConstantDecl*>& lhs, 00537 const std::pair<llvm::APSInt, EnumConstantDecl*>& rhs) 00538 { 00539 return lhs.first == rhs.first; 00540 } 00541 00542 /// GetTypeBeforeIntegralPromotion - Returns the pre-promotion type of 00543 /// potentially integral-promoted expression @p expr. 00544 static QualType GetTypeBeforeIntegralPromotion(Expr *&expr) { 00545 if (ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(expr)) 00546 expr = cleanups->getSubExpr(); 00547 while (ImplicitCastExpr *impcast = dyn_cast<ImplicitCastExpr>(expr)) { 00548 if (impcast->getCastKind() != CK_IntegralCast) break; 00549 expr = impcast->getSubExpr(); 00550 } 00551 return expr->getType(); 00552 } 00553 00554 StmtResult 00555 Sema::ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Expr *Cond, 00556 Decl *CondVar) { 00557 ExprResult CondResult; 00558 00559 VarDecl *ConditionVar = nullptr; 00560 if (CondVar) { 00561 ConditionVar = cast<VarDecl>(CondVar); 00562 CondResult = CheckConditionVariable(ConditionVar, SourceLocation(), false); 00563 if (CondResult.isInvalid()) 00564 return StmtError(); 00565 00566 Cond = CondResult.get(); 00567 } 00568 00569 if (!Cond) 00570 return StmtError(); 00571 00572 class SwitchConvertDiagnoser : public ICEConvertDiagnoser { 00573 Expr *Cond; 00574 00575 public: 00576 SwitchConvertDiagnoser(Expr *Cond) 00577 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/true, false, true), 00578 Cond(Cond) {} 00579 00580 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 00581 QualType T) override { 00582 return S.Diag(Loc, diag::err_typecheck_statement_requires_integer) << T; 00583 } 00584 00585 SemaDiagnosticBuilder diagnoseIncomplete( 00586 Sema &S, SourceLocation Loc, QualType T) override { 00587 return S.Diag(Loc, diag::err_switch_incomplete_class_type) 00588 << T << Cond->getSourceRange(); 00589 } 00590 00591 SemaDiagnosticBuilder diagnoseExplicitConv( 00592 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 00593 return S.Diag(Loc, diag::err_switch_explicit_conversion) << T << ConvTy; 00594 } 00595 00596 SemaDiagnosticBuilder noteExplicitConv( 00597 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 00598 return S.Diag(Conv->getLocation(), diag::note_switch_conversion) 00599 << ConvTy->isEnumeralType() << ConvTy; 00600 } 00601 00602 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 00603 QualType T) override { 00604 return S.Diag(Loc, diag::err_switch_multiple_conversions) << T; 00605 } 00606 00607 SemaDiagnosticBuilder noteAmbiguous( 00608 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 00609 return S.Diag(Conv->getLocation(), diag::note_switch_conversion) 00610 << ConvTy->isEnumeralType() << ConvTy; 00611 } 00612 00613 SemaDiagnosticBuilder diagnoseConversion( 00614 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 00615 llvm_unreachable("conversion functions are permitted"); 00616 } 00617 } SwitchDiagnoser(Cond); 00618 00619 CondResult = 00620 PerformContextualImplicitConversion(SwitchLoc, Cond, SwitchDiagnoser); 00621 if (CondResult.isInvalid()) return StmtError(); 00622 Cond = CondResult.get(); 00623 00624 // C99 6.8.4.2p5 - Integer promotions are performed on the controlling expr. 00625 CondResult = UsualUnaryConversions(Cond); 00626 if (CondResult.isInvalid()) return StmtError(); 00627 Cond = CondResult.get(); 00628 00629 if (!CondVar) { 00630 CondResult = ActOnFinishFullExpr(Cond, SwitchLoc); 00631 if (CondResult.isInvalid()) 00632 return StmtError(); 00633 Cond = CondResult.get(); 00634 } 00635 00636 getCurFunction()->setHasBranchIntoScope(); 00637 00638 SwitchStmt *SS = new (Context) SwitchStmt(Context, ConditionVar, Cond); 00639 getCurFunction()->SwitchStack.push_back(SS); 00640 return SS; 00641 } 00642 00643 static void AdjustAPSInt(llvm::APSInt &Val, unsigned BitWidth, bool IsSigned) { 00644 Val = Val.extOrTrunc(BitWidth); 00645 Val.setIsSigned(IsSigned); 00646 } 00647 00648 /// Check the specified case value is in range for the given unpromoted switch 00649 /// type. 00650 static void checkCaseValue(Sema &S, SourceLocation Loc, const llvm::APSInt &Val, 00651 unsigned UnpromotedWidth, bool UnpromotedSign) { 00652 // If the case value was signed and negative and the switch expression is 00653 // unsigned, don't bother to warn: this is implementation-defined behavior. 00654 // FIXME: Introduce a second, default-ignored warning for this case? 00655 if (UnpromotedWidth < Val.getBitWidth()) { 00656 llvm::APSInt ConvVal(Val); 00657 AdjustAPSInt(ConvVal, UnpromotedWidth, UnpromotedSign); 00658 AdjustAPSInt(ConvVal, Val.getBitWidth(), Val.isSigned()); 00659 // FIXME: Use different diagnostics for overflow in conversion to promoted 00660 // type versus "switch expression cannot have this value". Use proper 00661 // IntRange checking rather than just looking at the unpromoted type here. 00662 if (ConvVal != Val) 00663 S.Diag(Loc, diag::warn_case_value_overflow) << Val.toString(10) 00664 << ConvVal.toString(10); 00665 } 00666 } 00667 00668 /// Returns true if we should emit a diagnostic about this case expression not 00669 /// being a part of the enum used in the switch controlling expression. 00670 static bool ShouldDiagnoseSwitchCaseNotInEnum(const ASTContext &Ctx, 00671 const EnumDecl *ED, 00672 const Expr *CaseExpr) { 00673 // Don't warn if the 'case' expression refers to a static const variable of 00674 // the enum type. 00675 CaseExpr = CaseExpr->IgnoreParenImpCasts(); 00676 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseExpr)) { 00677 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 00678 if (!VD->hasGlobalStorage()) 00679 return true; 00680 QualType VarType = VD->getType(); 00681 if (!VarType.isConstQualified()) 00682 return true; 00683 QualType EnumType = Ctx.getTypeDeclType(ED); 00684 if (Ctx.hasSameUnqualifiedType(EnumType, VarType)) 00685 return false; 00686 } 00687 } 00688 return true; 00689 } 00690 00691 StmtResult 00692 Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, 00693 Stmt *BodyStmt) { 00694 SwitchStmt *SS = cast<SwitchStmt>(Switch); 00695 assert(SS == getCurFunction()->SwitchStack.back() && 00696 "switch stack missing push/pop!"); 00697 00698 if (!BodyStmt) return StmtError(); 00699 SS->setBody(BodyStmt, SwitchLoc); 00700 getCurFunction()->SwitchStack.pop_back(); 00701 00702 Expr *CondExpr = SS->getCond(); 00703 if (!CondExpr) return StmtError(); 00704 00705 QualType CondType = CondExpr->getType(); 00706 00707 Expr *CondExprBeforePromotion = CondExpr; 00708 QualType CondTypeBeforePromotion = 00709 GetTypeBeforeIntegralPromotion(CondExprBeforePromotion); 00710 00711 // C++ 6.4.2.p2: 00712 // Integral promotions are performed (on the switch condition). 00713 // 00714 // A case value unrepresentable by the original switch condition 00715 // type (before the promotion) doesn't make sense, even when it can 00716 // be represented by the promoted type. Therefore we need to find 00717 // the pre-promotion type of the switch condition. 00718 if (!CondExpr->isTypeDependent()) { 00719 // We have already converted the expression to an integral or enumeration 00720 // type, when we started the switch statement. If we don't have an 00721 // appropriate type now, just return an error. 00722 if (!CondType->isIntegralOrEnumerationType()) 00723 return StmtError(); 00724 00725 if (CondExpr->isKnownToHaveBooleanValue()) { 00726 // switch(bool_expr) {...} is often a programmer error, e.g. 00727 // switch(n && mask) { ... } // Doh - should be "n & mask". 00728 // One can always use an if statement instead of switch(bool_expr). 00729 Diag(SwitchLoc, diag::warn_bool_switch_condition) 00730 << CondExpr->getSourceRange(); 00731 } 00732 } 00733 00734 // Get the bitwidth of the switched-on value after promotions. We must 00735 // convert the integer case values to this width before comparison. 00736 bool HasDependentValue 00737 = CondExpr->isTypeDependent() || CondExpr->isValueDependent(); 00738 unsigned CondWidth = HasDependentValue ? 0 : Context.getIntWidth(CondType); 00739 bool CondIsSigned = CondType->isSignedIntegerOrEnumerationType(); 00740 00741 // Get the width and signedness that the condition might actually have, for 00742 // warning purposes. 00743 // FIXME: Grab an IntRange for the condition rather than using the unpromoted 00744 // type. 00745 unsigned CondWidthBeforePromotion 00746 = HasDependentValue ? 0 : Context.getIntWidth(CondTypeBeforePromotion); 00747 bool CondIsSignedBeforePromotion 00748 = CondTypeBeforePromotion->isSignedIntegerOrEnumerationType(); 00749 00750 // Accumulate all of the case values in a vector so that we can sort them 00751 // and detect duplicates. This vector contains the APInt for the case after 00752 // it has been converted to the condition type. 00753 typedef SmallVector<std::pair<llvm::APSInt, CaseStmt*>, 64> CaseValsTy; 00754 CaseValsTy CaseVals; 00755 00756 // Keep track of any GNU case ranges we see. The APSInt is the low value. 00757 typedef std::vector<std::pair<llvm::APSInt, CaseStmt*> > CaseRangesTy; 00758 CaseRangesTy CaseRanges; 00759 00760 DefaultStmt *TheDefaultStmt = nullptr; 00761 00762 bool CaseListIsErroneous = false; 00763 00764 for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue; 00765 SC = SC->getNextSwitchCase()) { 00766 00767 if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC)) { 00768 if (TheDefaultStmt) { 00769 Diag(DS->getDefaultLoc(), diag::err_multiple_default_labels_defined); 00770 Diag(TheDefaultStmt->getDefaultLoc(), diag::note_duplicate_case_prev); 00771 00772 // FIXME: Remove the default statement from the switch block so that 00773 // we'll return a valid AST. This requires recursing down the AST and 00774 // finding it, not something we are set up to do right now. For now, 00775 // just lop the entire switch stmt out of the AST. 00776 CaseListIsErroneous = true; 00777 } 00778 TheDefaultStmt = DS; 00779 00780 } else { 00781 CaseStmt *CS = cast<CaseStmt>(SC); 00782 00783 Expr *Lo = CS->getLHS(); 00784 00785 if (Lo->isTypeDependent() || Lo->isValueDependent()) { 00786 HasDependentValue = true; 00787 break; 00788 } 00789 00790 llvm::APSInt LoVal; 00791 00792 if (getLangOpts().CPlusPlus11) { 00793 // C++11 [stmt.switch]p2: the constant-expression shall be a converted 00794 // constant expression of the promoted type of the switch condition. 00795 ExprResult ConvLo = 00796 CheckConvertedConstantExpression(Lo, CondType, LoVal, CCEK_CaseValue); 00797 if (ConvLo.isInvalid()) { 00798 CaseListIsErroneous = true; 00799 continue; 00800 } 00801 Lo = ConvLo.get(); 00802 } else { 00803 // We already verified that the expression has a i-c-e value (C99 00804 // 6.8.4.2p3) - get that value now. 00805 LoVal = Lo->EvaluateKnownConstInt(Context); 00806 00807 // If the LHS is not the same type as the condition, insert an implicit 00808 // cast. 00809 Lo = DefaultLvalueConversion(Lo).get(); 00810 Lo = ImpCastExprToType(Lo, CondType, CK_IntegralCast).get(); 00811 } 00812 00813 // Check the unconverted value is within the range of possible values of 00814 // the switch expression. 00815 checkCaseValue(*this, Lo->getLocStart(), LoVal, 00816 CondWidthBeforePromotion, CondIsSignedBeforePromotion); 00817 00818 // Convert the value to the same width/sign as the condition. 00819 AdjustAPSInt(LoVal, CondWidth, CondIsSigned); 00820 00821 CS->setLHS(Lo); 00822 00823 // If this is a case range, remember it in CaseRanges, otherwise CaseVals. 00824 if (CS->getRHS()) { 00825 if (CS->getRHS()->isTypeDependent() || 00826 CS->getRHS()->isValueDependent()) { 00827 HasDependentValue = true; 00828 break; 00829 } 00830 CaseRanges.push_back(std::make_pair(LoVal, CS)); 00831 } else 00832 CaseVals.push_back(std::make_pair(LoVal, CS)); 00833 } 00834 } 00835 00836 if (!HasDependentValue) { 00837 // If we don't have a default statement, check whether the 00838 // condition is constant. 00839 llvm::APSInt ConstantCondValue; 00840 bool HasConstantCond = false; 00841 if (!HasDependentValue && !TheDefaultStmt) { 00842 HasConstantCond = CondExpr->EvaluateAsInt(ConstantCondValue, Context, 00843 Expr::SE_AllowSideEffects); 00844 assert(!HasConstantCond || 00845 (ConstantCondValue.getBitWidth() == CondWidth && 00846 ConstantCondValue.isSigned() == CondIsSigned)); 00847 } 00848 bool ShouldCheckConstantCond = HasConstantCond; 00849 00850 // Sort all the scalar case values so we can easily detect duplicates. 00851 std::stable_sort(CaseVals.begin(), CaseVals.end(), CmpCaseVals); 00852 00853 if (!CaseVals.empty()) { 00854 for (unsigned i = 0, e = CaseVals.size(); i != e; ++i) { 00855 if (ShouldCheckConstantCond && 00856 CaseVals[i].first == ConstantCondValue) 00857 ShouldCheckConstantCond = false; 00858 00859 if (i != 0 && CaseVals[i].first == CaseVals[i-1].first) { 00860 // If we have a duplicate, report it. 00861 // First, determine if either case value has a name 00862 StringRef PrevString, CurrString; 00863 Expr *PrevCase = CaseVals[i-1].second->getLHS()->IgnoreParenCasts(); 00864 Expr *CurrCase = CaseVals[i].second->getLHS()->IgnoreParenCasts(); 00865 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(PrevCase)) { 00866 PrevString = DeclRef->getDecl()->getName(); 00867 } 00868 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(CurrCase)) { 00869 CurrString = DeclRef->getDecl()->getName(); 00870 } 00871 SmallString<16> CaseValStr; 00872 CaseVals[i-1].first.toString(CaseValStr); 00873 00874 if (PrevString == CurrString) 00875 Diag(CaseVals[i].second->getLHS()->getLocStart(), 00876 diag::err_duplicate_case) << 00877 (PrevString.empty() ? CaseValStr.str() : PrevString); 00878 else 00879 Diag(CaseVals[i].second->getLHS()->getLocStart(), 00880 diag::err_duplicate_case_differing_expr) << 00881 (PrevString.empty() ? CaseValStr.str() : PrevString) << 00882 (CurrString.empty() ? CaseValStr.str() : CurrString) << 00883 CaseValStr; 00884 00885 Diag(CaseVals[i-1].second->getLHS()->getLocStart(), 00886 diag::note_duplicate_case_prev); 00887 // FIXME: We really want to remove the bogus case stmt from the 00888 // substmt, but we have no way to do this right now. 00889 CaseListIsErroneous = true; 00890 } 00891 } 00892 } 00893 00894 // Detect duplicate case ranges, which usually don't exist at all in 00895 // the first place. 00896 if (!CaseRanges.empty()) { 00897 // Sort all the case ranges by their low value so we can easily detect 00898 // overlaps between ranges. 00899 std::stable_sort(CaseRanges.begin(), CaseRanges.end()); 00900 00901 // Scan the ranges, computing the high values and removing empty ranges. 00902 std::vector<llvm::APSInt> HiVals; 00903 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 00904 llvm::APSInt &LoVal = CaseRanges[i].first; 00905 CaseStmt *CR = CaseRanges[i].second; 00906 Expr *Hi = CR->getRHS(); 00907 llvm::APSInt HiVal; 00908 00909 if (getLangOpts().CPlusPlus11) { 00910 // C++11 [stmt.switch]p2: the constant-expression shall be a converted 00911 // constant expression of the promoted type of the switch condition. 00912 ExprResult ConvHi = 00913 CheckConvertedConstantExpression(Hi, CondType, HiVal, 00914 CCEK_CaseValue); 00915 if (ConvHi.isInvalid()) { 00916 CaseListIsErroneous = true; 00917 continue; 00918 } 00919 Hi = ConvHi.get(); 00920 } else { 00921 HiVal = Hi->EvaluateKnownConstInt(Context); 00922 00923 // If the RHS is not the same type as the condition, insert an 00924 // implicit cast. 00925 Hi = DefaultLvalueConversion(Hi).get(); 00926 Hi = ImpCastExprToType(Hi, CondType, CK_IntegralCast).get(); 00927 } 00928 00929 // Check the unconverted value is within the range of possible values of 00930 // the switch expression. 00931 checkCaseValue(*this, Hi->getLocStart(), HiVal, 00932 CondWidthBeforePromotion, CondIsSignedBeforePromotion); 00933 00934 // Convert the value to the same width/sign as the condition. 00935 AdjustAPSInt(HiVal, CondWidth, CondIsSigned); 00936 00937 CR->setRHS(Hi); 00938 00939 // If the low value is bigger than the high value, the case is empty. 00940 if (LoVal > HiVal) { 00941 Diag(CR->getLHS()->getLocStart(), diag::warn_case_empty_range) 00942 << SourceRange(CR->getLHS()->getLocStart(), 00943 Hi->getLocEnd()); 00944 CaseRanges.erase(CaseRanges.begin()+i); 00945 --i, --e; 00946 continue; 00947 } 00948 00949 if (ShouldCheckConstantCond && 00950 LoVal <= ConstantCondValue && 00951 ConstantCondValue <= HiVal) 00952 ShouldCheckConstantCond = false; 00953 00954 HiVals.push_back(HiVal); 00955 } 00956 00957 // Rescan the ranges, looking for overlap with singleton values and other 00958 // ranges. Since the range list is sorted, we only need to compare case 00959 // ranges with their neighbors. 00960 for (unsigned i = 0, e = CaseRanges.size(); i != e; ++i) { 00961 llvm::APSInt &CRLo = CaseRanges[i].first; 00962 llvm::APSInt &CRHi = HiVals[i]; 00963 CaseStmt *CR = CaseRanges[i].second; 00964 00965 // Check to see whether the case range overlaps with any 00966 // singleton cases. 00967 CaseStmt *OverlapStmt = nullptr; 00968 llvm::APSInt OverlapVal(32); 00969 00970 // Find the smallest value >= the lower bound. If I is in the 00971 // case range, then we have overlap. 00972 CaseValsTy::iterator I = std::lower_bound(CaseVals.begin(), 00973 CaseVals.end(), CRLo, 00974 CaseCompareFunctor()); 00975 if (I != CaseVals.end() && I->first < CRHi) { 00976 OverlapVal = I->first; // Found overlap with scalar. 00977 OverlapStmt = I->second; 00978 } 00979 00980 // Find the smallest value bigger than the upper bound. 00981 I = std::upper_bound(I, CaseVals.end(), CRHi, CaseCompareFunctor()); 00982 if (I != CaseVals.begin() && (I-1)->first >= CRLo) { 00983 OverlapVal = (I-1)->first; // Found overlap with scalar. 00984 OverlapStmt = (I-1)->second; 00985 } 00986 00987 // Check to see if this case stmt overlaps with the subsequent 00988 // case range. 00989 if (i && CRLo <= HiVals[i-1]) { 00990 OverlapVal = HiVals[i-1]; // Found overlap with range. 00991 OverlapStmt = CaseRanges[i-1].second; 00992 } 00993 00994 if (OverlapStmt) { 00995 // If we have a duplicate, report it. 00996 Diag(CR->getLHS()->getLocStart(), diag::err_duplicate_case) 00997 << OverlapVal.toString(10); 00998 Diag(OverlapStmt->getLHS()->getLocStart(), 00999 diag::note_duplicate_case_prev); 01000 // FIXME: We really want to remove the bogus case stmt from the 01001 // substmt, but we have no way to do this right now. 01002 CaseListIsErroneous = true; 01003 } 01004 } 01005 } 01006 01007 // Complain if we have a constant condition and we didn't find a match. 01008 if (!CaseListIsErroneous && ShouldCheckConstantCond) { 01009 // TODO: it would be nice if we printed enums as enums, chars as 01010 // chars, etc. 01011 Diag(CondExpr->getExprLoc(), diag::warn_missing_case_for_condition) 01012 << ConstantCondValue.toString(10) 01013 << CondExpr->getSourceRange(); 01014 } 01015 01016 // Check to see if switch is over an Enum and handles all of its 01017 // values. We only issue a warning if there is not 'default:', but 01018 // we still do the analysis to preserve this information in the AST 01019 // (which can be used by flow-based analyes). 01020 // 01021 const EnumType *ET = CondTypeBeforePromotion->getAs<EnumType>(); 01022 01023 // If switch has default case, then ignore it. 01024 if (!CaseListIsErroneous && !HasConstantCond && ET) { 01025 const EnumDecl *ED = ET->getDecl(); 01026 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl*>, 64> 01027 EnumValsTy; 01028 EnumValsTy EnumVals; 01029 01030 // Gather all enum values, set their type and sort them, 01031 // allowing easier comparison with CaseVals. 01032 for (auto *EDI : ED->enumerators()) { 01033 llvm::APSInt Val = EDI->getInitVal(); 01034 AdjustAPSInt(Val, CondWidth, CondIsSigned); 01035 EnumVals.push_back(std::make_pair(Val, EDI)); 01036 } 01037 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals); 01038 EnumValsTy::iterator EIend = 01039 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals); 01040 01041 // See which case values aren't in enum. 01042 EnumValsTy::const_iterator EI = EnumVals.begin(); 01043 for (CaseValsTy::const_iterator CI = CaseVals.begin(); 01044 CI != CaseVals.end(); CI++) { 01045 while (EI != EIend && EI->first < CI->first) 01046 EI++; 01047 if (EI == EIend || EI->first > CI->first) { 01048 Expr *CaseExpr = CI->second->getLHS(); 01049 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr)) 01050 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum) 01051 << CondTypeBeforePromotion; 01052 } 01053 } 01054 // See which of case ranges aren't in enum 01055 EI = EnumVals.begin(); 01056 for (CaseRangesTy::const_iterator RI = CaseRanges.begin(); 01057 RI != CaseRanges.end() && EI != EIend; RI++) { 01058 while (EI != EIend && EI->first < RI->first) 01059 EI++; 01060 01061 if (EI == EIend || EI->first != RI->first) { 01062 Expr *CaseExpr = RI->second->getLHS(); 01063 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr)) 01064 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum) 01065 << CondTypeBeforePromotion; 01066 } 01067 01068 llvm::APSInt Hi = 01069 RI->second->getRHS()->EvaluateKnownConstInt(Context); 01070 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 01071 while (EI != EIend && EI->first < Hi) 01072 EI++; 01073 if (EI == EIend || EI->first != Hi) { 01074 Expr *CaseExpr = RI->second->getRHS(); 01075 if (ShouldDiagnoseSwitchCaseNotInEnum(Context, ED, CaseExpr)) 01076 Diag(CaseExpr->getExprLoc(), diag::warn_not_in_enum) 01077 << CondTypeBeforePromotion; 01078 } 01079 } 01080 01081 // Check which enum vals aren't in switch 01082 CaseValsTy::const_iterator CI = CaseVals.begin(); 01083 CaseRangesTy::const_iterator RI = CaseRanges.begin(); 01084 bool hasCasesNotInSwitch = false; 01085 01086 SmallVector<DeclarationName,8> UnhandledNames; 01087 01088 for (EI = EnumVals.begin(); EI != EIend; EI++){ 01089 // Drop unneeded case values 01090 while (CI != CaseVals.end() && CI->first < EI->first) 01091 CI++; 01092 01093 if (CI != CaseVals.end() && CI->first == EI->first) 01094 continue; 01095 01096 // Drop unneeded case ranges 01097 for (; RI != CaseRanges.end(); RI++) { 01098 llvm::APSInt Hi = 01099 RI->second->getRHS()->EvaluateKnownConstInt(Context); 01100 AdjustAPSInt(Hi, CondWidth, CondIsSigned); 01101 if (EI->first <= Hi) 01102 break; 01103 } 01104 01105 if (RI == CaseRanges.end() || EI->first < RI->first) { 01106 hasCasesNotInSwitch = true; 01107 UnhandledNames.push_back(EI->second->getDeclName()); 01108 } 01109 } 01110 01111 if (TheDefaultStmt && UnhandledNames.empty()) 01112 Diag(TheDefaultStmt->getDefaultLoc(), diag::warn_unreachable_default); 01113 01114 // Produce a nice diagnostic if multiple values aren't handled. 01115 switch (UnhandledNames.size()) { 01116 case 0: break; 01117 case 1: 01118 Diag(CondExpr->getExprLoc(), TheDefaultStmt 01119 ? diag::warn_def_missing_case1 : diag::warn_missing_case1) 01120 << UnhandledNames[0]; 01121 break; 01122 case 2: 01123 Diag(CondExpr->getExprLoc(), TheDefaultStmt 01124 ? diag::warn_def_missing_case2 : diag::warn_missing_case2) 01125 << UnhandledNames[0] << UnhandledNames[1]; 01126 break; 01127 case 3: 01128 Diag(CondExpr->getExprLoc(), TheDefaultStmt 01129 ? diag::warn_def_missing_case3 : diag::warn_missing_case3) 01130 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2]; 01131 break; 01132 default: 01133 Diag(CondExpr->getExprLoc(), TheDefaultStmt 01134 ? diag::warn_def_missing_cases : diag::warn_missing_cases) 01135 << (unsigned)UnhandledNames.size() 01136 << UnhandledNames[0] << UnhandledNames[1] << UnhandledNames[2]; 01137 break; 01138 } 01139 01140 if (!hasCasesNotInSwitch) 01141 SS->setAllEnumCasesCovered(); 01142 } 01143 } 01144 01145 if (BodyStmt) 01146 DiagnoseEmptyStmtBody(CondExpr->getLocEnd(), BodyStmt, 01147 diag::warn_empty_switch_body); 01148 01149 // FIXME: If the case list was broken is some way, we don't have a good system 01150 // to patch it up. Instead, just return the whole substmt as broken. 01151 if (CaseListIsErroneous) 01152 return StmtError(); 01153 01154 return SS; 01155 } 01156 01157 void 01158 Sema::DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, 01159 Expr *SrcExpr) { 01160 if (Diags.isIgnored(diag::warn_not_in_enum_assignment, SrcExpr->getExprLoc())) 01161 return; 01162 01163 if (const EnumType *ET = DstType->getAs<EnumType>()) 01164 if (!Context.hasSameUnqualifiedType(SrcType, DstType) && 01165 SrcType->isIntegerType()) { 01166 if (!SrcExpr->isTypeDependent() && !SrcExpr->isValueDependent() && 01167 SrcExpr->isIntegerConstantExpr(Context)) { 01168 // Get the bitwidth of the enum value before promotions. 01169 unsigned DstWidth = Context.getIntWidth(DstType); 01170 bool DstIsSigned = DstType->isSignedIntegerOrEnumerationType(); 01171 01172 llvm::APSInt RhsVal = SrcExpr->EvaluateKnownConstInt(Context); 01173 AdjustAPSInt(RhsVal, DstWidth, DstIsSigned); 01174 const EnumDecl *ED = ET->getDecl(); 01175 typedef SmallVector<std::pair<llvm::APSInt, EnumConstantDecl *>, 64> 01176 EnumValsTy; 01177 EnumValsTy EnumVals; 01178 01179 // Gather all enum values, set their type and sort them, 01180 // allowing easier comparison with rhs constant. 01181 for (auto *EDI : ED->enumerators()) { 01182 llvm::APSInt Val = EDI->getInitVal(); 01183 AdjustAPSInt(Val, DstWidth, DstIsSigned); 01184 EnumVals.push_back(std::make_pair(Val, EDI)); 01185 } 01186 if (EnumVals.empty()) 01187 return; 01188 std::stable_sort(EnumVals.begin(), EnumVals.end(), CmpEnumVals); 01189 EnumValsTy::iterator EIend = 01190 std::unique(EnumVals.begin(), EnumVals.end(), EqEnumVals); 01191 01192 // See which values aren't in the enum. 01193 EnumValsTy::const_iterator EI = EnumVals.begin(); 01194 while (EI != EIend && EI->first < RhsVal) 01195 EI++; 01196 if (EI == EIend || EI->first != RhsVal) { 01197 Diag(SrcExpr->getExprLoc(), diag::warn_not_in_enum_assignment) 01198 << DstType.getUnqualifiedType(); 01199 } 01200 } 01201 } 01202 } 01203 01204 StmtResult 01205 Sema::ActOnWhileStmt(SourceLocation WhileLoc, FullExprArg Cond, 01206 Decl *CondVar, Stmt *Body) { 01207 ExprResult CondResult(Cond.release()); 01208 01209 VarDecl *ConditionVar = nullptr; 01210 if (CondVar) { 01211 ConditionVar = cast<VarDecl>(CondVar); 01212 CondResult = CheckConditionVariable(ConditionVar, WhileLoc, true); 01213 if (CondResult.isInvalid()) 01214 return StmtError(); 01215 } 01216 Expr *ConditionExpr = CondResult.get(); 01217 if (!ConditionExpr) 01218 return StmtError(); 01219 CheckBreakContinueBinding(ConditionExpr); 01220 01221 DiagnoseUnusedExprResult(Body); 01222 01223 if (isa<NullStmt>(Body)) 01224 getCurCompoundScope().setHasEmptyLoopBodies(); 01225 01226 return new (Context) 01227 WhileStmt(Context, ConditionVar, ConditionExpr, Body, WhileLoc); 01228 } 01229 01230 StmtResult 01231 Sema::ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 01232 SourceLocation WhileLoc, SourceLocation CondLParen, 01233 Expr *Cond, SourceLocation CondRParen) { 01234 assert(Cond && "ActOnDoStmt(): missing expression"); 01235 01236 CheckBreakContinueBinding(Cond); 01237 ExprResult CondResult = CheckBooleanCondition(Cond, DoLoc); 01238 if (CondResult.isInvalid()) 01239 return StmtError(); 01240 Cond = CondResult.get(); 01241 01242 CondResult = ActOnFinishFullExpr(Cond, DoLoc); 01243 if (CondResult.isInvalid()) 01244 return StmtError(); 01245 Cond = CondResult.get(); 01246 01247 DiagnoseUnusedExprResult(Body); 01248 01249 return new (Context) DoStmt(Body, Cond, DoLoc, WhileLoc, CondRParen); 01250 } 01251 01252 namespace { 01253 // This visitor will traverse a conditional statement and store all 01254 // the evaluated decls into a vector. Simple is set to true if none 01255 // of the excluded constructs are used. 01256 class DeclExtractor : public EvaluatedExprVisitor<DeclExtractor> { 01257 llvm::SmallPtrSetImpl<VarDecl*> &Decls; 01258 SmallVectorImpl<SourceRange> &Ranges; 01259 bool Simple; 01260 public: 01261 typedef EvaluatedExprVisitor<DeclExtractor> Inherited; 01262 01263 DeclExtractor(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls, 01264 SmallVectorImpl<SourceRange> &Ranges) : 01265 Inherited(S.Context), 01266 Decls(Decls), 01267 Ranges(Ranges), 01268 Simple(true) {} 01269 01270 bool isSimple() { return Simple; } 01271 01272 // Replaces the method in EvaluatedExprVisitor. 01273 void VisitMemberExpr(MemberExpr* E) { 01274 Simple = false; 01275 } 01276 01277 // Any Stmt not whitelisted will cause the condition to be marked complex. 01278 void VisitStmt(Stmt *S) { 01279 Simple = false; 01280 } 01281 01282 void VisitBinaryOperator(BinaryOperator *E) { 01283 Visit(E->getLHS()); 01284 Visit(E->getRHS()); 01285 } 01286 01287 void VisitCastExpr(CastExpr *E) { 01288 Visit(E->getSubExpr()); 01289 } 01290 01291 void VisitUnaryOperator(UnaryOperator *E) { 01292 // Skip checking conditionals with derefernces. 01293 if (E->getOpcode() == UO_Deref) 01294 Simple = false; 01295 else 01296 Visit(E->getSubExpr()); 01297 } 01298 01299 void VisitConditionalOperator(ConditionalOperator *E) { 01300 Visit(E->getCond()); 01301 Visit(E->getTrueExpr()); 01302 Visit(E->getFalseExpr()); 01303 } 01304 01305 void VisitParenExpr(ParenExpr *E) { 01306 Visit(E->getSubExpr()); 01307 } 01308 01309 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 01310 Visit(E->getOpaqueValue()->getSourceExpr()); 01311 Visit(E->getFalseExpr()); 01312 } 01313 01314 void VisitIntegerLiteral(IntegerLiteral *E) { } 01315 void VisitFloatingLiteral(FloatingLiteral *E) { } 01316 void VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { } 01317 void VisitCharacterLiteral(CharacterLiteral *E) { } 01318 void VisitGNUNullExpr(GNUNullExpr *E) { } 01319 void VisitImaginaryLiteral(ImaginaryLiteral *E) { } 01320 01321 void VisitDeclRefExpr(DeclRefExpr *E) { 01322 VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()); 01323 if (!VD) return; 01324 01325 Ranges.push_back(E->getSourceRange()); 01326 01327 Decls.insert(VD); 01328 } 01329 01330 }; // end class DeclExtractor 01331 01332 // DeclMatcher checks to see if the decls are used in a non-evauluated 01333 // context. 01334 class DeclMatcher : public EvaluatedExprVisitor<DeclMatcher> { 01335 llvm::SmallPtrSetImpl<VarDecl*> &Decls; 01336 bool FoundDecl; 01337 01338 public: 01339 typedef EvaluatedExprVisitor<DeclMatcher> Inherited; 01340 01341 DeclMatcher(Sema &S, llvm::SmallPtrSetImpl<VarDecl*> &Decls, 01342 Stmt *Statement) : 01343 Inherited(S.Context), Decls(Decls), FoundDecl(false) { 01344 if (!Statement) return; 01345 01346 Visit(Statement); 01347 } 01348 01349 void VisitReturnStmt(ReturnStmt *S) { 01350 FoundDecl = true; 01351 } 01352 01353 void VisitBreakStmt(BreakStmt *S) { 01354 FoundDecl = true; 01355 } 01356 01357 void VisitGotoStmt(GotoStmt *S) { 01358 FoundDecl = true; 01359 } 01360 01361 void VisitCastExpr(CastExpr *E) { 01362 if (E->getCastKind() == CK_LValueToRValue) 01363 CheckLValueToRValueCast(E->getSubExpr()); 01364 else 01365 Visit(E->getSubExpr()); 01366 } 01367 01368 void CheckLValueToRValueCast(Expr *E) { 01369 E = E->IgnoreParenImpCasts(); 01370 01371 if (isa<DeclRefExpr>(E)) { 01372 return; 01373 } 01374 01375 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 01376 Visit(CO->getCond()); 01377 CheckLValueToRValueCast(CO->getTrueExpr()); 01378 CheckLValueToRValueCast(CO->getFalseExpr()); 01379 return; 01380 } 01381 01382 if (BinaryConditionalOperator *BCO = 01383 dyn_cast<BinaryConditionalOperator>(E)) { 01384 CheckLValueToRValueCast(BCO->getOpaqueValue()->getSourceExpr()); 01385 CheckLValueToRValueCast(BCO->getFalseExpr()); 01386 return; 01387 } 01388 01389 Visit(E); 01390 } 01391 01392 void VisitDeclRefExpr(DeclRefExpr *E) { 01393 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) 01394 if (Decls.count(VD)) 01395 FoundDecl = true; 01396 } 01397 01398 bool FoundDeclInUse() { return FoundDecl; } 01399 01400 }; // end class DeclMatcher 01401 01402 void CheckForLoopConditionalStatement(Sema &S, Expr *Second, 01403 Expr *Third, Stmt *Body) { 01404 // Condition is empty 01405 if (!Second) return; 01406 01407 if (S.Diags.isIgnored(diag::warn_variables_not_in_loop_body, 01408 Second->getLocStart())) 01409 return; 01410 01411 PartialDiagnostic PDiag = S.PDiag(diag::warn_variables_not_in_loop_body); 01412 llvm::SmallPtrSet<VarDecl*, 8> Decls; 01413 SmallVector<SourceRange, 10> Ranges; 01414 DeclExtractor DE(S, Decls, Ranges); 01415 DE.Visit(Second); 01416 01417 // Don't analyze complex conditionals. 01418 if (!DE.isSimple()) return; 01419 01420 // No decls found. 01421 if (Decls.size() == 0) return; 01422 01423 // Don't warn on volatile, static, or global variables. 01424 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(), 01425 E = Decls.end(); 01426 I != E; ++I) 01427 if ((*I)->getType().isVolatileQualified() || 01428 (*I)->hasGlobalStorage()) return; 01429 01430 if (DeclMatcher(S, Decls, Second).FoundDeclInUse() || 01431 DeclMatcher(S, Decls, Third).FoundDeclInUse() || 01432 DeclMatcher(S, Decls, Body).FoundDeclInUse()) 01433 return; 01434 01435 // Load decl names into diagnostic. 01436 if (Decls.size() > 4) 01437 PDiag << 0; 01438 else { 01439 PDiag << Decls.size(); 01440 for (llvm::SmallPtrSetImpl<VarDecl*>::iterator I = Decls.begin(), 01441 E = Decls.end(); 01442 I != E; ++I) 01443 PDiag << (*I)->getDeclName(); 01444 } 01445 01446 // Load SourceRanges into diagnostic if there is room. 01447 // Otherwise, load the SourceRange of the conditional expression. 01448 if (Ranges.size() <= PartialDiagnostic::MaxArguments) 01449 for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(), 01450 E = Ranges.end(); 01451 I != E; ++I) 01452 PDiag << *I; 01453 else 01454 PDiag << Second->getSourceRange(); 01455 01456 S.Diag(Ranges.begin()->getBegin(), PDiag); 01457 } 01458 01459 // If Statement is an incemement or decrement, return true and sets the 01460 // variables Increment and DRE. 01461 bool ProcessIterationStmt(Sema &S, Stmt* Statement, bool &Increment, 01462 DeclRefExpr *&DRE) { 01463 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Statement)) { 01464 switch (UO->getOpcode()) { 01465 default: return false; 01466 case UO_PostInc: 01467 case UO_PreInc: 01468 Increment = true; 01469 break; 01470 case UO_PostDec: 01471 case UO_PreDec: 01472 Increment = false; 01473 break; 01474 } 01475 DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()); 01476 return DRE; 01477 } 01478 01479 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(Statement)) { 01480 FunctionDecl *FD = Call->getDirectCallee(); 01481 if (!FD || !FD->isOverloadedOperator()) return false; 01482 switch (FD->getOverloadedOperator()) { 01483 default: return false; 01484 case OO_PlusPlus: 01485 Increment = true; 01486 break; 01487 case OO_MinusMinus: 01488 Increment = false; 01489 break; 01490 } 01491 DRE = dyn_cast<DeclRefExpr>(Call->getArg(0)); 01492 return DRE; 01493 } 01494 01495 return false; 01496 } 01497 01498 // A visitor to determine if a continue or break statement is a 01499 // subexpression. 01500 class BreakContinueFinder : public EvaluatedExprVisitor<BreakContinueFinder> { 01501 SourceLocation BreakLoc; 01502 SourceLocation ContinueLoc; 01503 public: 01504 BreakContinueFinder(Sema &S, Stmt* Body) : 01505 Inherited(S.Context) { 01506 Visit(Body); 01507 } 01508 01509 typedef EvaluatedExprVisitor<BreakContinueFinder> Inherited; 01510 01511 void VisitContinueStmt(ContinueStmt* E) { 01512 ContinueLoc = E->getContinueLoc(); 01513 } 01514 01515 void VisitBreakStmt(BreakStmt* E) { 01516 BreakLoc = E->getBreakLoc(); 01517 } 01518 01519 bool ContinueFound() { return ContinueLoc.isValid(); } 01520 bool BreakFound() { return BreakLoc.isValid(); } 01521 SourceLocation GetContinueLoc() { return ContinueLoc; } 01522 SourceLocation GetBreakLoc() { return BreakLoc; } 01523 01524 }; // end class BreakContinueFinder 01525 01526 // Emit a warning when a loop increment/decrement appears twice per loop 01527 // iteration. The conditions which trigger this warning are: 01528 // 1) The last statement in the loop body and the third expression in the 01529 // for loop are both increment or both decrement of the same variable 01530 // 2) No continue statements in the loop body. 01531 void CheckForRedundantIteration(Sema &S, Expr *Third, Stmt *Body) { 01532 // Return when there is nothing to check. 01533 if (!Body || !Third) return; 01534 01535 if (S.Diags.isIgnored(diag::warn_redundant_loop_iteration, 01536 Third->getLocStart())) 01537 return; 01538 01539 // Get the last statement from the loop body. 01540 CompoundStmt *CS = dyn_cast<CompoundStmt>(Body); 01541 if (!CS || CS->body_empty()) return; 01542 Stmt *LastStmt = CS->body_back(); 01543 if (!LastStmt) return; 01544 01545 bool LoopIncrement, LastIncrement; 01546 DeclRefExpr *LoopDRE, *LastDRE; 01547 01548 if (!ProcessIterationStmt(S, Third, LoopIncrement, LoopDRE)) return; 01549 if (!ProcessIterationStmt(S, LastStmt, LastIncrement, LastDRE)) return; 01550 01551 // Check that the two statements are both increments or both decrements 01552 // on the same variable. 01553 if (LoopIncrement != LastIncrement || 01554 LoopDRE->getDecl() != LastDRE->getDecl()) return; 01555 01556 if (BreakContinueFinder(S, Body).ContinueFound()) return; 01557 01558 S.Diag(LastDRE->getLocation(), diag::warn_redundant_loop_iteration) 01559 << LastDRE->getDecl() << LastIncrement; 01560 S.Diag(LoopDRE->getLocation(), diag::note_loop_iteration_here) 01561 << LoopIncrement; 01562 } 01563 01564 } // end namespace 01565 01566 01567 void Sema::CheckBreakContinueBinding(Expr *E) { 01568 if (!E || getLangOpts().CPlusPlus) 01569 return; 01570 BreakContinueFinder BCFinder(*this, E); 01571 Scope *BreakParent = CurScope->getBreakParent(); 01572 if (BCFinder.BreakFound() && BreakParent) { 01573 if (BreakParent->getFlags() & Scope::SwitchScope) { 01574 Diag(BCFinder.GetBreakLoc(), diag::warn_break_binds_to_switch); 01575 } else { 01576 Diag(BCFinder.GetBreakLoc(), diag::warn_loop_ctrl_binds_to_inner) 01577 << "break"; 01578 } 01579 } else if (BCFinder.ContinueFound() && CurScope->getContinueParent()) { 01580 Diag(BCFinder.GetContinueLoc(), diag::warn_loop_ctrl_binds_to_inner) 01581 << "continue"; 01582 } 01583 } 01584 01585 StmtResult 01586 Sema::ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, 01587 Stmt *First, FullExprArg second, Decl *secondVar, 01588 FullExprArg third, 01589 SourceLocation RParenLoc, Stmt *Body) { 01590 if (!getLangOpts().CPlusPlus) { 01591 if (DeclStmt *DS = dyn_cast_or_null<DeclStmt>(First)) { 01592 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 01593 // declare identifiers for objects having storage class 'auto' or 01594 // 'register'. 01595 for (auto *DI : DS->decls()) { 01596 VarDecl *VD = dyn_cast<VarDecl>(DI); 01597 if (VD && VD->isLocalVarDecl() && !VD->hasLocalStorage()) 01598 VD = nullptr; 01599 if (!VD) { 01600 Diag(DI->getLocation(), diag::err_non_local_variable_decl_in_for); 01601 DI->setInvalidDecl(); 01602 } 01603 } 01604 } 01605 } 01606 01607 CheckBreakContinueBinding(second.get()); 01608 CheckBreakContinueBinding(third.get()); 01609 01610 CheckForLoopConditionalStatement(*this, second.get(), third.get(), Body); 01611 CheckForRedundantIteration(*this, third.get(), Body); 01612 01613 ExprResult SecondResult(second.release()); 01614 VarDecl *ConditionVar = nullptr; 01615 if (secondVar) { 01616 ConditionVar = cast<VarDecl>(secondVar); 01617 SecondResult = CheckConditionVariable(ConditionVar, ForLoc, true); 01618 if (SecondResult.isInvalid()) 01619 return StmtError(); 01620 } 01621 01622 Expr *Third = third.release().getAs<Expr>(); 01623 01624 DiagnoseUnusedExprResult(First); 01625 DiagnoseUnusedExprResult(Third); 01626 DiagnoseUnusedExprResult(Body); 01627 01628 if (isa<NullStmt>(Body)) 01629 getCurCompoundScope().setHasEmptyLoopBodies(); 01630 01631 return new (Context) ForStmt(Context, First, SecondResult.get(), ConditionVar, 01632 Third, Body, ForLoc, LParenLoc, RParenLoc); 01633 } 01634 01635 /// In an Objective C collection iteration statement: 01636 /// for (x in y) 01637 /// x can be an arbitrary l-value expression. Bind it up as a 01638 /// full-expression. 01639 StmtResult Sema::ActOnForEachLValueExpr(Expr *E) { 01640 // Reduce placeholder expressions here. Note that this rejects the 01641 // use of pseudo-object l-values in this position. 01642 ExprResult result = CheckPlaceholderExpr(E); 01643 if (result.isInvalid()) return StmtError(); 01644 E = result.get(); 01645 01646 ExprResult FullExpr = ActOnFinishFullExpr(E); 01647 if (FullExpr.isInvalid()) 01648 return StmtError(); 01649 return StmtResult(static_cast<Stmt*>(FullExpr.get())); 01650 } 01651 01652 ExprResult 01653 Sema::CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection) { 01654 if (!collection) 01655 return ExprError(); 01656 01657 // Bail out early if we've got a type-dependent expression. 01658 if (collection->isTypeDependent()) return collection; 01659 01660 // Perform normal l-value conversion. 01661 ExprResult result = DefaultFunctionArrayLvalueConversion(collection); 01662 if (result.isInvalid()) 01663 return ExprError(); 01664 collection = result.get(); 01665 01666 // The operand needs to have object-pointer type. 01667 // TODO: should we do a contextual conversion? 01668 const ObjCObjectPointerType *pointerType = 01669 collection->getType()->getAs<ObjCObjectPointerType>(); 01670 if (!pointerType) 01671 return Diag(forLoc, diag::err_collection_expr_type) 01672 << collection->getType() << collection->getSourceRange(); 01673 01674 // Check that the operand provides 01675 // - countByEnumeratingWithState:objects:count: 01676 const ObjCObjectType *objectType = pointerType->getObjectType(); 01677 ObjCInterfaceDecl *iface = objectType->getInterface(); 01678 01679 // If we have a forward-declared type, we can't do this check. 01680 // Under ARC, it is an error not to have a forward-declared class. 01681 if (iface && 01682 RequireCompleteType(forLoc, QualType(objectType, 0), 01683 getLangOpts().ObjCAutoRefCount 01684 ? diag::err_arc_collection_forward 01685 : 0, 01686 collection)) { 01687 // Otherwise, if we have any useful type information, check that 01688 // the type declares the appropriate method. 01689 } else if (iface || !objectType->qual_empty()) { 01690 IdentifierInfo *selectorIdents[] = { 01691 &Context.Idents.get("countByEnumeratingWithState"), 01692 &Context.Idents.get("objects"), 01693 &Context.Idents.get("count") 01694 }; 01695 Selector selector = Context.Selectors.getSelector(3, &selectorIdents[0]); 01696 01697 ObjCMethodDecl *method = nullptr; 01698 01699 // If there's an interface, look in both the public and private APIs. 01700 if (iface) { 01701 method = iface->lookupInstanceMethod(selector); 01702 if (!method) method = iface->lookupPrivateMethod(selector); 01703 } 01704 01705 // Also check protocol qualifiers. 01706 if (!method) 01707 method = LookupMethodInQualifiedType(selector, pointerType, 01708 /*instance*/ true); 01709 01710 // If we didn't find it anywhere, give up. 01711 if (!method) { 01712 Diag(forLoc, diag::warn_collection_expr_type) 01713 << collection->getType() << selector << collection->getSourceRange(); 01714 } 01715 01716 // TODO: check for an incompatible signature? 01717 } 01718 01719 // Wrap up any cleanups in the expression. 01720 return collection; 01721 } 01722 01723 StmtResult 01724 Sema::ActOnObjCForCollectionStmt(SourceLocation ForLoc, 01725 Stmt *First, Expr *collection, 01726 SourceLocation RParenLoc) { 01727 01728 ExprResult CollectionExprResult = 01729 CheckObjCForCollectionOperand(ForLoc, collection); 01730 01731 if (First) { 01732 QualType FirstType; 01733 if (DeclStmt *DS = dyn_cast<DeclStmt>(First)) { 01734 if (!DS->isSingleDecl()) 01735 return StmtError(Diag((*DS->decl_begin())->getLocation(), 01736 diag::err_toomany_element_decls)); 01737 01738 VarDecl *D = dyn_cast<VarDecl>(DS->getSingleDecl()); 01739 if (!D || D->isInvalidDecl()) 01740 return StmtError(); 01741 01742 FirstType = D->getType(); 01743 // C99 6.8.5p3: The declaration part of a 'for' statement shall only 01744 // declare identifiers for objects having storage class 'auto' or 01745 // 'register'. 01746 if (!D->hasLocalStorage()) 01747 return StmtError(Diag(D->getLocation(), 01748 diag::err_non_local_variable_decl_in_for)); 01749 01750 // If the type contained 'auto', deduce the 'auto' to 'id'. 01751 if (FirstType->getContainedAutoType()) { 01752 OpaqueValueExpr OpaqueId(D->getLocation(), Context.getObjCIdType(), 01753 VK_RValue); 01754 Expr *DeducedInit = &OpaqueId; 01755 if (DeduceAutoType(D->getTypeSourceInfo(), DeducedInit, FirstType) == 01756 DAR_Failed) 01757 DiagnoseAutoDeductionFailure(D, DeducedInit); 01758 if (FirstType.isNull()) { 01759 D->setInvalidDecl(); 01760 return StmtError(); 01761 } 01762 01763 D->setType(FirstType); 01764 01765 if (ActiveTemplateInstantiations.empty()) { 01766 SourceLocation Loc = 01767 D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 01768 Diag(Loc, diag::warn_auto_var_is_id) 01769 << D->getDeclName(); 01770 } 01771 } 01772 01773 } else { 01774 Expr *FirstE = cast<Expr>(First); 01775 if (!FirstE->isTypeDependent() && !FirstE->isLValue()) 01776 return StmtError(Diag(First->getLocStart(), 01777 diag::err_selector_element_not_lvalue) 01778 << First->getSourceRange()); 01779 01780 FirstType = static_cast<Expr*>(First)->getType(); 01781 if (FirstType.isConstQualified()) 01782 Diag(ForLoc, diag::err_selector_element_const_type) 01783 << FirstType << First->getSourceRange(); 01784 } 01785 if (!FirstType->isDependentType() && 01786 !FirstType->isObjCObjectPointerType() && 01787 !FirstType->isBlockPointerType()) 01788 return StmtError(Diag(ForLoc, diag::err_selector_element_type) 01789 << FirstType << First->getSourceRange()); 01790 } 01791 01792 if (CollectionExprResult.isInvalid()) 01793 return StmtError(); 01794 01795 CollectionExprResult = ActOnFinishFullExpr(CollectionExprResult.get()); 01796 if (CollectionExprResult.isInvalid()) 01797 return StmtError(); 01798 01799 return new (Context) ObjCForCollectionStmt(First, CollectionExprResult.get(), 01800 nullptr, ForLoc, RParenLoc); 01801 } 01802 01803 /// Finish building a variable declaration for a for-range statement. 01804 /// \return true if an error occurs. 01805 static bool FinishForRangeVarDecl(Sema &SemaRef, VarDecl *Decl, Expr *Init, 01806 SourceLocation Loc, int DiagID) { 01807 // Deduce the type for the iterator variable now rather than leaving it to 01808 // AddInitializerToDecl, so we can produce a more suitable diagnostic. 01809 QualType InitType; 01810 if ((!isa<InitListExpr>(Init) && Init->getType()->isVoidType()) || 01811 SemaRef.DeduceAutoType(Decl->getTypeSourceInfo(), Init, InitType) == 01812 Sema::DAR_Failed) 01813 SemaRef.Diag(Loc, DiagID) << Init->getType(); 01814 if (InitType.isNull()) { 01815 Decl->setInvalidDecl(); 01816 return true; 01817 } 01818 Decl->setType(InitType); 01819 01820 // In ARC, infer lifetime. 01821 // FIXME: ARC may want to turn this into 'const __unsafe_unretained' if 01822 // we're doing the equivalent of fast iteration. 01823 if (SemaRef.getLangOpts().ObjCAutoRefCount && 01824 SemaRef.inferObjCARCLifetime(Decl)) 01825 Decl->setInvalidDecl(); 01826 01827 SemaRef.AddInitializerToDecl(Decl, Init, /*DirectInit=*/false, 01828 /*TypeMayContainAuto=*/false); 01829 SemaRef.FinalizeDeclaration(Decl); 01830 SemaRef.CurContext->addHiddenDecl(Decl); 01831 return false; 01832 } 01833 01834 namespace { 01835 01836 /// Produce a note indicating which begin/end function was implicitly called 01837 /// by a C++11 for-range statement. This is often not obvious from the code, 01838 /// nor from the diagnostics produced when analysing the implicit expressions 01839 /// required in a for-range statement. 01840 void NoteForRangeBeginEndFunction(Sema &SemaRef, Expr *E, 01841 Sema::BeginEndFunction BEF) { 01842 CallExpr *CE = dyn_cast<CallExpr>(E); 01843 if (!CE) 01844 return; 01845 FunctionDecl *D = dyn_cast<FunctionDecl>(CE->getCalleeDecl()); 01846 if (!D) 01847 return; 01848 SourceLocation Loc = D->getLocation(); 01849 01850 std::string Description; 01851 bool IsTemplate = false; 01852 if (FunctionTemplateDecl *FunTmpl = D->getPrimaryTemplate()) { 01853 Description = SemaRef.getTemplateArgumentBindingsText( 01854 FunTmpl->getTemplateParameters(), *D->getTemplateSpecializationArgs()); 01855 IsTemplate = true; 01856 } 01857 01858 SemaRef.Diag(Loc, diag::note_for_range_begin_end) 01859 << BEF << IsTemplate << Description << E->getType(); 01860 } 01861 01862 /// Build a variable declaration for a for-range statement. 01863 VarDecl *BuildForRangeVarDecl(Sema &SemaRef, SourceLocation Loc, 01864 QualType Type, const char *Name) { 01865 DeclContext *DC = SemaRef.CurContext; 01866 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 01867 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 01868 VarDecl *Decl = VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, 01869 TInfo, SC_None); 01870 Decl->setImplicit(); 01871 return Decl; 01872 } 01873 01874 } 01875 01876 static bool ObjCEnumerationCollection(Expr *Collection) { 01877 return !Collection->isTypeDependent() 01878 && Collection->getType()->getAs<ObjCObjectPointerType>() != nullptr; 01879 } 01880 01881 /// ActOnCXXForRangeStmt - Check and build a C++11 for-range statement. 01882 /// 01883 /// C++11 [stmt.ranged]: 01884 /// A range-based for statement is equivalent to 01885 /// 01886 /// { 01887 /// auto && __range = range-init; 01888 /// for ( auto __begin = begin-expr, 01889 /// __end = end-expr; 01890 /// __begin != __end; 01891 /// ++__begin ) { 01892 /// for-range-declaration = *__begin; 01893 /// statement 01894 /// } 01895 /// } 01896 /// 01897 /// The body of the loop is not available yet, since it cannot be analysed until 01898 /// we have determined the type of the for-range-declaration. 01899 StmtResult 01900 Sema::ActOnCXXForRangeStmt(SourceLocation ForLoc, 01901 Stmt *First, SourceLocation ColonLoc, Expr *Range, 01902 SourceLocation RParenLoc, BuildForRangeKind Kind) { 01903 if (!First) 01904 return StmtError(); 01905 01906 if (Range && ObjCEnumerationCollection(Range)) 01907 return ActOnObjCForCollectionStmt(ForLoc, First, Range, RParenLoc); 01908 01909 DeclStmt *DS = dyn_cast<DeclStmt>(First); 01910 assert(DS && "first part of for range not a decl stmt"); 01911 01912 if (!DS->isSingleDecl()) { 01913 Diag(DS->getStartLoc(), diag::err_type_defined_in_for_range); 01914 return StmtError(); 01915 } 01916 01917 Decl *LoopVar = DS->getSingleDecl(); 01918 if (LoopVar->isInvalidDecl() || !Range || 01919 DiagnoseUnexpandedParameterPack(Range, UPPC_Expression)) { 01920 LoopVar->setInvalidDecl(); 01921 return StmtError(); 01922 } 01923 01924 // Build auto && __range = range-init 01925 SourceLocation RangeLoc = Range->getLocStart(); 01926 VarDecl *RangeVar = BuildForRangeVarDecl(*this, RangeLoc, 01927 Context.getAutoRRefDeductType(), 01928 "__range"); 01929 if (FinishForRangeVarDecl(*this, RangeVar, Range, RangeLoc, 01930 diag::err_for_range_deduction_failure)) { 01931 LoopVar->setInvalidDecl(); 01932 return StmtError(); 01933 } 01934 01935 // Claim the type doesn't contain auto: we've already done the checking. 01936 DeclGroupPtrTy RangeGroup = 01937 BuildDeclaratorGroup(MutableArrayRef<Decl *>((Decl **)&RangeVar, 1), 01938 /*TypeMayContainAuto=*/ false); 01939 StmtResult RangeDecl = ActOnDeclStmt(RangeGroup, RangeLoc, RangeLoc); 01940 if (RangeDecl.isInvalid()) { 01941 LoopVar->setInvalidDecl(); 01942 return StmtError(); 01943 } 01944 01945 return BuildCXXForRangeStmt(ForLoc, ColonLoc, RangeDecl.get(), 01946 /*BeginEndDecl=*/nullptr, /*Cond=*/nullptr, 01947 /*Inc=*/nullptr, DS, RParenLoc, Kind); 01948 } 01949 01950 /// \brief Create the initialization, compare, and increment steps for 01951 /// the range-based for loop expression. 01952 /// This function does not handle array-based for loops, 01953 /// which are created in Sema::BuildCXXForRangeStmt. 01954 /// 01955 /// \returns a ForRangeStatus indicating success or what kind of error occurred. 01956 /// BeginExpr and EndExpr are set and FRS_Success is returned on success; 01957 /// CandidateSet and BEF are set and some non-success value is returned on 01958 /// failure. 01959 static Sema::ForRangeStatus BuildNonArrayForRange(Sema &SemaRef, Scope *S, 01960 Expr *BeginRange, Expr *EndRange, 01961 QualType RangeType, 01962 VarDecl *BeginVar, 01963 VarDecl *EndVar, 01964 SourceLocation ColonLoc, 01965 OverloadCandidateSet *CandidateSet, 01966 ExprResult *BeginExpr, 01967 ExprResult *EndExpr, 01968 Sema::BeginEndFunction *BEF) { 01969 DeclarationNameInfo BeginNameInfo( 01970 &SemaRef.PP.getIdentifierTable().get("begin"), ColonLoc); 01971 DeclarationNameInfo EndNameInfo(&SemaRef.PP.getIdentifierTable().get("end"), 01972 ColonLoc); 01973 01974 LookupResult BeginMemberLookup(SemaRef, BeginNameInfo, 01975 Sema::LookupMemberName); 01976 LookupResult EndMemberLookup(SemaRef, EndNameInfo, Sema::LookupMemberName); 01977 01978 if (CXXRecordDecl *D = RangeType->getAsCXXRecordDecl()) { 01979 // - if _RangeT is a class type, the unqualified-ids begin and end are 01980 // looked up in the scope of class _RangeT as if by class member access 01981 // lookup (3.4.5), and if either (or both) finds at least one 01982 // declaration, begin-expr and end-expr are __range.begin() and 01983 // __range.end(), respectively; 01984 SemaRef.LookupQualifiedName(BeginMemberLookup, D); 01985 SemaRef.LookupQualifiedName(EndMemberLookup, D); 01986 01987 if (BeginMemberLookup.empty() != EndMemberLookup.empty()) { 01988 SourceLocation RangeLoc = BeginVar->getLocation(); 01989 *BEF = BeginMemberLookup.empty() ? Sema::BEF_end : Sema::BEF_begin; 01990 01991 SemaRef.Diag(RangeLoc, diag::err_for_range_member_begin_end_mismatch) 01992 << RangeLoc << BeginRange->getType() << *BEF; 01993 return Sema::FRS_DiagnosticIssued; 01994 } 01995 } else { 01996 // - otherwise, begin-expr and end-expr are begin(__range) and 01997 // end(__range), respectively, where begin and end are looked up with 01998 // argument-dependent lookup (3.4.2). For the purposes of this name 01999 // lookup, namespace std is an associated namespace. 02000 02001 } 02002 02003 *BEF = Sema::BEF_begin; 02004 Sema::ForRangeStatus RangeStatus = 02005 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, BeginVar, 02006 Sema::BEF_begin, BeginNameInfo, 02007 BeginMemberLookup, CandidateSet, 02008 BeginRange, BeginExpr); 02009 02010 if (RangeStatus != Sema::FRS_Success) 02011 return RangeStatus; 02012 if (FinishForRangeVarDecl(SemaRef, BeginVar, BeginExpr->get(), ColonLoc, 02013 diag::err_for_range_iter_deduction_failure)) { 02014 NoteForRangeBeginEndFunction(SemaRef, BeginExpr->get(), *BEF); 02015 return Sema::FRS_DiagnosticIssued; 02016 } 02017 02018 *BEF = Sema::BEF_end; 02019 RangeStatus = 02020 SemaRef.BuildForRangeBeginEndCall(S, ColonLoc, ColonLoc, EndVar, 02021 Sema::BEF_end, EndNameInfo, 02022 EndMemberLookup, CandidateSet, 02023 EndRange, EndExpr); 02024 if (RangeStatus != Sema::FRS_Success) 02025 return RangeStatus; 02026 if (FinishForRangeVarDecl(SemaRef, EndVar, EndExpr->get(), ColonLoc, 02027 diag::err_for_range_iter_deduction_failure)) { 02028 NoteForRangeBeginEndFunction(SemaRef, EndExpr->get(), *BEF); 02029 return Sema::FRS_DiagnosticIssued; 02030 } 02031 return Sema::FRS_Success; 02032 } 02033 02034 /// Speculatively attempt to dereference an invalid range expression. 02035 /// If the attempt fails, this function will return a valid, null StmtResult 02036 /// and emit no diagnostics. 02037 static StmtResult RebuildForRangeWithDereference(Sema &SemaRef, Scope *S, 02038 SourceLocation ForLoc, 02039 Stmt *LoopVarDecl, 02040 SourceLocation ColonLoc, 02041 Expr *Range, 02042 SourceLocation RangeLoc, 02043 SourceLocation RParenLoc) { 02044 // Determine whether we can rebuild the for-range statement with a 02045 // dereferenced range expression. 02046 ExprResult AdjustedRange; 02047 { 02048 Sema::SFINAETrap Trap(SemaRef); 02049 02050 AdjustedRange = SemaRef.BuildUnaryOp(S, RangeLoc, UO_Deref, Range); 02051 if (AdjustedRange.isInvalid()) 02052 return StmtResult(); 02053 02054 StmtResult SR = 02055 SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc, 02056 AdjustedRange.get(), RParenLoc, 02057 Sema::BFRK_Check); 02058 if (SR.isInvalid()) 02059 return StmtResult(); 02060 } 02061 02062 // The attempt to dereference worked well enough that it could produce a valid 02063 // loop. Produce a fixit, and rebuild the loop with diagnostics enabled, in 02064 // case there are any other (non-fatal) problems with it. 02065 SemaRef.Diag(RangeLoc, diag::err_for_range_dereference) 02066 << Range->getType() << FixItHint::CreateInsertion(RangeLoc, "*"); 02067 return SemaRef.ActOnCXXForRangeStmt(ForLoc, LoopVarDecl, ColonLoc, 02068 AdjustedRange.get(), RParenLoc, 02069 Sema::BFRK_Rebuild); 02070 } 02071 02072 namespace { 02073 /// RAII object to automatically invalidate a declaration if an error occurs. 02074 struct InvalidateOnErrorScope { 02075 InvalidateOnErrorScope(Sema &SemaRef, Decl *D, bool Enabled) 02076 : Trap(SemaRef.Diags), D(D), Enabled(Enabled) {} 02077 ~InvalidateOnErrorScope() { 02078 if (Enabled && Trap.hasErrorOccurred()) 02079 D->setInvalidDecl(); 02080 } 02081 02082 DiagnosticErrorTrap Trap; 02083 Decl *D; 02084 bool Enabled; 02085 }; 02086 } 02087 02088 /// BuildCXXForRangeStmt - Build or instantiate a C++11 for-range statement. 02089 StmtResult 02090 Sema::BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation ColonLoc, 02091 Stmt *RangeDecl, Stmt *BeginEnd, Expr *Cond, 02092 Expr *Inc, Stmt *LoopVarDecl, 02093 SourceLocation RParenLoc, BuildForRangeKind Kind) { 02094 Scope *S = getCurScope(); 02095 02096 DeclStmt *RangeDS = cast<DeclStmt>(RangeDecl); 02097 VarDecl *RangeVar = cast<VarDecl>(RangeDS->getSingleDecl()); 02098 QualType RangeVarType = RangeVar->getType(); 02099 02100 DeclStmt *LoopVarDS = cast<DeclStmt>(LoopVarDecl); 02101 VarDecl *LoopVar = cast<VarDecl>(LoopVarDS->getSingleDecl()); 02102 02103 // If we hit any errors, mark the loop variable as invalid if its type 02104 // contains 'auto'. 02105 InvalidateOnErrorScope Invalidate(*this, LoopVar, 02106 LoopVar->getType()->isUndeducedType()); 02107 02108 StmtResult BeginEndDecl = BeginEnd; 02109 ExprResult NotEqExpr = Cond, IncrExpr = Inc; 02110 02111 if (RangeVarType->isDependentType()) { 02112 // The range is implicitly used as a placeholder when it is dependent. 02113 RangeVar->markUsed(Context); 02114 02115 // Deduce any 'auto's in the loop variable as 'DependentTy'. We'll fill 02116 // them in properly when we instantiate the loop. 02117 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) 02118 LoopVar->setType(SubstAutoType(LoopVar->getType(), Context.DependentTy)); 02119 } else if (!BeginEndDecl.get()) { 02120 SourceLocation RangeLoc = RangeVar->getLocation(); 02121 02122 const QualType RangeVarNonRefType = RangeVarType.getNonReferenceType(); 02123 02124 ExprResult BeginRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType, 02125 VK_LValue, ColonLoc); 02126 if (BeginRangeRef.isInvalid()) 02127 return StmtError(); 02128 02129 ExprResult EndRangeRef = BuildDeclRefExpr(RangeVar, RangeVarNonRefType, 02130 VK_LValue, ColonLoc); 02131 if (EndRangeRef.isInvalid()) 02132 return StmtError(); 02133 02134 QualType AutoType = Context.getAutoDeductType(); 02135 Expr *Range = RangeVar->getInit(); 02136 if (!Range) 02137 return StmtError(); 02138 QualType RangeType = Range->getType(); 02139 02140 if (RequireCompleteType(RangeLoc, RangeType, 02141 diag::err_for_range_incomplete_type)) 02142 return StmtError(); 02143 02144 // Build auto __begin = begin-expr, __end = end-expr. 02145 VarDecl *BeginVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, 02146 "__begin"); 02147 VarDecl *EndVar = BuildForRangeVarDecl(*this, ColonLoc, AutoType, 02148 "__end"); 02149 02150 // Build begin-expr and end-expr and attach to __begin and __end variables. 02151 ExprResult BeginExpr, EndExpr; 02152 if (const ArrayType *UnqAT = RangeType->getAsArrayTypeUnsafe()) { 02153 // - if _RangeT is an array type, begin-expr and end-expr are __range and 02154 // __range + __bound, respectively, where __bound is the array bound. If 02155 // _RangeT is an array of unknown size or an array of incomplete type, 02156 // the program is ill-formed; 02157 02158 // begin-expr is __range. 02159 BeginExpr = BeginRangeRef; 02160 if (FinishForRangeVarDecl(*this, BeginVar, BeginRangeRef.get(), ColonLoc, 02161 diag::err_for_range_iter_deduction_failure)) { 02162 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 02163 return StmtError(); 02164 } 02165 02166 // Find the array bound. 02167 ExprResult BoundExpr; 02168 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(UnqAT)) 02169 BoundExpr = IntegerLiteral::Create( 02170 Context, CAT->getSize(), Context.getPointerDiffType(), RangeLoc); 02171 else if (const VariableArrayType *VAT = 02172 dyn_cast<VariableArrayType>(UnqAT)) 02173 BoundExpr = VAT->getSizeExpr(); 02174 else { 02175 // Can't be a DependentSizedArrayType or an IncompleteArrayType since 02176 // UnqAT is not incomplete and Range is not type-dependent. 02177 llvm_unreachable("Unexpected array type in for-range"); 02178 } 02179 02180 // end-expr is __range + __bound. 02181 EndExpr = ActOnBinOp(S, ColonLoc, tok::plus, EndRangeRef.get(), 02182 BoundExpr.get()); 02183 if (EndExpr.isInvalid()) 02184 return StmtError(); 02185 if (FinishForRangeVarDecl(*this, EndVar, EndExpr.get(), ColonLoc, 02186 diag::err_for_range_iter_deduction_failure)) { 02187 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 02188 return StmtError(); 02189 } 02190 } else { 02191 OverloadCandidateSet CandidateSet(RangeLoc, 02192 OverloadCandidateSet::CSK_Normal); 02193 Sema::BeginEndFunction BEFFailure; 02194 ForRangeStatus RangeStatus = 02195 BuildNonArrayForRange(*this, S, BeginRangeRef.get(), 02196 EndRangeRef.get(), RangeType, 02197 BeginVar, EndVar, ColonLoc, &CandidateSet, 02198 &BeginExpr, &EndExpr, &BEFFailure); 02199 02200 if (Kind == BFRK_Build && RangeStatus == FRS_NoViableFunction && 02201 BEFFailure == BEF_begin) { 02202 // If the range is being built from an array parameter, emit a 02203 // a diagnostic that it is being treated as a pointer. 02204 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Range)) { 02205 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 02206 QualType ArrayTy = PVD->getOriginalType(); 02207 QualType PointerTy = PVD->getType(); 02208 if (PointerTy->isPointerType() && ArrayTy->isArrayType()) { 02209 Diag(Range->getLocStart(), diag::err_range_on_array_parameter) 02210 << RangeLoc << PVD << ArrayTy << PointerTy; 02211 Diag(PVD->getLocation(), diag::note_declared_at); 02212 return StmtError(); 02213 } 02214 } 02215 } 02216 02217 // If building the range failed, try dereferencing the range expression 02218 // unless a diagnostic was issued or the end function is problematic. 02219 StmtResult SR = RebuildForRangeWithDereference(*this, S, ForLoc, 02220 LoopVarDecl, ColonLoc, 02221 Range, RangeLoc, 02222 RParenLoc); 02223 if (SR.isInvalid() || SR.isUsable()) 02224 return SR; 02225 } 02226 02227 // Otherwise, emit diagnostics if we haven't already. 02228 if (RangeStatus == FRS_NoViableFunction) { 02229 Expr *Range = BEFFailure ? EndRangeRef.get() : BeginRangeRef.get(); 02230 Diag(Range->getLocStart(), diag::err_for_range_invalid) 02231 << RangeLoc << Range->getType() << BEFFailure; 02232 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Range); 02233 } 02234 // Return an error if no fix was discovered. 02235 if (RangeStatus != FRS_Success) 02236 return StmtError(); 02237 } 02238 02239 assert(!BeginExpr.isInvalid() && !EndExpr.isInvalid() && 02240 "invalid range expression in for loop"); 02241 02242 // C++11 [dcl.spec.auto]p7: BeginType and EndType must be the same. 02243 QualType BeginType = BeginVar->getType(), EndType = EndVar->getType(); 02244 if (!Context.hasSameType(BeginType, EndType)) { 02245 Diag(RangeLoc, diag::err_for_range_begin_end_types_differ) 02246 << BeginType << EndType; 02247 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 02248 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 02249 } 02250 02251 Decl *BeginEndDecls[] = { BeginVar, EndVar }; 02252 // Claim the type doesn't contain auto: we've already done the checking. 02253 DeclGroupPtrTy BeginEndGroup = 02254 BuildDeclaratorGroup(MutableArrayRef<Decl *>(BeginEndDecls, 2), 02255 /*TypeMayContainAuto=*/ false); 02256 BeginEndDecl = ActOnDeclStmt(BeginEndGroup, ColonLoc, ColonLoc); 02257 02258 const QualType BeginRefNonRefType = BeginType.getNonReferenceType(); 02259 ExprResult BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 02260 VK_LValue, ColonLoc); 02261 if (BeginRef.isInvalid()) 02262 return StmtError(); 02263 02264 ExprResult EndRef = BuildDeclRefExpr(EndVar, EndType.getNonReferenceType(), 02265 VK_LValue, ColonLoc); 02266 if (EndRef.isInvalid()) 02267 return StmtError(); 02268 02269 // Build and check __begin != __end expression. 02270 NotEqExpr = ActOnBinOp(S, ColonLoc, tok::exclaimequal, 02271 BeginRef.get(), EndRef.get()); 02272 NotEqExpr = ActOnBooleanCondition(S, ColonLoc, NotEqExpr.get()); 02273 NotEqExpr = ActOnFinishFullExpr(NotEqExpr.get()); 02274 if (NotEqExpr.isInvalid()) { 02275 Diag(RangeLoc, diag::note_for_range_invalid_iterator) 02276 << RangeLoc << 0 << BeginRangeRef.get()->getType(); 02277 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 02278 if (!Context.hasSameType(BeginType, EndType)) 02279 NoteForRangeBeginEndFunction(*this, EndExpr.get(), BEF_end); 02280 return StmtError(); 02281 } 02282 02283 // Build and check ++__begin expression. 02284 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 02285 VK_LValue, ColonLoc); 02286 if (BeginRef.isInvalid()) 02287 return StmtError(); 02288 02289 IncrExpr = ActOnUnaryOp(S, ColonLoc, tok::plusplus, BeginRef.get()); 02290 IncrExpr = ActOnFinishFullExpr(IncrExpr.get()); 02291 if (IncrExpr.isInvalid()) { 02292 Diag(RangeLoc, diag::note_for_range_invalid_iterator) 02293 << RangeLoc << 2 << BeginRangeRef.get()->getType() ; 02294 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 02295 return StmtError(); 02296 } 02297 02298 // Build and check *__begin expression. 02299 BeginRef = BuildDeclRefExpr(BeginVar, BeginRefNonRefType, 02300 VK_LValue, ColonLoc); 02301 if (BeginRef.isInvalid()) 02302 return StmtError(); 02303 02304 ExprResult DerefExpr = ActOnUnaryOp(S, ColonLoc, tok::star, BeginRef.get()); 02305 if (DerefExpr.isInvalid()) { 02306 Diag(RangeLoc, diag::note_for_range_invalid_iterator) 02307 << RangeLoc << 1 << BeginRangeRef.get()->getType(); 02308 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 02309 return StmtError(); 02310 } 02311 02312 // Attach *__begin as initializer for VD. Don't touch it if we're just 02313 // trying to determine whether this would be a valid range. 02314 if (!LoopVar->isInvalidDecl() && Kind != BFRK_Check) { 02315 AddInitializerToDecl(LoopVar, DerefExpr.get(), /*DirectInit=*/false, 02316 /*TypeMayContainAuto=*/true); 02317 if (LoopVar->isInvalidDecl()) 02318 NoteForRangeBeginEndFunction(*this, BeginExpr.get(), BEF_begin); 02319 } 02320 } 02321 02322 // Don't bother to actually allocate the result if we're just trying to 02323 // determine whether it would be valid. 02324 if (Kind == BFRK_Check) 02325 return StmtResult(); 02326 02327 return new (Context) CXXForRangeStmt( 02328 RangeDS, cast_or_null<DeclStmt>(BeginEndDecl.get()), NotEqExpr.get(), 02329 IncrExpr.get(), LoopVarDS, /*Body=*/nullptr, ForLoc, ColonLoc, RParenLoc); 02330 } 02331 02332 /// FinishObjCForCollectionStmt - Attach the body to a objective-C foreach 02333 /// statement. 02334 StmtResult Sema::FinishObjCForCollectionStmt(Stmt *S, Stmt *B) { 02335 if (!S || !B) 02336 return StmtError(); 02337 ObjCForCollectionStmt * ForStmt = cast<ObjCForCollectionStmt>(S); 02338 02339 ForStmt->setBody(B); 02340 return S; 02341 } 02342 02343 /// FinishCXXForRangeStmt - Attach the body to a C++0x for-range statement. 02344 /// This is a separate step from ActOnCXXForRangeStmt because analysis of the 02345 /// body cannot be performed until after the type of the range variable is 02346 /// determined. 02347 StmtResult Sema::FinishCXXForRangeStmt(Stmt *S, Stmt *B) { 02348 if (!S || !B) 02349 return StmtError(); 02350 02351 if (isa<ObjCForCollectionStmt>(S)) 02352 return FinishObjCForCollectionStmt(S, B); 02353 02354 CXXForRangeStmt *ForStmt = cast<CXXForRangeStmt>(S); 02355 ForStmt->setBody(B); 02356 02357 DiagnoseEmptyStmtBody(ForStmt->getRParenLoc(), B, 02358 diag::warn_empty_range_based_for_body); 02359 02360 return S; 02361 } 02362 02363 StmtResult Sema::ActOnGotoStmt(SourceLocation GotoLoc, 02364 SourceLocation LabelLoc, 02365 LabelDecl *TheDecl) { 02366 getCurFunction()->setHasBranchIntoScope(); 02367 TheDecl->markUsed(Context); 02368 return new (Context) GotoStmt(TheDecl, GotoLoc, LabelLoc); 02369 } 02370 02371 StmtResult 02372 Sema::ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, 02373 Expr *E) { 02374 // Convert operand to void* 02375 if (!E->isTypeDependent()) { 02376 QualType ETy = E->getType(); 02377 QualType DestTy = Context.getPointerType(Context.VoidTy.withConst()); 02378 ExprResult ExprRes = E; 02379 AssignConvertType ConvTy = 02380 CheckSingleAssignmentConstraints(DestTy, ExprRes); 02381 if (ExprRes.isInvalid()) 02382 return StmtError(); 02383 E = ExprRes.get(); 02384 if (DiagnoseAssignmentResult(ConvTy, StarLoc, DestTy, ETy, E, AA_Passing)) 02385 return StmtError(); 02386 } 02387 02388 ExprResult ExprRes = ActOnFinishFullExpr(E); 02389 if (ExprRes.isInvalid()) 02390 return StmtError(); 02391 E = ExprRes.get(); 02392 02393 getCurFunction()->setHasIndirectGoto(); 02394 02395 return new (Context) IndirectGotoStmt(GotoLoc, StarLoc, E); 02396 } 02397 02398 StmtResult 02399 Sema::ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope) { 02400 Scope *S = CurScope->getContinueParent(); 02401 if (!S) { 02402 // C99 6.8.6.2p1: A break shall appear only in or as a loop body. 02403 return StmtError(Diag(ContinueLoc, diag::err_continue_not_in_loop)); 02404 } 02405 02406 return new (Context) ContinueStmt(ContinueLoc); 02407 } 02408 02409 StmtResult 02410 Sema::ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope) { 02411 Scope *S = CurScope->getBreakParent(); 02412 if (!S) { 02413 // C99 6.8.6.3p1: A break shall appear only in or as a switch/loop body. 02414 return StmtError(Diag(BreakLoc, diag::err_break_not_in_loop_or_switch)); 02415 } 02416 if (S->isOpenMPLoopScope()) 02417 return StmtError(Diag(BreakLoc, diag::err_omp_loop_cannot_use_stmt) 02418 << "break"); 02419 02420 return new (Context) BreakStmt(BreakLoc); 02421 } 02422 02423 /// \brief Determine whether the given expression is a candidate for 02424 /// copy elision in either a return statement or a throw expression. 02425 /// 02426 /// \param ReturnType If we're determining the copy elision candidate for 02427 /// a return statement, this is the return type of the function. If we're 02428 /// determining the copy elision candidate for a throw expression, this will 02429 /// be a NULL type. 02430 /// 02431 /// \param E The expression being returned from the function or block, or 02432 /// being thrown. 02433 /// 02434 /// \param AllowFunctionParameter Whether we allow function parameters to 02435 /// be considered NRVO candidates. C++ prohibits this for NRVO itself, but 02436 /// we re-use this logic to determine whether we should try to move as part of 02437 /// a return or throw (which does allow function parameters). 02438 /// 02439 /// \returns The NRVO candidate variable, if the return statement may use the 02440 /// NRVO, or NULL if there is no such candidate. 02441 VarDecl *Sema::getCopyElisionCandidate(QualType ReturnType, 02442 Expr *E, 02443 bool AllowFunctionParameter) { 02444 if (!getLangOpts().CPlusPlus) 02445 return nullptr; 02446 02447 // - in a return statement in a function [where] ... 02448 // ... the expression is the name of a non-volatile automatic object ... 02449 DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E->IgnoreParens()); 02450 if (!DR || DR->refersToEnclosingLocal()) 02451 return nullptr; 02452 VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()); 02453 if (!VD) 02454 return nullptr; 02455 02456 if (isCopyElisionCandidate(ReturnType, VD, AllowFunctionParameter)) 02457 return VD; 02458 return nullptr; 02459 } 02460 02461 bool Sema::isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, 02462 bool AllowFunctionParameter) { 02463 QualType VDType = VD->getType(); 02464 // - in a return statement in a function with ... 02465 // ... a class return type ... 02466 if (!ReturnType.isNull() && !ReturnType->isDependentType()) { 02467 if (!ReturnType->isRecordType()) 02468 return false; 02469 // ... the same cv-unqualified type as the function return type ... 02470 if (!VDType->isDependentType() && 02471 !Context.hasSameUnqualifiedType(ReturnType, VDType)) 02472 return false; 02473 } 02474 02475 // ...object (other than a function or catch-clause parameter)... 02476 if (VD->getKind() != Decl::Var && 02477 !(AllowFunctionParameter && VD->getKind() == Decl::ParmVar)) 02478 return false; 02479 if (VD->isExceptionVariable()) return false; 02480 02481 // ...automatic... 02482 if (!VD->hasLocalStorage()) return false; 02483 02484 // ...non-volatile... 02485 if (VD->getType().isVolatileQualified()) return false; 02486 02487 // __block variables can't be allocated in a way that permits NRVO. 02488 if (VD->hasAttr<BlocksAttr>()) return false; 02489 02490 // Variables with higher required alignment than their type's ABI 02491 // alignment cannot use NRVO. 02492 if (!VD->getType()->isDependentType() && VD->hasAttr<AlignedAttr>() && 02493 Context.getDeclAlign(VD) > Context.getTypeAlignInChars(VD->getType())) 02494 return false; 02495 02496 return true; 02497 } 02498 02499 /// \brief Perform the initialization of a potentially-movable value, which 02500 /// is the result of return value. 02501 /// 02502 /// This routine implements C++0x [class.copy]p33, which attempts to treat 02503 /// returned lvalues as rvalues in certain cases (to prefer move construction), 02504 /// then falls back to treating them as lvalues if that failed. 02505 ExprResult 02506 Sema::PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 02507 const VarDecl *NRVOCandidate, 02508 QualType ResultType, 02509 Expr *Value, 02510 bool AllowNRVO) { 02511 // C++0x [class.copy]p33: 02512 // When the criteria for elision of a copy operation are met or would 02513 // be met save for the fact that the source object is a function 02514 // parameter, and the object to be copied is designated by an lvalue, 02515 // overload resolution to select the constructor for the copy is first 02516 // performed as if the object were designated by an rvalue. 02517 ExprResult Res = ExprError(); 02518 if (AllowNRVO && 02519 (NRVOCandidate || getCopyElisionCandidate(ResultType, Value, true))) { 02520 ImplicitCastExpr AsRvalue(ImplicitCastExpr::OnStack, 02521 Value->getType(), CK_NoOp, Value, VK_XValue); 02522 02523 Expr *InitExpr = &AsRvalue; 02524 InitializationKind Kind 02525 = InitializationKind::CreateCopy(Value->getLocStart(), 02526 Value->getLocStart()); 02527 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 02528 02529 // [...] If overload resolution fails, or if the type of the first 02530 // parameter of the selected constructor is not an rvalue reference 02531 // to the object's type (possibly cv-qualified), overload resolution 02532 // is performed again, considering the object as an lvalue. 02533 if (Seq) { 02534 for (InitializationSequence::step_iterator Step = Seq.step_begin(), 02535 StepEnd = Seq.step_end(); 02536 Step != StepEnd; ++Step) { 02537 if (Step->Kind != InitializationSequence::SK_ConstructorInitialization) 02538 continue; 02539 02540 CXXConstructorDecl *Constructor 02541 = cast<CXXConstructorDecl>(Step->Function.Function); 02542 02543 const RValueReferenceType *RRefType 02544 = Constructor->getParamDecl(0)->getType() 02545 ->getAs<RValueReferenceType>(); 02546 02547 // If we don't meet the criteria, break out now. 02548 if (!RRefType || 02549 !Context.hasSameUnqualifiedType(RRefType->getPointeeType(), 02550 Context.getTypeDeclType(Constructor->getParent()))) 02551 break; 02552 02553 // Promote "AsRvalue" to the heap, since we now need this 02554 // expression node to persist. 02555 Value = ImplicitCastExpr::Create(Context, Value->getType(), 02556 CK_NoOp, Value, nullptr, VK_XValue); 02557 02558 // Complete type-checking the initialization of the return type 02559 // using the constructor we found. 02560 Res = Seq.Perform(*this, Entity, Kind, Value); 02561 } 02562 } 02563 } 02564 02565 // Either we didn't meet the criteria for treating an lvalue as an rvalue, 02566 // above, or overload resolution failed. Either way, we need to try 02567 // (again) now with the return value expression as written. 02568 if (Res.isInvalid()) 02569 Res = PerformCopyInitialization(Entity, SourceLocation(), Value); 02570 02571 return Res; 02572 } 02573 02574 /// \brief Determine whether the declared return type of the specified function 02575 /// contains 'auto'. 02576 static bool hasDeducedReturnType(FunctionDecl *FD) { 02577 const FunctionProtoType *FPT = 02578 FD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>(); 02579 return FPT->getReturnType()->isUndeducedType(); 02580 } 02581 02582 /// ActOnCapScopeReturnStmt - Utility routine to type-check return statements 02583 /// for capturing scopes. 02584 /// 02585 StmtResult 02586 Sema::ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 02587 // If this is the first return we've seen, infer the return type. 02588 // [expr.prim.lambda]p4 in C++11; block literals follow the same rules. 02589 CapturingScopeInfo *CurCap = cast<CapturingScopeInfo>(getCurFunction()); 02590 QualType FnRetType = CurCap->ReturnType; 02591 LambdaScopeInfo *CurLambda = dyn_cast<LambdaScopeInfo>(CurCap); 02592 02593 if (CurLambda && hasDeducedReturnType(CurLambda->CallOperator)) { 02594 // In C++1y, the return type may involve 'auto'. 02595 // FIXME: Blocks might have a return type of 'auto' explicitly specified. 02596 FunctionDecl *FD = CurLambda->CallOperator; 02597 if (CurCap->ReturnType.isNull()) 02598 CurCap->ReturnType = FD->getReturnType(); 02599 02600 AutoType *AT = CurCap->ReturnType->getContainedAutoType(); 02601 assert(AT && "lost auto type from lambda return type"); 02602 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) { 02603 FD->setInvalidDecl(); 02604 return StmtError(); 02605 } 02606 CurCap->ReturnType = FnRetType = FD->getReturnType(); 02607 } else if (CurCap->HasImplicitReturnType) { 02608 // For blocks/lambdas with implicit return types, we check each return 02609 // statement individually, and deduce the common return type when the block 02610 // or lambda is completed. 02611 // FIXME: Fold this into the 'auto' codepath above. 02612 if (RetValExp && !isa<InitListExpr>(RetValExp)) { 02613 ExprResult Result = DefaultFunctionArrayLvalueConversion(RetValExp); 02614 if (Result.isInvalid()) 02615 return StmtError(); 02616 RetValExp = Result.get(); 02617 02618 if (!CurContext->isDependentContext()) 02619 FnRetType = RetValExp->getType(); 02620 else 02621 FnRetType = CurCap->ReturnType = Context.DependentTy; 02622 } else { 02623 if (RetValExp) { 02624 // C++11 [expr.lambda.prim]p4 bans inferring the result from an 02625 // initializer list, because it is not an expression (even 02626 // though we represent it as one). We still deduce 'void'. 02627 Diag(ReturnLoc, diag::err_lambda_return_init_list) 02628 << RetValExp->getSourceRange(); 02629 } 02630 02631 FnRetType = Context.VoidTy; 02632 } 02633 02634 // Although we'll properly infer the type of the block once it's completed, 02635 // make sure we provide a return type now for better error recovery. 02636 if (CurCap->ReturnType.isNull()) 02637 CurCap->ReturnType = FnRetType; 02638 } 02639 assert(!FnRetType.isNull()); 02640 02641 if (BlockScopeInfo *CurBlock = dyn_cast<BlockScopeInfo>(CurCap)) { 02642 if (CurBlock->FunctionType->getAs<FunctionType>()->getNoReturnAttr()) { 02643 Diag(ReturnLoc, diag::err_noreturn_block_has_return_expr); 02644 return StmtError(); 02645 } 02646 } else if (CapturedRegionScopeInfo *CurRegion = 02647 dyn_cast<CapturedRegionScopeInfo>(CurCap)) { 02648 Diag(ReturnLoc, diag::err_return_in_captured_stmt) << CurRegion->getRegionName(); 02649 return StmtError(); 02650 } else { 02651 assert(CurLambda && "unknown kind of captured scope"); 02652 if (CurLambda->CallOperator->getType()->getAs<FunctionType>() 02653 ->getNoReturnAttr()) { 02654 Diag(ReturnLoc, diag::err_noreturn_lambda_has_return_expr); 02655 return StmtError(); 02656 } 02657 } 02658 02659 // Otherwise, verify that this result type matches the previous one. We are 02660 // pickier with blocks than for normal functions because we don't have GCC 02661 // compatibility to worry about here. 02662 const VarDecl *NRVOCandidate = nullptr; 02663 if (FnRetType->isDependentType()) { 02664 // Delay processing for now. TODO: there are lots of dependent 02665 // types we can conclusively prove aren't void. 02666 } else if (FnRetType->isVoidType()) { 02667 if (RetValExp && !isa<InitListExpr>(RetValExp) && 02668 !(getLangOpts().CPlusPlus && 02669 (RetValExp->isTypeDependent() || 02670 RetValExp->getType()->isVoidType()))) { 02671 if (!getLangOpts().CPlusPlus && 02672 RetValExp->getType()->isVoidType()) 02673 Diag(ReturnLoc, diag::ext_return_has_void_expr) << "literal" << 2; 02674 else { 02675 Diag(ReturnLoc, diag::err_return_block_has_expr); 02676 RetValExp = nullptr; 02677 } 02678 } 02679 } else if (!RetValExp) { 02680 return StmtError(Diag(ReturnLoc, diag::err_block_return_missing_expr)); 02681 } else if (!RetValExp->isTypeDependent()) { 02682 // we have a non-void block with an expression, continue checking 02683 02684 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 02685 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 02686 // function return. 02687 02688 // In C++ the return statement is handled via a copy initialization. 02689 // the C version of which boils down to CheckSingleAssignmentConstraints. 02690 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false); 02691 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, 02692 FnRetType, 02693 NRVOCandidate != nullptr); 02694 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, 02695 FnRetType, RetValExp); 02696 if (Res.isInvalid()) { 02697 // FIXME: Cleanup temporaries here, anyway? 02698 return StmtError(); 02699 } 02700 RetValExp = Res.get(); 02701 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc); 02702 } else { 02703 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false); 02704 } 02705 02706 if (RetValExp) { 02707 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc); 02708 if (ER.isInvalid()) 02709 return StmtError(); 02710 RetValExp = ER.get(); 02711 } 02712 ReturnStmt *Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, 02713 NRVOCandidate); 02714 02715 // If we need to check for the named return value optimization, 02716 // or if we need to infer the return type, 02717 // save the return statement in our scope for later processing. 02718 if (CurCap->HasImplicitReturnType || NRVOCandidate) 02719 FunctionScopes.back()->Returns.push_back(Result); 02720 02721 return Result; 02722 } 02723 02724 namespace { 02725 /// \brief Marks all typedefs in all local classes in a type referenced. 02726 /// 02727 /// In a function like 02728 /// auto f() { 02729 /// struct S { typedef int a; }; 02730 /// return S(); 02731 /// } 02732 /// 02733 /// the local type escapes and could be referenced in some TUs but not in 02734 /// others. Pretend that all local typedefs are always referenced, to not warn 02735 /// on this. This isn't necessary if f has internal linkage, or the typedef 02736 /// is private. 02737 class LocalTypedefNameReferencer 02738 : public RecursiveASTVisitor<LocalTypedefNameReferencer> { 02739 public: 02740 LocalTypedefNameReferencer(Sema &S) : S(S) {} 02741 bool VisitRecordType(const RecordType *RT); 02742 private: 02743 Sema &S; 02744 }; 02745 bool LocalTypedefNameReferencer::VisitRecordType(const RecordType *RT) { 02746 auto *R = dyn_cast<CXXRecordDecl>(RT->getDecl()); 02747 if (!R || !R->isLocalClass() || !R->isLocalClass()->isExternallyVisible() || 02748 R->isDependentType()) 02749 return true; 02750 for (auto *TmpD : R->decls()) 02751 if (auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 02752 if (T->getAccess() != AS_private || R->hasFriends()) 02753 S.MarkAnyDeclReferenced(T->getLocation(), T, /*OdrUse=*/false); 02754 return true; 02755 } 02756 } 02757 02758 TypeLoc Sema::getReturnTypeLoc(FunctionDecl *FD) const { 02759 TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc().IgnoreParens(); 02760 while (auto ATL = TL.getAs<AttributedTypeLoc>()) 02761 TL = ATL.getModifiedLoc().IgnoreParens(); 02762 return TL.castAs<FunctionProtoTypeLoc>().getReturnLoc(); 02763 } 02764 02765 /// Deduce the return type for a function from a returned expression, per 02766 /// C++1y [dcl.spec.auto]p6. 02767 bool Sema::DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, 02768 SourceLocation ReturnLoc, 02769 Expr *&RetExpr, 02770 AutoType *AT) { 02771 TypeLoc OrigResultType = getReturnTypeLoc(FD); 02772 QualType Deduced; 02773 02774 if (RetExpr && isa<InitListExpr>(RetExpr)) { 02775 // If the deduction is for a return statement and the initializer is 02776 // a braced-init-list, the program is ill-formed. 02777 Diag(RetExpr->getExprLoc(), 02778 getCurLambda() ? diag::err_lambda_return_init_list 02779 : diag::err_auto_fn_return_init_list) 02780 << RetExpr->getSourceRange(); 02781 return true; 02782 } 02783 02784 if (FD->isDependentContext()) { 02785 // C++1y [dcl.spec.auto]p12: 02786 // Return type deduction [...] occurs when the definition is 02787 // instantiated even if the function body contains a return 02788 // statement with a non-type-dependent operand. 02789 assert(AT->isDeduced() && "should have deduced to dependent type"); 02790 return false; 02791 } else if (RetExpr) { 02792 // If the deduction is for a return statement and the initializer is 02793 // a braced-init-list, the program is ill-formed. 02794 if (isa<InitListExpr>(RetExpr)) { 02795 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_return_init_list); 02796 return true; 02797 } 02798 02799 // Otherwise, [...] deduce a value for U using the rules of template 02800 // argument deduction. 02801 DeduceAutoResult DAR = DeduceAutoType(OrigResultType, RetExpr, Deduced); 02802 02803 if (DAR == DAR_Failed && !FD->isInvalidDecl()) 02804 Diag(RetExpr->getExprLoc(), diag::err_auto_fn_deduction_failure) 02805 << OrigResultType.getType() << RetExpr->getType(); 02806 02807 if (DAR != DAR_Succeeded) 02808 return true; 02809 02810 // If a local type is part of the returned type, mark its fields as 02811 // referenced. 02812 LocalTypedefNameReferencer Referencer(*this); 02813 Referencer.TraverseType(RetExpr->getType()); 02814 } else { 02815 // In the case of a return with no operand, the initializer is considered 02816 // to be void(). 02817 // 02818 // Deduction here can only succeed if the return type is exactly 'cv auto' 02819 // or 'decltype(auto)', so just check for that case directly. 02820 if (!OrigResultType.getType()->getAs<AutoType>()) { 02821 Diag(ReturnLoc, diag::err_auto_fn_return_void_but_not_auto) 02822 << OrigResultType.getType(); 02823 return true; 02824 } 02825 // We always deduce U = void in this case. 02826 Deduced = SubstAutoType(OrigResultType.getType(), Context.VoidTy); 02827 if (Deduced.isNull()) 02828 return true; 02829 } 02830 02831 // If a function with a declared return type that contains a placeholder type 02832 // has multiple return statements, the return type is deduced for each return 02833 // statement. [...] if the type deduced is not the same in each deduction, 02834 // the program is ill-formed. 02835 if (AT->isDeduced() && !FD->isInvalidDecl()) { 02836 AutoType *NewAT = Deduced->getContainedAutoType(); 02837 if (!FD->isDependentContext() && 02838 !Context.hasSameType(AT->getDeducedType(), NewAT->getDeducedType())) { 02839 const LambdaScopeInfo *LambdaSI = getCurLambda(); 02840 if (LambdaSI && LambdaSI->HasImplicitReturnType) { 02841 Diag(ReturnLoc, diag::err_typecheck_missing_return_type_incompatible) 02842 << NewAT->getDeducedType() << AT->getDeducedType() 02843 << true /*IsLambda*/; 02844 } else { 02845 Diag(ReturnLoc, diag::err_auto_fn_different_deductions) 02846 << (AT->isDecltypeAuto() ? 1 : 0) 02847 << NewAT->getDeducedType() << AT->getDeducedType(); 02848 } 02849 return true; 02850 } 02851 } else if (!FD->isInvalidDecl()) { 02852 // Update all declarations of the function to have the deduced return type. 02853 Context.adjustDeducedFunctionResultType(FD, Deduced); 02854 } 02855 02856 return false; 02857 } 02858 02859 StmtResult 02860 Sema::ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, 02861 Scope *CurScope) { 02862 StmtResult R = BuildReturnStmt(ReturnLoc, RetValExp); 02863 if (R.isInvalid()) { 02864 return R; 02865 } 02866 02867 if (VarDecl *VD = 02868 const_cast<VarDecl*>(cast<ReturnStmt>(R.get())->getNRVOCandidate())) { 02869 CurScope->addNRVOCandidate(VD); 02870 } else { 02871 CurScope->setNoNRVO(); 02872 } 02873 02874 return R; 02875 } 02876 02877 StmtResult Sema::BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp) { 02878 // Check for unexpanded parameter packs. 02879 if (RetValExp && DiagnoseUnexpandedParameterPack(RetValExp)) 02880 return StmtError(); 02881 02882 if (isa<CapturingScopeInfo>(getCurFunction())) 02883 return ActOnCapScopeReturnStmt(ReturnLoc, RetValExp); 02884 02885 QualType FnRetType; 02886 QualType RelatedRetType; 02887 const AttrVec *Attrs = nullptr; 02888 bool isObjCMethod = false; 02889 02890 if (const FunctionDecl *FD = getCurFunctionDecl()) { 02891 FnRetType = FD->getReturnType(); 02892 if (FD->hasAttrs()) 02893 Attrs = &FD->getAttrs(); 02894 if (FD->isNoReturn()) 02895 Diag(ReturnLoc, diag::warn_noreturn_function_has_return_expr) 02896 << FD->getDeclName(); 02897 } else if (ObjCMethodDecl *MD = getCurMethodDecl()) { 02898 FnRetType = MD->getReturnType(); 02899 isObjCMethod = true; 02900 if (MD->hasAttrs()) 02901 Attrs = &MD->getAttrs(); 02902 if (MD->hasRelatedResultType() && MD->getClassInterface()) { 02903 // In the implementation of a method with a related return type, the 02904 // type used to type-check the validity of return statements within the 02905 // method body is a pointer to the type of the class being implemented. 02906 RelatedRetType = Context.getObjCInterfaceType(MD->getClassInterface()); 02907 RelatedRetType = Context.getObjCObjectPointerType(RelatedRetType); 02908 } 02909 } else // If we don't have a function/method context, bail. 02910 return StmtError(); 02911 02912 // FIXME: Add a flag to the ScopeInfo to indicate whether we're performing 02913 // deduction. 02914 if (getLangOpts().CPlusPlus14) { 02915 if (AutoType *AT = FnRetType->getContainedAutoType()) { 02916 FunctionDecl *FD = cast<FunctionDecl>(CurContext); 02917 if (DeduceFunctionTypeFromReturnExpr(FD, ReturnLoc, RetValExp, AT)) { 02918 FD->setInvalidDecl(); 02919 return StmtError(); 02920 } else { 02921 FnRetType = FD->getReturnType(); 02922 } 02923 } 02924 } 02925 02926 bool HasDependentReturnType = FnRetType->isDependentType(); 02927 02928 ReturnStmt *Result = nullptr; 02929 if (FnRetType->isVoidType()) { 02930 if (RetValExp) { 02931 if (isa<InitListExpr>(RetValExp)) { 02932 // We simply never allow init lists as the return value of void 02933 // functions. This is compatible because this was never allowed before, 02934 // so there's no legacy code to deal with. 02935 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 02936 int FunctionKind = 0; 02937 if (isa<ObjCMethodDecl>(CurDecl)) 02938 FunctionKind = 1; 02939 else if (isa<CXXConstructorDecl>(CurDecl)) 02940 FunctionKind = 2; 02941 else if (isa<CXXDestructorDecl>(CurDecl)) 02942 FunctionKind = 3; 02943 02944 Diag(ReturnLoc, diag::err_return_init_list) 02945 << CurDecl->getDeclName() << FunctionKind 02946 << RetValExp->getSourceRange(); 02947 02948 // Drop the expression. 02949 RetValExp = nullptr; 02950 } else if (!RetValExp->isTypeDependent()) { 02951 // C99 6.8.6.4p1 (ext_ since GCC warns) 02952 unsigned D = diag::ext_return_has_expr; 02953 if (RetValExp->getType()->isVoidType()) { 02954 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 02955 if (isa<CXXConstructorDecl>(CurDecl) || 02956 isa<CXXDestructorDecl>(CurDecl)) 02957 D = diag::err_ctor_dtor_returns_void; 02958 else 02959 D = diag::ext_return_has_void_expr; 02960 } 02961 else { 02962 ExprResult Result = RetValExp; 02963 Result = IgnoredValueConversions(Result.get()); 02964 if (Result.isInvalid()) 02965 return StmtError(); 02966 RetValExp = Result.get(); 02967 RetValExp = ImpCastExprToType(RetValExp, 02968 Context.VoidTy, CK_ToVoid).get(); 02969 } 02970 // return of void in constructor/destructor is illegal in C++. 02971 if (D == diag::err_ctor_dtor_returns_void) { 02972 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 02973 Diag(ReturnLoc, D) 02974 << CurDecl->getDeclName() << isa<CXXDestructorDecl>(CurDecl) 02975 << RetValExp->getSourceRange(); 02976 } 02977 // return (some void expression); is legal in C++. 02978 else if (D != diag::ext_return_has_void_expr || 02979 !getLangOpts().CPlusPlus) { 02980 NamedDecl *CurDecl = getCurFunctionOrMethodDecl(); 02981 02982 int FunctionKind = 0; 02983 if (isa<ObjCMethodDecl>(CurDecl)) 02984 FunctionKind = 1; 02985 else if (isa<CXXConstructorDecl>(CurDecl)) 02986 FunctionKind = 2; 02987 else if (isa<CXXDestructorDecl>(CurDecl)) 02988 FunctionKind = 3; 02989 02990 Diag(ReturnLoc, D) 02991 << CurDecl->getDeclName() << FunctionKind 02992 << RetValExp->getSourceRange(); 02993 } 02994 } 02995 02996 if (RetValExp) { 02997 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc); 02998 if (ER.isInvalid()) 02999 return StmtError(); 03000 RetValExp = ER.get(); 03001 } 03002 } 03003 03004 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, nullptr); 03005 } else if (!RetValExp && !HasDependentReturnType) { 03006 unsigned DiagID = diag::warn_return_missing_expr; // C90 6.6.6.4p4 03007 // C99 6.8.6.4p1 (ext_ since GCC warns) 03008 if (getLangOpts().C99) DiagID = diag::ext_return_missing_expr; 03009 03010 if (FunctionDecl *FD = getCurFunctionDecl()) 03011 Diag(ReturnLoc, DiagID) << FD->getIdentifier() << 0/*fn*/; 03012 else 03013 Diag(ReturnLoc, DiagID) << getCurMethodDecl()->getDeclName() << 1/*meth*/; 03014 Result = new (Context) ReturnStmt(ReturnLoc); 03015 } else { 03016 assert(RetValExp || HasDependentReturnType); 03017 const VarDecl *NRVOCandidate = nullptr; 03018 03019 QualType RetType = RelatedRetType.isNull() ? FnRetType : RelatedRetType; 03020 03021 // C99 6.8.6.4p3(136): The return statement is not an assignment. The 03022 // overlap restriction of subclause 6.5.16.1 does not apply to the case of 03023 // function return. 03024 03025 // In C++ the return statement is handled via a copy initialization, 03026 // the C version of which boils down to CheckSingleAssignmentConstraints. 03027 if (RetValExp) 03028 NRVOCandidate = getCopyElisionCandidate(FnRetType, RetValExp, false); 03029 if (!HasDependentReturnType && !RetValExp->isTypeDependent()) { 03030 // we have a non-void function with an expression, continue checking 03031 InitializedEntity Entity = InitializedEntity::InitializeResult(ReturnLoc, 03032 RetType, 03033 NRVOCandidate != nullptr); 03034 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRVOCandidate, 03035 RetType, RetValExp); 03036 if (Res.isInvalid()) { 03037 // FIXME: Clean up temporaries here anyway? 03038 return StmtError(); 03039 } 03040 RetValExp = Res.getAs<Expr>(); 03041 03042 // If we have a related result type, we need to implicitly 03043 // convert back to the formal result type. We can't pretend to 03044 // initialize the result again --- we might end double-retaining 03045 // --- so instead we initialize a notional temporary. 03046 if (!RelatedRetType.isNull()) { 03047 Entity = InitializedEntity::InitializeRelatedResult(getCurMethodDecl(), 03048 FnRetType); 03049 Res = PerformCopyInitialization(Entity, ReturnLoc, RetValExp); 03050 if (Res.isInvalid()) { 03051 // FIXME: Clean up temporaries here anyway? 03052 return StmtError(); 03053 } 03054 RetValExp = Res.getAs<Expr>(); 03055 } 03056 03057 CheckReturnValExpr(RetValExp, FnRetType, ReturnLoc, isObjCMethod, Attrs, 03058 getCurFunctionDecl()); 03059 } 03060 03061 if (RetValExp) { 03062 ExprResult ER = ActOnFinishFullExpr(RetValExp, ReturnLoc); 03063 if (ER.isInvalid()) 03064 return StmtError(); 03065 RetValExp = ER.get(); 03066 } 03067 Result = new (Context) ReturnStmt(ReturnLoc, RetValExp, NRVOCandidate); 03068 } 03069 03070 // If we need to check for the named return value optimization, save the 03071 // return statement in our scope for later processing. 03072 if (Result->getNRVOCandidate()) 03073 FunctionScopes.back()->Returns.push_back(Result); 03074 03075 return Result; 03076 } 03077 03078 StmtResult 03079 Sema::ActOnObjCAtCatchStmt(SourceLocation AtLoc, 03080 SourceLocation RParen, Decl *Parm, 03081 Stmt *Body) { 03082 VarDecl *Var = cast_or_null<VarDecl>(Parm); 03083 if (Var && Var->isInvalidDecl()) 03084 return StmtError(); 03085 03086 return new (Context) ObjCAtCatchStmt(AtLoc, RParen, Var, Body); 03087 } 03088 03089 StmtResult 03090 Sema::ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body) { 03091 return new (Context) ObjCAtFinallyStmt(AtLoc, Body); 03092 } 03093 03094 StmtResult 03095 Sema::ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 03096 MultiStmtArg CatchStmts, Stmt *Finally) { 03097 if (!getLangOpts().ObjCExceptions) 03098 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@try"; 03099 03100 getCurFunction()->setHasBranchProtectedScope(); 03101 unsigned NumCatchStmts = CatchStmts.size(); 03102 return ObjCAtTryStmt::Create(Context, AtLoc, Try, CatchStmts.data(), 03103 NumCatchStmts, Finally); 03104 } 03105 03106 StmtResult Sema::BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw) { 03107 if (Throw) { 03108 ExprResult Result = DefaultLvalueConversion(Throw); 03109 if (Result.isInvalid()) 03110 return StmtError(); 03111 03112 Result = ActOnFinishFullExpr(Result.get()); 03113 if (Result.isInvalid()) 03114 return StmtError(); 03115 Throw = Result.get(); 03116 03117 QualType ThrowType = Throw->getType(); 03118 // Make sure the expression type is an ObjC pointer or "void *". 03119 if (!ThrowType->isDependentType() && 03120 !ThrowType->isObjCObjectPointerType()) { 03121 const PointerType *PT = ThrowType->getAs<PointerType>(); 03122 if (!PT || !PT->getPointeeType()->isVoidType()) 03123 return StmtError(Diag(AtLoc, diag::error_objc_throw_expects_object) 03124 << Throw->getType() << Throw->getSourceRange()); 03125 } 03126 } 03127 03128 return new (Context) ObjCAtThrowStmt(AtLoc, Throw); 03129 } 03130 03131 StmtResult 03132 Sema::ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 03133 Scope *CurScope) { 03134 if (!getLangOpts().ObjCExceptions) 03135 Diag(AtLoc, diag::err_objc_exceptions_disabled) << "@throw"; 03136 03137 if (!Throw) { 03138 // @throw without an expression designates a rethrow (which much occur 03139 // in the context of an @catch clause). 03140 Scope *AtCatchParent = CurScope; 03141 while (AtCatchParent && !AtCatchParent->isAtCatchScope()) 03142 AtCatchParent = AtCatchParent->getParent(); 03143 if (!AtCatchParent) 03144 return StmtError(Diag(AtLoc, diag::error_rethrow_used_outside_catch)); 03145 } 03146 return BuildObjCAtThrowStmt(AtLoc, Throw); 03147 } 03148 03149 ExprResult 03150 Sema::ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand) { 03151 ExprResult result = DefaultLvalueConversion(operand); 03152 if (result.isInvalid()) 03153 return ExprError(); 03154 operand = result.get(); 03155 03156 // Make sure the expression type is an ObjC pointer or "void *". 03157 QualType type = operand->getType(); 03158 if (!type->isDependentType() && 03159 !type->isObjCObjectPointerType()) { 03160 const PointerType *pointerType = type->getAs<PointerType>(); 03161 if (!pointerType || !pointerType->getPointeeType()->isVoidType()) { 03162 if (getLangOpts().CPlusPlus) { 03163 if (RequireCompleteType(atLoc, type, 03164 diag::err_incomplete_receiver_type)) 03165 return Diag(atLoc, diag::error_objc_synchronized_expects_object) 03166 << type << operand->getSourceRange(); 03167 03168 ExprResult result = PerformContextuallyConvertToObjCPointer(operand); 03169 if (!result.isUsable()) 03170 return Diag(atLoc, diag::error_objc_synchronized_expects_object) 03171 << type << operand->getSourceRange(); 03172 03173 operand = result.get(); 03174 } else { 03175 return Diag(atLoc, diag::error_objc_synchronized_expects_object) 03176 << type << operand->getSourceRange(); 03177 } 03178 } 03179 } 03180 03181 // The operand to @synchronized is a full-expression. 03182 return ActOnFinishFullExpr(operand); 03183 } 03184 03185 StmtResult 03186 Sema::ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SyncExpr, 03187 Stmt *SyncBody) { 03188 // We can't jump into or indirect-jump out of a @synchronized block. 03189 getCurFunction()->setHasBranchProtectedScope(); 03190 return new (Context) ObjCAtSynchronizedStmt(AtLoc, SyncExpr, SyncBody); 03191 } 03192 03193 /// ActOnCXXCatchBlock - Takes an exception declaration and a handler block 03194 /// and creates a proper catch handler from them. 03195 StmtResult 03196 Sema::ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, 03197 Stmt *HandlerBlock) { 03198 // There's nothing to test that ActOnExceptionDecl didn't already test. 03199 return new (Context) 03200 CXXCatchStmt(CatchLoc, cast_or_null<VarDecl>(ExDecl), HandlerBlock); 03201 } 03202 03203 StmtResult 03204 Sema::ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body) { 03205 getCurFunction()->setHasBranchProtectedScope(); 03206 return new (Context) ObjCAutoreleasePoolStmt(AtLoc, Body); 03207 } 03208 03209 namespace { 03210 03211 class TypeWithHandler { 03212 QualType t; 03213 CXXCatchStmt *stmt; 03214 public: 03215 TypeWithHandler(const QualType &type, CXXCatchStmt *statement) 03216 : t(type), stmt(statement) {} 03217 03218 // An arbitrary order is fine as long as it places identical 03219 // types next to each other. 03220 bool operator<(const TypeWithHandler &y) const { 03221 if (t.getAsOpaquePtr() < y.t.getAsOpaquePtr()) 03222 return true; 03223 if (t.getAsOpaquePtr() > y.t.getAsOpaquePtr()) 03224 return false; 03225 else 03226 return getTypeSpecStartLoc() < y.getTypeSpecStartLoc(); 03227 } 03228 03229 bool operator==(const TypeWithHandler& other) const { 03230 return t == other.t; 03231 } 03232 03233 CXXCatchStmt *getCatchStmt() const { return stmt; } 03234 SourceLocation getTypeSpecStartLoc() const { 03235 return stmt->getExceptionDecl()->getTypeSpecStartLoc(); 03236 } 03237 }; 03238 03239 } 03240 03241 /// ActOnCXXTryBlock - Takes a try compound-statement and a number of 03242 /// handlers and creates a try statement from them. 03243 StmtResult Sema::ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 03244 ArrayRef<Stmt *> Handlers) { 03245 // Don't report an error if 'try' is used in system headers. 03246 if (!getLangOpts().CXXExceptions && 03247 !getSourceManager().isInSystemHeader(TryLoc)) 03248 Diag(TryLoc, diag::err_exceptions_disabled) << "try"; 03249 03250 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope()) 03251 Diag(TryLoc, diag::err_omp_simd_region_cannot_use_stmt) << "try"; 03252 03253 const unsigned NumHandlers = Handlers.size(); 03254 assert(NumHandlers > 0 && 03255 "The parser shouldn't call this if there are no handlers."); 03256 03257 SmallVector<TypeWithHandler, 8> TypesWithHandlers; 03258 03259 for (unsigned i = 0; i < NumHandlers; ++i) { 03260 CXXCatchStmt *Handler = cast<CXXCatchStmt>(Handlers[i]); 03261 if (!Handler->getExceptionDecl()) { 03262 if (i < NumHandlers - 1) 03263 return StmtError(Diag(Handler->getLocStart(), 03264 diag::err_early_catch_all)); 03265 03266 continue; 03267 } 03268 03269 const QualType CaughtType = Handler->getCaughtType(); 03270 const QualType CanonicalCaughtType = Context.getCanonicalType(CaughtType); 03271 TypesWithHandlers.push_back(TypeWithHandler(CanonicalCaughtType, Handler)); 03272 } 03273 03274 // Detect handlers for the same type as an earlier one. 03275 if (NumHandlers > 1) { 03276 llvm::array_pod_sort(TypesWithHandlers.begin(), TypesWithHandlers.end()); 03277 03278 TypeWithHandler prev = TypesWithHandlers[0]; 03279 for (unsigned i = 1; i < TypesWithHandlers.size(); ++i) { 03280 TypeWithHandler curr = TypesWithHandlers[i]; 03281 03282 if (curr == prev) { 03283 Diag(curr.getTypeSpecStartLoc(), 03284 diag::warn_exception_caught_by_earlier_handler) 03285 << curr.getCatchStmt()->getCaughtType().getAsString(); 03286 Diag(prev.getTypeSpecStartLoc(), 03287 diag::note_previous_exception_handler) 03288 << prev.getCatchStmt()->getCaughtType().getAsString(); 03289 } 03290 03291 prev = curr; 03292 } 03293 } 03294 03295 getCurFunction()->setHasBranchProtectedScope(); 03296 03297 // FIXME: We should detect handlers that cannot catch anything because an 03298 // earlier handler catches a superclass. Need to find a method that is not 03299 // quadratic for this. 03300 // Neither of these are explicitly forbidden, but every compiler detects them 03301 // and warns. 03302 03303 return CXXTryStmt::Create(Context, TryLoc, TryBlock, Handlers); 03304 } 03305 03306 StmtResult 03307 Sema::ActOnSEHTryBlock(bool IsCXXTry, 03308 SourceLocation TryLoc, 03309 Stmt *TryBlock, 03310 Stmt *Handler) { 03311 assert(TryBlock && Handler); 03312 03313 getCurFunction()->setHasBranchProtectedScope(); 03314 03315 return SEHTryStmt::Create(Context,IsCXXTry,TryLoc,TryBlock,Handler); 03316 } 03317 03318 StmtResult 03319 Sema::ActOnSEHExceptBlock(SourceLocation Loc, 03320 Expr *FilterExpr, 03321 Stmt *Block) { 03322 assert(FilterExpr && Block); 03323 03324 if(!FilterExpr->getType()->isIntegerType()) { 03325 return StmtError(Diag(FilterExpr->getExprLoc(), 03326 diag::err_filter_expression_integral) 03327 << FilterExpr->getType()); 03328 } 03329 03330 return SEHExceptStmt::Create(Context,Loc,FilterExpr,Block); 03331 } 03332 03333 StmtResult 03334 Sema::ActOnSEHFinallyBlock(SourceLocation Loc, 03335 Stmt *Block) { 03336 assert(Block); 03337 return SEHFinallyStmt::Create(Context,Loc,Block); 03338 } 03339 03340 StmtResult 03341 Sema::ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope) { 03342 Scope *SEHTryParent = CurScope; 03343 while (SEHTryParent && !SEHTryParent->isSEHTryScope()) 03344 SEHTryParent = SEHTryParent->getParent(); 03345 if (!SEHTryParent) 03346 return StmtError(Diag(Loc, diag::err_ms___leave_not_in___try)); 03347 03348 return new (Context) SEHLeaveStmt(Loc); 03349 } 03350 03351 StmtResult Sema::BuildMSDependentExistsStmt(SourceLocation KeywordLoc, 03352 bool IsIfExists, 03353 NestedNameSpecifierLoc QualifierLoc, 03354 DeclarationNameInfo NameInfo, 03355 Stmt *Nested) 03356 { 03357 return new (Context) MSDependentExistsStmt(KeywordLoc, IsIfExists, 03358 QualifierLoc, NameInfo, 03359 cast<CompoundStmt>(Nested)); 03360 } 03361 03362 03363 StmtResult Sema::ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, 03364 bool IsIfExists, 03365 CXXScopeSpec &SS, 03366 UnqualifiedId &Name, 03367 Stmt *Nested) { 03368 return BuildMSDependentExistsStmt(KeywordLoc, IsIfExists, 03369 SS.getWithLocInContext(Context), 03370 GetNameFromUnqualifiedId(Name), 03371 Nested); 03372 } 03373 03374 RecordDecl* 03375 Sema::CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, 03376 unsigned NumParams) { 03377 DeclContext *DC = CurContext; 03378 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext())) 03379 DC = DC->getParent(); 03380 03381 RecordDecl *RD = nullptr; 03382 if (getLangOpts().CPlusPlus) 03383 RD = CXXRecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, 03384 /*Id=*/nullptr); 03385 else 03386 RD = RecordDecl::Create(Context, TTK_Struct, DC, Loc, Loc, /*Id=*/nullptr); 03387 03388 RD->setCapturedRecord(); 03389 DC->addDecl(RD); 03390 RD->setImplicit(); 03391 RD->startDefinition(); 03392 03393 assert(NumParams > 0 && "CapturedStmt requires context parameter"); 03394 CD = CapturedDecl::Create(Context, CurContext, NumParams); 03395 DC->addDecl(CD); 03396 return RD; 03397 } 03398 03399 static void buildCapturedStmtCaptureList( 03400 SmallVectorImpl<CapturedStmt::Capture> &Captures, 03401 SmallVectorImpl<Expr *> &CaptureInits, 03402 ArrayRef<CapturingScopeInfo::Capture> Candidates) { 03403 03404 typedef ArrayRef<CapturingScopeInfo::Capture>::const_iterator CaptureIter; 03405 for (CaptureIter Cap = Candidates.begin(); Cap != Candidates.end(); ++Cap) { 03406 03407 if (Cap->isThisCapture()) { 03408 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(), 03409 CapturedStmt::VCK_This)); 03410 CaptureInits.push_back(Cap->getInitExpr()); 03411 continue; 03412 } else if (Cap->isVLATypeCapture()) { 03413 Captures.push_back( 03414 CapturedStmt::Capture(Cap->getLocation(), CapturedStmt::VCK_VLAType)); 03415 CaptureInits.push_back(nullptr); 03416 continue; 03417 } 03418 03419 assert(Cap->isReferenceCapture() && 03420 "non-reference capture not yet implemented"); 03421 03422 Captures.push_back(CapturedStmt::Capture(Cap->getLocation(), 03423 CapturedStmt::VCK_ByRef, 03424 Cap->getVariable())); 03425 CaptureInits.push_back(Cap->getInitExpr()); 03426 } 03427 } 03428 03429 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, 03430 CapturedRegionKind Kind, 03431 unsigned NumParams) { 03432 CapturedDecl *CD = nullptr; 03433 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, NumParams); 03434 03435 // Build the context parameter 03436 DeclContext *DC = CapturedDecl::castToDeclContext(CD); 03437 IdentifierInfo *ParamName = &Context.Idents.get("__context"); 03438 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD)); 03439 ImplicitParamDecl *Param 03440 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType); 03441 DC->addDecl(Param); 03442 03443 CD->setContextParam(0, Param); 03444 03445 // Enter the capturing scope for this captured region. 03446 PushCapturedRegionScope(CurScope, CD, RD, Kind); 03447 03448 if (CurScope) 03449 PushDeclContext(CurScope, CD); 03450 else 03451 CurContext = CD; 03452 03453 PushExpressionEvaluationContext(PotentiallyEvaluated); 03454 } 03455 03456 void Sema::ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, 03457 CapturedRegionKind Kind, 03458 ArrayRef<CapturedParamNameType> Params) { 03459 CapturedDecl *CD = nullptr; 03460 RecordDecl *RD = CreateCapturedStmtRecordDecl(CD, Loc, Params.size()); 03461 03462 // Build the context parameter 03463 DeclContext *DC = CapturedDecl::castToDeclContext(CD); 03464 bool ContextIsFound = false; 03465 unsigned ParamNum = 0; 03466 for (ArrayRef<CapturedParamNameType>::iterator I = Params.begin(), 03467 E = Params.end(); 03468 I != E; ++I, ++ParamNum) { 03469 if (I->second.isNull()) { 03470 assert(!ContextIsFound && 03471 "null type has been found already for '__context' parameter"); 03472 IdentifierInfo *ParamName = &Context.Idents.get("__context"); 03473 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD)); 03474 ImplicitParamDecl *Param 03475 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType); 03476 DC->addDecl(Param); 03477 CD->setContextParam(ParamNum, Param); 03478 ContextIsFound = true; 03479 } else { 03480 IdentifierInfo *ParamName = &Context.Idents.get(I->first); 03481 ImplicitParamDecl *Param 03482 = ImplicitParamDecl::Create(Context, DC, Loc, ParamName, I->second); 03483 DC->addDecl(Param); 03484 CD->setParam(ParamNum, Param); 03485 } 03486 } 03487 assert(ContextIsFound && "no null type for '__context' parameter"); 03488 if (!ContextIsFound) { 03489 // Add __context implicitly if it is not specified. 03490 IdentifierInfo *ParamName = &Context.Idents.get("__context"); 03491 QualType ParamType = Context.getPointerType(Context.getTagDeclType(RD)); 03492 ImplicitParamDecl *Param = 03493 ImplicitParamDecl::Create(Context, DC, Loc, ParamName, ParamType); 03494 DC->addDecl(Param); 03495 CD->setContextParam(ParamNum, Param); 03496 } 03497 // Enter the capturing scope for this captured region. 03498 PushCapturedRegionScope(CurScope, CD, RD, Kind); 03499 03500 if (CurScope) 03501 PushDeclContext(CurScope, CD); 03502 else 03503 CurContext = CD; 03504 03505 PushExpressionEvaluationContext(PotentiallyEvaluated); 03506 } 03507 03508 void Sema::ActOnCapturedRegionError() { 03509 DiscardCleanupsInEvaluationContext(); 03510 PopExpressionEvaluationContext(); 03511 03512 CapturedRegionScopeInfo *RSI = getCurCapturedRegion(); 03513 RecordDecl *Record = RSI->TheRecordDecl; 03514 Record->setInvalidDecl(); 03515 03516 SmallVector<Decl*, 4> Fields(Record->fields()); 03517 ActOnFields(/*Scope=*/nullptr, Record->getLocation(), Record, Fields, 03518 SourceLocation(), SourceLocation(), /*AttributeList=*/nullptr); 03519 03520 PopDeclContext(); 03521 PopFunctionScopeInfo(); 03522 } 03523 03524 StmtResult Sema::ActOnCapturedRegionEnd(Stmt *S) { 03525 CapturedRegionScopeInfo *RSI = getCurCapturedRegion(); 03526 03527 SmallVector<CapturedStmt::Capture, 4> Captures; 03528 SmallVector<Expr *, 4> CaptureInits; 03529 buildCapturedStmtCaptureList(Captures, CaptureInits, RSI->Captures); 03530 03531 CapturedDecl *CD = RSI->TheCapturedDecl; 03532 RecordDecl *RD = RSI->TheRecordDecl; 03533 03534 CapturedStmt *Res = CapturedStmt::Create(getASTContext(), S, 03535 RSI->CapRegionKind, Captures, 03536 CaptureInits, CD, RD); 03537 03538 CD->setBody(Res->getCapturedStmt()); 03539 RD->completeDefinition(); 03540 03541 DiscardCleanupsInEvaluationContext(); 03542 PopExpressionEvaluationContext(); 03543 03544 PopDeclContext(); 03545 PopFunctionScopeInfo(); 03546 03547 return Res; 03548 }