1 //===--- JumpDiagnostics.cpp - Protected scope jump analysis ------*- C++ -*-=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the JumpScopeChecker class, which is used to diagnose
11 // jumps that enter a protected scope in an invalid way.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Sema/SemaInternal.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/StmtCXX.h"
20 #include "clang/AST/StmtObjC.h"
21 #include "llvm/ADT/BitVector.h"
22 using namespace clang;
26 /// JumpScopeChecker - This object is used by Sema to diagnose invalid jumps
27 /// into VLA and other protected scopes. For example, this rejects:
32 class JumpScopeChecker {
35 /// GotoScope - This is a record that we use to keep track of all of the
36 /// scopes that are introduced by VLAs and other things that scope jumps like
37 /// gotos. This scope tree has nothing to do with the source scope tree,
38 /// because you can have multiple VLA scopes per compound statement, and most
39 /// compound statements don't introduce any scopes.
41 /// ParentScope - The index in ScopeMap of the parent scope. This is 0 for
42 /// the parent scope is the function body.
45 /// InDiag - The note to emit if there is a jump into this scope.
48 /// OutDiag - The note to emit if there is an indirect jump out
49 /// of this scope. Direct jumps always clean up their current scope
50 /// in an orderly way.
53 /// Loc - Location to emit the diagnostic.
56 GotoScope(unsigned parentScope, unsigned InDiag, unsigned OutDiag,
58 : ParentScope(parentScope), InDiag(InDiag), OutDiag(OutDiag), Loc(L) {}
61 SmallVector<GotoScope, 48> Scopes;
62 llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
63 SmallVector<Stmt*, 16> Jumps;
65 SmallVector<IndirectGotoStmt*, 4> IndirectJumps;
66 SmallVector<LabelDecl*, 4> IndirectJumpTargets;
68 JumpScopeChecker(Stmt *Body, Sema &S);
70 void BuildScopeInformation(Decl *D, unsigned &ParentScope);
71 void BuildScopeInformation(VarDecl *D, const BlockDecl *BDecl,
72 unsigned &ParentScope);
73 void BuildScopeInformation(Stmt *S, unsigned &origParentScope);
76 void VerifyIndirectJumps();
77 void NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes);
78 void DiagnoseIndirectJump(IndirectGotoStmt *IG, unsigned IGScope,
79 LabelDecl *Target, unsigned TargetScope);
80 void CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
81 unsigned JumpDiag, unsigned JumpDiagWarning,
82 unsigned JumpDiagCXX98Compat);
84 unsigned GetDeepestCommonScope(unsigned A, unsigned B);
86 } // end anonymous namespace
89 JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s) : S(s) {
90 // Add a scope entry for function scope.
91 Scopes.push_back(GotoScope(~0U, ~0U, ~0U, SourceLocation()));
93 // Build information for the top level compound statement, so that we have a
94 // defined scope record for every "goto" and label.
95 unsigned BodyParentScope = 0;
96 BuildScopeInformation(Body, BodyParentScope);
98 // Check that all jumps we saw are kosher.
100 VerifyIndirectJumps();
103 /// GetDeepestCommonScope - Finds the innermost scope enclosing the
105 unsigned JumpScopeChecker::GetDeepestCommonScope(unsigned A, unsigned B) {
107 // Inner scopes are created after outer scopes and therefore have
110 assert(Scopes[B].ParentScope < B);
111 B = Scopes[B].ParentScope;
113 assert(Scopes[A].ParentScope < A);
114 A = Scopes[A].ParentScope;
120 typedef std::pair<unsigned,unsigned> ScopePair;
122 /// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a
123 /// diagnostic that should be emitted if control goes over it. If not, return 0.
124 static ScopePair GetDiagForGotoScopeDecl(ASTContext &Context, const Decl *D) {
125 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
127 if (VD->getType()->isVariablyModifiedType())
128 InDiag = diag::note_protected_by_vla;
130 if (VD->hasAttr<BlocksAttr>())
131 return ScopePair(diag::note_protected_by___block,
132 diag::note_exits___block);
134 if (VD->hasAttr<CleanupAttr>())
135 return ScopePair(diag::note_protected_by_cleanup,
136 diag::note_exits_cleanup);
138 if (Context.getLangOpts().ObjCAutoRefCount && VD->hasLocalStorage()) {
139 switch (VD->getType().getObjCLifetime()) {
140 case Qualifiers::OCL_None:
141 case Qualifiers::OCL_ExplicitNone:
142 case Qualifiers::OCL_Autoreleasing:
145 case Qualifiers::OCL_Strong:
146 case Qualifiers::OCL_Weak:
147 return ScopePair(diag::note_protected_by_objc_ownership,
148 diag::note_exits_objc_ownership);
152 if (Context.getLangOpts().CPlusPlus && VD->hasLocalStorage()) {
153 // C++11 [stmt.dcl]p3:
154 // A program that jumps from a point where a variable with automatic
155 // storage duration is not in scope to a point where it is in scope
156 // is ill-formed unless the variable has scalar type, class type with
157 // a trivial default constructor and a trivial destructor, a
158 // cv-qualified version of one of these types, or an array of one of
159 // the preceding types and is declared without an initializer.
161 // C++03 [stmt.dcl.p3:
162 // A program that jumps from a point where a local variable
163 // with automatic storage duration is not in scope to a point
164 // where it is in scope is ill-formed unless the variable has
165 // POD type and is declared without an initializer.
167 const Expr *Init = VD->getInit();
169 return ScopePair(InDiag, 0);
171 const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init);
173 Init = EWC->getSubExpr();
175 const MaterializeTemporaryExpr *M = NULL;
176 Init = Init->findMaterializedTemporary(M);
178 SmallVector<const Expr *, 2> CommaLHSs;
179 SmallVector<SubobjectAdjustment, 2> Adjustments;
180 Init = Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
182 QualType QT = Init->getType();
184 return ScopePair(diag::note_protected_by_variable_init, 0);
186 const Type *T = QT.getTypePtr();
187 if (T->isArrayType())
188 T = T->getBaseElementTypeUnsafe();
190 const CXXRecordDecl *Record = T->getAsCXXRecordDecl();
192 return ScopePair(diag::note_protected_by_variable_init, 0);
194 // If we need to call a non trivial destructor for this variable,
195 // record an out diagnostic.
196 unsigned OutDiag = 0;
197 if (!Init->isGLValue() && !Record->hasTrivialDestructor())
198 OutDiag = diag::note_exits_dtor;
200 if (const CXXConstructExpr *cce = dyn_cast<CXXConstructExpr>(Init)) {
201 const CXXConstructorDecl *ctor = cce->getConstructor();
202 // For a variable declared without an initializer, we will have
203 // call-style initialization and the initializer will be the
204 // CXXConstructExpr with no intervening nodes.
205 if (ctor->isTrivial() && ctor->isDefaultConstructor() &&
206 VD->getInit() == Init && VD->getInitStyle() == VarDecl::CallInit) {
208 InDiag = diag::note_protected_by_variable_nontriv_destructor;
209 else if (!Record->isPOD())
210 InDiag = diag::note_protected_by_variable_non_pod;
211 return ScopePair(InDiag, OutDiag);
215 return ScopePair(diag::note_protected_by_variable_init, OutDiag);
218 return ScopePair(InDiag, 0);
221 if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
222 if (TD->getUnderlyingType()->isVariablyModifiedType())
223 return ScopePair(diag::note_protected_by_vla_typedef, 0);
226 if (const TypeAliasDecl *TD = dyn_cast<TypeAliasDecl>(D)) {
227 if (TD->getUnderlyingType()->isVariablyModifiedType())
228 return ScopePair(diag::note_protected_by_vla_type_alias, 0);
231 return ScopePair(0U, 0U);
234 /// \brief Build scope information for a declaration that is part of a DeclStmt.
235 void JumpScopeChecker::BuildScopeInformation(Decl *D, unsigned &ParentScope) {
236 // If this decl causes a new scope, push and switch to it.
237 std::pair<unsigned,unsigned> Diags = GetDiagForGotoScopeDecl(S.Context, D);
238 if (Diags.first || Diags.second) {
239 Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second,
241 ParentScope = Scopes.size()-1;
244 // If the decl has an initializer, walk it with the potentially new
245 // scope we just installed.
246 if (VarDecl *VD = dyn_cast<VarDecl>(D))
247 if (Expr *Init = VD->getInit())
248 BuildScopeInformation(Init, ParentScope);
251 /// \brief Build scope information for a captured block literal variables.
252 void JumpScopeChecker::BuildScopeInformation(VarDecl *D,
253 const BlockDecl *BDecl,
254 unsigned &ParentScope) {
255 // exclude captured __block variables; there's no destructor
256 // associated with the block literal for them.
257 if (D->hasAttr<BlocksAttr>())
259 QualType T = D->getType();
260 QualType::DestructionKind destructKind = T.isDestructedType();
261 if (destructKind != QualType::DK_none) {
262 std::pair<unsigned,unsigned> Diags;
263 switch (destructKind) {
264 case QualType::DK_cxx_destructor:
265 Diags = ScopePair(diag::note_enters_block_captures_cxx_obj,
266 diag::note_exits_block_captures_cxx_obj);
268 case QualType::DK_objc_strong_lifetime:
269 Diags = ScopePair(diag::note_enters_block_captures_strong,
270 diag::note_exits_block_captures_strong);
272 case QualType::DK_objc_weak_lifetime:
273 Diags = ScopePair(diag::note_enters_block_captures_weak,
274 diag::note_exits_block_captures_weak);
276 case QualType::DK_none:
277 llvm_unreachable("non-lifetime captured variable");
279 SourceLocation Loc = D->getLocation();
281 Loc = BDecl->getLocation();
282 Scopes.push_back(GotoScope(ParentScope,
283 Diags.first, Diags.second, Loc));
284 ParentScope = Scopes.size()-1;
288 /// BuildScopeInformation - The statements from CI to CE are known to form a
289 /// coherent VLA scope with a specified parent node. Walk through the
290 /// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
291 /// walking the AST as needed.
292 void JumpScopeChecker::BuildScopeInformation(Stmt *S, unsigned &origParentScope) {
293 // If this is a statement, rather than an expression, scopes within it don't
294 // propagate out into the enclosing scope. Otherwise we have to worry
295 // about block literals, which have the lifetime of their enclosing statement.
296 unsigned independentParentScope = origParentScope;
297 unsigned &ParentScope = ((isa<Expr>(S) && !isa<StmtExpr>(S))
298 ? origParentScope : independentParentScope);
300 bool SkipFirstSubStmt = false;
302 // If we found a label, remember that it is in ParentScope scope.
303 switch (S->getStmtClass()) {
304 case Stmt::AddrLabelExprClass:
305 IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel());
308 case Stmt::IndirectGotoStmtClass:
309 // "goto *&&lbl;" is a special case which we treat as equivalent
310 // to a normal goto. In addition, we don't calculate scope in the
311 // operand (to avoid recording the address-of-label use), which
312 // works only because of the restricted set of expressions which
313 // we detect as constant targets.
314 if (cast<IndirectGotoStmt>(S)->getConstantTarget()) {
315 LabelAndGotoScopes[S] = ParentScope;
320 LabelAndGotoScopes[S] = ParentScope;
321 IndirectJumps.push_back(cast<IndirectGotoStmt>(S));
324 case Stmt::SwitchStmtClass:
325 // Evaluate the condition variable before entering the scope of the switch
327 if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) {
328 BuildScopeInformation(Var, ParentScope);
329 SkipFirstSubStmt = true;
333 case Stmt::GotoStmtClass:
334 // Remember both what scope a goto is in as well as the fact that we have
335 // it. This makes the second scan not have to walk the AST again.
336 LabelAndGotoScopes[S] = ParentScope;
340 case Stmt::CXXTryStmtClass: {
341 CXXTryStmt *TS = cast<CXXTryStmt>(S);
342 unsigned newParentScope;
343 Scopes.push_back(GotoScope(ParentScope,
344 diag::note_protected_by_cxx_try,
345 diag::note_exits_cxx_try,
346 TS->getSourceRange().getBegin()));
347 if (Stmt *TryBlock = TS->getTryBlock())
348 BuildScopeInformation(TryBlock, (newParentScope = Scopes.size()-1));
350 // Jump from the catch into the try is not allowed either.
351 for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) {
352 CXXCatchStmt *CS = TS->getHandler(I);
353 Scopes.push_back(GotoScope(ParentScope,
354 diag::note_protected_by_cxx_catch,
355 diag::note_exits_cxx_catch,
356 CS->getSourceRange().getBegin()));
357 BuildScopeInformation(CS->getHandlerBlock(),
358 (newParentScope = Scopes.size()-1));
367 for (Stmt::child_range CI = S->children(); CI; ++CI) {
368 if (SkipFirstSubStmt) {
369 SkipFirstSubStmt = false;
374 if (SubStmt == 0) continue;
376 // Cases, labels, and defaults aren't "scope parents". It's also
377 // important to handle these iteratively instead of recursively in
378 // order to avoid blowing out the stack.
381 if (CaseStmt *CS = dyn_cast<CaseStmt>(SubStmt))
382 Next = CS->getSubStmt();
383 else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SubStmt))
384 Next = DS->getSubStmt();
385 else if (LabelStmt *LS = dyn_cast<LabelStmt>(SubStmt))
386 Next = LS->getSubStmt();
390 LabelAndGotoScopes[SubStmt] = ParentScope;
394 // If this is a declstmt with a VLA definition, it defines a scope from here
395 // to the end of the containing context.
396 if (DeclStmt *DS = dyn_cast<DeclStmt>(SubStmt)) {
397 // The decl statement creates a scope if any of the decls in it are VLAs
398 // or have the cleanup attribute.
399 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
401 BuildScopeInformation(*I, ParentScope);
404 // Disallow jumps into any part of an @try statement by pushing a scope and
405 // walking all sub-stmts in that scope.
406 if (ObjCAtTryStmt *AT = dyn_cast<ObjCAtTryStmt>(SubStmt)) {
407 unsigned newParentScope;
408 // Recursively walk the AST for the @try part.
409 Scopes.push_back(GotoScope(ParentScope,
410 diag::note_protected_by_objc_try,
411 diag::note_exits_objc_try,
413 if (Stmt *TryPart = AT->getTryBody())
414 BuildScopeInformation(TryPart, (newParentScope = Scopes.size()-1));
416 // Jump from the catch to the finally or try is not valid.
417 for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) {
418 ObjCAtCatchStmt *AC = AT->getCatchStmt(I);
419 Scopes.push_back(GotoScope(ParentScope,
420 diag::note_protected_by_objc_catch,
421 diag::note_exits_objc_catch,
422 AC->getAtCatchLoc()));
423 // @catches are nested and it isn't
424 BuildScopeInformation(AC->getCatchBody(),
425 (newParentScope = Scopes.size()-1));
428 // Jump from the finally to the try or catch is not valid.
429 if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
430 Scopes.push_back(GotoScope(ParentScope,
431 diag::note_protected_by_objc_finally,
432 diag::note_exits_objc_finally,
433 AF->getAtFinallyLoc()));
434 BuildScopeInformation(AF, (newParentScope = Scopes.size()-1));
440 unsigned newParentScope;
441 // Disallow jumps into the protected statement of an @synchronized, but
442 // allow jumps into the object expression it protects.
443 if (ObjCAtSynchronizedStmt *AS = dyn_cast<ObjCAtSynchronizedStmt>(SubStmt)){
444 // Recursively walk the AST for the @synchronized object expr, it is
445 // evaluated in the normal scope.
446 BuildScopeInformation(AS->getSynchExpr(), ParentScope);
448 // Recursively walk the AST for the @synchronized part, protected by a new
450 Scopes.push_back(GotoScope(ParentScope,
451 diag::note_protected_by_objc_synchronized,
452 diag::note_exits_objc_synchronized,
453 AS->getAtSynchronizedLoc()));
454 BuildScopeInformation(AS->getSynchBody(),
455 (newParentScope = Scopes.size()-1));
459 // Disallow jumps into the protected statement of an @autoreleasepool.
460 if (ObjCAutoreleasePoolStmt *AS = dyn_cast<ObjCAutoreleasePoolStmt>(SubStmt)){
461 // Recursively walk the AST for the @autoreleasepool part, protected by a new
463 Scopes.push_back(GotoScope(ParentScope,
464 diag::note_protected_by_objc_autoreleasepool,
465 diag::note_exits_objc_autoreleasepool,
467 BuildScopeInformation(AS->getSubStmt(), (newParentScope = Scopes.size()-1));
471 // Disallow jumps past full-expressions that use blocks with
472 // non-trivial cleanups of their captures. This is theoretically
473 // implementable but a lot of work which we haven't felt up to doing.
474 if (ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(SubStmt)) {
475 for (unsigned i = 0, e = EWC->getNumObjects(); i != e; ++i) {
476 const BlockDecl *BDecl = EWC->getObject(i);
477 for (BlockDecl::capture_const_iterator ci = BDecl->capture_begin(),
478 ce = BDecl->capture_end(); ci != ce; ++ci) {
479 VarDecl *variable = ci->getVariable();
480 BuildScopeInformation(variable, BDecl, ParentScope);
485 // Recursively walk the AST.
486 BuildScopeInformation(SubStmt, ParentScope);
490 /// VerifyJumps - Verify each element of the Jumps array to see if they are
491 /// valid, emitting diagnostics if not.
492 void JumpScopeChecker::VerifyJumps() {
493 while (!Jumps.empty()) {
494 Stmt *Jump = Jumps.pop_back_val();
497 if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
498 CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(),
499 diag::err_goto_into_protected_scope,
500 diag::warn_goto_into_protected_scope,
501 diag::warn_cxx98_compat_goto_into_protected_scope);
505 // We only get indirect gotos here when they have a constant target.
506 if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) {
507 LabelDecl *Target = IGS->getConstantTarget();
508 CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(),
509 diag::err_goto_into_protected_scope,
510 diag::warn_goto_into_protected_scope,
511 diag::warn_cxx98_compat_goto_into_protected_scope);
515 SwitchStmt *SS = cast<SwitchStmt>(Jump);
516 for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
517 SC = SC->getNextSwitchCase()) {
518 assert(LabelAndGotoScopes.count(SC) && "Case not visited?");
520 if (CaseStmt *CS = dyn_cast<CaseStmt>(SC))
521 Loc = CS->getLocStart();
522 else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC))
523 Loc = DS->getLocStart();
525 Loc = SC->getLocStart();
526 CheckJump(SS, SC, Loc, diag::err_switch_into_protected_scope, 0,
527 diag::warn_cxx98_compat_switch_into_protected_scope);
532 /// VerifyIndirectJumps - Verify whether any possible indirect jump
533 /// might cross a protection boundary. Unlike direct jumps, indirect
534 /// jumps count cleanups as protection boundaries: since there's no
535 /// way to know where the jump is going, we can't implicitly run the
536 /// right cleanups the way we can with direct jumps.
538 /// Thus, an indirect jump is "trivial" if it bypasses no
539 /// initializations and no teardowns. More formally, an indirect jump
540 /// from A to B is trivial if the path out from A to DCA(A,B) is
541 /// trivial and the path in from DCA(A,B) to B is trivial, where
542 /// DCA(A,B) is the deepest common ancestor of A and B.
543 /// Jump-triviality is transitive but asymmetric.
545 /// A path in is trivial if none of the entered scopes have an InDiag.
546 /// A path out is trivial is none of the exited scopes have an OutDiag.
548 /// Under these definitions, this function checks that the indirect
549 /// jump between A and B is trivial for every indirect goto statement A
550 /// and every label B whose address was taken in the function.
551 void JumpScopeChecker::VerifyIndirectJumps() {
552 if (IndirectJumps.empty()) return;
554 // If there aren't any address-of-label expressions in this function,
555 // complain about the first indirect goto.
556 if (IndirectJumpTargets.empty()) {
557 S.Diag(IndirectJumps[0]->getGotoLoc(),
558 diag::err_indirect_goto_without_addrlabel);
562 // Collect a single representative of every scope containing an
563 // indirect goto. For most code bases, this substantially cuts
564 // down on the number of jump sites we'll have to consider later.
565 typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope;
566 SmallVector<JumpScope, 32> JumpScopes;
568 llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap;
569 for (SmallVectorImpl<IndirectGotoStmt*>::iterator
570 I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) {
571 IndirectGotoStmt *IG = *I;
572 assert(LabelAndGotoScopes.count(IG) &&
573 "indirect jump didn't get added to scopes?");
574 unsigned IGScope = LabelAndGotoScopes[IG];
575 IndirectGotoStmt *&Entry = JumpScopesMap[IGScope];
576 if (!Entry) Entry = IG;
578 JumpScopes.reserve(JumpScopesMap.size());
579 for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator
580 I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I)
581 JumpScopes.push_back(*I);
584 // Collect a single representative of every scope containing a
585 // label whose address was taken somewhere in the function.
586 // For most code bases, there will be only one such scope.
587 llvm::DenseMap<unsigned, LabelDecl*> TargetScopes;
588 for (SmallVectorImpl<LabelDecl*>::iterator
589 I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end();
591 LabelDecl *TheLabel = *I;
592 assert(LabelAndGotoScopes.count(TheLabel->getStmt()) &&
593 "Referenced label didn't get added to scopes?");
594 unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()];
595 LabelDecl *&Target = TargetScopes[LabelScope];
596 if (!Target) Target = TheLabel;
599 // For each target scope, make sure it's trivially reachable from
600 // every scope containing a jump site.
602 // A path between scopes always consists of exitting zero or more
603 // scopes, then entering zero or more scopes. We build a set of
604 // of scopes S from which the target scope can be trivially
605 // entered, then verify that every jump scope can be trivially
606 // exitted to reach a scope in S.
607 llvm::BitVector Reachable(Scopes.size(), false);
608 for (llvm::DenseMap<unsigned,LabelDecl*>::iterator
609 TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) {
610 unsigned TargetScope = TI->first;
611 LabelDecl *TargetLabel = TI->second;
615 // Mark all the enclosing scopes from which you can safely jump
616 // into the target scope. 'Min' will end up being the index of
617 // the shallowest such scope.
618 unsigned Min = TargetScope;
622 // Don't go beyond the outermost scope.
625 // Stop if we can't trivially enter the current scope.
626 if (Scopes[Min].InDiag) break;
628 Min = Scopes[Min].ParentScope;
631 // Walk through all the jump sites, checking that they can trivially
632 // reach this label scope.
633 for (SmallVectorImpl<JumpScope>::iterator
634 I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) {
635 unsigned Scope = I->first;
637 // Walk out the "scope chain" for this scope, looking for a scope
638 // we've marked reachable. For well-formed code this amortizes
639 // to O(JumpScopes.size() / Scopes.size()): we only iterate
640 // when we see something unmarked, and in well-formed code we
641 // mark everything we iterate past.
642 bool IsReachable = false;
644 if (Reachable.test(Scope)) {
645 // If we find something reachable, mark all the scopes we just
646 // walked through as reachable.
647 for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope)
653 // Don't walk out if we've reached the top-level scope or we've
654 // gotten shallower than the shallowest reachable scope.
655 if (Scope == 0 || Scope < Min) break;
657 // Don't walk out through an out-diagnostic.
658 if (Scopes[Scope].OutDiag) break;
660 Scope = Scopes[Scope].ParentScope;
663 // Only diagnose if we didn't find something.
664 if (IsReachable) continue;
666 DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope);
671 /// Return true if a particular error+note combination must be downgraded to a
672 /// warning in Microsoft mode.
673 static bool IsMicrosoftJumpWarning(unsigned JumpDiag, unsigned InDiagNote) {
674 return (JumpDiag == diag::err_goto_into_protected_scope &&
675 (InDiagNote == diag::note_protected_by_variable_init ||
676 InDiagNote == diag::note_protected_by_variable_nontriv_destructor));
679 /// Return true if a particular note should be downgraded to a compatibility
680 /// warning in C++11 mode.
681 static bool IsCXX98CompatWarning(Sema &S, unsigned InDiagNote) {
682 return S.getLangOpts().CPlusPlus11 &&
683 InDiagNote == diag::note_protected_by_variable_non_pod;
686 /// Produce primary diagnostic for an indirect jump statement.
687 static void DiagnoseIndirectJumpStmt(Sema &S, IndirectGotoStmt *Jump,
688 LabelDecl *Target, bool &Diagnosed) {
691 S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
692 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
696 /// Produce note diagnostics for a jump into a protected scope.
697 void JumpScopeChecker::NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes) {
698 assert(!ToScopes.empty());
699 for (unsigned I = 0, E = ToScopes.size(); I != E; ++I)
700 if (Scopes[ToScopes[I]].InDiag)
701 S.Diag(Scopes[ToScopes[I]].Loc, Scopes[ToScopes[I]].InDiag);
704 /// Diagnose an indirect jump which is known to cross scopes.
705 void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump,
708 unsigned TargetScope) {
709 assert(JumpScope != TargetScope);
711 unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope);
712 bool Diagnosed = false;
714 // Walk out the scope chain until we reach the common ancestor.
715 for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope)
716 if (Scopes[I].OutDiag) {
717 DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
718 S.Diag(Scopes[I].Loc, Scopes[I].OutDiag);
721 SmallVector<unsigned, 10> ToScopesCXX98Compat;
723 // Now walk into the scopes containing the label whose address was taken.
724 for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope)
725 if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
726 ToScopesCXX98Compat.push_back(I);
727 else if (Scopes[I].InDiag) {
728 DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
729 S.Diag(Scopes[I].Loc, Scopes[I].InDiag);
732 // Diagnose this jump if it would be ill-formed in C++98.
733 if (!Diagnosed && !ToScopesCXX98Compat.empty()) {
734 S.Diag(Jump->getGotoLoc(),
735 diag::warn_cxx98_compat_indirect_goto_in_protected_scope);
736 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
737 NoteJumpIntoScopes(ToScopesCXX98Compat);
741 /// CheckJump - Validate that the specified jump statement is valid: that it is
742 /// jumping within or out of its current scope, not into a deeper one.
743 void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
744 unsigned JumpDiagError, unsigned JumpDiagWarning,
745 unsigned JumpDiagCXX98Compat) {
746 assert(LabelAndGotoScopes.count(From) && "Jump didn't get added to scopes?");
747 unsigned FromScope = LabelAndGotoScopes[From];
749 assert(LabelAndGotoScopes.count(To) && "Jump didn't get added to scopes?");
750 unsigned ToScope = LabelAndGotoScopes[To];
752 // Common case: exactly the same scope, which is fine.
753 if (FromScope == ToScope) return;
755 unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope);
757 // It's okay to jump out from a nested scope.
758 if (CommonScope == ToScope) return;
760 // Pull out (and reverse) any scopes we might need to diagnose skipping.
761 SmallVector<unsigned, 10> ToScopesCXX98Compat;
762 SmallVector<unsigned, 10> ToScopesError;
763 SmallVector<unsigned, 10> ToScopesWarning;
764 for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope) {
765 if (S.getLangOpts().MicrosoftMode && JumpDiagWarning != 0 &&
766 IsMicrosoftJumpWarning(JumpDiagError, Scopes[I].InDiag))
767 ToScopesWarning.push_back(I);
768 else if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
769 ToScopesCXX98Compat.push_back(I);
770 else if (Scopes[I].InDiag)
771 ToScopesError.push_back(I);
775 if (!ToScopesWarning.empty()) {
776 S.Diag(DiagLoc, JumpDiagWarning);
777 NoteJumpIntoScopes(ToScopesWarning);
781 if (!ToScopesError.empty()) {
782 S.Diag(DiagLoc, JumpDiagError);
783 NoteJumpIntoScopes(ToScopesError);
786 // Handle -Wc++98-compat warnings if the jump is well-formed.
787 if (ToScopesError.empty() && !ToScopesCXX98Compat.empty()) {
788 S.Diag(DiagLoc, JumpDiagCXX98Compat);
789 NoteJumpIntoScopes(ToScopesCXX98Compat);
793 void Sema::DiagnoseInvalidJumps(Stmt *Body) {
794 (void)JumpScopeChecker(Body, *this);