JumpDiagnostics.cpp revision 226633
1//===--- JumpDiagnostics.cpp - Protected scope jump analysis ------*- C++ -*-=//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the JumpScopeChecker class, which is used to diagnose
11// jumps that enter a protected scope in an invalid way.
12//
13//===----------------------------------------------------------------------===//
14
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/StmtObjC.h"
20#include "clang/AST/StmtCXX.h"
21#include "llvm/ADT/BitVector.h"
22using namespace clang;
23
24namespace {
25
26/// JumpScopeChecker - This object is used by Sema to diagnose invalid jumps
27/// into VLA and other protected scopes.  For example, this rejects:
28///    goto L;
29///    int a[n];
30///  L:
31///
32class JumpScopeChecker {
33  Sema &S;
34
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.
40  struct GotoScope {
41    /// ParentScope - The index in ScopeMap of the parent scope.  This is 0 for
42    /// the parent scope is the function body.
43    unsigned ParentScope;
44
45    /// InDiag - The diagnostic to emit if there is a jump into this scope.
46    unsigned InDiag;
47
48    /// OutDiag - The diagnostic 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.
51    unsigned OutDiag;
52
53    /// Loc - Location to emit the diagnostic.
54    SourceLocation Loc;
55
56    GotoScope(unsigned parentScope, unsigned InDiag, unsigned OutDiag,
57              SourceLocation L)
58      : ParentScope(parentScope), InDiag(InDiag), OutDiag(OutDiag), Loc(L) {}
59  };
60
61  SmallVector<GotoScope, 48> Scopes;
62  llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
63  SmallVector<Stmt*, 16> Jumps;
64
65  SmallVector<IndirectGotoStmt*, 4> IndirectJumps;
66  SmallVector<LabelDecl*, 4> IndirectJumpTargets;
67public:
68  JumpScopeChecker(Stmt *Body, Sema &S);
69private:
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);
74
75  void VerifyJumps();
76  void VerifyIndirectJumps();
77  void DiagnoseIndirectJump(IndirectGotoStmt *IG, unsigned IGScope,
78                            LabelDecl *Target, unsigned TargetScope);
79  void CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
80                 unsigned JumpDiag, unsigned JumpDiagWarning);
81
82  unsigned GetDeepestCommonScope(unsigned A, unsigned B);
83};
84} // end anonymous namespace
85
86
87JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s) : S(s) {
88  // Add a scope entry for function scope.
89  Scopes.push_back(GotoScope(~0U, ~0U, ~0U, SourceLocation()));
90
91  // Build information for the top level compound statement, so that we have a
92  // defined scope record for every "goto" and label.
93  unsigned BodyParentScope = 0;
94  BuildScopeInformation(Body, BodyParentScope);
95
96  // Check that all jumps we saw are kosher.
97  VerifyJumps();
98  VerifyIndirectJumps();
99}
100
101/// GetDeepestCommonScope - Finds the innermost scope enclosing the
102/// two scopes.
103unsigned JumpScopeChecker::GetDeepestCommonScope(unsigned A, unsigned B) {
104  while (A != B) {
105    // Inner scopes are created after outer scopes and therefore have
106    // higher indices.
107    if (A < B) {
108      assert(Scopes[B].ParentScope < B);
109      B = Scopes[B].ParentScope;
110    } else {
111      assert(Scopes[A].ParentScope < A);
112      A = Scopes[A].ParentScope;
113    }
114  }
115  return A;
116}
117
118typedef std::pair<unsigned,unsigned> ScopePair;
119
120/// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a
121/// diagnostic that should be emitted if control goes over it. If not, return 0.
122static ScopePair GetDiagForGotoScopeDecl(ASTContext &Context, const Decl *D) {
123  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
124    unsigned InDiag = 0, OutDiag = 0;
125    if (VD->getType()->isVariablyModifiedType())
126      InDiag = diag::note_protected_by_vla;
127
128    if (VD->hasAttr<BlocksAttr>())
129      return ScopePair(diag::note_protected_by___block,
130                       diag::note_exits___block);
131
132    if (VD->hasAttr<CleanupAttr>())
133      return ScopePair(diag::note_protected_by_cleanup,
134                       diag::note_exits_cleanup);
135
136    if (Context.getLangOptions().ObjCAutoRefCount && VD->hasLocalStorage()) {
137      switch (VD->getType().getObjCLifetime()) {
138      case Qualifiers::OCL_None:
139      case Qualifiers::OCL_ExplicitNone:
140      case Qualifiers::OCL_Autoreleasing:
141        break;
142
143      case Qualifiers::OCL_Strong:
144      case Qualifiers::OCL_Weak:
145        return ScopePair(diag::note_protected_by_objc_ownership,
146                         diag::note_exits_objc_ownership);
147      }
148    }
149
150    if (Context.getLangOptions().CPlusPlus && VD->hasLocalStorage()) {
151      // C++0x [stmt.dcl]p3:
152      //   A program that jumps from a point where a variable with automatic
153      //   storage duration is not in scope to a point where it is in scope
154      //   is ill-formed unless the variable has scalar type, class type with
155      //   a trivial default constructor and a trivial destructor, a
156      //   cv-qualified version of one of these types, or an array of one of
157      //   the preceding types and is declared without an initializer.
158
159      // C++03 [stmt.dcl.p3:
160      //   A program that jumps from a point where a local variable
161      //   with automatic storage duration is not in scope to a point
162      //   where it is in scope is ill-formed unless the variable has
163      //   POD type and is declared without an initializer.
164
165      if (const Expr *init = VD->getInit()) {
166        // We actually give variables of record type (or array thereof)
167        // an initializer even if that initializer only calls a trivial
168        // ctor.  Detect that case.
169        // FIXME: With generalized initializer lists, this may
170        // classify "X x{};" as having no initializer.
171        unsigned inDiagToUse = diag::note_protected_by_variable_init;
172
173        const CXXRecordDecl *record = 0;
174
175        if (const CXXConstructExpr *cce = dyn_cast<CXXConstructExpr>(init)) {
176          const CXXConstructorDecl *ctor = cce->getConstructor();
177          record = ctor->getParent();
178
179          if (ctor->isTrivial() && ctor->isDefaultConstructor()) {
180            if (Context.getLangOptions().CPlusPlus0x) {
181              inDiagToUse = (record->hasTrivialDestructor() ? 0 :
182                        diag::note_protected_by_variable_nontriv_destructor);
183            } else {
184              if (record->isPOD())
185                inDiagToUse = 0;
186            }
187          }
188        } else if (VD->getType()->isArrayType()) {
189          record = VD->getType()->getBaseElementTypeUnsafe()
190                                ->getAsCXXRecordDecl();
191        }
192
193        if (inDiagToUse)
194          InDiag = inDiagToUse;
195
196        // Also object to indirect jumps which leave scopes with dtors.
197        if (record && !record->hasTrivialDestructor())
198          OutDiag = diag::note_exits_dtor;
199      }
200    }
201
202    return ScopePair(InDiag, OutDiag);
203  }
204
205  if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
206    if (TD->getUnderlyingType()->isVariablyModifiedType())
207      return ScopePair(diag::note_protected_by_vla_typedef, 0);
208  }
209
210  if (const TypeAliasDecl *TD = dyn_cast<TypeAliasDecl>(D)) {
211    if (TD->getUnderlyingType()->isVariablyModifiedType())
212      return ScopePair(diag::note_protected_by_vla_type_alias, 0);
213  }
214
215  return ScopePair(0U, 0U);
216}
217
218/// \brief Build scope information for a declaration that is part of a DeclStmt.
219void JumpScopeChecker::BuildScopeInformation(Decl *D, unsigned &ParentScope) {
220  // If this decl causes a new scope, push and switch to it.
221  std::pair<unsigned,unsigned> Diags = GetDiagForGotoScopeDecl(S.Context, D);
222  if (Diags.first || Diags.second) {
223    Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second,
224                               D->getLocation()));
225    ParentScope = Scopes.size()-1;
226  }
227
228  // If the decl has an initializer, walk it with the potentially new
229  // scope we just installed.
230  if (VarDecl *VD = dyn_cast<VarDecl>(D))
231    if (Expr *Init = VD->getInit())
232      BuildScopeInformation(Init, ParentScope);
233}
234
235/// \brief Build scope information for a captured block literal variables.
236void JumpScopeChecker::BuildScopeInformation(VarDecl *D,
237                                             const BlockDecl *BDecl,
238                                             unsigned &ParentScope) {
239  // exclude captured __block variables; there's no destructor
240  // associated with the block literal for them.
241  if (D->hasAttr<BlocksAttr>())
242    return;
243  QualType T = D->getType();
244  QualType::DestructionKind destructKind = T.isDestructedType();
245  if (destructKind != QualType::DK_none) {
246    std::pair<unsigned,unsigned> Diags;
247    switch (destructKind) {
248      case QualType::DK_cxx_destructor:
249        Diags = ScopePair(diag::note_enters_block_captures_cxx_obj,
250                          diag::note_exits_block_captures_cxx_obj);
251        break;
252      case QualType::DK_objc_strong_lifetime:
253        Diags = ScopePair(diag::note_enters_block_captures_strong,
254                          diag::note_exits_block_captures_strong);
255        break;
256      case QualType::DK_objc_weak_lifetime:
257        Diags = ScopePair(diag::note_enters_block_captures_weak,
258                          diag::note_exits_block_captures_weak);
259        break;
260      case QualType::DK_none:
261        llvm_unreachable("no-liftime captured variable");
262    }
263    SourceLocation Loc = D->getLocation();
264    if (Loc.isInvalid())
265      Loc = BDecl->getLocation();
266    Scopes.push_back(GotoScope(ParentScope,
267                               Diags.first, Diags.second, Loc));
268    ParentScope = Scopes.size()-1;
269  }
270}
271
272/// BuildScopeInformation - The statements from CI to CE are known to form a
273/// coherent VLA scope with a specified parent node.  Walk through the
274/// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
275/// walking the AST as needed.
276void JumpScopeChecker::BuildScopeInformation(Stmt *S, unsigned &origParentScope) {
277  // If this is a statement, rather than an expression, scopes within it don't
278  // propagate out into the enclosing scope.  Otherwise we have to worry
279  // about block literals, which have the lifetime of their enclosing statement.
280  unsigned independentParentScope = origParentScope;
281  unsigned &ParentScope = ((isa<Expr>(S) && !isa<StmtExpr>(S))
282                            ? origParentScope : independentParentScope);
283
284  bool SkipFirstSubStmt = false;
285
286  // If we found a label, remember that it is in ParentScope scope.
287  switch (S->getStmtClass()) {
288  case Stmt::AddrLabelExprClass:
289    IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel());
290    break;
291
292  case Stmt::IndirectGotoStmtClass:
293    // "goto *&&lbl;" is a special case which we treat as equivalent
294    // to a normal goto.  In addition, we don't calculate scope in the
295    // operand (to avoid recording the address-of-label use), which
296    // works only because of the restricted set of expressions which
297    // we detect as constant targets.
298    if (cast<IndirectGotoStmt>(S)->getConstantTarget()) {
299      LabelAndGotoScopes[S] = ParentScope;
300      Jumps.push_back(S);
301      return;
302    }
303
304    LabelAndGotoScopes[S] = ParentScope;
305    IndirectJumps.push_back(cast<IndirectGotoStmt>(S));
306    break;
307
308  case Stmt::SwitchStmtClass:
309    // Evaluate the condition variable before entering the scope of the switch
310    // statement.
311    if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) {
312      BuildScopeInformation(Var, ParentScope);
313      SkipFirstSubStmt = true;
314    }
315    // Fall through
316
317  case Stmt::GotoStmtClass:
318    // Remember both what scope a goto is in as well as the fact that we have
319    // it.  This makes the second scan not have to walk the AST again.
320    LabelAndGotoScopes[S] = ParentScope;
321    Jumps.push_back(S);
322    break;
323
324  default:
325    break;
326  }
327
328  for (Stmt::child_range CI = S->children(); CI; ++CI) {
329    if (SkipFirstSubStmt) {
330      SkipFirstSubStmt = false;
331      continue;
332    }
333
334    Stmt *SubStmt = *CI;
335    if (SubStmt == 0) continue;
336
337    // Cases, labels, and defaults aren't "scope parents".  It's also
338    // important to handle these iteratively instead of recursively in
339    // order to avoid blowing out the stack.
340    while (true) {
341      Stmt *Next;
342      if (CaseStmt *CS = dyn_cast<CaseStmt>(SubStmt))
343        Next = CS->getSubStmt();
344      else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SubStmt))
345        Next = DS->getSubStmt();
346      else if (LabelStmt *LS = dyn_cast<LabelStmt>(SubStmt))
347        Next = LS->getSubStmt();
348      else
349        break;
350
351      LabelAndGotoScopes[SubStmt] = ParentScope;
352      SubStmt = Next;
353    }
354
355    // If this is a declstmt with a VLA definition, it defines a scope from here
356    // to the end of the containing context.
357    if (DeclStmt *DS = dyn_cast<DeclStmt>(SubStmt)) {
358      // The decl statement creates a scope if any of the decls in it are VLAs
359      // or have the cleanup attribute.
360      for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
361           I != E; ++I)
362        BuildScopeInformation(*I, ParentScope);
363      continue;
364    }
365    // Disallow jumps into any part of an @try statement by pushing a scope and
366    // walking all sub-stmts in that scope.
367    if (ObjCAtTryStmt *AT = dyn_cast<ObjCAtTryStmt>(SubStmt)) {
368      unsigned newParentScope;
369      // Recursively walk the AST for the @try part.
370      Scopes.push_back(GotoScope(ParentScope,
371                                 diag::note_protected_by_objc_try,
372                                 diag::note_exits_objc_try,
373                                 AT->getAtTryLoc()));
374      if (Stmt *TryPart = AT->getTryBody())
375        BuildScopeInformation(TryPart, (newParentScope = Scopes.size()-1));
376
377      // Jump from the catch to the finally or try is not valid.
378      for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) {
379        ObjCAtCatchStmt *AC = AT->getCatchStmt(I);
380        Scopes.push_back(GotoScope(ParentScope,
381                                   diag::note_protected_by_objc_catch,
382                                   diag::note_exits_objc_catch,
383                                   AC->getAtCatchLoc()));
384        // @catches are nested and it isn't
385        BuildScopeInformation(AC->getCatchBody(),
386                              (newParentScope = Scopes.size()-1));
387      }
388
389      // Jump from the finally to the try or catch is not valid.
390      if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
391        Scopes.push_back(GotoScope(ParentScope,
392                                   diag::note_protected_by_objc_finally,
393                                   diag::note_exits_objc_finally,
394                                   AF->getAtFinallyLoc()));
395        BuildScopeInformation(AF, (newParentScope = Scopes.size()-1));
396      }
397
398      continue;
399    }
400
401    unsigned newParentScope;
402    // Disallow jumps into the protected statement of an @synchronized, but
403    // allow jumps into the object expression it protects.
404    if (ObjCAtSynchronizedStmt *AS = dyn_cast<ObjCAtSynchronizedStmt>(SubStmt)){
405      // Recursively walk the AST for the @synchronized object expr, it is
406      // evaluated in the normal scope.
407      BuildScopeInformation(AS->getSynchExpr(), ParentScope);
408
409      // Recursively walk the AST for the @synchronized part, protected by a new
410      // scope.
411      Scopes.push_back(GotoScope(ParentScope,
412                                 diag::note_protected_by_objc_synchronized,
413                                 diag::note_exits_objc_synchronized,
414                                 AS->getAtSynchronizedLoc()));
415      BuildScopeInformation(AS->getSynchBody(),
416                            (newParentScope = Scopes.size()-1));
417      continue;
418    }
419
420    // Disallow jumps into any part of a C++ try statement. This is pretty
421    // much the same as for Obj-C.
422    if (CXXTryStmt *TS = dyn_cast<CXXTryStmt>(SubStmt)) {
423      Scopes.push_back(GotoScope(ParentScope,
424                                 diag::note_protected_by_cxx_try,
425                                 diag::note_exits_cxx_try,
426                                 TS->getSourceRange().getBegin()));
427      if (Stmt *TryBlock = TS->getTryBlock())
428        BuildScopeInformation(TryBlock, (newParentScope = Scopes.size()-1));
429
430      // Jump from the catch into the try is not allowed either.
431      for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) {
432        CXXCatchStmt *CS = TS->getHandler(I);
433        Scopes.push_back(GotoScope(ParentScope,
434                                   diag::note_protected_by_cxx_catch,
435                                   diag::note_exits_cxx_catch,
436                                   CS->getSourceRange().getBegin()));
437        BuildScopeInformation(CS->getHandlerBlock(),
438                              (newParentScope = Scopes.size()-1));
439      }
440
441      continue;
442    }
443
444    // Disallow jumps into the protected statement of an @autoreleasepool.
445    if (ObjCAutoreleasePoolStmt *AS = dyn_cast<ObjCAutoreleasePoolStmt>(SubStmt)){
446      // Recursively walk the AST for the @autoreleasepool part, protected by a new
447      // scope.
448      Scopes.push_back(GotoScope(ParentScope,
449                                 diag::note_protected_by_objc_autoreleasepool,
450                                 diag::note_exits_objc_autoreleasepool,
451                                 AS->getAtLoc()));
452      BuildScopeInformation(AS->getSubStmt(), (newParentScope = Scopes.size()-1));
453      continue;
454    }
455
456    if (const BlockExpr *BE = dyn_cast<BlockExpr>(SubStmt)) {
457        const BlockDecl *BDecl = BE->getBlockDecl();
458        for (BlockDecl::capture_const_iterator ci = BDecl->capture_begin(),
459             ce = BDecl->capture_end(); ci != ce; ++ci) {
460          VarDecl *variable = ci->getVariable();
461          BuildScopeInformation(variable, BDecl, ParentScope);
462        }
463    }
464
465    // Recursively walk the AST.
466    BuildScopeInformation(SubStmt, ParentScope);
467  }
468}
469
470/// VerifyJumps - Verify each element of the Jumps array to see if they are
471/// valid, emitting diagnostics if not.
472void JumpScopeChecker::VerifyJumps() {
473  while (!Jumps.empty()) {
474    Stmt *Jump = Jumps.pop_back_val();
475
476    // With a goto,
477    if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
478      CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(),
479                diag::err_goto_into_protected_scope,
480                diag::warn_goto_into_protected_scope);
481      continue;
482    }
483
484    // We only get indirect gotos here when they have a constant target.
485    if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) {
486      LabelDecl *Target = IGS->getConstantTarget();
487      CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(),
488                diag::err_goto_into_protected_scope,
489                diag::warn_goto_into_protected_scope);
490      continue;
491    }
492
493    SwitchStmt *SS = cast<SwitchStmt>(Jump);
494    for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
495         SC = SC->getNextSwitchCase()) {
496      assert(LabelAndGotoScopes.count(SC) && "Case not visited?");
497      CheckJump(SS, SC, SC->getLocStart(),
498                diag::err_switch_into_protected_scope, 0);
499    }
500  }
501}
502
503/// VerifyIndirectJumps - Verify whether any possible indirect jump
504/// might cross a protection boundary.  Unlike direct jumps, indirect
505/// jumps count cleanups as protection boundaries:  since there's no
506/// way to know where the jump is going, we can't implicitly run the
507/// right cleanups the way we can with direct jumps.
508///
509/// Thus, an indirect jump is "trivial" if it bypasses no
510/// initializations and no teardowns.  More formally, an indirect jump
511/// from A to B is trivial if the path out from A to DCA(A,B) is
512/// trivial and the path in from DCA(A,B) to B is trivial, where
513/// DCA(A,B) is the deepest common ancestor of A and B.
514/// Jump-triviality is transitive but asymmetric.
515///
516/// A path in is trivial if none of the entered scopes have an InDiag.
517/// A path out is trivial is none of the exited scopes have an OutDiag.
518///
519/// Under these definitions, this function checks that the indirect
520/// jump between A and B is trivial for every indirect goto statement A
521/// and every label B whose address was taken in the function.
522void JumpScopeChecker::VerifyIndirectJumps() {
523  if (IndirectJumps.empty()) return;
524
525  // If there aren't any address-of-label expressions in this function,
526  // complain about the first indirect goto.
527  if (IndirectJumpTargets.empty()) {
528    S.Diag(IndirectJumps[0]->getGotoLoc(),
529           diag::err_indirect_goto_without_addrlabel);
530    return;
531  }
532
533  // Collect a single representative of every scope containing an
534  // indirect goto.  For most code bases, this substantially cuts
535  // down on the number of jump sites we'll have to consider later.
536  typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope;
537  SmallVector<JumpScope, 32> JumpScopes;
538  {
539    llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap;
540    for (SmallVectorImpl<IndirectGotoStmt*>::iterator
541           I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) {
542      IndirectGotoStmt *IG = *I;
543      assert(LabelAndGotoScopes.count(IG) &&
544             "indirect jump didn't get added to scopes?");
545      unsigned IGScope = LabelAndGotoScopes[IG];
546      IndirectGotoStmt *&Entry = JumpScopesMap[IGScope];
547      if (!Entry) Entry = IG;
548    }
549    JumpScopes.reserve(JumpScopesMap.size());
550    for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator
551           I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I)
552      JumpScopes.push_back(*I);
553  }
554
555  // Collect a single representative of every scope containing a
556  // label whose address was taken somewhere in the function.
557  // For most code bases, there will be only one such scope.
558  llvm::DenseMap<unsigned, LabelDecl*> TargetScopes;
559  for (SmallVectorImpl<LabelDecl*>::iterator
560         I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end();
561       I != E; ++I) {
562    LabelDecl *TheLabel = *I;
563    assert(LabelAndGotoScopes.count(TheLabel->getStmt()) &&
564           "Referenced label didn't get added to scopes?");
565    unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()];
566    LabelDecl *&Target = TargetScopes[LabelScope];
567    if (!Target) Target = TheLabel;
568  }
569
570  // For each target scope, make sure it's trivially reachable from
571  // every scope containing a jump site.
572  //
573  // A path between scopes always consists of exitting zero or more
574  // scopes, then entering zero or more scopes.  We build a set of
575  // of scopes S from which the target scope can be trivially
576  // entered, then verify that every jump scope can be trivially
577  // exitted to reach a scope in S.
578  llvm::BitVector Reachable(Scopes.size(), false);
579  for (llvm::DenseMap<unsigned,LabelDecl*>::iterator
580         TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) {
581    unsigned TargetScope = TI->first;
582    LabelDecl *TargetLabel = TI->second;
583
584    Reachable.reset();
585
586    // Mark all the enclosing scopes from which you can safely jump
587    // into the target scope.  'Min' will end up being the index of
588    // the shallowest such scope.
589    unsigned Min = TargetScope;
590    while (true) {
591      Reachable.set(Min);
592
593      // Don't go beyond the outermost scope.
594      if (Min == 0) break;
595
596      // Stop if we can't trivially enter the current scope.
597      if (Scopes[Min].InDiag) break;
598
599      Min = Scopes[Min].ParentScope;
600    }
601
602    // Walk through all the jump sites, checking that they can trivially
603    // reach this label scope.
604    for (SmallVectorImpl<JumpScope>::iterator
605           I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) {
606      unsigned Scope = I->first;
607
608      // Walk out the "scope chain" for this scope, looking for a scope
609      // we've marked reachable.  For well-formed code this amortizes
610      // to O(JumpScopes.size() / Scopes.size()):  we only iterate
611      // when we see something unmarked, and in well-formed code we
612      // mark everything we iterate past.
613      bool IsReachable = false;
614      while (true) {
615        if (Reachable.test(Scope)) {
616          // If we find something reachable, mark all the scopes we just
617          // walked through as reachable.
618          for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope)
619            Reachable.set(S);
620          IsReachable = true;
621          break;
622        }
623
624        // Don't walk out if we've reached the top-level scope or we've
625        // gotten shallower than the shallowest reachable scope.
626        if (Scope == 0 || Scope < Min) break;
627
628        // Don't walk out through an out-diagnostic.
629        if (Scopes[Scope].OutDiag) break;
630
631        Scope = Scopes[Scope].ParentScope;
632      }
633
634      // Only diagnose if we didn't find something.
635      if (IsReachable) continue;
636
637      DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope);
638    }
639  }
640}
641
642/// Diagnose an indirect jump which is known to cross scopes.
643void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump,
644                                            unsigned JumpScope,
645                                            LabelDecl *Target,
646                                            unsigned TargetScope) {
647  assert(JumpScope != TargetScope);
648
649  S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
650  S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
651
652  unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope);
653
654  // Walk out the scope chain until we reach the common ancestor.
655  for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope)
656    if (Scopes[I].OutDiag)
657      S.Diag(Scopes[I].Loc, Scopes[I].OutDiag);
658
659  // Now walk into the scopes containing the label whose address was taken.
660  for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope)
661    if (Scopes[I].InDiag)
662      S.Diag(Scopes[I].Loc, Scopes[I].InDiag);
663}
664
665/// Return true if a particular error+note combination must be downgraded
666/// to a warning in Microsoft mode.
667static bool IsMicrosoftJumpWarning(unsigned JumpDiag, unsigned InDiagNote)
668{
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));
672}
673
674
675/// CheckJump - Validate that the specified jump statement is valid: that it is
676/// jumping within or out of its current scope, not into a deeper one.
677void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
678                             unsigned JumpDiagError, unsigned JumpDiagWarning) {
679  assert(LabelAndGotoScopes.count(From) && "Jump didn't get added to scopes?");
680  unsigned FromScope = LabelAndGotoScopes[From];
681
682  assert(LabelAndGotoScopes.count(To) && "Jump didn't get added to scopes?");
683  unsigned ToScope = LabelAndGotoScopes[To];
684
685  // Common case: exactly the same scope, which is fine.
686  if (FromScope == ToScope) return;
687
688  unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope);
689
690  // It's okay to jump out from a nested scope.
691  if (CommonScope == ToScope) return;
692
693  // Pull out (and reverse) any scopes we might need to diagnose skipping.
694  SmallVector<unsigned, 10> ToScopesError;
695  SmallVector<unsigned, 10> ToScopesWarning;
696  for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope) {
697    if (S.getLangOptions().MicrosoftMode && JumpDiagWarning != 0 &&
698        IsMicrosoftJumpWarning(JumpDiagError, Scopes[I].InDiag))
699      ToScopesWarning.push_back(I);
700    else if (Scopes[I].InDiag)
701      ToScopesError.push_back(I);
702  }
703
704  // Handle warnings.
705  if (!ToScopesWarning.empty()) {
706    S.Diag(DiagLoc, JumpDiagWarning);
707    for (unsigned i = 0, e = ToScopesWarning.size(); i != e; ++i)
708      S.Diag(Scopes[ToScopesWarning[i]].Loc, Scopes[ToScopesWarning[i]].InDiag);
709  }
710
711  // Handle errors.
712  if (!ToScopesError.empty()) {
713    S.Diag(DiagLoc, JumpDiagError);
714    // Emit diagnostics note for whatever is left in ToScopesError.
715    for (unsigned i = 0, e = ToScopesError.size(); i != e; ++i)
716      S.Diag(Scopes[ToScopesError[i]].Loc, Scopes[ToScopesError[i]].InDiag);
717  }
718}
719
720void Sema::DiagnoseInvalidJumps(Stmt *Body) {
721  (void)JumpScopeChecker(Body, *this);
722}
723