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 /// Permissive - True when recovering from errors, in which case precautions
36 /// are taken to handle incomplete scope information.
37 const bool Permissive;
39 /// GotoScope - This is a record that we use to keep track of all of the
40 /// scopes that are introduced by VLAs and other things that scope jumps like
41 /// gotos. This scope tree has nothing to do with the source scope tree,
42 /// because you can have multiple VLA scopes per compound statement, and most
43 /// compound statements don't introduce any scopes.
45 /// ParentScope - The index in ScopeMap of the parent scope. This is 0 for
46 /// the parent scope is the function body.
49 /// InDiag - The note to emit if there is a jump into this scope.
52 /// OutDiag - The note to emit if there is an indirect jump out
53 /// of this scope. Direct jumps always clean up their current scope
54 /// in an orderly way.
57 /// Loc - Location to emit the diagnostic.
60 GotoScope(unsigned parentScope, unsigned InDiag, unsigned OutDiag,
62 : ParentScope(parentScope), InDiag(InDiag), OutDiag(OutDiag), Loc(L) {}
65 SmallVector<GotoScope, 48> Scopes;
66 llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
67 SmallVector<Stmt*, 16> Jumps;
69 SmallVector<IndirectGotoStmt*, 4> IndirectJumps;
70 SmallVector<LabelDecl*, 4> IndirectJumpTargets;
72 JumpScopeChecker(Stmt *Body, Sema &S);
74 void BuildScopeInformation(Decl *D, unsigned &ParentScope);
75 void BuildScopeInformation(VarDecl *D, const BlockDecl *BDecl,
76 unsigned &ParentScope);
77 void BuildScopeInformation(Stmt *S, unsigned &origParentScope);
80 void VerifyIndirectJumps();
81 void NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes);
82 void DiagnoseIndirectJump(IndirectGotoStmt *IG, unsigned IGScope,
83 LabelDecl *Target, unsigned TargetScope);
84 void CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
85 unsigned JumpDiag, unsigned JumpDiagWarning,
86 unsigned JumpDiagCXX98Compat);
88 unsigned GetDeepestCommonScope(unsigned A, unsigned B);
90 } // end anonymous namespace
92 #define CHECK_PERMISSIVE(x) (assert(Permissive || !(x)), (Permissive && (x)))
94 JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s)
95 : S(s), Permissive(s.hasAnyUnrecoverableErrorsInThisFunction()) {
96 // Add a scope entry for function scope.
97 Scopes.push_back(GotoScope(~0U, ~0U, ~0U, SourceLocation()));
99 // Build information for the top level compound statement, so that we have a
100 // defined scope record for every "goto" and label.
101 unsigned BodyParentScope = 0;
102 BuildScopeInformation(Body, BodyParentScope);
104 // Check that all jumps we saw are kosher.
106 VerifyIndirectJumps();
109 /// GetDeepestCommonScope - Finds the innermost scope enclosing the
111 unsigned JumpScopeChecker::GetDeepestCommonScope(unsigned A, unsigned B) {
113 // Inner scopes are created after outer scopes and therefore have
116 assert(Scopes[B].ParentScope < B);
117 B = Scopes[B].ParentScope;
119 assert(Scopes[A].ParentScope < A);
120 A = Scopes[A].ParentScope;
126 typedef std::pair<unsigned,unsigned> ScopePair;
128 /// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a
129 /// diagnostic that should be emitted if control goes over it. If not, return 0.
130 static ScopePair GetDiagForGotoScopeDecl(Sema &S, const Decl *D) {
131 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
133 unsigned OutDiag = 0;
135 if (VD->getType()->isVariablyModifiedType())
136 InDiag = diag::note_protected_by_vla;
138 if (VD->hasAttr<BlocksAttr>())
139 return ScopePair(diag::note_protected_by___block,
140 diag::note_exits___block);
142 if (VD->hasAttr<CleanupAttr>())
143 return ScopePair(diag::note_protected_by_cleanup,
144 diag::note_exits_cleanup);
146 if (VD->hasLocalStorage()) {
147 switch (VD->getType().isDestructedType()) {
148 case QualType::DK_objc_strong_lifetime:
149 case QualType::DK_objc_weak_lifetime:
150 return ScopePair(diag::note_protected_by_objc_ownership,
151 diag::note_exits_objc_ownership);
153 case QualType::DK_cxx_destructor:
154 OutDiag = diag::note_exits_dtor;
157 case QualType::DK_none:
162 const Expr *Init = VD->getInit();
163 if (S.Context.getLangOpts().CPlusPlus && VD->hasLocalStorage() && Init) {
164 // C++11 [stmt.dcl]p3:
165 // A program that jumps from a point where a variable with automatic
166 // storage duration is not in scope to a point where it is in scope
167 // is ill-formed unless the variable has scalar type, class type with
168 // a trivial default constructor and a trivial destructor, a
169 // cv-qualified version of one of these types, or an array of one of
170 // the preceding types and is declared without an initializer.
172 // C++03 [stmt.dcl.p3:
173 // A program that jumps from a point where a local variable
174 // with automatic storage duration is not in scope to a point
175 // where it is in scope is ill-formed unless the variable has
176 // POD type and is declared without an initializer.
178 InDiag = diag::note_protected_by_variable_init;
180 // For a variable of (array of) class type declared without an
181 // initializer, we will have call-style initialization and the initializer
182 // will be the CXXConstructExpr with no intervening nodes.
183 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
184 const CXXConstructorDecl *Ctor = CCE->getConstructor();
185 if (Ctor->isTrivial() && Ctor->isDefaultConstructor() &&
186 VD->getInitStyle() == VarDecl::CallInit) {
188 InDiag = diag::note_protected_by_variable_nontriv_destructor;
189 else if (!Ctor->getParent()->isPOD())
190 InDiag = diag::note_protected_by_variable_non_pod;
197 return ScopePair(InDiag, OutDiag);
200 if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
201 if (TD->getUnderlyingType()->isVariablyModifiedType())
202 return ScopePair(isa<TypedefDecl>(TD)
203 ? diag::note_protected_by_vla_typedef
204 : diag::note_protected_by_vla_type_alias,
208 return ScopePair(0U, 0U);
211 /// \brief Build scope information for a declaration that is part of a DeclStmt.
212 void JumpScopeChecker::BuildScopeInformation(Decl *D, unsigned &ParentScope) {
213 // If this decl causes a new scope, push and switch to it.
214 std::pair<unsigned,unsigned> Diags = GetDiagForGotoScopeDecl(S, D);
215 if (Diags.first || Diags.second) {
216 Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second,
218 ParentScope = Scopes.size()-1;
221 // If the decl has an initializer, walk it with the potentially new
222 // scope we just installed.
223 if (VarDecl *VD = dyn_cast<VarDecl>(D))
224 if (Expr *Init = VD->getInit())
225 BuildScopeInformation(Init, ParentScope);
228 /// \brief Build scope information for a captured block literal variables.
229 void JumpScopeChecker::BuildScopeInformation(VarDecl *D,
230 const BlockDecl *BDecl,
231 unsigned &ParentScope) {
232 // exclude captured __block variables; there's no destructor
233 // associated with the block literal for them.
234 if (D->hasAttr<BlocksAttr>())
236 QualType T = D->getType();
237 QualType::DestructionKind destructKind = T.isDestructedType();
238 if (destructKind != QualType::DK_none) {
239 std::pair<unsigned,unsigned> Diags;
240 switch (destructKind) {
241 case QualType::DK_cxx_destructor:
242 Diags = ScopePair(diag::note_enters_block_captures_cxx_obj,
243 diag::note_exits_block_captures_cxx_obj);
245 case QualType::DK_objc_strong_lifetime:
246 Diags = ScopePair(diag::note_enters_block_captures_strong,
247 diag::note_exits_block_captures_strong);
249 case QualType::DK_objc_weak_lifetime:
250 Diags = ScopePair(diag::note_enters_block_captures_weak,
251 diag::note_exits_block_captures_weak);
253 case QualType::DK_none:
254 llvm_unreachable("non-lifetime captured variable");
256 SourceLocation Loc = D->getLocation();
258 Loc = BDecl->getLocation();
259 Scopes.push_back(GotoScope(ParentScope,
260 Diags.first, Diags.second, Loc));
261 ParentScope = Scopes.size()-1;
265 /// BuildScopeInformation - The statements from CI to CE are known to form a
266 /// coherent VLA scope with a specified parent node. Walk through the
267 /// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
268 /// walking the AST as needed.
269 void JumpScopeChecker::BuildScopeInformation(Stmt *S, unsigned &origParentScope) {
270 // If this is a statement, rather than an expression, scopes within it don't
271 // propagate out into the enclosing scope. Otherwise we have to worry
272 // about block literals, which have the lifetime of their enclosing statement.
273 unsigned independentParentScope = origParentScope;
274 unsigned &ParentScope = ((isa<Expr>(S) && !isa<StmtExpr>(S))
275 ? origParentScope : independentParentScope);
277 bool SkipFirstSubStmt = false;
279 // If we found a label, remember that it is in ParentScope scope.
280 switch (S->getStmtClass()) {
281 case Stmt::AddrLabelExprClass:
282 IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel());
285 case Stmt::IndirectGotoStmtClass:
286 // "goto *&&lbl;" is a special case which we treat as equivalent
287 // to a normal goto. In addition, we don't calculate scope in the
288 // operand (to avoid recording the address-of-label use), which
289 // works only because of the restricted set of expressions which
290 // we detect as constant targets.
291 if (cast<IndirectGotoStmt>(S)->getConstantTarget()) {
292 LabelAndGotoScopes[S] = ParentScope;
297 LabelAndGotoScopes[S] = ParentScope;
298 IndirectJumps.push_back(cast<IndirectGotoStmt>(S));
301 case Stmt::SwitchStmtClass:
302 // Evaluate the condition variable before entering the scope of the switch
304 if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) {
305 BuildScopeInformation(Var, ParentScope);
306 SkipFirstSubStmt = true;
310 case Stmt::GotoStmtClass:
311 // Remember both what scope a goto is in as well as the fact that we have
312 // it. This makes the second scan not have to walk the AST again.
313 LabelAndGotoScopes[S] = ParentScope;
317 case Stmt::CXXTryStmtClass: {
318 CXXTryStmt *TS = cast<CXXTryStmt>(S);
319 unsigned newParentScope;
320 Scopes.push_back(GotoScope(ParentScope,
321 diag::note_protected_by_cxx_try,
322 diag::note_exits_cxx_try,
323 TS->getSourceRange().getBegin()));
324 if (Stmt *TryBlock = TS->getTryBlock())
325 BuildScopeInformation(TryBlock, (newParentScope = Scopes.size()-1));
327 // Jump from the catch into the try is not allowed either.
328 for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) {
329 CXXCatchStmt *CS = TS->getHandler(I);
330 Scopes.push_back(GotoScope(ParentScope,
331 diag::note_protected_by_cxx_catch,
332 diag::note_exits_cxx_catch,
333 CS->getSourceRange().getBegin()));
334 BuildScopeInformation(CS->getHandlerBlock(),
335 (newParentScope = Scopes.size()-1));
344 for (Stmt::child_range CI = S->children(); CI; ++CI) {
345 if (SkipFirstSubStmt) {
346 SkipFirstSubStmt = false;
351 if (!SubStmt) continue;
353 // Cases, labels, and defaults aren't "scope parents". It's also
354 // important to handle these iteratively instead of recursively in
355 // order to avoid blowing out the stack.
358 if (CaseStmt *CS = dyn_cast<CaseStmt>(SubStmt))
359 Next = CS->getSubStmt();
360 else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SubStmt))
361 Next = DS->getSubStmt();
362 else if (LabelStmt *LS = dyn_cast<LabelStmt>(SubStmt))
363 Next = LS->getSubStmt();
367 LabelAndGotoScopes[SubStmt] = ParentScope;
371 // If this is a declstmt with a VLA definition, it defines a scope from here
372 // to the end of the containing context.
373 if (DeclStmt *DS = dyn_cast<DeclStmt>(SubStmt)) {
374 // The decl statement creates a scope if any of the decls in it are VLAs
375 // or have the cleanup attribute.
376 for (auto *I : DS->decls())
377 BuildScopeInformation(I, ParentScope);
380 // Disallow jumps into any part of an @try statement by pushing a scope and
381 // walking all sub-stmts in that scope.
382 if (ObjCAtTryStmt *AT = dyn_cast<ObjCAtTryStmt>(SubStmt)) {
383 unsigned newParentScope;
384 // Recursively walk the AST for the @try part.
385 Scopes.push_back(GotoScope(ParentScope,
386 diag::note_protected_by_objc_try,
387 diag::note_exits_objc_try,
389 if (Stmt *TryPart = AT->getTryBody())
390 BuildScopeInformation(TryPart, (newParentScope = Scopes.size()-1));
392 // Jump from the catch to the finally or try is not valid.
393 for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) {
394 ObjCAtCatchStmt *AC = AT->getCatchStmt(I);
395 Scopes.push_back(GotoScope(ParentScope,
396 diag::note_protected_by_objc_catch,
397 diag::note_exits_objc_catch,
398 AC->getAtCatchLoc()));
399 // @catches are nested and it isn't
400 BuildScopeInformation(AC->getCatchBody(),
401 (newParentScope = Scopes.size()-1));
404 // Jump from the finally to the try or catch is not valid.
405 if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
406 Scopes.push_back(GotoScope(ParentScope,
407 diag::note_protected_by_objc_finally,
408 diag::note_exits_objc_finally,
409 AF->getAtFinallyLoc()));
410 BuildScopeInformation(AF, (newParentScope = Scopes.size()-1));
416 unsigned newParentScope;
417 // Disallow jumps into the protected statement of an @synchronized, but
418 // allow jumps into the object expression it protects.
419 if (ObjCAtSynchronizedStmt *AS = dyn_cast<ObjCAtSynchronizedStmt>(SubStmt)){
420 // Recursively walk the AST for the @synchronized object expr, it is
421 // evaluated in the normal scope.
422 BuildScopeInformation(AS->getSynchExpr(), ParentScope);
424 // Recursively walk the AST for the @synchronized part, protected by a new
426 Scopes.push_back(GotoScope(ParentScope,
427 diag::note_protected_by_objc_synchronized,
428 diag::note_exits_objc_synchronized,
429 AS->getAtSynchronizedLoc()));
430 BuildScopeInformation(AS->getSynchBody(),
431 (newParentScope = Scopes.size()-1));
435 // Disallow jumps into the protected statement of an @autoreleasepool.
436 if (ObjCAutoreleasePoolStmt *AS = dyn_cast<ObjCAutoreleasePoolStmt>(SubStmt)){
437 // Recursively walk the AST for the @autoreleasepool part, protected by a new
439 Scopes.push_back(GotoScope(ParentScope,
440 diag::note_protected_by_objc_autoreleasepool,
441 diag::note_exits_objc_autoreleasepool,
443 BuildScopeInformation(AS->getSubStmt(), (newParentScope = Scopes.size()-1));
447 // Disallow jumps past full-expressions that use blocks with
448 // non-trivial cleanups of their captures. This is theoretically
449 // implementable but a lot of work which we haven't felt up to doing.
450 if (ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(SubStmt)) {
451 for (unsigned i = 0, e = EWC->getNumObjects(); i != e; ++i) {
452 const BlockDecl *BDecl = EWC->getObject(i);
453 for (const auto &CI : BDecl->captures()) {
454 VarDecl *variable = CI.getVariable();
455 BuildScopeInformation(variable, BDecl, ParentScope);
460 // Disallow jumps out of scopes containing temporaries lifetime-extended to
461 // automatic storage duration.
462 if (MaterializeTemporaryExpr *MTE =
463 dyn_cast<MaterializeTemporaryExpr>(SubStmt)) {
464 if (MTE->getStorageDuration() == SD_Automatic) {
465 SmallVector<const Expr *, 4> CommaLHS;
466 SmallVector<SubobjectAdjustment, 4> Adjustments;
467 const Expr *ExtendedObject =
468 MTE->GetTemporaryExpr()->skipRValueSubobjectAdjustments(
469 CommaLHS, Adjustments);
470 if (ExtendedObject->getType().isDestructedType()) {
471 Scopes.push_back(GotoScope(ParentScope, 0,
472 diag::note_exits_temporary_dtor,
473 ExtendedObject->getExprLoc()));
474 ParentScope = Scopes.size()-1;
479 // Recursively walk the AST.
480 BuildScopeInformation(SubStmt, ParentScope);
484 /// VerifyJumps - Verify each element of the Jumps array to see if they are
485 /// valid, emitting diagnostics if not.
486 void JumpScopeChecker::VerifyJumps() {
487 while (!Jumps.empty()) {
488 Stmt *Jump = Jumps.pop_back_val();
491 if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
492 CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(),
493 diag::err_goto_into_protected_scope,
494 diag::ext_goto_into_protected_scope,
495 diag::warn_cxx98_compat_goto_into_protected_scope);
499 // We only get indirect gotos here when they have a constant target.
500 if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) {
501 LabelDecl *Target = IGS->getConstantTarget();
502 CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(),
503 diag::err_goto_into_protected_scope,
504 diag::ext_goto_into_protected_scope,
505 diag::warn_cxx98_compat_goto_into_protected_scope);
509 SwitchStmt *SS = cast<SwitchStmt>(Jump);
510 for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
511 SC = SC->getNextSwitchCase()) {
512 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(SC)))
515 if (CaseStmt *CS = dyn_cast<CaseStmt>(SC))
516 Loc = CS->getLocStart();
517 else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC))
518 Loc = DS->getLocStart();
520 Loc = SC->getLocStart();
521 CheckJump(SS, SC, Loc, diag::err_switch_into_protected_scope, 0,
522 diag::warn_cxx98_compat_switch_into_protected_scope);
527 /// VerifyIndirectJumps - Verify whether any possible indirect jump
528 /// might cross a protection boundary. Unlike direct jumps, indirect
529 /// jumps count cleanups as protection boundaries: since there's no
530 /// way to know where the jump is going, we can't implicitly run the
531 /// right cleanups the way we can with direct jumps.
533 /// Thus, an indirect jump is "trivial" if it bypasses no
534 /// initializations and no teardowns. More formally, an indirect jump
535 /// from A to B is trivial if the path out from A to DCA(A,B) is
536 /// trivial and the path in from DCA(A,B) to B is trivial, where
537 /// DCA(A,B) is the deepest common ancestor of A and B.
538 /// Jump-triviality is transitive but asymmetric.
540 /// A path in is trivial if none of the entered scopes have an InDiag.
541 /// A path out is trivial is none of the exited scopes have an OutDiag.
543 /// Under these definitions, this function checks that the indirect
544 /// jump between A and B is trivial for every indirect goto statement A
545 /// and every label B whose address was taken in the function.
546 void JumpScopeChecker::VerifyIndirectJumps() {
547 if (IndirectJumps.empty()) return;
549 // If there aren't any address-of-label expressions in this function,
550 // complain about the first indirect goto.
551 if (IndirectJumpTargets.empty()) {
552 S.Diag(IndirectJumps[0]->getGotoLoc(),
553 diag::err_indirect_goto_without_addrlabel);
557 // Collect a single representative of every scope containing an
558 // indirect goto. For most code bases, this substantially cuts
559 // down on the number of jump sites we'll have to consider later.
560 typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope;
561 SmallVector<JumpScope, 32> JumpScopes;
563 llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap;
564 for (SmallVectorImpl<IndirectGotoStmt*>::iterator
565 I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) {
566 IndirectGotoStmt *IG = *I;
567 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(IG)))
569 unsigned IGScope = LabelAndGotoScopes[IG];
570 IndirectGotoStmt *&Entry = JumpScopesMap[IGScope];
571 if (!Entry) Entry = IG;
573 JumpScopes.reserve(JumpScopesMap.size());
574 for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator
575 I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I)
576 JumpScopes.push_back(*I);
579 // Collect a single representative of every scope containing a
580 // label whose address was taken somewhere in the function.
581 // For most code bases, there will be only one such scope.
582 llvm::DenseMap<unsigned, LabelDecl*> TargetScopes;
583 for (SmallVectorImpl<LabelDecl*>::iterator
584 I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end();
586 LabelDecl *TheLabel = *I;
587 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(TheLabel->getStmt())))
589 unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()];
590 LabelDecl *&Target = TargetScopes[LabelScope];
591 if (!Target) Target = TheLabel;
594 // For each target scope, make sure it's trivially reachable from
595 // every scope containing a jump site.
597 // A path between scopes always consists of exitting zero or more
598 // scopes, then entering zero or more scopes. We build a set of
599 // of scopes S from which the target scope can be trivially
600 // entered, then verify that every jump scope can be trivially
601 // exitted to reach a scope in S.
602 llvm::BitVector Reachable(Scopes.size(), false);
603 for (llvm::DenseMap<unsigned,LabelDecl*>::iterator
604 TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) {
605 unsigned TargetScope = TI->first;
606 LabelDecl *TargetLabel = TI->second;
610 // Mark all the enclosing scopes from which you can safely jump
611 // into the target scope. 'Min' will end up being the index of
612 // the shallowest such scope.
613 unsigned Min = TargetScope;
617 // Don't go beyond the outermost scope.
620 // Stop if we can't trivially enter the current scope.
621 if (Scopes[Min].InDiag) break;
623 Min = Scopes[Min].ParentScope;
626 // Walk through all the jump sites, checking that they can trivially
627 // reach this label scope.
628 for (SmallVectorImpl<JumpScope>::iterator
629 I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) {
630 unsigned Scope = I->first;
632 // Walk out the "scope chain" for this scope, looking for a scope
633 // we've marked reachable. For well-formed code this amortizes
634 // to O(JumpScopes.size() / Scopes.size()): we only iterate
635 // when we see something unmarked, and in well-formed code we
636 // mark everything we iterate past.
637 bool IsReachable = false;
639 if (Reachable.test(Scope)) {
640 // If we find something reachable, mark all the scopes we just
641 // walked through as reachable.
642 for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope)
648 // Don't walk out if we've reached the top-level scope or we've
649 // gotten shallower than the shallowest reachable scope.
650 if (Scope == 0 || Scope < Min) break;
652 // Don't walk out through an out-diagnostic.
653 if (Scopes[Scope].OutDiag) break;
655 Scope = Scopes[Scope].ParentScope;
658 // Only diagnose if we didn't find something.
659 if (IsReachable) continue;
661 DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope);
666 /// Return true if a particular error+note combination must be downgraded to a
667 /// warning in Microsoft mode.
668 static bool IsMicrosoftJumpWarning(unsigned JumpDiag, unsigned InDiagNote) {
669 return (JumpDiag == diag::err_goto_into_protected_scope &&
670 (InDiagNote == diag::note_protected_by_variable_init ||
671 InDiagNote == diag::note_protected_by_variable_nontriv_destructor));
674 /// Return true if a particular note should be downgraded to a compatibility
675 /// warning in C++11 mode.
676 static bool IsCXX98CompatWarning(Sema &S, unsigned InDiagNote) {
677 return S.getLangOpts().CPlusPlus11 &&
678 InDiagNote == diag::note_protected_by_variable_non_pod;
681 /// Produce primary diagnostic for an indirect jump statement.
682 static void DiagnoseIndirectJumpStmt(Sema &S, IndirectGotoStmt *Jump,
683 LabelDecl *Target, bool &Diagnosed) {
686 S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
687 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
691 /// Produce note diagnostics for a jump into a protected scope.
692 void JumpScopeChecker::NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes) {
693 if (CHECK_PERMISSIVE(ToScopes.empty()))
695 for (unsigned I = 0, E = ToScopes.size(); I != E; ++I)
696 if (Scopes[ToScopes[I]].InDiag)
697 S.Diag(Scopes[ToScopes[I]].Loc, Scopes[ToScopes[I]].InDiag);
700 /// Diagnose an indirect jump which is known to cross scopes.
701 void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump,
704 unsigned TargetScope) {
705 if (CHECK_PERMISSIVE(JumpScope == TargetScope))
708 unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope);
709 bool Diagnosed = false;
711 // Walk out the scope chain until we reach the common ancestor.
712 for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope)
713 if (Scopes[I].OutDiag) {
714 DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
715 S.Diag(Scopes[I].Loc, Scopes[I].OutDiag);
718 SmallVector<unsigned, 10> ToScopesCXX98Compat;
720 // Now walk into the scopes containing the label whose address was taken.
721 for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope)
722 if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
723 ToScopesCXX98Compat.push_back(I);
724 else if (Scopes[I].InDiag) {
725 DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
726 S.Diag(Scopes[I].Loc, Scopes[I].InDiag);
729 // Diagnose this jump if it would be ill-formed in C++98.
730 if (!Diagnosed && !ToScopesCXX98Compat.empty()) {
731 S.Diag(Jump->getGotoLoc(),
732 diag::warn_cxx98_compat_indirect_goto_in_protected_scope);
733 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
734 NoteJumpIntoScopes(ToScopesCXX98Compat);
738 /// CheckJump - Validate that the specified jump statement is valid: that it is
739 /// jumping within or out of its current scope, not into a deeper one.
740 void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
741 unsigned JumpDiagError, unsigned JumpDiagWarning,
742 unsigned JumpDiagCXX98Compat) {
743 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(From)))
745 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(To)))
748 unsigned FromScope = LabelAndGotoScopes[From];
749 unsigned ToScope = LabelAndGotoScopes[To];
751 // Common case: exactly the same scope, which is fine.
752 if (FromScope == ToScope) return;
754 unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope);
756 // It's okay to jump out from a nested scope.
757 if (CommonScope == ToScope) return;
759 // Pull out (and reverse) any scopes we might need to diagnose skipping.
760 SmallVector<unsigned, 10> ToScopesCXX98Compat;
761 SmallVector<unsigned, 10> ToScopesError;
762 SmallVector<unsigned, 10> ToScopesWarning;
763 for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope) {
764 if (S.getLangOpts().MSVCCompat && JumpDiagWarning != 0 &&
765 IsMicrosoftJumpWarning(JumpDiagError, Scopes[I].InDiag))
766 ToScopesWarning.push_back(I);
767 else if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
768 ToScopesCXX98Compat.push_back(I);
769 else if (Scopes[I].InDiag)
770 ToScopesError.push_back(I);
774 if (!ToScopesWarning.empty()) {
775 S.Diag(DiagLoc, JumpDiagWarning);
776 NoteJumpIntoScopes(ToScopesWarning);
780 if (!ToScopesError.empty()) {
781 S.Diag(DiagLoc, JumpDiagError);
782 NoteJumpIntoScopes(ToScopesError);
785 // Handle -Wc++98-compat warnings if the jump is well-formed.
786 if (ToScopesError.empty() && !ToScopesCXX98Compat.empty()) {
787 S.Diag(DiagLoc, JumpDiagCXX98Compat);
788 NoteJumpIntoScopes(ToScopesCXX98Compat);
792 void Sema::DiagnoseInvalidJumps(Stmt *Body) {
793 (void)JumpScopeChecker(Body, *this);