blob: 8cabc922855af472101cf03a580b26c62a93293b [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"
Douglas Gregore4135162011-05-27 16:05:29 +000018#include "clang/AST/ExprCXX.h"
Chris Lattner16f00492009-04-26 01:32:48 +000019#include "clang/AST/StmtObjC.h"
Sebastian Redl972041f2009-04-27 20:27:31 +000020#include "clang/AST/StmtCXX.h"
Douglas Gregore737f502010-08-12 20:07:10 +000021#include "llvm/ADT/BitVector.h"
Chris Lattner5af280c2009-04-19 04:46:21 +000022using 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;
Mike Stump1eb44332009-09-09 15:08:12 +000034
Chris Lattner5af280c2009-04-19 04:46:21 +000035 /// 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;
Mike Stump1eb44332009-09-09 15:08:12 +000044
John McCallddb0b4d2010-05-12 00:58:13 +000045 /// 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;
Mike Stump1eb44332009-09-09 15:08:12 +000052
Chris Lattner5af280c2009-04-19 04:46:21 +000053 /// Loc - Location to emit the diagnostic.
54 SourceLocation Loc;
Mike Stump1eb44332009-09-09 15:08:12 +000055
John McCallddb0b4d2010-05-12 00:58:13 +000056 GotoScope(unsigned parentScope, unsigned InDiag, unsigned OutDiag,
57 SourceLocation L)
58 : ParentScope(parentScope), InDiag(InDiag), OutDiag(OutDiag), Loc(L) {}
Chris Lattner5af280c2009-04-19 04:46:21 +000059 };
Mike Stump1eb44332009-09-09 15:08:12 +000060
Chris Lattner5af280c2009-04-19 04:46:21 +000061 llvm::SmallVector<GotoScope, 48> Scopes;
62 llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
63 llvm::SmallVector<Stmt*, 16> Jumps;
John McCallddb0b4d2010-05-12 00:58:13 +000064
65 llvm::SmallVector<IndirectGotoStmt*, 4> IndirectJumps;
Chris Lattnerad8dcf42011-02-17 07:39:24 +000066 llvm::SmallVector<LabelDecl*, 4> IndirectJumpTargets;
Chris Lattner5af280c2009-04-19 04:46:21 +000067public:
68 JumpScopeChecker(Stmt *Body, Sema &S);
69private:
Douglas Gregor43dec6b2010-06-21 23:44:13 +000070 void BuildScopeInformation(Decl *D, unsigned &ParentScope);
Chris Lattner5af280c2009-04-19 04:46:21 +000071 void BuildScopeInformation(Stmt *S, unsigned ParentScope);
72 void VerifyJumps();
John McCallddb0b4d2010-05-12 00:58:13 +000073 void VerifyIndirectJumps();
74 void DiagnoseIndirectJump(IndirectGotoStmt *IG, unsigned IGScope,
Chris Lattnerad8dcf42011-02-17 07:39:24 +000075 LabelDecl *Target, unsigned TargetScope);
Chris Lattner5af280c2009-04-19 04:46:21 +000076 void CheckJump(Stmt *From, Stmt *To,
77 SourceLocation DiagLoc, unsigned JumpDiag);
John McCall5e2a7ac2010-05-12 02:37:54 +000078
79 unsigned GetDeepestCommonScope(unsigned A, unsigned B);
Chris Lattner5af280c2009-04-19 04:46:21 +000080};
81} // end anonymous namespace
82
83
84JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s) : S(s) {
85 // Add a scope entry for function scope.
John McCallddb0b4d2010-05-12 00:58:13 +000086 Scopes.push_back(GotoScope(~0U, ~0U, ~0U, SourceLocation()));
Mike Stump1eb44332009-09-09 15:08:12 +000087
Chris Lattner5af280c2009-04-19 04:46:21 +000088 // Build information for the top level compound statement, so that we have a
89 // defined scope record for every "goto" and label.
90 BuildScopeInformation(Body, 0);
Mike Stump1eb44332009-09-09 15:08:12 +000091
Chris Lattner5af280c2009-04-19 04:46:21 +000092 // Check that all jumps we saw are kosher.
93 VerifyJumps();
John McCallddb0b4d2010-05-12 00:58:13 +000094 VerifyIndirectJumps();
Chris Lattner5af280c2009-04-19 04:46:21 +000095}
Mike Stump1eb44332009-09-09 15:08:12 +000096
John McCall5e2a7ac2010-05-12 02:37:54 +000097/// GetDeepestCommonScope - Finds the innermost scope enclosing the
98/// two scopes.
99unsigned JumpScopeChecker::GetDeepestCommonScope(unsigned A, unsigned B) {
100 while (A != B) {
101 // Inner scopes are created after outer scopes and therefore have
102 // higher indices.
103 if (A < B) {
104 assert(Scopes[B].ParentScope < B);
105 B = Scopes[B].ParentScope;
106 } else {
107 assert(Scopes[A].ParentScope < A);
108 A = Scopes[A].ParentScope;
109 }
110 }
111 return A;
112}
113
John McCallf85e1932011-06-15 23:02:42 +0000114typedef std::pair<unsigned,unsigned> ScopePair;
115
Chris Lattner5af280c2009-04-19 04:46:21 +0000116/// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a
117/// diagnostic that should be emitted if control goes over it. If not, return 0.
John McCallf85e1932011-06-15 23:02:42 +0000118static ScopePair GetDiagForGotoScopeDecl(ASTContext &Context, const Decl *D) {
Chris Lattner5af280c2009-04-19 04:46:21 +0000119 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
John McCallddb0b4d2010-05-12 00:58:13 +0000120 unsigned InDiag = 0, OutDiag = 0;
Chris Lattner5af280c2009-04-19 04:46:21 +0000121 if (VD->getType()->isVariablyModifiedType())
John McCallddb0b4d2010-05-12 00:58:13 +0000122 InDiag = diag::note_protected_by_vla;
123
John McCallf85e1932011-06-15 23:02:42 +0000124 if (VD->hasAttr<BlocksAttr>())
125 return ScopePair(diag::note_protected_by___block,
126 diag::note_exits___block);
127
128 if (VD->hasAttr<CleanupAttr>())
129 return ScopePair(diag::note_protected_by_cleanup,
130 diag::note_exits_cleanup);
131
132 if (Context.getLangOptions().ObjCAutoRefCount && VD->hasLocalStorage()) {
133 switch (VD->getType().getObjCLifetime()) {
134 case Qualifiers::OCL_None:
135 case Qualifiers::OCL_ExplicitNone:
136 case Qualifiers::OCL_Autoreleasing:
137 break;
138
139 case Qualifiers::OCL_Strong:
140 case Qualifiers::OCL_Weak:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000141 return ScopePair(diag::note_protected_by_objc_ownership,
142 diag::note_exits_objc_ownership);
John McCallf85e1932011-06-15 23:02:42 +0000143 }
144 }
145
146 if (Context.getLangOptions().CPlusPlus && VD->hasLocalStorage()) {
147 // C++0x [stmt.dcl]p3:
148 // A program that jumps from a point where a variable with automatic
149 // storage duration is not in scope to a point where it is in scope
150 // is ill-formed unless the variable has scalar type, class type with
151 // a trivial default constructor and a trivial destructor, a
152 // cv-qualified version of one of these types, or an array of one of
153 // the preceding types and is declared without an initializer.
154
155 // C++03 [stmt.dcl.p3:
156 // A program that jumps from a point where a local variable
157 // with automatic storage duration is not in scope to a point
158 // where it is in scope is ill-formed unless the variable has
159 // POD type and is declared without an initializer.
160
161 if (const Expr *init = VD->getInit()) {
162 // We actually give variables of record type (or array thereof)
163 // an initializer even if that initializer only calls a trivial
164 // ctor. Detect that case.
165 // FIXME: With generalized initializer lists, this may
166 // classify "X x{};" as having no initializer.
167 unsigned inDiagToUse = diag::note_protected_by_variable_init;
168
169 const CXXRecordDecl *record = 0;
170
171 if (const CXXConstructExpr *cce = dyn_cast<CXXConstructExpr>(init)) {
172 const CXXConstructorDecl *ctor = cce->getConstructor();
173 record = ctor->getParent();
174
175 if (ctor->isTrivial() && ctor->isDefaultConstructor()) {
176 if (Context.getLangOptions().CPlusPlus0x) {
177 inDiagToUse = (record->hasTrivialDestructor() ? 0 :
178 diag::note_protected_by_variable_nontriv_destructor);
179 } else {
180 if (record->isPOD())
181 inDiagToUse = 0;
182 }
Douglas Gregore4135162011-05-27 16:05:29 +0000183 }
John McCallf85e1932011-06-15 23:02:42 +0000184 } else if (VD->getType()->isArrayType()) {
185 record = VD->getType()->getBaseElementTypeUnsafe()
186 ->getAsCXXRecordDecl();
Douglas Gregore4135162011-05-27 16:05:29 +0000187 }
John McCallf85e1932011-06-15 23:02:42 +0000188
189 if (inDiagToUse)
190 InDiag = inDiagToUse;
191
192 // Also object to indirect jumps which leave scopes with dtors.
193 if (record && !record->hasTrivialDestructor())
Douglas Gregorf61103e2011-05-27 21:28:00 +0000194 OutDiag = diag::note_exits_dtor;
Douglas Gregor025291b2010-07-01 00:21:21 +0000195 }
John McCallddb0b4d2010-05-12 00:58:13 +0000196 }
Chris Lattner6d97e5e2010-03-01 20:59:53 +0000197
John McCallf85e1932011-06-15 23:02:42 +0000198 return ScopePair(InDiag, OutDiag);
Chris Lattner5af280c2009-04-19 04:46:21 +0000199 }
Mike Stump1eb44332009-09-09 15:08:12 +0000200
John McCallddb0b4d2010-05-12 00:58:13 +0000201 if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
202 if (TD->getUnderlyingType()->isVariablyModifiedType())
John McCallf85e1932011-06-15 23:02:42 +0000203 return ScopePair(diag::note_protected_by_vla_typedef, 0);
John McCallddb0b4d2010-05-12 00:58:13 +0000204 }
205
Richard Smith162e1c12011-04-15 14:24:37 +0000206 if (const TypeAliasDecl *TD = dyn_cast<TypeAliasDecl>(D)) {
207 if (TD->getUnderlyingType()->isVariablyModifiedType())
John McCallf85e1932011-06-15 23:02:42 +0000208 return ScopePair(diag::note_protected_by_vla_type_alias, 0);
Richard Smith162e1c12011-04-15 14:24:37 +0000209 }
210
John McCallf85e1932011-06-15 23:02:42 +0000211 return ScopePair(0U, 0U);
Chris Lattner5af280c2009-04-19 04:46:21 +0000212}
213
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000214/// \brief Build scope information for a declaration that is part of a DeclStmt.
215void JumpScopeChecker::BuildScopeInformation(Decl *D, unsigned &ParentScope) {
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000216 // If this decl causes a new scope, push and switch to it.
John McCallf85e1932011-06-15 23:02:42 +0000217 std::pair<unsigned,unsigned> Diags = GetDiagForGotoScopeDecl(S.Context, D);
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000218 if (Diags.first || Diags.second) {
219 Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second,
220 D->getLocation()));
221 ParentScope = Scopes.size()-1;
222 }
223
224 // If the decl has an initializer, walk it with the potentially new
225 // scope we just installed.
226 if (VarDecl *VD = dyn_cast<VarDecl>(D))
227 if (Expr *Init = VD->getInit())
228 BuildScopeInformation(Init, ParentScope);
229}
Chris Lattner5af280c2009-04-19 04:46:21 +0000230
231/// BuildScopeInformation - The statements from CI to CE are known to form a
232/// coherent VLA scope with a specified parent node. Walk through the
233/// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
234/// walking the AST as needed.
235void JumpScopeChecker::BuildScopeInformation(Stmt *S, unsigned ParentScope) {
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000236 bool SkipFirstSubStmt = false;
237
Chris Lattner5af280c2009-04-19 04:46:21 +0000238 // If we found a label, remember that it is in ParentScope scope.
John McCallddb0b4d2010-05-12 00:58:13 +0000239 switch (S->getStmtClass()) {
John McCallddb0b4d2010-05-12 00:58:13 +0000240 case Stmt::AddrLabelExprClass:
241 IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel());
242 break;
243
244 case Stmt::IndirectGotoStmtClass:
John McCall95c225d2010-10-28 08:53:48 +0000245 // "goto *&&lbl;" is a special case which we treat as equivalent
246 // to a normal goto. In addition, we don't calculate scope in the
247 // operand (to avoid recording the address-of-label use), which
248 // works only because of the restricted set of expressions which
249 // we detect as constant targets.
250 if (cast<IndirectGotoStmt>(S)->getConstantTarget()) {
251 LabelAndGotoScopes[S] = ParentScope;
252 Jumps.push_back(S);
253 return;
254 }
255
John McCallddb0b4d2010-05-12 00:58:13 +0000256 LabelAndGotoScopes[S] = ParentScope;
257 IndirectJumps.push_back(cast<IndirectGotoStmt>(S));
258 break;
259
John McCallddb0b4d2010-05-12 00:58:13 +0000260 case Stmt::SwitchStmtClass:
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000261 // Evaluate the condition variable before entering the scope of the switch
262 // statement.
263 if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) {
264 BuildScopeInformation(Var, ParentScope);
265 SkipFirstSubStmt = true;
266 }
267 // Fall through
268
269 case Stmt::GotoStmtClass:
Chris Lattner5af280c2009-04-19 04:46:21 +0000270 // Remember both what scope a goto is in as well as the fact that we have
271 // it. This makes the second scan not have to walk the AST again.
272 LabelAndGotoScopes[S] = ParentScope;
273 Jumps.push_back(S);
John McCallddb0b4d2010-05-12 00:58:13 +0000274 break;
275
276 default:
277 break;
Chris Lattner5af280c2009-04-19 04:46:21 +0000278 }
Mike Stump1eb44332009-09-09 15:08:12 +0000279
John McCall7502c1d2011-02-13 04:07:26 +0000280 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000281 if (SkipFirstSubStmt) {
282 SkipFirstSubStmt = false;
283 continue;
284 }
285
Chris Lattner5af280c2009-04-19 04:46:21 +0000286 Stmt *SubStmt = *CI;
287 if (SubStmt == 0) continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000288
John McCall97ba4812010-08-02 23:33:14 +0000289 // Cases, labels, and defaults aren't "scope parents". It's also
290 // important to handle these iteratively instead of recursively in
291 // order to avoid blowing out the stack.
292 while (true) {
293 Stmt *Next;
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000294 if (CaseStmt *CS = dyn_cast<CaseStmt>(SubStmt))
295 Next = CS->getSubStmt();
296 else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SubStmt))
297 Next = DS->getSubStmt();
298 else if (LabelStmt *LS = dyn_cast<LabelStmt>(SubStmt))
299 Next = LS->getSubStmt();
John McCall97ba4812010-08-02 23:33:14 +0000300 else
301 break;
302
303 LabelAndGotoScopes[SubStmt] = ParentScope;
304 SubStmt = Next;
305 }
306
Chris Lattner5af280c2009-04-19 04:46:21 +0000307 // If this is a declstmt with a VLA definition, it defines a scope from here
308 // to the end of the containing context.
309 if (DeclStmt *DS = dyn_cast<DeclStmt>(SubStmt)) {
Chris Lattner6d97e5e2010-03-01 20:59:53 +0000310 // The decl statement creates a scope if any of the decls in it are VLAs
311 // or have the cleanup attribute.
Chris Lattner5af280c2009-04-19 04:46:21 +0000312 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
Douglas Gregor43dec6b2010-06-21 23:44:13 +0000313 I != E; ++I)
314 BuildScopeInformation(*I, ParentScope);
Chris Lattner5af280c2009-04-19 04:46:21 +0000315 continue;
316 }
317
318 // Disallow jumps into any part of an @try statement by pushing a scope and
319 // walking all sub-stmts in that scope.
320 if (ObjCAtTryStmt *AT = dyn_cast<ObjCAtTryStmt>(SubStmt)) {
321 // Recursively walk the AST for the @try part.
John McCallddb0b4d2010-05-12 00:58:13 +0000322 Scopes.push_back(GotoScope(ParentScope,
323 diag::note_protected_by_objc_try,
324 diag::note_exits_objc_try,
Chris Lattner5af280c2009-04-19 04:46:21 +0000325 AT->getAtTryLoc()));
326 if (Stmt *TryPart = AT->getTryBody())
327 BuildScopeInformation(TryPart, Scopes.size()-1);
328
329 // Jump from the catch to the finally or try is not valid.
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +0000330 for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) {
331 ObjCAtCatchStmt *AC = AT->getCatchStmt(I);
Chris Lattner5af280c2009-04-19 04:46:21 +0000332 Scopes.push_back(GotoScope(ParentScope,
333 diag::note_protected_by_objc_catch,
John McCallddb0b4d2010-05-12 00:58:13 +0000334 diag::note_exits_objc_catch,
Chris Lattner5af280c2009-04-19 04:46:21 +0000335 AC->getAtCatchLoc()));
Mike Stump1eb44332009-09-09 15:08:12 +0000336 // @catches are nested and it isn't
Chris Lattner5af280c2009-04-19 04:46:21 +0000337 BuildScopeInformation(AC->getCatchBody(), Scopes.size()-1);
338 }
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Chris Lattner5af280c2009-04-19 04:46:21 +0000340 // Jump from the finally to the try or catch is not valid.
341 if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
342 Scopes.push_back(GotoScope(ParentScope,
343 diag::note_protected_by_objc_finally,
John McCallddb0b4d2010-05-12 00:58:13 +0000344 diag::note_exits_objc_finally,
Chris Lattner5af280c2009-04-19 04:46:21 +0000345 AF->getAtFinallyLoc()));
346 BuildScopeInformation(AF, Scopes.size()-1);
347 }
Mike Stump1eb44332009-09-09 15:08:12 +0000348
Chris Lattner5af280c2009-04-19 04:46:21 +0000349 continue;
350 }
Mike Stump1eb44332009-09-09 15:08:12 +0000351
Chris Lattner46c3c4b2009-04-21 06:01:00 +0000352 // Disallow jumps into the protected statement of an @synchronized, but
353 // allow jumps into the object expression it protects.
354 if (ObjCAtSynchronizedStmt *AS = dyn_cast<ObjCAtSynchronizedStmt>(SubStmt)){
355 // Recursively walk the AST for the @synchronized object expr, it is
356 // evaluated in the normal scope.
357 BuildScopeInformation(AS->getSynchExpr(), ParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Chris Lattner46c3c4b2009-04-21 06:01:00 +0000359 // Recursively walk the AST for the @synchronized part, protected by a new
360 // scope.
361 Scopes.push_back(GotoScope(ParentScope,
362 diag::note_protected_by_objc_synchronized,
John McCallddb0b4d2010-05-12 00:58:13 +0000363 diag::note_exits_objc_synchronized,
Chris Lattner46c3c4b2009-04-21 06:01:00 +0000364 AS->getAtSynchronizedLoc()));
365 BuildScopeInformation(AS->getSynchBody(), Scopes.size()-1);
366 continue;
367 }
Sebastian Redl972041f2009-04-27 20:27:31 +0000368
369 // Disallow jumps into any part of a C++ try statement. This is pretty
370 // much the same as for Obj-C.
371 if (CXXTryStmt *TS = dyn_cast<CXXTryStmt>(SubStmt)) {
John McCallddb0b4d2010-05-12 00:58:13 +0000372 Scopes.push_back(GotoScope(ParentScope,
373 diag::note_protected_by_cxx_try,
374 diag::note_exits_cxx_try,
Sebastian Redl972041f2009-04-27 20:27:31 +0000375 TS->getSourceRange().getBegin()));
376 if (Stmt *TryBlock = TS->getTryBlock())
377 BuildScopeInformation(TryBlock, Scopes.size()-1);
378
379 // Jump from the catch into the try is not allowed either.
Mike Stump1eb44332009-09-09 15:08:12 +0000380 for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) {
Sebastian Redl972041f2009-04-27 20:27:31 +0000381 CXXCatchStmt *CS = TS->getHandler(I);
382 Scopes.push_back(GotoScope(ParentScope,
383 diag::note_protected_by_cxx_catch,
John McCallddb0b4d2010-05-12 00:58:13 +0000384 diag::note_exits_cxx_catch,
Sebastian Redl972041f2009-04-27 20:27:31 +0000385 CS->getSourceRange().getBegin()));
386 BuildScopeInformation(CS->getHandlerBlock(), Scopes.size()-1);
387 }
388
389 continue;
390 }
391
John McCallf85e1932011-06-15 23:02:42 +0000392 // Disallow jumps into the protected statement of an @autoreleasepool.
393 if (ObjCAutoreleasePoolStmt *AS = dyn_cast<ObjCAutoreleasePoolStmt>(SubStmt)){
394 // Recursively walk the AST for the @autoreleasepool part, protected by a new
395 // scope.
396 Scopes.push_back(GotoScope(ParentScope,
397 diag::note_protected_by_objc_autoreleasepool,
398 diag::note_exits_objc_autoreleasepool,
399 AS->getAtLoc()));
400 BuildScopeInformation(AS->getSubStmt(), Scopes.size()-1);
401 continue;
402 }
403
Chris Lattner5af280c2009-04-19 04:46:21 +0000404 // Recursively walk the AST.
405 BuildScopeInformation(SubStmt, ParentScope);
406 }
407}
408
409/// VerifyJumps - Verify each element of the Jumps array to see if they are
410/// valid, emitting diagnostics if not.
411void JumpScopeChecker::VerifyJumps() {
412 while (!Jumps.empty()) {
413 Stmt *Jump = Jumps.pop_back_val();
Mike Stump1eb44332009-09-09 15:08:12 +0000414
415 // With a goto,
Chris Lattner5af280c2009-04-19 04:46:21 +0000416 if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000417 CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(),
Chris Lattner5af280c2009-04-19 04:46:21 +0000418 diag::err_goto_into_protected_scope);
419 continue;
420 }
Mike Stump1eb44332009-09-09 15:08:12 +0000421
John McCall95c225d2010-10-28 08:53:48 +0000422 // We only get indirect gotos here when they have a constant target.
423 if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000424 LabelDecl *Target = IGS->getConstantTarget();
425 CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(),
John McCall95c225d2010-10-28 08:53:48 +0000426 diag::err_goto_into_protected_scope);
427 continue;
428 }
429
John McCallddb0b4d2010-05-12 00:58:13 +0000430 SwitchStmt *SS = cast<SwitchStmt>(Jump);
431 for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
432 SC = SC->getNextSwitchCase()) {
433 assert(LabelAndGotoScopes.count(SC) && "Case not visited?");
434 CheckJump(SS, SC, SC->getLocStart(),
435 diag::err_switch_into_protected_scope);
Chris Lattner5af280c2009-04-19 04:46:21 +0000436 }
437 }
438}
439
John McCall5e2a7ac2010-05-12 02:37:54 +0000440/// VerifyIndirectJumps - Verify whether any possible indirect jump
441/// might cross a protection boundary. Unlike direct jumps, indirect
442/// jumps count cleanups as protection boundaries: since there's no
443/// way to know where the jump is going, we can't implicitly run the
444/// right cleanups the way we can with direct jumps.
John McCallddb0b4d2010-05-12 00:58:13 +0000445///
John McCall5e2a7ac2010-05-12 02:37:54 +0000446/// Thus, an indirect jump is "trivial" if it bypasses no
447/// initializations and no teardowns. More formally, an indirect jump
448/// from A to B is trivial if the path out from A to DCA(A,B) is
449/// trivial and the path in from DCA(A,B) to B is trivial, where
450/// DCA(A,B) is the deepest common ancestor of A and B.
451/// Jump-triviality is transitive but asymmetric.
452///
John McCallddb0b4d2010-05-12 00:58:13 +0000453/// A path in is trivial if none of the entered scopes have an InDiag.
454/// A path out is trivial is none of the exited scopes have an OutDiag.
John McCall5e2a7ac2010-05-12 02:37:54 +0000455///
456/// Under these definitions, this function checks that the indirect
457/// jump between A and B is trivial for every indirect goto statement A
458/// and every label B whose address was taken in the function.
John McCallddb0b4d2010-05-12 00:58:13 +0000459void JumpScopeChecker::VerifyIndirectJumps() {
460 if (IndirectJumps.empty()) return;
461
462 // If there aren't any address-of-label expressions in this function,
463 // complain about the first indirect goto.
464 if (IndirectJumpTargets.empty()) {
465 S.Diag(IndirectJumps[0]->getGotoLoc(),
466 diag::err_indirect_goto_without_addrlabel);
467 return;
468 }
469
John McCall5e2a7ac2010-05-12 02:37:54 +0000470 // Collect a single representative of every scope containing an
471 // indirect goto. For most code bases, this substantially cuts
472 // down on the number of jump sites we'll have to consider later.
John McCallddb0b4d2010-05-12 00:58:13 +0000473 typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope;
474 llvm::SmallVector<JumpScope, 32> JumpScopes;
475 {
476 llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap;
477 for (llvm::SmallVectorImpl<IndirectGotoStmt*>::iterator
478 I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) {
479 IndirectGotoStmt *IG = *I;
480 assert(LabelAndGotoScopes.count(IG) &&
481 "indirect jump didn't get added to scopes?");
482 unsigned IGScope = LabelAndGotoScopes[IG];
483 IndirectGotoStmt *&Entry = JumpScopesMap[IGScope];
484 if (!Entry) Entry = IG;
485 }
486 JumpScopes.reserve(JumpScopesMap.size());
487 for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator
488 I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I)
489 JumpScopes.push_back(*I);
490 }
491
John McCall5e2a7ac2010-05-12 02:37:54 +0000492 // Collect a single representative of every scope containing a
493 // label whose address was taken somewhere in the function.
494 // For most code bases, there will be only one such scope.
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000495 llvm::DenseMap<unsigned, LabelDecl*> TargetScopes;
496 for (llvm::SmallVectorImpl<LabelDecl*>::iterator
John McCallddb0b4d2010-05-12 00:58:13 +0000497 I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end();
498 I != E; ++I) {
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000499 LabelDecl *TheLabel = *I;
500 assert(LabelAndGotoScopes.count(TheLabel->getStmt()) &&
John McCallddb0b4d2010-05-12 00:58:13 +0000501 "Referenced label didn't get added to scopes?");
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000502 unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()];
503 LabelDecl *&Target = TargetScopes[LabelScope];
John McCallddb0b4d2010-05-12 00:58:13 +0000504 if (!Target) Target = TheLabel;
505 }
506
John McCall5e2a7ac2010-05-12 02:37:54 +0000507 // For each target scope, make sure it's trivially reachable from
508 // every scope containing a jump site.
509 //
510 // A path between scopes always consists of exitting zero or more
511 // scopes, then entering zero or more scopes. We build a set of
512 // of scopes S from which the target scope can be trivially
513 // entered, then verify that every jump scope can be trivially
514 // exitted to reach a scope in S.
John McCallddb0b4d2010-05-12 00:58:13 +0000515 llvm::BitVector Reachable(Scopes.size(), false);
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000516 for (llvm::DenseMap<unsigned,LabelDecl*>::iterator
John McCallddb0b4d2010-05-12 00:58:13 +0000517 TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) {
518 unsigned TargetScope = TI->first;
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000519 LabelDecl *TargetLabel = TI->second;
John McCallddb0b4d2010-05-12 00:58:13 +0000520
521 Reachable.reset();
522
523 // Mark all the enclosing scopes from which you can safely jump
John McCall5e2a7ac2010-05-12 02:37:54 +0000524 // into the target scope. 'Min' will end up being the index of
525 // the shallowest such scope.
John McCallddb0b4d2010-05-12 00:58:13 +0000526 unsigned Min = TargetScope;
527 while (true) {
528 Reachable.set(Min);
529
530 // Don't go beyond the outermost scope.
531 if (Min == 0) break;
532
John McCall5e2a7ac2010-05-12 02:37:54 +0000533 // Stop if we can't trivially enter the current scope.
John McCallddb0b4d2010-05-12 00:58:13 +0000534 if (Scopes[Min].InDiag) break;
535
536 Min = Scopes[Min].ParentScope;
537 }
538
539 // Walk through all the jump sites, checking that they can trivially
540 // reach this label scope.
541 for (llvm::SmallVectorImpl<JumpScope>::iterator
542 I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) {
543 unsigned Scope = I->first;
544
545 // Walk out the "scope chain" for this scope, looking for a scope
John McCall5e2a7ac2010-05-12 02:37:54 +0000546 // we've marked reachable. For well-formed code this amortizes
547 // to O(JumpScopes.size() / Scopes.size()): we only iterate
548 // when we see something unmarked, and in well-formed code we
549 // mark everything we iterate past.
John McCallddb0b4d2010-05-12 00:58:13 +0000550 bool IsReachable = false;
551 while (true) {
552 if (Reachable.test(Scope)) {
553 // If we find something reachable, mark all the scopes we just
554 // walked through as reachable.
555 for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope)
556 Reachable.set(S);
557 IsReachable = true;
558 break;
559 }
560
561 // Don't walk out if we've reached the top-level scope or we've
562 // gotten shallower than the shallowest reachable scope.
563 if (Scope == 0 || Scope < Min) break;
564
565 // Don't walk out through an out-diagnostic.
566 if (Scopes[Scope].OutDiag) break;
567
568 Scope = Scopes[Scope].ParentScope;
569 }
570
571 // Only diagnose if we didn't find something.
572 if (IsReachable) continue;
573
574 DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope);
575 }
576 }
577}
578
John McCall5e2a7ac2010-05-12 02:37:54 +0000579/// Diagnose an indirect jump which is known to cross scopes.
John McCallddb0b4d2010-05-12 00:58:13 +0000580void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump,
581 unsigned JumpScope,
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000582 LabelDecl *Target,
John McCallddb0b4d2010-05-12 00:58:13 +0000583 unsigned TargetScope) {
584 assert(JumpScope != TargetScope);
585
John McCall95c225d2010-10-28 08:53:48 +0000586 S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
Chris Lattnerad8dcf42011-02-17 07:39:24 +0000587 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
John McCallddb0b4d2010-05-12 00:58:13 +0000588
John McCall5e2a7ac2010-05-12 02:37:54 +0000589 unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope);
John McCallddb0b4d2010-05-12 00:58:13 +0000590
John McCall5e2a7ac2010-05-12 02:37:54 +0000591 // Walk out the scope chain until we reach the common ancestor.
592 for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope)
593 if (Scopes[I].OutDiag)
594 S.Diag(Scopes[I].Loc, Scopes[I].OutDiag);
John McCallddb0b4d2010-05-12 00:58:13 +0000595
596 // Now walk into the scopes containing the label whose address was taken.
John McCall5e2a7ac2010-05-12 02:37:54 +0000597 for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope)
598 if (Scopes[I].InDiag)
599 S.Diag(Scopes[I].Loc, Scopes[I].InDiag);
John McCallddb0b4d2010-05-12 00:58:13 +0000600}
601
Chris Lattner5af280c2009-04-19 04:46:21 +0000602/// CheckJump - Validate that the specified jump statement is valid: that it is
603/// jumping within or out of its current scope, not into a deeper one.
604void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To,
605 SourceLocation DiagLoc, unsigned JumpDiag) {
606 assert(LabelAndGotoScopes.count(From) && "Jump didn't get added to scopes?");
607 unsigned FromScope = LabelAndGotoScopes[From];
608
609 assert(LabelAndGotoScopes.count(To) && "Jump didn't get added to scopes?");
610 unsigned ToScope = LabelAndGotoScopes[To];
Mike Stump1eb44332009-09-09 15:08:12 +0000611
Chris Lattner5af280c2009-04-19 04:46:21 +0000612 // Common case: exactly the same scope, which is fine.
613 if (FromScope == ToScope) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000614
John McCall5e2a7ac2010-05-12 02:37:54 +0000615 unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000616
John McCall5e2a7ac2010-05-12 02:37:54 +0000617 // It's okay to jump out from a nested scope.
618 if (CommonScope == ToScope) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000619
John McCall5e2a7ac2010-05-12 02:37:54 +0000620 // Pull out (and reverse) any scopes we might need to diagnose skipping.
621 llvm::SmallVector<unsigned, 10> ToScopes;
622 for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope)
623 if (Scopes[I].InDiag)
624 ToScopes.push_back(I);
Chris Lattner5af280c2009-04-19 04:46:21 +0000625
John McCall5e2a7ac2010-05-12 02:37:54 +0000626 // If the only scopes present are cleanup scopes, we're okay.
John McCallddb0b4d2010-05-12 00:58:13 +0000627 if (ToScopes.empty()) return;
628
629 S.Diag(DiagLoc, JumpDiag);
630
Chris Lattner5af280c2009-04-19 04:46:21 +0000631 // Emit diagnostics for whatever is left in ToScopes.
632 for (unsigned i = 0, e = ToScopes.size(); i != e; ++i)
John McCallddb0b4d2010-05-12 00:58:13 +0000633 S.Diag(Scopes[ToScopes[i]].Loc, Scopes[ToScopes[i]].InDiag);
Chris Lattner5af280c2009-04-19 04:46:21 +0000634}
635
636void Sema::DiagnoseInvalidJumps(Stmt *Body) {
Douglas Gregor6490ae52009-11-17 06:14:37 +0000637 (void)JumpScopeChecker(Body, *this);
Chris Lattner5af280c2009-04-19 04:46:21 +0000638}