JumpDiagnostics.cpp revision 207619
1193323Sed//===--- JumpDiagnostics.cpp - Analyze Jump Targets for VLA issues --------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This file implements the JumpScopeChecker class, which is used to diagnose
11193323Sed// jumps that enter a VLA scope in an invalid way.
12193323Sed//
13193323Sed//===----------------------------------------------------------------------===//
14193323Sed
15193323Sed#include "Sema.h"
16193323Sed#include "clang/AST/Expr.h"
17193323Sed#include "clang/AST/StmtObjC.h"
18193323Sed#include "clang/AST/StmtCXX.h"
19193323Sedusing namespace clang;
20249423Sdim
21218893Sdimnamespace {
22234353Sdim
23193323Sed/// JumpScopeChecker - This object is used by Sema to diagnose invalid jumps
24193323Sed/// into VLA and other protected scopes.  For example, this rejects:
25198892Srdivacky///    goto L;
26193323Sed///    int a[n];
27193323Sed///  L:
28251662Sdim///
29193323Sedclass JumpScopeChecker {
30198090Srdivacky  Sema &S;
31193323Sed
32198090Srdivacky  /// GotoScope - This is a record that we use to keep track of all of the
33198090Srdivacky  /// scopes that are introduced by VLAs and other things that scope jumps like
34198090Srdivacky  /// gotos.  This scope tree has nothing to do with the source scope tree,
35207618Srdivacky  /// because you can have multiple VLA scopes per compound statement, and most
36198090Srdivacky  /// compound statements don't introduce any scopes.
37198090Srdivacky  struct GotoScope {
38193323Sed    /// ParentScope - The index in ScopeMap of the parent scope.  This is 0 for
39198090Srdivacky    /// the parent scope is the function body.
40195098Sed    unsigned ParentScope;
41206274Srdivacky
42263508Sdim    /// Diag - The diagnostic to emit if there is a jump into this scope.
43198090Srdivacky    unsigned Diag;
44263508Sdim
45198090Srdivacky    /// Loc - Location to emit the diagnostic.
46198090Srdivacky    SourceLocation Loc;
47198090Srdivacky
48218893Sdim    GotoScope(unsigned parentScope, unsigned diag, SourceLocation L)
49206274Srdivacky    : ParentScope(parentScope), Diag(diag), Loc(L) {}
50206274Srdivacky  };
51193323Sed
52198090Srdivacky  llvm::SmallVector<GotoScope, 48> Scopes;
53243830Sdim  llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
54212904Sdim  llvm::SmallVector<Stmt*, 16> Jumps;
55193323Sedpublic:
56193323Sed  JumpScopeChecker(Stmt *Body, Sema &S);
57193323Sedprivate:
58193323Sed  void BuildScopeInformation(Stmt *S, unsigned ParentScope);
59198090Srdivacky  void VerifyJumps();
60193323Sed  void CheckJump(Stmt *From, Stmt *To,
61193323Sed                 SourceLocation DiagLoc, unsigned JumpDiag);
62193323Sed};
63210299Sed} // end anonymous namespace
64193323Sed
65193323Sed
66198090SrdivackyJumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s) : S(s) {
67193323Sed  // Add a scope entry for function scope.
68263508Sdim  Scopes.push_back(GotoScope(~0U, ~0U, SourceLocation()));
69198090Srdivacky
70198090Srdivacky  // Build information for the top level compound statement, so that we have a
71198090Srdivacky  // defined scope record for every "goto" and label.
72198090Srdivacky  BuildScopeInformation(Body, 0);
73210299Sed
74198090Srdivacky  // Check that all jumps we saw are kosher.
75198090Srdivacky  VerifyJumps();
76198090Srdivacky}
77198090Srdivacky
78198090Srdivacky/// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a
79210299Sed/// diagnostic that should be emitted if control goes over it. If not, return 0.
80193323Sedstatic unsigned GetDiagForGotoScopeDecl(const Decl *D, bool isCPlusPlus) {
81193323Sed  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
82193323Sed    if (VD->getType()->isVariablyModifiedType())
83206274Srdivacky      return diag::note_protected_by_vla;
84206274Srdivacky    if (VD->hasAttr<CleanupAttr>())
85206274Srdivacky      return diag::note_protected_by_cleanup;
86193323Sed    if (VD->hasAttr<BlocksAttr>())
87193323Sed      return diag::note_protected_by___block;
88193323Sed    // FIXME: In C++0x, we have to check more conditions than "did we
89193323Sed    // just give it an initializer?". See 6.7p3.
90202878Srdivacky    if (isCPlusPlus && VD->hasLocalStorage() && VD->hasInit())
91193323Sed      return diag::note_protected_by_variable_init;
92193323Sed
93202878Srdivacky  } else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
94210299Sed    if (TD->getUnderlyingType()->isVariablyModifiedType())
95234353Sdim      return diag::note_protected_by_vla_typedef;
96234353Sdim  }
97234353Sdim
98234353Sdim  return 0;
99234353Sdim}
100206274Srdivacky
101206274Srdivacky
102206274Srdivacky/// BuildScopeInformation - The statements from CI to CE are known to form a
103210299Sed/// coherent VLA scope with a specified parent node.  Walk through the
104193323Sed/// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
105193323Sed/// walking the AST as needed.
106193323Sedvoid JumpScopeChecker::BuildScopeInformation(Stmt *S, unsigned ParentScope) {
107206274Srdivacky
108210299Sed  // If we found a label, remember that it is in ParentScope scope.
109206274Srdivacky  if (isa<LabelStmt>(S) || isa<DefaultStmt>(S) || isa<CaseStmt>(S)) {
110206274Srdivacky    LabelAndGotoScopes[S] = ParentScope;
111206274Srdivacky  } else if (isa<GotoStmt>(S) || isa<SwitchStmt>(S) ||
112193323Sed             isa<IndirectGotoStmt>(S) || isa<AddrLabelExpr>(S)) {
113206274Srdivacky    // Remember both what scope a goto is in as well as the fact that we have
114206274Srdivacky    // it.  This makes the second scan not have to walk the AST again.
115210299Sed    LabelAndGotoScopes[S] = ParentScope;
116206274Srdivacky    Jumps.push_back(S);
117206274Srdivacky  }
118206274Srdivacky
119210299Sed  for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
120193323Sed       ++CI) {
121206274Srdivacky    Stmt *SubStmt = *CI;
122210299Sed    if (SubStmt == 0) continue;
123193323Sed
124193323Sed    bool isCPlusPlus = this->S.getLangOptions().CPlusPlus;
125193323Sed
126263508Sdim    // If this is a declstmt with a VLA definition, it defines a scope from here
127263508Sdim    // to the end of the containing context.
128193323Sed    if (DeclStmt *DS = dyn_cast<DeclStmt>(SubStmt)) {
129193323Sed      // The decl statement creates a scope if any of the decls in it are VLAs
130193323Sed      // or have the cleanup attribute.
131193323Sed      for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
132198090Srdivacky           I != E; ++I) {
133193323Sed        // If this decl causes a new scope, push and switch to it.
134203954Srdivacky        if (unsigned Diag = GetDiagForGotoScopeDecl(*I, isCPlusPlus)) {
135210299Sed          Scopes.push_back(GotoScope(ParentScope, Diag, (*I)->getLocation()));
136206274Srdivacky          ParentScope = Scopes.size()-1;
137207618Srdivacky        }
138206274Srdivacky
139243830Sdim        // If the decl has an initializer, walk it with the potentially new
140243830Sdim        // scope we just installed.
141206274Srdivacky        if (VarDecl *VD = dyn_cast<VarDecl>(*I))
142251662Sdim          if (Expr *Init = VD->getInit())
143251662Sdim            BuildScopeInformation(Init, ParentScope);
144251662Sdim      }
145206274Srdivacky      continue;
146206274Srdivacky    }
147210299Sed
148263508Sdim    // Disallow jumps into any part of an @try statement by pushing a scope and
149210299Sed    // walking all sub-stmts in that scope.
150206274Srdivacky    if (ObjCAtTryStmt *AT = dyn_cast<ObjCAtTryStmt>(SubStmt)) {
151206274Srdivacky      // Recursively walk the AST for the @try part.
152206274Srdivacky      Scopes.push_back(GotoScope(ParentScope,diag::note_protected_by_objc_try,
153210299Sed                                 AT->getAtTryLoc()));
154193323Sed      if (Stmt *TryPart = AT->getTryBody())
155210299Sed        BuildScopeInformation(TryPart, Scopes.size()-1);
156193323Sed
157210299Sed      // Jump from the catch to the finally or try is not valid.
158193323Sed      for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) {
159193323Sed        ObjCAtCatchStmt *AC = AT->getCatchStmt(I);
160193323Sed        Scopes.push_back(GotoScope(ParentScope,
161193323Sed                                   diag::note_protected_by_objc_catch,
162193323Sed                                   AC->getAtCatchLoc()));
163193323Sed        // @catches are nested and it isn't
164193323Sed        BuildScopeInformation(AC->getCatchBody(), Scopes.size()-1);
165193323Sed      }
166210299Sed
167203954Srdivacky      // Jump from the finally to the try or catch is not valid.
168203954Srdivacky      if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
169203954Srdivacky        Scopes.push_back(GotoScope(ParentScope,
170203954Srdivacky                                   diag::note_protected_by_objc_finally,
171203954Srdivacky                                   AF->getAtFinallyLoc()));
172203954Srdivacky        BuildScopeInformation(AF, Scopes.size()-1);
173203954Srdivacky      }
174210299Sed
175210299Sed      continue;
176206274Srdivacky    }
177206274Srdivacky
178206274Srdivacky    // Disallow jumps into the protected statement of an @synchronized, but
179210299Sed    // allow jumps into the object expression it protects.
180193323Sed    if (ObjCAtSynchronizedStmt *AS = dyn_cast<ObjCAtSynchronizedStmt>(SubStmt)){
181193323Sed      // Recursively walk the AST for the @synchronized object expr, it is
182193323Sed      // evaluated in the normal scope.
183210299Sed      BuildScopeInformation(AS->getSynchExpr(), ParentScope);
184203954Srdivacky
185203954Srdivacky      // Recursively walk the AST for the @synchronized part, protected by a new
186203954Srdivacky      // scope.
187210299Sed      Scopes.push_back(GotoScope(ParentScope,
188203954Srdivacky                                 diag::note_protected_by_objc_synchronized,
189203954Srdivacky                                 AS->getAtSynchronizedLoc()));
190203954Srdivacky      BuildScopeInformation(AS->getSynchBody(), Scopes.size()-1);
191203954Srdivacky      continue;
192221345Sdim    }
193221345Sdim
194223017Sdim    // Disallow jumps into any part of a C++ try statement. This is pretty
195223017Sdim    // much the same as for Obj-C.
196223017Sdim    if (CXXTryStmt *TS = dyn_cast<CXXTryStmt>(SubStmt)) {
197223017Sdim      Scopes.push_back(GotoScope(ParentScope, diag::note_protected_by_cxx_try,
198223017Sdim                                 TS->getSourceRange().getBegin()));
199223017Sdim      if (Stmt *TryBlock = TS->getTryBlock())
200221345Sdim        BuildScopeInformation(TryBlock, Scopes.size()-1);
201223017Sdim
202223017Sdim      // Jump from the catch into the try is not allowed either.
203234353Sdim      for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) {
204234353Sdim        CXXCatchStmt *CS = TS->getHandler(I);
205234353Sdim        Scopes.push_back(GotoScope(ParentScope,
206234353Sdim                                   diag::note_protected_by_cxx_catch,
207234353Sdim                                   CS->getSourceRange().getBegin()));
208193323Sed        BuildScopeInformation(CS->getHandlerBlock(), Scopes.size()-1);
209193323Sed      }
210193323Sed
211193323Sed      continue;
212193323Sed    }
213203954Srdivacky
214210299Sed    // Recursively walk the AST.
215210299Sed    BuildScopeInformation(SubStmt, ParentScope);
216210299Sed  }
217193323Sed}
218203954Srdivacky
219210299Sed/// VerifyJumps - Verify each element of the Jumps array to see if they are
220202878Srdivacky/// valid, emitting diagnostics if not.
221202878Srdivackyvoid JumpScopeChecker::VerifyJumps() {
222210299Sed  while (!Jumps.empty()) {
223193323Sed    Stmt *Jump = Jumps.pop_back_val();
224193323Sed
225193323Sed    // With a goto,
226193323Sed    if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
227198090Srdivacky      CheckJump(GS, GS->getLabel(), GS->getGotoLoc(),
228193323Sed                diag::err_goto_into_protected_scope);
229193323Sed      continue;
230193323Sed    }
231207618Srdivacky
232207618Srdivacky    if (SwitchStmt *SS = dyn_cast<SwitchStmt>(Jump)) {
233193323Sed      for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
234207618Srdivacky           SC = SC->getNextSwitchCase()) {
235210299Sed        assert(LabelAndGotoScopes.count(SC) && "Case not visited?");
236206274Srdivacky        CheckJump(SS, SC, SC->getLocStart(),
237206274Srdivacky                  diag::err_switch_into_protected_scope);
238206274Srdivacky      }
239206274Srdivacky      continue;
240210299Sed    }
241263508Sdim
242263508Sdim    unsigned DiagnosticScope;
243210299Sed
244210299Sed    // We don't know where an indirect goto goes, require that it be at the
245206274Srdivacky    // top level of scoping.
246206274Srdivacky    if (IndirectGotoStmt *IG = dyn_cast<IndirectGotoStmt>(Jump)) {
247206274Srdivacky      assert(LabelAndGotoScopes.count(Jump) &&
248210299Sed             "Jump didn't get added to scopes?");
249206274Srdivacky      unsigned GotoScope = LabelAndGotoScopes[IG];
250206274Srdivacky      if (GotoScope == 0) continue;  // indirect jump is ok.
251210299Sed      S.Diag(IG->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
252206274Srdivacky      DiagnosticScope = GotoScope;
253206274Srdivacky    } else {
254206274Srdivacky      // We model &&Label as a jump for purposes of scope tracking.  We actually
255210299Sed      // don't care *where* the address of label is, but we require the *label
256206274Srdivacky      // itself* to be in scope 0.  If it is nested inside of a VLA scope, then
257206274Srdivacky      // it is possible for an indirect goto to illegally enter the VLA scope by
258206274Srdivacky      // indirectly jumping to the label.
259210299Sed      assert(isa<AddrLabelExpr>(Jump) && "Unknown jump type");
260206274Srdivacky      LabelStmt *TheLabel = cast<AddrLabelExpr>(Jump)->getLabel();
261206274Srdivacky
262206274Srdivacky      assert(LabelAndGotoScopes.count(TheLabel) &&
263210299Sed             "Referenced label didn't get added to scopes?");
264206274Srdivacky      unsigned LabelScope = LabelAndGotoScopes[TheLabel];
265206274Srdivacky      if (LabelScope == 0) continue; // Addr of label is ok.
266206274Srdivacky
267210299Sed      S.Diag(Jump->getLocStart(), diag::err_addr_of_label_in_protected_scope);
268206274Srdivacky      DiagnosticScope = LabelScope;
269206274Srdivacky    }
270234353Sdim
271206274Srdivacky    // Report all the things that would be skipped over by this &&label or
272210299Sed    // indirect goto.
273206274Srdivacky    while (DiagnosticScope != 0) {
274210299Sed      S.Diag(Scopes[DiagnosticScope].Loc, Scopes[DiagnosticScope].Diag);
275206274Srdivacky      DiagnosticScope = Scopes[DiagnosticScope].ParentScope;
276210299Sed    }
277234353Sdim  }
278234353Sdim}
279234353Sdim
280234353Sdim/// CheckJump - Validate that the specified jump statement is valid: that it is
281234353Sdim/// jumping within or out of its current scope, not into a deeper one.
282234353Sdimvoid JumpScopeChecker::CheckJump(Stmt *From, Stmt *To,
283234353Sdim                                 SourceLocation DiagLoc, unsigned JumpDiag) {
284206274Srdivacky  assert(LabelAndGotoScopes.count(From) && "Jump didn't get added to scopes?");
285206274Srdivacky  unsigned FromScope = LabelAndGotoScopes[From];
286206274Srdivacky
287206274Srdivacky  assert(LabelAndGotoScopes.count(To) && "Jump didn't get added to scopes?");
288206274Srdivacky  unsigned ToScope = LabelAndGotoScopes[To];
289210299Sed
290263508Sdim  // Common case: exactly the same scope, which is fine.
291263508Sdim  if (FromScope == ToScope) return;
292263508Sdim
293263508Sdim  // The only valid mismatch jump case happens when the jump is more deeply
294206274Srdivacky  // nested inside the jump target.  Do a quick scan to see if the jump is valid
295206274Srdivacky  // because valid code is more common than invalid code.
296206274Srdivacky  unsigned TestScope = Scopes[FromScope].ParentScope;
297206274Srdivacky  while (TestScope != ~0U) {
298193323Sed    // If we found the jump target, then we're jumping out of our current scope,
299206274Srdivacky    // which is perfectly fine.
300206274Srdivacky    if (TestScope == ToScope) return;
301206274Srdivacky
302210299Sed    // Otherwise, scan up the hierarchy.
303206274Srdivacky    TestScope = Scopes[TestScope].ParentScope;
304206274Srdivacky  }
305206274Srdivacky
306210299Sed  // If we get here, then we know we have invalid code.  Diagnose the bad jump,
307210299Sed  // and then emit a note at each VLA being jumped out of.
308202878Srdivacky  S.Diag(DiagLoc, JumpDiag);
309202878Srdivacky
310202878Srdivacky  // Eliminate the common prefix of the jump and the target.  Start by
311202878Srdivacky  // linearizing both scopes, reversing them as we go.
312202878Srdivacky  std::vector<unsigned> FromScopes, ToScopes;
313202878Srdivacky  for (TestScope = FromScope; TestScope != ~0U;
314210299Sed       TestScope = Scopes[TestScope].ParentScope)
315202878Srdivacky    FromScopes.push_back(TestScope);
316202878Srdivacky  for (TestScope = ToScope; TestScope != ~0U;
317202878Srdivacky       TestScope = Scopes[TestScope].ParentScope)
318210299Sed    ToScopes.push_back(TestScope);
319202878Srdivacky
320202878Srdivacky  // Remove any common entries (such as the top-level function scope).
321202878Srdivacky  while (!FromScopes.empty() && FromScopes.back() == ToScopes.back()) {
322202878Srdivacky    FromScopes.pop_back();
323202878Srdivacky    ToScopes.pop_back();
324202878Srdivacky  }
325203954Srdivacky
326203954Srdivacky  // Emit diagnostics for whatever is left in ToScopes.
327203954Srdivacky  for (unsigned i = 0, e = ToScopes.size(); i != e; ++i)
328203954Srdivacky    S.Diag(Scopes[ToScopes[i]].Loc, Scopes[ToScopes[i]].Diag);
329198892Srdivacky}
330198892Srdivacky
331203954Srdivackyvoid Sema::DiagnoseInvalidJumps(Stmt *Body) {
332205218Srdivacky  (void)JumpScopeChecker(Body, *this);
333198892Srdivacky}
334212904Sdim