blob: 867d78fef6a7c11fcd0ed8be8347f04cfe35102b [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
John McCall2d887082010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
John McCall384aff82010-08-25 07:42:41 +000016#include "clang/AST/DeclCXX.h"
Chris Lattner5af280c2009-04-19 04:46:21 +000017#include "clang/AST/Expr.h"
Chris Lattner16f00492009-04-26 01:32:48 +000018#include "clang/AST/StmtObjC.h"
Sebastian Redl972041f2009-04-27 20:27:31 +000019#include "clang/AST/StmtCXX.h"
Douglas Gregore737f502010-08-12 20:07:10 +000020#include "llvm/ADT/BitVector.h"
Chris Lattner5af280c2009-04-19 04:46:21 +000021using namespace clang;
22
23namespace {
24
25/// JumpScopeChecker - This object is used by Sema to diagnose invalid jumps
26/// into VLA and other protected scopes. For example, this rejects:
27/// goto L;
28/// int a[n];
29/// L:
30///
31class JumpScopeChecker {
32 Sema &S;
Mike Stump1eb44332009-09-09 15:08:12 +000033
Chris Lattner5af280c2009-04-19 04:46:21 +000034 /// GotoScope - This is a record that we use to keep track of all of the
35 /// scopes that are introduced by VLAs and other things that scope jumps like
36 /// gotos. This scope tree has nothing to do with the source scope tree,
37 /// because you can have multiple VLA scopes per compound statement, and most
38 /// compound statements don't introduce any scopes.
39 struct GotoScope {
40 /// ParentScope - The index in ScopeMap of the parent scope. This is 0 for
41 /// the parent scope is the function body.
42 unsigned ParentScope;
Mike Stump1eb44332009-09-09 15:08:12 +000043
John McCallddb0b4d2010-05-12 00:58:13 +000044 /// InDiag - The diagnostic to emit if there is a jump into this scope.
45 unsigned InDiag;
46
47 /// OutDiag - The diagnostic to emit if there is an indirect jump out
48 /// of this scope. Direct jumps always clean up their current scope
49 /// in an orderly way.
50 unsigned OutDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000051
Chris Lattner5af280c2009-04-19 04:46:21 +000052 /// Loc - Location to emit the diagnostic.
53 SourceLocation Loc;
Mike Stump1eb44332009-09-09 15:08:12 +000054
John McCallddb0b4d2010-05-12 00:58:13 +000055 GotoScope(unsigned parentScope, unsigned InDiag, unsigned OutDiag,
56 SourceLocation L)
57 : ParentScope(parentScope), InDiag(InDiag), OutDiag(OutDiag), Loc(L) {}
Chris Lattner5af280c2009-04-19 04:46:21 +000058 };
Mike Stump1eb44332009-09-09 15:08:12 +000059
Chris Lattner5af280c2009-04-19 04:46:21 +000060 llvm::SmallVector<GotoScope, 48> Scopes;
61 llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
62 llvm::SmallVector<Stmt*, 16> Jumps;
John McCallddb0b4d2010-05-12 00:58:13 +000063
64 llvm::SmallVector<IndirectGotoStmt*, 4> IndirectJumps;
Chris Lattnerad8dcf42011-02-17 07:39:24 +000065 llvm::SmallVector<LabelDecl*, 4> IndirectJumpTargets;
Chris Lattner5af280c2009-04-19 04:46:21 +000066public:
67 JumpScopeChecker(Stmt *Body, Sema &S);
68private:
Douglas Gregor43dec6b2010-06-21 23:44:13 +000069 void BuildScopeInformation(Decl *D, unsigned &ParentScope);
Chris Lattner5af280c2009-04-19 04:46:21 +000070 void BuildScopeInformation(Stmt *S, unsigned ParentScope);
71 void VerifyJumps();
John McCallddb0b4d2010-05-12 00:58:13 +000072 void VerifyIndirectJumps();
73 void DiagnoseIndirectJump(IndirectGotoStmt *IG, unsigned IGScope,
Chris Lattnerad8dcf42011-02-17 07:39:24 +000074 LabelDecl *Target, unsigned TargetScope);
Chris Lattner5af280c2009-04-19 04:46:21 +000075 void CheckJump(Stmt *From, Stmt *To,
76 SourceLocation DiagLoc, unsigned JumpDiag);
John McCall5e2a7ac2010-05-12 02:37:54 +000077
78 unsigned GetDeepestCommonScope(unsigned A, unsigned B);
Chris Lattner5af280c2009-04-19 04:46:21 +000079};
80} // end anonymous namespace
81
82
83JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s) : S(s) {
84 // Add a scope entry for function scope.
John McCallddb0b4d2010-05-12 00:58:13 +000085 Scopes.push_back(GotoScope(~0U, ~0U, ~0U, SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +000086
Chris Lattner5af280c2009-04-19 04:46:21 +000087 // Build information for the top level compound statement, so that we have a
88 // defined scope record for every "goto" and label.
89 BuildScopeInformation(Body, 0);
Mike Stump1eb44332009-09-09 15:08:12 +000090
Chris Lattner5af280c2009-04-19 04:46:21 +000091 // Check that all jumps we saw are kosher.
92 VerifyJumps();
John McCallddb0b4d2010-05-12 00:58:13 +000093 VerifyIndirectJumps();
Chris Lattner5af280c2009-04-19 04:46:21 +000094}
Mike Stump1eb44332009-09-09 15:08:12 +000095
John McCall5e2a7ac2010-05-12 02:37:54 +000096/// GetDeepestCommonScope - Finds the innermost scope enclosing the
97/// two scopes.
98unsigned JumpScopeChecker::GetDeepestCommonScope(unsigned A, unsigned B) {
99 while (A != B) {
100 // Inner scopes are created after outer scopes and therefore have
101 // higher indices.
102 if (A < B) {
103 assert(Scopes[B].ParentScope < B);
104 B = Scopes[B].ParentScope;
105 } else {
106 assert(Scopes[A].ParentScope < A);
107 A = Scopes[A].ParentScope;
108 }
109 }
110 return A;
111}
112
Chris Lattner5af280c2009-04-19 04:46:21 +0000113/// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a
114/// diagnostic that should be emitted if control goes over it. If not, return 0.
John McCallddb0b4d2010-05-12 00:58:13 +0000115static std::pair<unsigned,unsigned>
116 GetDiagForGotoScopeDecl(const Decl *D, bool isCPlusPlus) {
Chris Lattner5af280c2009-04-19 04:46:21 +0000117 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallddb0b4d2010-05-12 00:58:13 +0000118 unsigned InDiag = 0, OutDiag = 0;
Chris Lattner5af280c2009-04-19 04:46:21 +0000119 if (VD->getType()->isVariablyModifiedType())
John McCallddb0b4d2010-05-12 00:58:13 +0000120 InDiag = diag::note_protected_by_vla;
121
122 if (VD->hasAttr<BlocksAttr>()) {
123 InDiag = diag::note_protected_by___block;
124 OutDiag = diag::note_exits___block;
125 } else if (VD->hasAttr<CleanupAttr>()) {
126 InDiag = diag::note_protected_by_cleanup;
127 OutDiag = diag::note_exits_cleanup;
128 } else if (isCPlusPlus) {
129 // FIXME: In C++0x, we have to check more conditions than "did we
130 // just give it an initializer?". See 6.7p3.
131 if (VD->hasLocalStorage() && VD->hasInit())
132 InDiag = diag::note_protected_by_variable_init;
133
134 CanQualType T = VD->getType()->getCanonicalTypeUnqualified();
Douglas Gregor025291b2010-07-01 00:21:21 +0000135 if (!T->isDependentType()) {
136 while (CanQual<ArrayType> AT = T->getAs<ArrayType>())
137 T = AT->getElementType();
138 if (CanQual<RecordType> RT = T->getAs<RecordType>())
139 if (!cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor())
140 OutDiag = diag::note_exits_dtor;
141 }
John McCallddb0b4d2010-05-12 00:58:13 +0000142 }
Chris Lattner6d97e5e2010-03-01 20:59:53 +0000143
John McCallddb0b4d2010-05-12 00:58:13 +0000144 return std::make_pair(InDiag, OutDiag);
Chris Lattner5af280c2009-04-19 04:46:21 +0000145 }
Mike Stump1eb44332009-09-09 15:08:12 +0000146
John McCallddb0b4d2010-05-12 00:58:13 +0000147 if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
148 if (TD->getUnderlyingType()->isVariablyModifiedType())
149 return std::make_pair((unsigned) diag::note_protected_by_vla_typedef, 0);
150 }
151
Richard Smith162e1c12011-04-15 14:24:37 +0000152 if (const TypeAliasDecl *TD = dyn_cast<TypeAliasDecl>(D)) {
153 if (TD->getUnderlyingType()->isVariablyModifiedType())
154 return std::make_pair((unsigned) diag::note_protected_by_vla_type_alias, 0);
155 }
156
John McCallddb0b4d2010-05-12 00:58:13 +0000157 return std::make_pair(0U, 0U);
Chris Lattner5af280c2009-04-19 04:46:21 +0000158}
159
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000160/// \brief Build scope information for a declaration that is part of a DeclStmt.
161void JumpScopeChecker::BuildScopeInformation(Decl *D, unsigned &ParentScope) {
162 bool isCPlusPlus = this->S.getLangOptions().CPlusPlus;
163
164 // If this decl causes a new scope, push and switch to it.
165 std::pair<unsigned,unsigned> Diags
166 = GetDiagForGotoScopeDecl(D, isCPlusPlus);
167 if (Diags.first || Diags.second) {
168 Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second,
169 D->getLocation()));
170 ParentScope = Scopes.size()-1;
171 }
172
173 // If the decl has an initializer, walk it with the potentially new
174 // scope we just installed.
175 if (VarDecl *VD = dyn_cast<VarDecl>(D))
176 if (Expr *Init = VD->getInit())
177 BuildScopeInformation(Init, ParentScope);
178}
Chris Lattner5af280c2009-04-19 04:46:21 +0000179
180/// BuildScopeInformation - The statements from CI to CE are known to form a
181/// coherent VLA scope with a specified parent node. Walk through the
182/// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
183/// walking the AST as needed.
184void JumpScopeChecker::BuildScopeInformation(Stmt *S, unsigned ParentScope) {
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000185 bool SkipFirstSubStmt = false;
186
Chris Lattner5af280c2009-04-19 04:46:21 +0000187 // If we found a label, remember that it is in ParentScope scope.
John McCallddb0b4d2010-05-12 00:58:13 +0000188 switch (S->getStmtClass()) {
John McCallddb0b4d2010-05-12 00:58:13 +0000189 case Stmt::AddrLabelExprClass:
190 IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel());
191 break;
192
193 case Stmt::IndirectGotoStmtClass:
John McCall95c225d2010-10-28 08:53:48 +0000194 // "goto *&&lbl;" is a special case which we treat as equivalent
195 // to a normal goto. In addition, we don't calculate scope in the
196 // operand (to avoid recording the address-of-label use), which
197 // works only because of the restricted set of expressions which
198 // we detect as constant targets.
199 if (cast<IndirectGotoStmt>(S)->getConstantTarget()) {
200 LabelAndGotoScopes[S] = ParentScope;
201 Jumps.push_back(S);
202 return;
203 }
204
John McCallddb0b4d2010-05-12 00:58:13 +0000205 LabelAndGotoScopes[S] = ParentScope;
206 IndirectJumps.push_back(cast<IndirectGotoStmt>(S));
207 break;
208
John McCallddb0b4d2010-05-12 00:58:13 +0000209 case Stmt::SwitchStmtClass:
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000210 // Evaluate the condition variable before entering the scope of the switch
211 // statement.
212 if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) {
213 BuildScopeInformation(Var, ParentScope);
214 SkipFirstSubStmt = true;
215 }
216 // Fall through
217
218 case Stmt::GotoStmtClass:
Chris Lattner5af280c2009-04-19 04:46:21 +0000219 // Remember both what scope a goto is in as well as the fact that we have
220 // it. This makes the second scan not have to walk the AST again.
221 LabelAndGotoScopes[S] = ParentScope;
222 Jumps.push_back(S);
John McCallddb0b4d2010-05-12 00:58:13 +0000223 break;
224
225 default:
226 break;
Chris Lattner5af280c2009-04-19 04:46:21 +0000227 }
Mike Stump1eb44332009-09-09 15:08:12 +0000228
John McCall7502c1d2011-02-13 04:07:26 +0000229 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000230 if (SkipFirstSubStmt) {
231 SkipFirstSubStmt = false;
232 continue;
233 }
234
Chris Lattner5af280c2009-04-19 04:46:21 +0000235 Stmt *SubStmt = *CI;
236 if (SubStmt == 0) continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000237
John McCall97ba4812010-08-02 23:33:14 +0000238 // Cases, labels, and defaults aren't "scope parents". It's also
239 // important to handle these iteratively instead of recursively in
240 // order to avoid blowing out the stack.
241 while (true) {
242 Stmt *Next;
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000243 if (CaseStmt *CS = dyn_cast<CaseStmt>(SubStmt))
244 Next = CS->getSubStmt();
245 else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SubStmt))
246 Next = DS->getSubStmt();
247 else if (LabelStmt *LS = dyn_cast<LabelStmt>(SubStmt))
248 Next = LS->getSubStmt();
John McCall97ba4812010-08-02 23:33:14 +0000249 else
250 break;
251
252 LabelAndGotoScopes[SubStmt] = ParentScope;
253 SubStmt = Next;
254 }
255
Chris Lattner5af280c2009-04-19 04:46:21 +0000256 // If this is a declstmt with a VLA definition, it defines a scope from here
257 // to the end of the containing context.
258 if (DeclStmt *DS = dyn_cast<DeclStmt>(SubStmt)) {
Chris Lattner6d97e5e2010-03-01 20:59:53 +0000259 // The decl statement creates a scope if any of the decls in it are VLAs
260 // or have the cleanup attribute.
Chris Lattner5af280c2009-04-19 04:46:21 +0000261 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000262 I != E; ++I)
263 BuildScopeInformation(*I, ParentScope);
Chris Lattner5af280c2009-04-19 04:46:21 +0000264 continue;
265 }
266
267 // Disallow jumps into any part of an @try statement by pushing a scope and
268 // walking all sub-stmts in that scope.
269 if (ObjCAtTryStmt *AT = dyn_cast<ObjCAtTryStmt>(SubStmt)) {
270 // Recursively walk the AST for the @try part.
John McCallddb0b4d2010-05-12 00:58:13 +0000271 Scopes.push_back(GotoScope(ParentScope,
272 diag::note_protected_by_objc_try,
273 diag::note_exits_objc_try,
Chris Lattner5af280c2009-04-19 04:46:21 +0000274 AT->getAtTryLoc()));
275 if (Stmt *TryPart = AT->getTryBody())
276 BuildScopeInformation(TryPart, Scopes.size()-1);
277
278 // Jump from the catch to the finally or try is not valid.
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +0000279 for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) {
280 ObjCAtCatchStmt *AC = AT->getCatchStmt(I);
Chris Lattner5af280c2009-04-19 04:46:21 +0000281 Scopes.push_back(GotoScope(ParentScope,
282 diag::note_protected_by_objc_catch,
John McCallddb0b4d2010-05-12 00:58:13 +0000283 diag::note_exits_objc_catch,
Chris Lattner5af280c2009-04-19 04:46:21 +0000284 AC->getAtCatchLoc()));
Mike Stump1eb44332009-09-09 15:08:12 +0000285 // @catches are nested and it isn't
Chris Lattner5af280c2009-04-19 04:46:21 +0000286 BuildScopeInformation(AC->getCatchBody(), Scopes.size()-1);
287 }
Mike Stump1eb44332009-09-09 15:08:12 +0000288
Chris Lattner5af280c2009-04-19 04:46:21 +0000289 // Jump from the finally to the try or catch is not valid.
290 if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
291 Scopes.push_back(GotoScope(ParentScope,
292 diag::note_protected_by_objc_finally,
John McCallddb0b4d2010-05-12 00:58:13 +0000293 diag::note_exits_objc_finally,
Chris Lattner5af280c2009-04-19 04:46:21 +0000294 AF->getAtFinallyLoc()));
295 BuildScopeInformation(AF, Scopes.size()-1);
296 }
Mike Stump1eb44332009-09-09 15:08:12 +0000297
Chris Lattner5af280c2009-04-19 04:46:21 +0000298 continue;
299 }
Mike Stump1eb44332009-09-09 15:08:12 +0000300
Chris Lattner46c3c4b2009-04-21 06:01:00 +0000301 // Disallow jumps into the protected statement of an @synchronized, but
302 // allow jumps into the object expression it protects.
303 if (ObjCAtSynchronizedStmt *AS = dyn_cast<ObjCAtSynchronizedStmt>(SubStmt)){
304 // Recursively walk the AST for the @synchronized object expr, it is
305 // evaluated in the normal scope.
306 BuildScopeInformation(AS->getSynchExpr(), ParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000307
Chris Lattner46c3c4b2009-04-21 06:01:00 +0000308 // Recursively walk the AST for the @synchronized part, protected by a new
309 // scope.
310 Scopes.push_back(GotoScope(ParentScope,
311 diag::note_protected_by_objc_synchronized,
John McCallddb0b4d2010-05-12 00:58:13 +0000312 diag::note_exits_objc_synchronized,
Chris Lattner46c3c4b2009-04-21 06:01:00 +0000313 AS->getAtSynchronizedLoc()));
314 BuildScopeInformation(AS->getSynchBody(), Scopes.size()-1);
315 continue;
316 }
Sebastian Redl972041f2009-04-27 20:27:31 +0000317
318 // Disallow jumps into any part of a C++ try statement. This is pretty
319 // much the same as for Obj-C.
320 if (CXXTryStmt *TS = dyn_cast<CXXTryStmt>(SubStmt)) {
John McCallddb0b4d2010-05-12 00:58:13 +0000321 Scopes.push_back(GotoScope(ParentScope,
322 diag::note_protected_by_cxx_try,
323 diag::note_exits_cxx_try,
Sebastian Redl972041f2009-04-27 20:27:31 +0000324 TS->getSourceRange().getBegin()));
325 if (Stmt *TryBlock = TS->getTryBlock())
326 BuildScopeInformation(TryBlock, Scopes.size()-1);
327
328 // Jump from the catch into the try is not allowed either.
Mike Stump1eb44332009-09-09 15:08:12 +0000329 for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000330 CXXCatchStmt *CS = TS->getHandler(I);
331 Scopes.push_back(GotoScope(ParentScope,
332 diag::note_protected_by_cxx_catch,
John McCallddb0b4d2010-05-12 00:58:13 +0000333 diag::note_exits_cxx_catch,
Sebastian Redl972041f2009-04-27 20:27:31 +0000334 CS->getSourceRange().getBegin()));
335 BuildScopeInformation(CS->getHandlerBlock(), Scopes.size()-1);
336 }
337
338 continue;
339 }
340
Chris Lattner5af280c2009-04-19 04:46:21 +0000341 // Recursively walk the AST.
342 BuildScopeInformation(SubStmt, ParentScope);
343 }
344}
345
346/// VerifyJumps - Verify each element of the Jumps array to see if they are
347/// valid, emitting diagnostics if not.
348void JumpScopeChecker::VerifyJumps() {
349 while (!Jumps.empty()) {
350 Stmt *Jump = Jumps.pop_back_val();
Mike Stump1eb44332009-09-09 15:08:12 +0000351
352 // With a goto,
Chris Lattner5af280c2009-04-19 04:46:21 +0000353 if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000354 CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(),
Chris Lattner5af280c2009-04-19 04:46:21 +0000355 diag::err_goto_into_protected_scope);
356 continue;
357 }
Mike Stump1eb44332009-09-09 15:08:12 +0000358
John McCall95c225d2010-10-28 08:53:48 +0000359 // We only get indirect gotos here when they have a constant target.
360 if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000361 LabelDecl *Target = IGS->getConstantTarget();
362 CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(),
John McCall95c225d2010-10-28 08:53:48 +0000363 diag::err_goto_into_protected_scope);
364 continue;
365 }
366
John McCallddb0b4d2010-05-12 00:58:13 +0000367 SwitchStmt *SS = cast<SwitchStmt>(Jump);
368 for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
369 SC = SC->getNextSwitchCase()) {
370 assert(LabelAndGotoScopes.count(SC) && "Case not visited?");
371 CheckJump(SS, SC, SC->getLocStart(),
372 diag::err_switch_into_protected_scope);
Chris Lattner5af280c2009-04-19 04:46:21 +0000373 }
374 }
375}
376
John McCall5e2a7ac2010-05-12 02:37:54 +0000377/// VerifyIndirectJumps - Verify whether any possible indirect jump
378/// might cross a protection boundary. Unlike direct jumps, indirect
379/// jumps count cleanups as protection boundaries: since there's no
380/// way to know where the jump is going, we can't implicitly run the
381/// right cleanups the way we can with direct jumps.
John McCallddb0b4d2010-05-12 00:58:13 +0000382///
John McCall5e2a7ac2010-05-12 02:37:54 +0000383/// Thus, an indirect jump is "trivial" if it bypasses no
384/// initializations and no teardowns. More formally, an indirect jump
385/// from A to B is trivial if the path out from A to DCA(A,B) is
386/// trivial and the path in from DCA(A,B) to B is trivial, where
387/// DCA(A,B) is the deepest common ancestor of A and B.
388/// Jump-triviality is transitive but asymmetric.
389///
John McCallddb0b4d2010-05-12 00:58:13 +0000390/// A path in is trivial if none of the entered scopes have an InDiag.
391/// A path out is trivial is none of the exited scopes have an OutDiag.
John McCall5e2a7ac2010-05-12 02:37:54 +0000392///
393/// Under these definitions, this function checks that the indirect
394/// jump between A and B is trivial for every indirect goto statement A
395/// and every label B whose address was taken in the function.
John McCallddb0b4d2010-05-12 00:58:13 +0000396void JumpScopeChecker::VerifyIndirectJumps() {
397 if (IndirectJumps.empty()) return;
398
399 // If there aren't any address-of-label expressions in this function,
400 // complain about the first indirect goto.
401 if (IndirectJumpTargets.empty()) {
402 S.Diag(IndirectJumps[0]->getGotoLoc(),
403 diag::err_indirect_goto_without_addrlabel);
404 return;
405 }
406
John McCall5e2a7ac2010-05-12 02:37:54 +0000407 // Collect a single representative of every scope containing an
408 // indirect goto. For most code bases, this substantially cuts
409 // down on the number of jump sites we'll have to consider later.
John McCallddb0b4d2010-05-12 00:58:13 +0000410 typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope;
411 llvm::SmallVector<JumpScope, 32> JumpScopes;
412 {
413 llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap;
414 for (llvm::SmallVectorImpl<IndirectGotoStmt*>::iterator
415 I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) {
416 IndirectGotoStmt *IG = *I;
417 assert(LabelAndGotoScopes.count(IG) &&
418 "indirect jump didn't get added to scopes?");
419 unsigned IGScope = LabelAndGotoScopes[IG];
420 IndirectGotoStmt *&Entry = JumpScopesMap[IGScope];
421 if (!Entry) Entry = IG;
422 }
423 JumpScopes.reserve(JumpScopesMap.size());
424 for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator
425 I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I)
426 JumpScopes.push_back(*I);
427 }
428
John McCall5e2a7ac2010-05-12 02:37:54 +0000429 // Collect a single representative of every scope containing a
430 // label whose address was taken somewhere in the function.
431 // For most code bases, there will be only one such scope.
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000432 llvm::DenseMap<unsigned, LabelDecl*> TargetScopes;
433 for (llvm::SmallVectorImpl<LabelDecl*>::iterator
John McCallddb0b4d2010-05-12 00:58:13 +0000434 I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end();
435 I != E; ++I) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000436 LabelDecl *TheLabel = *I;
437 assert(LabelAndGotoScopes.count(TheLabel->getStmt()) &&
John McCallddb0b4d2010-05-12 00:58:13 +0000438 "Referenced label didn't get added to scopes?");
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000439 unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()];
440 LabelDecl *&Target = TargetScopes[LabelScope];
John McCallddb0b4d2010-05-12 00:58:13 +0000441 if (!Target) Target = TheLabel;
442 }
443
John McCall5e2a7ac2010-05-12 02:37:54 +0000444 // For each target scope, make sure it's trivially reachable from
445 // every scope containing a jump site.
446 //
447 // A path between scopes always consists of exitting zero or more
448 // scopes, then entering zero or more scopes. We build a set of
449 // of scopes S from which the target scope can be trivially
450 // entered, then verify that every jump scope can be trivially
451 // exitted to reach a scope in S.
John McCallddb0b4d2010-05-12 00:58:13 +0000452 llvm::BitVector Reachable(Scopes.size(), false);
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000453 for (llvm::DenseMap<unsigned,LabelDecl*>::iterator
John McCallddb0b4d2010-05-12 00:58:13 +0000454 TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) {
455 unsigned TargetScope = TI->first;
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000456 LabelDecl *TargetLabel = TI->second;
John McCallddb0b4d2010-05-12 00:58:13 +0000457
458 Reachable.reset();
459
460 // Mark all the enclosing scopes from which you can safely jump
John McCall5e2a7ac2010-05-12 02:37:54 +0000461 // into the target scope. 'Min' will end up being the index of
462 // the shallowest such scope.
John McCallddb0b4d2010-05-12 00:58:13 +0000463 unsigned Min = TargetScope;
464 while (true) {
465 Reachable.set(Min);
466
467 // Don't go beyond the outermost scope.
468 if (Min == 0) break;
469
John McCall5e2a7ac2010-05-12 02:37:54 +0000470 // Stop if we can't trivially enter the current scope.
John McCallddb0b4d2010-05-12 00:58:13 +0000471 if (Scopes[Min].InDiag) break;
472
473 Min = Scopes[Min].ParentScope;
474 }
475
476 // Walk through all the jump sites, checking that they can trivially
477 // reach this label scope.
478 for (llvm::SmallVectorImpl<JumpScope>::iterator
479 I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) {
480 unsigned Scope = I->first;
481
482 // Walk out the "scope chain" for this scope, looking for a scope
John McCall5e2a7ac2010-05-12 02:37:54 +0000483 // we've marked reachable. For well-formed code this amortizes
484 // to O(JumpScopes.size() / Scopes.size()): we only iterate
485 // when we see something unmarked, and in well-formed code we
486 // mark everything we iterate past.
John McCallddb0b4d2010-05-12 00:58:13 +0000487 bool IsReachable = false;
488 while (true) {
489 if (Reachable.test(Scope)) {
490 // If we find something reachable, mark all the scopes we just
491 // walked through as reachable.
492 for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope)
493 Reachable.set(S);
494 IsReachable = true;
495 break;
496 }
497
498 // Don't walk out if we've reached the top-level scope or we've
499 // gotten shallower than the shallowest reachable scope.
500 if (Scope == 0 || Scope < Min) break;
501
502 // Don't walk out through an out-diagnostic.
503 if (Scopes[Scope].OutDiag) break;
504
505 Scope = Scopes[Scope].ParentScope;
506 }
507
508 // Only diagnose if we didn't find something.
509 if (IsReachable) continue;
510
511 DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope);
512 }
513 }
514}
515
John McCall5e2a7ac2010-05-12 02:37:54 +0000516/// Diagnose an indirect jump which is known to cross scopes.
John McCallddb0b4d2010-05-12 00:58:13 +0000517void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump,
518 unsigned JumpScope,
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000519 LabelDecl *Target,
John McCallddb0b4d2010-05-12 00:58:13 +0000520 unsigned TargetScope) {
521 assert(JumpScope != TargetScope);
522
John McCall95c225d2010-10-28 08:53:48 +0000523 S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000524 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
John McCallddb0b4d2010-05-12 00:58:13 +0000525
John McCall5e2a7ac2010-05-12 02:37:54 +0000526 unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope);
John McCallddb0b4d2010-05-12 00:58:13 +0000527
John McCall5e2a7ac2010-05-12 02:37:54 +0000528 // Walk out the scope chain until we reach the common ancestor.
529 for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope)
530 if (Scopes[I].OutDiag)
531 S.Diag(Scopes[I].Loc, Scopes[I].OutDiag);
John McCallddb0b4d2010-05-12 00:58:13 +0000532
533 // Now walk into the scopes containing the label whose address was taken.
John McCall5e2a7ac2010-05-12 02:37:54 +0000534 for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope)
535 if (Scopes[I].InDiag)
536 S.Diag(Scopes[I].Loc, Scopes[I].InDiag);
John McCallddb0b4d2010-05-12 00:58:13 +0000537}
538
Chris Lattner5af280c2009-04-19 04:46:21 +0000539/// CheckJump - Validate that the specified jump statement is valid: that it is
540/// jumping within or out of its current scope, not into a deeper one.
541void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To,
542 SourceLocation DiagLoc, unsigned JumpDiag) {
543 assert(LabelAndGotoScopes.count(From) && "Jump didn't get added to scopes?");
544 unsigned FromScope = LabelAndGotoScopes[From];
545
546 assert(LabelAndGotoScopes.count(To) && "Jump didn't get added to scopes?");
547 unsigned ToScope = LabelAndGotoScopes[To];
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Chris Lattner5af280c2009-04-19 04:46:21 +0000549 // Common case: exactly the same scope, which is fine.
550 if (FromScope == ToScope) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000551
John McCall5e2a7ac2010-05-12 02:37:54 +0000552 unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000553
John McCall5e2a7ac2010-05-12 02:37:54 +0000554 // It's okay to jump out from a nested scope.
555 if (CommonScope == ToScope) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000556
John McCall5e2a7ac2010-05-12 02:37:54 +0000557 // Pull out (and reverse) any scopes we might need to diagnose skipping.
558 llvm::SmallVector<unsigned, 10> ToScopes;
559 for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope)
560 if (Scopes[I].InDiag)
561 ToScopes.push_back(I);
Chris Lattner5af280c2009-04-19 04:46:21 +0000562
John McCall5e2a7ac2010-05-12 02:37:54 +0000563 // If the only scopes present are cleanup scopes, we're okay.
John McCallddb0b4d2010-05-12 00:58:13 +0000564 if (ToScopes.empty()) return;
565
566 S.Diag(DiagLoc, JumpDiag);
567
Chris Lattner5af280c2009-04-19 04:46:21 +0000568 // Emit diagnostics for whatever is left in ToScopes.
569 for (unsigned i = 0, e = ToScopes.size(); i != e; ++i)
John McCallddb0b4d2010-05-12 00:58:13 +0000570 S.Diag(Scopes[ToScopes[i]].Loc, Scopes[ToScopes[i]].InDiag);
Chris Lattner5af280c2009-04-19 04:46:21 +0000571}
572
573void Sema::DiagnoseInvalidJumps(Stmt *Body) {
Douglas Gregor6490ae52009-11-17 06:14:37 +0000574 (void)JumpScopeChecker(Body, *this);
Chris Lattner5af280c2009-04-19 04:46:21 +0000575}