blob: b812f06f76be3063d6764fcc2a8c12b775534d91 [file] [log] [blame]
Chris Lattner5af280c2009-04-19 04:46:21 +00001//===--- JumpDiagnostics.cpp - Analyze Jump Targets for VLA issues --------===//
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 VLA scope in an invalid way.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sema.h"
16#include "clang/AST/Expr.h"
17using namespace clang;
18
19namespace {
20
21/// JumpScopeChecker - This object is used by Sema to diagnose invalid jumps
22/// into VLA and other protected scopes. For example, this rejects:
23/// goto L;
24/// int a[n];
25/// L:
26///
27class JumpScopeChecker {
28 Sema &S;
29
30 /// GotoScope - This is a record that we use to keep track of all of the
31 /// scopes that are introduced by VLAs and other things that scope jumps like
32 /// gotos. This scope tree has nothing to do with the source scope tree,
33 /// because you can have multiple VLA scopes per compound statement, and most
34 /// compound statements don't introduce any scopes.
35 struct GotoScope {
36 /// ParentScope - The index in ScopeMap of the parent scope. This is 0 for
37 /// the parent scope is the function body.
38 unsigned ParentScope;
39
40 /// Diag - The diagnostic to emit if there is a jump into this scope.
41 unsigned Diag;
42
43 /// Loc - Location to emit the diagnostic.
44 SourceLocation Loc;
45
46 GotoScope(unsigned parentScope, unsigned diag, SourceLocation L)
47 : ParentScope(parentScope), Diag(diag), Loc(L) {}
48 };
49
50 llvm::SmallVector<GotoScope, 48> Scopes;
51 llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
52 llvm::SmallVector<Stmt*, 16> Jumps;
53public:
54 JumpScopeChecker(Stmt *Body, Sema &S);
55private:
56 void BuildScopeInformation(Stmt *S, unsigned ParentScope);
57 void VerifyJumps();
58 void CheckJump(Stmt *From, Stmt *To,
59 SourceLocation DiagLoc, unsigned JumpDiag);
60};
61} // end anonymous namespace
62
63
64JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s) : S(s) {
65 // Add a scope entry for function scope.
66 Scopes.push_back(GotoScope(~0U, ~0U, SourceLocation()));
67
68 // Build information for the top level compound statement, so that we have a
69 // defined scope record for every "goto" and label.
70 BuildScopeInformation(Body, 0);
71
72 // Check that all jumps we saw are kosher.
73 VerifyJumps();
74}
75
76/// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a
77/// diagnostic that should be emitted if control goes over it. If not, return 0.
78static unsigned GetDiagForGotoScopeDecl(const Decl *D) {
79 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
80 if (VD->getType()->isVariablyModifiedType())
81 return diag::note_protected_by_vla;
82 if (VD->hasAttr<CleanupAttr>())
83 return diag::note_protected_by_cleanup;
84 } else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
85 if (TD->getUnderlyingType()->isVariablyModifiedType())
86 return diag::note_protected_by_vla_typedef;
87 }
88
89 return 0;
90}
91
92
93/// BuildScopeInformation - The statements from CI to CE are known to form a
94/// coherent VLA scope with a specified parent node. Walk through the
95/// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
96/// walking the AST as needed.
97void JumpScopeChecker::BuildScopeInformation(Stmt *S, unsigned ParentScope) {
98
99 // If we found a label, remember that it is in ParentScope scope.
100 if (isa<LabelStmt>(S) || isa<DefaultStmt>(S) || isa<CaseStmt>(S)) {
101 LabelAndGotoScopes[S] = ParentScope;
102 } else if (isa<GotoStmt>(S) || isa<SwitchStmt>(S) ||
103 isa<IndirectGotoStmt>(S) || isa<AddrLabelExpr>(S)) {
104 // Remember both what scope a goto is in as well as the fact that we have
105 // it. This makes the second scan not have to walk the AST again.
106 LabelAndGotoScopes[S] = ParentScope;
107 Jumps.push_back(S);
108 }
109
110 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
111 ++CI) {
112 Stmt *SubStmt = *CI;
113 if (SubStmt == 0) continue;
114
115 // FIXME: diagnose jumps past initialization: required in C++, warning in C.
116 // goto L; int X = 4; L: ;
117 // FIXME: what about jumps into C++ catch blocks, what are the rules?
118
119 // If this is a declstmt with a VLA definition, it defines a scope from here
120 // to the end of the containing context.
121 if (DeclStmt *DS = dyn_cast<DeclStmt>(SubStmt)) {
122 // The decl statement creates a scope if any of the decls in it are VLAs or
123 // have the cleanup attribute.
124 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
125 I != E; ++I) {
126 // If this decl causes a new scope, push and switch to it.
127 if (unsigned Diag = GetDiagForGotoScopeDecl(*I)) {
128 Scopes.push_back(GotoScope(ParentScope, Diag, (*I)->getLocation()));
129 ParentScope = Scopes.size()-1;
130 }
131
132 // If the decl has an initializer, walk it with the potentially new
133 // scope we just installed.
134 if (VarDecl *VD = dyn_cast<VarDecl>(*I))
135 if (Expr *Init = VD->getInit())
136 BuildScopeInformation(Init, ParentScope);
137 }
138 continue;
139 }
140
141 // Disallow jumps into any part of an @try statement by pushing a scope and
142 // walking all sub-stmts in that scope.
143 if (ObjCAtTryStmt *AT = dyn_cast<ObjCAtTryStmt>(SubStmt)) {
144 // Recursively walk the AST for the @try part.
145 Scopes.push_back(GotoScope(ParentScope,diag::note_protected_by_objc_try,
146 AT->getAtTryLoc()));
147 if (Stmt *TryPart = AT->getTryBody())
148 BuildScopeInformation(TryPart, Scopes.size()-1);
149
150 // Jump from the catch to the finally or try is not valid.
151 for (ObjCAtCatchStmt *AC = AT->getCatchStmts(); AC;
152 AC = AC->getNextCatchStmt()) {
153 Scopes.push_back(GotoScope(ParentScope,
154 diag::note_protected_by_objc_catch,
155 AC->getAtCatchLoc()));
156 // @catches are nested and it isn't
157 BuildScopeInformation(AC->getCatchBody(), Scopes.size()-1);
158 }
159
160 // Jump from the finally to the try or catch is not valid.
161 if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
162 Scopes.push_back(GotoScope(ParentScope,
163 diag::note_protected_by_objc_finally,
164 AF->getAtFinallyLoc()));
165 BuildScopeInformation(AF, Scopes.size()-1);
166 }
167
168 continue;
169 }
170
Chris Lattner46c3c4b2009-04-21 06:01:00 +0000171 // Disallow jumps into the protected statement of an @synchronized, but
172 // allow jumps into the object expression it protects.
173 if (ObjCAtSynchronizedStmt *AS = dyn_cast<ObjCAtSynchronizedStmt>(SubStmt)){
174 // Recursively walk the AST for the @synchronized object expr, it is
175 // evaluated in the normal scope.
176 BuildScopeInformation(AS->getSynchExpr(), ParentScope);
177
178 // Recursively walk the AST for the @synchronized part, protected by a new
179 // scope.
180 Scopes.push_back(GotoScope(ParentScope,
181 diag::note_protected_by_objc_synchronized,
182 AS->getAtSynchronizedLoc()));
183 BuildScopeInformation(AS->getSynchBody(), Scopes.size()-1);
184 continue;
185 }
186
Chris Lattner5af280c2009-04-19 04:46:21 +0000187 // Recursively walk the AST.
188 BuildScopeInformation(SubStmt, ParentScope);
189 }
190}
191
192/// VerifyJumps - Verify each element of the Jumps array to see if they are
193/// valid, emitting diagnostics if not.
194void JumpScopeChecker::VerifyJumps() {
195 while (!Jumps.empty()) {
196 Stmt *Jump = Jumps.pop_back_val();
197
198 // With a goto,
199 if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
200 CheckJump(GS, GS->getLabel(), GS->getGotoLoc(),
201 diag::err_goto_into_protected_scope);
202 continue;
203 }
204
205 if (SwitchStmt *SS = dyn_cast<SwitchStmt>(Jump)) {
206 for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
207 SC = SC->getNextSwitchCase()) {
208 assert(LabelAndGotoScopes.count(SC) && "Case not visited?");
209 CheckJump(SS, SC, SC->getLocStart(),
210 diag::err_switch_into_protected_scope);
211 }
212 continue;
213 }
214
215 unsigned DiagnosticScope;
216
217 // We don't know where an indirect goto goes, require that it be at the
218 // top level of scoping.
219 if (IndirectGotoStmt *IG = dyn_cast<IndirectGotoStmt>(Jump)) {
220 assert(LabelAndGotoScopes.count(Jump) &&
221 "Jump didn't get added to scopes?");
222 unsigned GotoScope = LabelAndGotoScopes[IG];
223 if (GotoScope == 0) continue; // indirect jump is ok.
224 S.Diag(IG->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
225 DiagnosticScope = GotoScope;
226 } else {
227 // We model &&Label as a jump for purposes of scope tracking. We actually
228 // don't care *where* the address of label is, but we require the *label
229 // itself* to be in scope 0. If it is nested inside of a VLA scope, then
230 // it is possible for an indirect goto to illegally enter the VLA scope by
231 // indirectly jumping to the label.
232 assert(isa<AddrLabelExpr>(Jump) && "Unknown jump type");
233 LabelStmt *TheLabel = cast<AddrLabelExpr>(Jump)->getLabel();
234
235 assert(LabelAndGotoScopes.count(TheLabel) &&
236 "Referenced label didn't get added to scopes?");
237 unsigned LabelScope = LabelAndGotoScopes[TheLabel];
238 if (LabelScope == 0) continue; // Addr of label is ok.
239
240 S.Diag(Jump->getLocStart(), diag::err_addr_of_label_in_protected_scope);
241 DiagnosticScope = LabelScope;
242 }
243
244 // Report all the things that would be skipped over by this &&label or
245 // indirect goto.
246 while (DiagnosticScope != 0) {
247 S.Diag(Scopes[DiagnosticScope].Loc, Scopes[DiagnosticScope].Diag);
248 DiagnosticScope = Scopes[DiagnosticScope].ParentScope;
249 }
250 }
251}
252
253/// CheckJump - Validate that the specified jump statement is valid: that it is
254/// jumping within or out of its current scope, not into a deeper one.
255void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To,
256 SourceLocation DiagLoc, unsigned JumpDiag) {
257 assert(LabelAndGotoScopes.count(From) && "Jump didn't get added to scopes?");
258 unsigned FromScope = LabelAndGotoScopes[From];
259
260 assert(LabelAndGotoScopes.count(To) && "Jump didn't get added to scopes?");
261 unsigned ToScope = LabelAndGotoScopes[To];
262
263 // Common case: exactly the same scope, which is fine.
264 if (FromScope == ToScope) return;
265
266 // The only valid mismatch jump case happens when the jump is more deeply
267 // nested inside the jump target. Do a quick scan to see if the jump is valid
268 // because valid code is more common than invalid code.
269 unsigned TestScope = Scopes[FromScope].ParentScope;
270 while (TestScope != ~0U) {
271 // If we found the jump target, then we're jumping out of our current scope,
272 // which is perfectly fine.
273 if (TestScope == ToScope) return;
274
275 // Otherwise, scan up the hierarchy.
276 TestScope = Scopes[TestScope].ParentScope;
277 }
278
279 // If we get here, then we know we have invalid code. Diagnose the bad jump,
280 // and then emit a note at each VLA being jumped out of.
281 S.Diag(DiagLoc, JumpDiag);
282
283 // Eliminate the common prefix of the jump and the target. Start by
284 // linearizing both scopes, reversing them as we go.
285 std::vector<unsigned> FromScopes, ToScopes;
286 for (TestScope = FromScope; TestScope != ~0U;
287 TestScope = Scopes[TestScope].ParentScope)
288 FromScopes.push_back(TestScope);
289 for (TestScope = ToScope; TestScope != ~0U;
290 TestScope = Scopes[TestScope].ParentScope)
291 ToScopes.push_back(TestScope);
292
293 // Remove any common entries (such as the top-level function scope).
294 while (!FromScopes.empty() && FromScopes.back() == ToScopes.back()) {
295 FromScopes.pop_back();
296 ToScopes.pop_back();
297 }
298
299 // Emit diagnostics for whatever is left in ToScopes.
300 for (unsigned i = 0, e = ToScopes.size(); i != e; ++i)
301 S.Diag(Scopes[ToScopes[i]].Loc, Scopes[ToScopes[i]].Diag);
302}
303
304void Sema::DiagnoseInvalidJumps(Stmt *Body) {
305 JumpScopeChecker(Body, *this);
306}