JumpDiagnostics.cpp revision 208600
1193326Sed//===--- JumpDiagnostics.cpp - Analyze Jump Targets for VLA issues --------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed// This file implements the JumpScopeChecker class, which is used to diagnose
11193326Sed// jumps that enter a VLA scope in an invalid way.
12193326Sed//
13193326Sed//===----------------------------------------------------------------------===//
14193326Sed
15208600Srdivacky#include "llvm/ADT/BitVector.h"
16193326Sed#include "Sema.h"
17193326Sed#include "clang/AST/Expr.h"
18193326Sed#include "clang/AST/StmtObjC.h"
19193326Sed#include "clang/AST/StmtCXX.h"
20193326Sedusing namespace clang;
21193326Sed
22193326Sednamespace {
23193326Sed
24193326Sed/// JumpScopeChecker - This object is used by Sema to diagnose invalid jumps
25193326Sed/// into VLA and other protected scopes.  For example, this rejects:
26193326Sed///    goto L;
27193326Sed///    int a[n];
28193326Sed///  L:
29193326Sed///
30193326Sedclass JumpScopeChecker {
31193326Sed  Sema &S;
32198092Srdivacky
33193326Sed  /// GotoScope - This is a record that we use to keep track of all of the
34193326Sed  /// scopes that are introduced by VLAs and other things that scope jumps like
35193326Sed  /// gotos.  This scope tree has nothing to do with the source scope tree,
36193326Sed  /// because you can have multiple VLA scopes per compound statement, and most
37193326Sed  /// compound statements don't introduce any scopes.
38193326Sed  struct GotoScope {
39193326Sed    /// ParentScope - The index in ScopeMap of the parent scope.  This is 0 for
40193326Sed    /// the parent scope is the function body.
41193326Sed    unsigned ParentScope;
42198092Srdivacky
43208600Srdivacky    /// InDiag - The diagnostic to emit if there is a jump into this scope.
44208600Srdivacky    unsigned InDiag;
45198092Srdivacky
46208600Srdivacky    /// OutDiag - The diagnostic to emit if there is an indirect jump out
47208600Srdivacky    /// of this scope.  Direct jumps always clean up their current scope
48208600Srdivacky    /// in an orderly way.
49208600Srdivacky    unsigned OutDiag;
50208600Srdivacky
51193326Sed    /// Loc - Location to emit the diagnostic.
52193326Sed    SourceLocation Loc;
53198092Srdivacky
54208600Srdivacky    GotoScope(unsigned parentScope, unsigned InDiag, unsigned OutDiag,
55208600Srdivacky              SourceLocation L)
56208600Srdivacky      : ParentScope(parentScope), InDiag(InDiag), OutDiag(OutDiag), Loc(L) {}
57193326Sed  };
58198092Srdivacky
59193326Sed  llvm::SmallVector<GotoScope, 48> Scopes;
60193326Sed  llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
61193326Sed  llvm::SmallVector<Stmt*, 16> Jumps;
62208600Srdivacky
63208600Srdivacky  llvm::SmallVector<IndirectGotoStmt*, 4> IndirectJumps;
64208600Srdivacky  llvm::SmallVector<LabelStmt*, 4> IndirectJumpTargets;
65193326Sedpublic:
66193326Sed  JumpScopeChecker(Stmt *Body, Sema &S);
67193326Sedprivate:
68193326Sed  void BuildScopeInformation(Stmt *S, unsigned ParentScope);
69193326Sed  void VerifyJumps();
70208600Srdivacky  void VerifyIndirectJumps();
71208600Srdivacky  void DiagnoseIndirectJump(IndirectGotoStmt *IG, unsigned IGScope,
72208600Srdivacky                            LabelStmt *Target, unsigned TargetScope);
73193326Sed  void CheckJump(Stmt *From, Stmt *To,
74193326Sed                 SourceLocation DiagLoc, unsigned JumpDiag);
75208600Srdivacky
76208600Srdivacky  unsigned GetDeepestCommonScope(unsigned A, unsigned B);
77193326Sed};
78193326Sed} // end anonymous namespace
79193326Sed
80193326Sed
81193326SedJumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s) : S(s) {
82193326Sed  // Add a scope entry for function scope.
83208600Srdivacky  Scopes.push_back(GotoScope(~0U, ~0U, ~0U, SourceLocation()));
84198092Srdivacky
85193326Sed  // Build information for the top level compound statement, so that we have a
86193326Sed  // defined scope record for every "goto" and label.
87193326Sed  BuildScopeInformation(Body, 0);
88198092Srdivacky
89193326Sed  // Check that all jumps we saw are kosher.
90193326Sed  VerifyJumps();
91208600Srdivacky  VerifyIndirectJumps();
92193326Sed}
93198092Srdivacky
94208600Srdivacky/// GetDeepestCommonScope - Finds the innermost scope enclosing the
95208600Srdivacky/// two scopes.
96208600Srdivackyunsigned JumpScopeChecker::GetDeepestCommonScope(unsigned A, unsigned B) {
97208600Srdivacky  while (A != B) {
98208600Srdivacky    // Inner scopes are created after outer scopes and therefore have
99208600Srdivacky    // higher indices.
100208600Srdivacky    if (A < B) {
101208600Srdivacky      assert(Scopes[B].ParentScope < B);
102208600Srdivacky      B = Scopes[B].ParentScope;
103208600Srdivacky    } else {
104208600Srdivacky      assert(Scopes[A].ParentScope < A);
105208600Srdivacky      A = Scopes[A].ParentScope;
106208600Srdivacky    }
107208600Srdivacky  }
108208600Srdivacky  return A;
109208600Srdivacky}
110208600Srdivacky
111193326Sed/// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a
112193326Sed/// diagnostic that should be emitted if control goes over it. If not, return 0.
113208600Srdivackystatic std::pair<unsigned,unsigned>
114208600Srdivacky    GetDiagForGotoScopeDecl(const Decl *D, bool isCPlusPlus) {
115193326Sed  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
116208600Srdivacky    unsigned InDiag = 0, OutDiag = 0;
117193326Sed    if (VD->getType()->isVariablyModifiedType())
118208600Srdivacky      InDiag = diag::note_protected_by_vla;
119208600Srdivacky
120208600Srdivacky    if (VD->hasAttr<BlocksAttr>()) {
121208600Srdivacky      InDiag = diag::note_protected_by___block;
122208600Srdivacky      OutDiag = diag::note_exits___block;
123208600Srdivacky    } else if (VD->hasAttr<CleanupAttr>()) {
124208600Srdivacky      InDiag = diag::note_protected_by_cleanup;
125208600Srdivacky      OutDiag = diag::note_exits_cleanup;
126208600Srdivacky    } else if (isCPlusPlus) {
127208600Srdivacky      // FIXME: In C++0x, we have to check more conditions than "did we
128208600Srdivacky      // just give it an initializer?". See 6.7p3.
129208600Srdivacky      if (VD->hasLocalStorage() && VD->hasInit())
130208600Srdivacky        InDiag = diag::note_protected_by_variable_init;
131208600Srdivacky
132208600Srdivacky      CanQualType T = VD->getType()->getCanonicalTypeUnqualified();
133208600Srdivacky      while (CanQual<ArrayType> AT = T->getAs<ArrayType>())
134208600Srdivacky        T = AT->getElementType();
135208600Srdivacky      if (CanQual<RecordType> RT = T->getAs<RecordType>())
136208600Srdivacky        if (!cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor())
137208600Srdivacky          OutDiag = diag::note_exits_dtor;
138208600Srdivacky    }
139204643Srdivacky
140208600Srdivacky    return std::make_pair(InDiag, OutDiag);
141208600Srdivacky  }
142208600Srdivacky
143208600Srdivacky  if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
144193326Sed    if (TD->getUnderlyingType()->isVariablyModifiedType())
145208600Srdivacky      return std::make_pair((unsigned) diag::note_protected_by_vla_typedef, 0);
146193326Sed  }
147198092Srdivacky
148208600Srdivacky  return std::make_pair(0U, 0U);
149193326Sed}
150193326Sed
151193326Sed
152193326Sed/// BuildScopeInformation - The statements from CI to CE are known to form a
153193326Sed/// coherent VLA scope with a specified parent node.  Walk through the
154193326Sed/// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
155193326Sed/// walking the AST as needed.
156193326Sedvoid JumpScopeChecker::BuildScopeInformation(Stmt *S, unsigned ParentScope) {
157198092Srdivacky
158193326Sed  // If we found a label, remember that it is in ParentScope scope.
159208600Srdivacky  switch (S->getStmtClass()) {
160208600Srdivacky  case Stmt::LabelStmtClass:
161208600Srdivacky  case Stmt::DefaultStmtClass:
162208600Srdivacky  case Stmt::CaseStmtClass:
163193326Sed    LabelAndGotoScopes[S] = ParentScope;
164208600Srdivacky    break;
165208600Srdivacky
166208600Srdivacky  case Stmt::AddrLabelExprClass:
167208600Srdivacky    IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel());
168208600Srdivacky    break;
169208600Srdivacky
170208600Srdivacky  case Stmt::IndirectGotoStmtClass:
171208600Srdivacky    LabelAndGotoScopes[S] = ParentScope;
172208600Srdivacky    IndirectJumps.push_back(cast<IndirectGotoStmt>(S));
173208600Srdivacky    break;
174208600Srdivacky
175208600Srdivacky  case Stmt::GotoStmtClass:
176208600Srdivacky  case Stmt::SwitchStmtClass:
177193326Sed    // Remember both what scope a goto is in as well as the fact that we have
178193326Sed    // it.  This makes the second scan not have to walk the AST again.
179193326Sed    LabelAndGotoScopes[S] = ParentScope;
180193326Sed    Jumps.push_back(S);
181208600Srdivacky    break;
182208600Srdivacky
183208600Srdivacky  default:
184208600Srdivacky    break;
185193326Sed  }
186198092Srdivacky
187193326Sed  for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
188193326Sed       ++CI) {
189193326Sed    Stmt *SubStmt = *CI;
190193326Sed    if (SubStmt == 0) continue;
191198092Srdivacky
192204643Srdivacky    bool isCPlusPlus = this->S.getLangOptions().CPlusPlus;
193193326Sed
194193326Sed    // If this is a declstmt with a VLA definition, it defines a scope from here
195193326Sed    // to the end of the containing context.
196193326Sed    if (DeclStmt *DS = dyn_cast<DeclStmt>(SubStmt)) {
197204643Srdivacky      // The decl statement creates a scope if any of the decls in it are VLAs
198204643Srdivacky      // or have the cleanup attribute.
199193326Sed      for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
200193326Sed           I != E; ++I) {
201193326Sed        // If this decl causes a new scope, push and switch to it.
202208600Srdivacky        std::pair<unsigned,unsigned> Diags
203208600Srdivacky          = GetDiagForGotoScopeDecl(*I, isCPlusPlus);
204208600Srdivacky        if (Diags.first || Diags.second) {
205208600Srdivacky          Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second,
206208600Srdivacky                                     (*I)->getLocation()));
207193326Sed          ParentScope = Scopes.size()-1;
208193326Sed        }
209198092Srdivacky
210193326Sed        // If the decl has an initializer, walk it with the potentially new
211193326Sed        // scope we just installed.
212193326Sed        if (VarDecl *VD = dyn_cast<VarDecl>(*I))
213193326Sed          if (Expr *Init = VD->getInit())
214193326Sed            BuildScopeInformation(Init, ParentScope);
215193326Sed      }
216193326Sed      continue;
217193326Sed    }
218193326Sed
219193326Sed    // Disallow jumps into any part of an @try statement by pushing a scope and
220193326Sed    // walking all sub-stmts in that scope.
221193326Sed    if (ObjCAtTryStmt *AT = dyn_cast<ObjCAtTryStmt>(SubStmt)) {
222193326Sed      // Recursively walk the AST for the @try part.
223208600Srdivacky      Scopes.push_back(GotoScope(ParentScope,
224208600Srdivacky                                 diag::note_protected_by_objc_try,
225208600Srdivacky                                 diag::note_exits_objc_try,
226193326Sed                                 AT->getAtTryLoc()));
227193326Sed      if (Stmt *TryPart = AT->getTryBody())
228193326Sed        BuildScopeInformation(TryPart, Scopes.size()-1);
229193326Sed
230193326Sed      // Jump from the catch to the finally or try is not valid.
231207619Srdivacky      for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) {
232207619Srdivacky        ObjCAtCatchStmt *AC = AT->getCatchStmt(I);
233193326Sed        Scopes.push_back(GotoScope(ParentScope,
234193326Sed                                   diag::note_protected_by_objc_catch,
235208600Srdivacky                                   diag::note_exits_objc_catch,
236193326Sed                                   AC->getAtCatchLoc()));
237198092Srdivacky        // @catches are nested and it isn't
238193326Sed        BuildScopeInformation(AC->getCatchBody(), Scopes.size()-1);
239193326Sed      }
240198092Srdivacky
241193326Sed      // Jump from the finally to the try or catch is not valid.
242193326Sed      if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
243193326Sed        Scopes.push_back(GotoScope(ParentScope,
244193326Sed                                   diag::note_protected_by_objc_finally,
245208600Srdivacky                                   diag::note_exits_objc_finally,
246193326Sed                                   AF->getAtFinallyLoc()));
247193326Sed        BuildScopeInformation(AF, Scopes.size()-1);
248193326Sed      }
249198092Srdivacky
250193326Sed      continue;
251193326Sed    }
252198092Srdivacky
253193326Sed    // Disallow jumps into the protected statement of an @synchronized, but
254193326Sed    // allow jumps into the object expression it protects.
255193326Sed    if (ObjCAtSynchronizedStmt *AS = dyn_cast<ObjCAtSynchronizedStmt>(SubStmt)){
256193326Sed      // Recursively walk the AST for the @synchronized object expr, it is
257193326Sed      // evaluated in the normal scope.
258193326Sed      BuildScopeInformation(AS->getSynchExpr(), ParentScope);
259198092Srdivacky
260193326Sed      // Recursively walk the AST for the @synchronized part, protected by a new
261193326Sed      // scope.
262193326Sed      Scopes.push_back(GotoScope(ParentScope,
263193326Sed                                 diag::note_protected_by_objc_synchronized,
264208600Srdivacky                                 diag::note_exits_objc_synchronized,
265193326Sed                                 AS->getAtSynchronizedLoc()));
266193326Sed      BuildScopeInformation(AS->getSynchBody(), Scopes.size()-1);
267193326Sed      continue;
268193326Sed    }
269193326Sed
270193326Sed    // Disallow jumps into any part of a C++ try statement. This is pretty
271193326Sed    // much the same as for Obj-C.
272193326Sed    if (CXXTryStmt *TS = dyn_cast<CXXTryStmt>(SubStmt)) {
273208600Srdivacky      Scopes.push_back(GotoScope(ParentScope,
274208600Srdivacky                                 diag::note_protected_by_cxx_try,
275208600Srdivacky                                 diag::note_exits_cxx_try,
276193326Sed                                 TS->getSourceRange().getBegin()));
277193326Sed      if (Stmt *TryBlock = TS->getTryBlock())
278193326Sed        BuildScopeInformation(TryBlock, Scopes.size()-1);
279193326Sed
280193326Sed      // Jump from the catch into the try is not allowed either.
281198092Srdivacky      for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) {
282193326Sed        CXXCatchStmt *CS = TS->getHandler(I);
283193326Sed        Scopes.push_back(GotoScope(ParentScope,
284193326Sed                                   diag::note_protected_by_cxx_catch,
285208600Srdivacky                                   diag::note_exits_cxx_catch,
286193326Sed                                   CS->getSourceRange().getBegin()));
287193326Sed        BuildScopeInformation(CS->getHandlerBlock(), Scopes.size()-1);
288193326Sed      }
289193326Sed
290193326Sed      continue;
291193326Sed    }
292193326Sed
293193326Sed    // Recursively walk the AST.
294193326Sed    BuildScopeInformation(SubStmt, ParentScope);
295193326Sed  }
296193326Sed}
297193326Sed
298193326Sed/// VerifyJumps - Verify each element of the Jumps array to see if they are
299193326Sed/// valid, emitting diagnostics if not.
300193326Sedvoid JumpScopeChecker::VerifyJumps() {
301193326Sed  while (!Jumps.empty()) {
302193326Sed    Stmt *Jump = Jumps.pop_back_val();
303198092Srdivacky
304198092Srdivacky    // With a goto,
305193326Sed    if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
306193326Sed      CheckJump(GS, GS->getLabel(), GS->getGotoLoc(),
307193326Sed                diag::err_goto_into_protected_scope);
308193326Sed      continue;
309193326Sed    }
310198092Srdivacky
311208600Srdivacky    SwitchStmt *SS = cast<SwitchStmt>(Jump);
312208600Srdivacky    for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
313208600Srdivacky         SC = SC->getNextSwitchCase()) {
314208600Srdivacky      assert(LabelAndGotoScopes.count(SC) && "Case not visited?");
315208600Srdivacky      CheckJump(SS, SC, SC->getLocStart(),
316208600Srdivacky                diag::err_switch_into_protected_scope);
317193326Sed    }
318208600Srdivacky  }
319208600Srdivacky}
320193326Sed
321208600Srdivacky/// VerifyIndirectJumps - Verify whether any possible indirect jump
322208600Srdivacky/// might cross a protection boundary.  Unlike direct jumps, indirect
323208600Srdivacky/// jumps count cleanups as protection boundaries:  since there's no
324208600Srdivacky/// way to know where the jump is going, we can't implicitly run the
325208600Srdivacky/// right cleanups the way we can with direct jumps.
326208600Srdivacky///
327208600Srdivacky/// Thus, an indirect jump is "trivial" if it bypasses no
328208600Srdivacky/// initializations and no teardowns.  More formally, an indirect jump
329208600Srdivacky/// from A to B is trivial if the path out from A to DCA(A,B) is
330208600Srdivacky/// trivial and the path in from DCA(A,B) to B is trivial, where
331208600Srdivacky/// DCA(A,B) is the deepest common ancestor of A and B.
332208600Srdivacky/// Jump-triviality is transitive but asymmetric.
333208600Srdivacky///
334208600Srdivacky/// A path in is trivial if none of the entered scopes have an InDiag.
335208600Srdivacky/// A path out is trivial is none of the exited scopes have an OutDiag.
336208600Srdivacky///
337208600Srdivacky/// Under these definitions, this function checks that the indirect
338208600Srdivacky/// jump between A and B is trivial for every indirect goto statement A
339208600Srdivacky/// and every label B whose address was taken in the function.
340208600Srdivackyvoid JumpScopeChecker::VerifyIndirectJumps() {
341208600Srdivacky  if (IndirectJumps.empty()) return;
342198092Srdivacky
343208600Srdivacky  // If there aren't any address-of-label expressions in this function,
344208600Srdivacky  // complain about the first indirect goto.
345208600Srdivacky  if (IndirectJumpTargets.empty()) {
346208600Srdivacky    S.Diag(IndirectJumps[0]->getGotoLoc(),
347208600Srdivacky           diag::err_indirect_goto_without_addrlabel);
348208600Srdivacky    return;
349208600Srdivacky  }
350198092Srdivacky
351208600Srdivacky  // Collect a single representative of every scope containing an
352208600Srdivacky  // indirect goto.  For most code bases, this substantially cuts
353208600Srdivacky  // down on the number of jump sites we'll have to consider later.
354208600Srdivacky  typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope;
355208600Srdivacky  llvm::SmallVector<JumpScope, 32> JumpScopes;
356208600Srdivacky  {
357208600Srdivacky    llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap;
358208600Srdivacky    for (llvm::SmallVectorImpl<IndirectGotoStmt*>::iterator
359208600Srdivacky           I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) {
360208600Srdivacky      IndirectGotoStmt *IG = *I;
361208600Srdivacky      assert(LabelAndGotoScopes.count(IG) &&
362208600Srdivacky             "indirect jump didn't get added to scopes?");
363208600Srdivacky      unsigned IGScope = LabelAndGotoScopes[IG];
364208600Srdivacky      IndirectGotoStmt *&Entry = JumpScopesMap[IGScope];
365208600Srdivacky      if (!Entry) Entry = IG;
366208600Srdivacky    }
367208600Srdivacky    JumpScopes.reserve(JumpScopesMap.size());
368208600Srdivacky    for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator
369208600Srdivacky           I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I)
370208600Srdivacky      JumpScopes.push_back(*I);
371208600Srdivacky  }
372198092Srdivacky
373208600Srdivacky  // Collect a single representative of every scope containing a
374208600Srdivacky  // label whose address was taken somewhere in the function.
375208600Srdivacky  // For most code bases, there will be only one such scope.
376208600Srdivacky  llvm::DenseMap<unsigned, LabelStmt*> TargetScopes;
377208600Srdivacky  for (llvm::SmallVectorImpl<LabelStmt*>::iterator
378208600Srdivacky         I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end();
379208600Srdivacky       I != E; ++I) {
380208600Srdivacky    LabelStmt *TheLabel = *I;
381208600Srdivacky    assert(LabelAndGotoScopes.count(TheLabel) &&
382208600Srdivacky           "Referenced label didn't get added to scopes?");
383208600Srdivacky    unsigned LabelScope = LabelAndGotoScopes[TheLabel];
384208600Srdivacky    LabelStmt *&Target = TargetScopes[LabelScope];
385208600Srdivacky    if (!Target) Target = TheLabel;
386208600Srdivacky  }
387208600Srdivacky
388208600Srdivacky  // For each target scope, make sure it's trivially reachable from
389208600Srdivacky  // every scope containing a jump site.
390208600Srdivacky  //
391208600Srdivacky  // A path between scopes always consists of exitting zero or more
392208600Srdivacky  // scopes, then entering zero or more scopes.  We build a set of
393208600Srdivacky  // of scopes S from which the target scope can be trivially
394208600Srdivacky  // entered, then verify that every jump scope can be trivially
395208600Srdivacky  // exitted to reach a scope in S.
396208600Srdivacky  llvm::BitVector Reachable(Scopes.size(), false);
397208600Srdivacky  for (llvm::DenseMap<unsigned,LabelStmt*>::iterator
398208600Srdivacky         TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) {
399208600Srdivacky    unsigned TargetScope = TI->first;
400208600Srdivacky    LabelStmt *TargetLabel = TI->second;
401208600Srdivacky
402208600Srdivacky    Reachable.reset();
403208600Srdivacky
404208600Srdivacky    // Mark all the enclosing scopes from which you can safely jump
405208600Srdivacky    // into the target scope.  'Min' will end up being the index of
406208600Srdivacky    // the shallowest such scope.
407208600Srdivacky    unsigned Min = TargetScope;
408208600Srdivacky    while (true) {
409208600Srdivacky      Reachable.set(Min);
410208600Srdivacky
411208600Srdivacky      // Don't go beyond the outermost scope.
412208600Srdivacky      if (Min == 0) break;
413208600Srdivacky
414208600Srdivacky      // Stop if we can't trivially enter the current scope.
415208600Srdivacky      if (Scopes[Min].InDiag) break;
416208600Srdivacky
417208600Srdivacky      Min = Scopes[Min].ParentScope;
418193326Sed    }
419193326Sed
420208600Srdivacky    // Walk through all the jump sites, checking that they can trivially
421208600Srdivacky    // reach this label scope.
422208600Srdivacky    for (llvm::SmallVectorImpl<JumpScope>::iterator
423208600Srdivacky           I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) {
424208600Srdivacky      unsigned Scope = I->first;
425208600Srdivacky
426208600Srdivacky      // Walk out the "scope chain" for this scope, looking for a scope
427208600Srdivacky      // we've marked reachable.  For well-formed code this amortizes
428208600Srdivacky      // to O(JumpScopes.size() / Scopes.size()):  we only iterate
429208600Srdivacky      // when we see something unmarked, and in well-formed code we
430208600Srdivacky      // mark everything we iterate past.
431208600Srdivacky      bool IsReachable = false;
432208600Srdivacky      while (true) {
433208600Srdivacky        if (Reachable.test(Scope)) {
434208600Srdivacky          // If we find something reachable, mark all the scopes we just
435208600Srdivacky          // walked through as reachable.
436208600Srdivacky          for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope)
437208600Srdivacky            Reachable.set(S);
438208600Srdivacky          IsReachable = true;
439208600Srdivacky          break;
440208600Srdivacky        }
441208600Srdivacky
442208600Srdivacky        // Don't walk out if we've reached the top-level scope or we've
443208600Srdivacky        // gotten shallower than the shallowest reachable scope.
444208600Srdivacky        if (Scope == 0 || Scope < Min) break;
445208600Srdivacky
446208600Srdivacky        // Don't walk out through an out-diagnostic.
447208600Srdivacky        if (Scopes[Scope].OutDiag) break;
448208600Srdivacky
449208600Srdivacky        Scope = Scopes[Scope].ParentScope;
450208600Srdivacky      }
451208600Srdivacky
452208600Srdivacky      // Only diagnose if we didn't find something.
453208600Srdivacky      if (IsReachable) continue;
454208600Srdivacky
455208600Srdivacky      DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope);
456193326Sed    }
457193326Sed  }
458193326Sed}
459193326Sed
460208600Srdivacky/// Diagnose an indirect jump which is known to cross scopes.
461208600Srdivackyvoid JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump,
462208600Srdivacky                                            unsigned JumpScope,
463208600Srdivacky                                            LabelStmt *Target,
464208600Srdivacky                                            unsigned TargetScope) {
465208600Srdivacky  assert(JumpScope != TargetScope);
466208600Srdivacky
467208600Srdivacky  S.Diag(Jump->getGotoLoc(), diag::warn_indirect_goto_in_protected_scope);
468208600Srdivacky  S.Diag(Target->getIdentLoc(), diag::note_indirect_goto_target);
469208600Srdivacky
470208600Srdivacky  unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope);
471208600Srdivacky
472208600Srdivacky  // Walk out the scope chain until we reach the common ancestor.
473208600Srdivacky  for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope)
474208600Srdivacky    if (Scopes[I].OutDiag)
475208600Srdivacky      S.Diag(Scopes[I].Loc, Scopes[I].OutDiag);
476208600Srdivacky
477208600Srdivacky  // Now walk into the scopes containing the label whose address was taken.
478208600Srdivacky  for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope)
479208600Srdivacky    if (Scopes[I].InDiag)
480208600Srdivacky      S.Diag(Scopes[I].Loc, Scopes[I].InDiag);
481208600Srdivacky}
482208600Srdivacky
483193326Sed/// CheckJump - Validate that the specified jump statement is valid: that it is
484193326Sed/// jumping within or out of its current scope, not into a deeper one.
485193326Sedvoid JumpScopeChecker::CheckJump(Stmt *From, Stmt *To,
486193326Sed                                 SourceLocation DiagLoc, unsigned JumpDiag) {
487193326Sed  assert(LabelAndGotoScopes.count(From) && "Jump didn't get added to scopes?");
488193326Sed  unsigned FromScope = LabelAndGotoScopes[From];
489193326Sed
490193326Sed  assert(LabelAndGotoScopes.count(To) && "Jump didn't get added to scopes?");
491193326Sed  unsigned ToScope = LabelAndGotoScopes[To];
492198092Srdivacky
493193326Sed  // Common case: exactly the same scope, which is fine.
494193326Sed  if (FromScope == ToScope) return;
495198092Srdivacky
496208600Srdivacky  unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope);
497198092Srdivacky
498208600Srdivacky  // It's okay to jump out from a nested scope.
499208600Srdivacky  if (CommonScope == ToScope) return;
500198092Srdivacky
501208600Srdivacky  // Pull out (and reverse) any scopes we might need to diagnose skipping.
502208600Srdivacky  llvm::SmallVector<unsigned, 10> ToScopes;
503208600Srdivacky  for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope)
504208600Srdivacky    if (Scopes[I].InDiag)
505208600Srdivacky      ToScopes.push_back(I);
506193326Sed
507208600Srdivacky  // If the only scopes present are cleanup scopes, we're okay.
508208600Srdivacky  if (ToScopes.empty()) return;
509193326Sed
510208600Srdivacky  S.Diag(DiagLoc, JumpDiag);
511198092Srdivacky
512193326Sed  // Emit diagnostics for whatever is left in ToScopes.
513193326Sed  for (unsigned i = 0, e = ToScopes.size(); i != e; ++i)
514208600Srdivacky    S.Diag(Scopes[ToScopes[i]].Loc, Scopes[ToScopes[i]].InDiag);
515193326Sed}
516193326Sed
517193326Sedvoid Sema::DiagnoseInvalidJumps(Stmt *Body) {
518199482Srdivacky  (void)JumpScopeChecker(Body, *this);
519193326Sed}
520