blob: c8743df90e340f70d043fa0b118ab49d60508aa6 [file] [log] [blame]
Francois Pichet2731b7d2011-09-09 11:02:57 +00001//===--- JumpDiagnostics.cpp - Protected scope jump analysis ------*- C++ -*-=//
Chris Lattner1a1fdbd2009-04-19 04:46:21 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner1a1fdbd2009-04-19 04:46:21 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the JumpScopeChecker class, which is used to diagnose
Francois Pichet2731b7d2011-09-09 11:02:57 +000010// jumps that enter a protected scope in an invalid way.
Chris Lattner1a1fdbd2009-04-19 04:46:21 +000011//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall28a0cf72010-08-25 07:42:41 +000015#include "clang/AST/DeclCXX.h"
Chris Lattner1a1fdbd2009-04-19 04:46:21 +000016#include "clang/AST/Expr.h"
Douglas Gregor27d0c442011-05-27 16:05:29 +000017#include "clang/AST/ExprCXX.h"
Sebastian Redl4de47b42009-04-27 20:27:31 +000018#include "clang/AST/StmtCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/StmtObjC.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000020#include "llvm/ADT/BitVector.h"
Chris Lattner1a1fdbd2009-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 Stump11289f42009-09-09 15:08:12 +000033
Alp Tokere265cf12014-05-09 08:40:10 +000034 /// Permissive - True when recovering from errors, in which case precautions
35 /// are taken to handle incomplete scope information.
36 const bool Permissive;
37
Chris Lattner1a1fdbd2009-04-19 04:46:21 +000038 /// GotoScope - This is a record that we use to keep track of all of the
39 /// scopes that are introduced by VLAs and other things that scope jumps like
40 /// gotos. This scope tree has nothing to do with the source scope tree,
41 /// because you can have multiple VLA scopes per compound statement, and most
42 /// compound statements don't introduce any scopes.
43 struct GotoScope {
44 /// ParentScope - The index in ScopeMap of the parent scope. This is 0 for
45 /// the parent scope is the function body.
46 unsigned ParentScope;
Mike Stump11289f42009-09-09 15:08:12 +000047
Richard Smithfe2750d2011-10-20 21:42:12 +000048 /// InDiag - The note to emit if there is a jump into this scope.
John McCallcf819ab2010-05-12 00:58:13 +000049 unsigned InDiag;
50
Richard Smithfe2750d2011-10-20 21:42:12 +000051 /// OutDiag - The note to emit if there is an indirect jump out
John McCallcf819ab2010-05-12 00:58:13 +000052 /// of this scope. Direct jumps always clean up their current scope
53 /// in an orderly way.
54 unsigned OutDiag;
Mike Stump11289f42009-09-09 15:08:12 +000055
Chris Lattner1a1fdbd2009-04-19 04:46:21 +000056 /// Loc - Location to emit the diagnostic.
57 SourceLocation Loc;
Mike Stump11289f42009-09-09 15:08:12 +000058
John McCallcf819ab2010-05-12 00:58:13 +000059 GotoScope(unsigned parentScope, unsigned InDiag, unsigned OutDiag,
60 SourceLocation L)
61 : ParentScope(parentScope), InDiag(InDiag), OutDiag(OutDiag), Loc(L) {}
Chris Lattner1a1fdbd2009-04-19 04:46:21 +000062 };
Mike Stump11289f42009-09-09 15:08:12 +000063
Chris Lattner0e62c1c2011-07-23 10:55:15 +000064 SmallVector<GotoScope, 48> Scopes;
Chris Lattner1a1fdbd2009-04-19 04:46:21 +000065 llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000066 SmallVector<Stmt*, 16> Jumps;
John McCallcf819ab2010-05-12 00:58:13 +000067
Jennifer Yub8fee672019-06-03 15:57:25 +000068 SmallVector<Stmt*, 4> IndirectJumps;
69 SmallVector<Stmt*, 4> AsmJumps;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000070 SmallVector<LabelDecl*, 4> IndirectJumpTargets;
Jennifer Yub8fee672019-06-03 15:57:25 +000071 SmallVector<LabelDecl*, 4> AsmJumpTargets;
Chris Lattner1a1fdbd2009-04-19 04:46:21 +000072public:
73 JumpScopeChecker(Stmt *Body, Sema &S);
74private:
Douglas Gregor27b98ea2010-06-21 23:44:13 +000075 void BuildScopeInformation(Decl *D, unsigned &ParentScope);
Hubert Tong64c2f5a2015-06-04 22:53:21 +000076 void BuildScopeInformation(VarDecl *D, const BlockDecl *BDecl,
Fariborz Jahanian256d39d2011-07-11 18:04:54 +000077 unsigned &ParentScope);
78 void BuildScopeInformation(Stmt *S, unsigned &origParentScope);
Hubert Tong64c2f5a2015-06-04 22:53:21 +000079
Chris Lattner1a1fdbd2009-04-19 04:46:21 +000080 void VerifyJumps();
Jennifer Yub8fee672019-06-03 15:57:25 +000081 void VerifyIndirectOrAsmJumps(bool IsAsmGoto);
Bill Wendling8ac06af2012-02-22 09:38:11 +000082 void NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes);
Jennifer Yub8fee672019-06-03 15:57:25 +000083 void DiagnoseIndirectOrAsmJump(Stmt *IG, unsigned IGScope, LabelDecl *Target,
84 unsigned TargetScope);
Francois Pichet051f5e52011-09-13 10:26:51 +000085 void CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
Richard Smithfe2750d2011-10-20 21:42:12 +000086 unsigned JumpDiag, unsigned JumpDiagWarning,
87 unsigned JumpDiagCXX98Compat);
Ehsan Akhgari31097582014-09-22 02:21:54 +000088 void CheckGotoStmt(GotoStmt *GS);
John McCall42f9f1f2010-05-12 02:37:54 +000089
90 unsigned GetDeepestCommonScope(unsigned A, unsigned B);
Chris Lattner1a1fdbd2009-04-19 04:46:21 +000091};
92} // end anonymous namespace
93
Alp Tokere265cf12014-05-09 08:40:10 +000094#define CHECK_PERMISSIVE(x) (assert(Permissive || !(x)), (Permissive && (x)))
Chris Lattner1a1fdbd2009-04-19 04:46:21 +000095
Alp Tokere265cf12014-05-09 08:40:10 +000096JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s)
97 : S(s), Permissive(s.hasAnyUnrecoverableErrorsInThisFunction()) {
Chris Lattner1a1fdbd2009-04-19 04:46:21 +000098 // Add a scope entry for function scope.
John McCallcf819ab2010-05-12 00:58:13 +000099 Scopes.push_back(GotoScope(~0U, ~0U, ~0U, SourceLocation()));
Mike Stump11289f42009-09-09 15:08:12 +0000100
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000101 // Build information for the top level compound statement, so that we have a
102 // defined scope record for every "goto" and label.
Fariborz Jahanian256d39d2011-07-11 18:04:54 +0000103 unsigned BodyParentScope = 0;
104 BuildScopeInformation(Body, BodyParentScope);
Mike Stump11289f42009-09-09 15:08:12 +0000105
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000106 // Check that all jumps we saw are kosher.
107 VerifyJumps();
Jennifer Yub8fee672019-06-03 15:57:25 +0000108 VerifyIndirectOrAsmJumps(false);
109 VerifyIndirectOrAsmJumps(true);
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000110}
Mike Stump11289f42009-09-09 15:08:12 +0000111
John McCall42f9f1f2010-05-12 02:37:54 +0000112/// GetDeepestCommonScope - Finds the innermost scope enclosing the
113/// two scopes.
114unsigned JumpScopeChecker::GetDeepestCommonScope(unsigned A, unsigned B) {
115 while (A != B) {
116 // Inner scopes are created after outer scopes and therefore have
117 // higher indices.
118 if (A < B) {
119 assert(Scopes[B].ParentScope < B);
120 B = Scopes[B].ParentScope;
121 } else {
122 assert(Scopes[A].ParentScope < A);
123 A = Scopes[A].ParentScope;
124 }
125 }
126 return A;
127}
128
John McCall31168b02011-06-15 23:02:42 +0000129typedef std::pair<unsigned,unsigned> ScopePair;
130
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000131/// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a
132/// diagnostic that should be emitted if control goes over it. If not, return 0.
Richard Smithc934e4f2013-12-12 01:27:02 +0000133static ScopePair GetDiagForGotoScopeDecl(Sema &S, const Decl *D) {
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000134 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Rafael Espindola44938a72012-10-28 02:44:03 +0000135 unsigned InDiag = 0;
Richard Smithc934e4f2013-12-12 01:27:02 +0000136 unsigned OutDiag = 0;
137
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000138 if (VD->getType()->isVariablyModifiedType())
John McCallcf819ab2010-05-12 00:58:13 +0000139 InDiag = diag::note_protected_by_vla;
140
John McCall31168b02011-06-15 23:02:42 +0000141 if (VD->hasAttr<BlocksAttr>())
142 return ScopePair(diag::note_protected_by___block,
143 diag::note_exits___block);
144
145 if (VD->hasAttr<CleanupAttr>())
146 return ScopePair(diag::note_protected_by_cleanup,
147 diag::note_exits_cleanup);
148
Richard Smithc934e4f2013-12-12 01:27:02 +0000149 if (VD->hasLocalStorage()) {
150 switch (VD->getType().isDestructedType()) {
151 case QualType::DK_objc_strong_lifetime:
John McCall039f2bb2015-10-21 18:06:38 +0000152 return ScopePair(diag::note_protected_by_objc_strong_init,
153 diag::note_exits_objc_strong);
154
Richard Smithc934e4f2013-12-12 01:27:02 +0000155 case QualType::DK_objc_weak_lifetime:
John McCall039f2bb2015-10-21 18:06:38 +0000156 return ScopePair(diag::note_protected_by_objc_weak_init,
157 diag::note_exits_objc_weak);
Richard Smithc934e4f2013-12-12 01:27:02 +0000158
Akira Hatanaka7275da02018-02-28 07:15:55 +0000159 case QualType::DK_nontrivial_c_struct:
160 return ScopePair(diag::note_protected_by_non_trivial_c_struct_init,
161 diag::note_exits_dtor);
162
Richard Smithc934e4f2013-12-12 01:27:02 +0000163 case QualType::DK_cxx_destructor:
164 OutDiag = diag::note_exits_dtor;
165 break;
166
167 case QualType::DK_none:
168 break;
John McCall31168b02011-06-15 23:02:42 +0000169 }
170 }
171
Richard Smithc934e4f2013-12-12 01:27:02 +0000172 const Expr *Init = VD->getInit();
173 if (S.Context.getLangOpts().CPlusPlus && VD->hasLocalStorage() && Init) {
Richard Smithfe2750d2011-10-20 21:42:12 +0000174 // C++11 [stmt.dcl]p3:
John McCall31168b02011-06-15 23:02:42 +0000175 // A program that jumps from a point where a variable with automatic
176 // storage duration is not in scope to a point where it is in scope
177 // is ill-formed unless the variable has scalar type, class type with
Hubert Tong64c2f5a2015-06-04 22:53:21 +0000178 // a trivial default constructor and a trivial destructor, a
John McCall31168b02011-06-15 23:02:42 +0000179 // cv-qualified version of one of these types, or an array of one of
180 // the preceding types and is declared without an initializer.
181
182 // C++03 [stmt.dcl.p3:
183 // A program that jumps from a point where a local variable
184 // with automatic storage duration is not in scope to a point
185 // where it is in scope is ill-formed unless the variable has
186 // POD type and is declared without an initializer.
187
Richard Smithc934e4f2013-12-12 01:27:02 +0000188 InDiag = diag::note_protected_by_variable_init;
John McCall31168b02011-06-15 23:02:42 +0000189
Richard Smithc934e4f2013-12-12 01:27:02 +0000190 // For a variable of (array of) class type declared without an
191 // initializer, we will have call-style initialization and the initializer
192 // will be the CXXConstructExpr with no intervening nodes.
193 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
194 const CXXConstructorDecl *Ctor = CCE->getConstructor();
195 if (Ctor->isTrivial() && Ctor->isDefaultConstructor() &&
196 VD->getInitStyle() == VarDecl::CallInit) {
Rafael Espindola44938a72012-10-28 02:44:03 +0000197 if (OutDiag)
198 InDiag = diag::note_protected_by_variable_nontriv_destructor;
Richard Smithc934e4f2013-12-12 01:27:02 +0000199 else if (!Ctor->getParent()->isPOD())
Rafael Espindola44938a72012-10-28 02:44:03 +0000200 InDiag = diag::note_protected_by_variable_non_pod;
Richard Smithc934e4f2013-12-12 01:27:02 +0000201 else
202 InDiag = 0;
Douglas Gregor27d0c442011-05-27 16:05:29 +0000203 }
Douglas Gregor5a5fcd82010-07-01 00:21:21 +0000204 }
John McCallcf819ab2010-05-12 00:58:13 +0000205 }
Rafael Espindola44938a72012-10-28 02:44:03 +0000206
Richard Smithc934e4f2013-12-12 01:27:02 +0000207 return ScopePair(InDiag, OutDiag);
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000208 }
Mike Stump11289f42009-09-09 15:08:12 +0000209
Richard Smithc934e4f2013-12-12 01:27:02 +0000210 if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
John McCallcf819ab2010-05-12 00:58:13 +0000211 if (TD->getUnderlyingType()->isVariablyModifiedType())
Richard Smithc934e4f2013-12-12 01:27:02 +0000212 return ScopePair(isa<TypedefDecl>(TD)
213 ? diag::note_protected_by_vla_typedef
214 : diag::note_protected_by_vla_type_alias,
215 0);
Richard Smithdda56e42011-04-15 14:24:37 +0000216 }
217
John McCall31168b02011-06-15 23:02:42 +0000218 return ScopePair(0U, 0U);
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000219}
220
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000221/// Build scope information for a declaration that is part of a DeclStmt.
Douglas Gregor27b98ea2010-06-21 23:44:13 +0000222void JumpScopeChecker::BuildScopeInformation(Decl *D, unsigned &ParentScope) {
Douglas Gregor27b98ea2010-06-21 23:44:13 +0000223 // If this decl causes a new scope, push and switch to it.
Richard Smithc934e4f2013-12-12 01:27:02 +0000224 std::pair<unsigned,unsigned> Diags = GetDiagForGotoScopeDecl(S, D);
Douglas Gregor27b98ea2010-06-21 23:44:13 +0000225 if (Diags.first || Diags.second) {
226 Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second,
227 D->getLocation()));
228 ParentScope = Scopes.size()-1;
229 }
Hubert Tong64c2f5a2015-06-04 22:53:21 +0000230
Douglas Gregor27b98ea2010-06-21 23:44:13 +0000231 // If the decl has an initializer, walk it with the potentially new
232 // scope we just installed.
233 if (VarDecl *VD = dyn_cast<VarDecl>(D))
234 if (Expr *Init = VD->getInit())
235 BuildScopeInformation(Init, ParentScope);
236}
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000237
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000238/// Build scope information for a captured block literal variables.
Hubert Tong64c2f5a2015-06-04 22:53:21 +0000239void JumpScopeChecker::BuildScopeInformation(VarDecl *D,
240 const BlockDecl *BDecl,
Fariborz Jahanian256d39d2011-07-11 18:04:54 +0000241 unsigned &ParentScope) {
242 // exclude captured __block variables; there's no destructor
243 // associated with the block literal for them.
244 if (D->hasAttr<BlocksAttr>())
245 return;
246 QualType T = D->getType();
247 QualType::DestructionKind destructKind = T.isDestructedType();
248 if (destructKind != QualType::DK_none) {
249 std::pair<unsigned,unsigned> Diags;
250 switch (destructKind) {
251 case QualType::DK_cxx_destructor:
252 Diags = ScopePair(diag::note_enters_block_captures_cxx_obj,
253 diag::note_exits_block_captures_cxx_obj);
254 break;
255 case QualType::DK_objc_strong_lifetime:
256 Diags = ScopePair(diag::note_enters_block_captures_strong,
257 diag::note_exits_block_captures_strong);
258 break;
259 case QualType::DK_objc_weak_lifetime:
260 Diags = ScopePair(diag::note_enters_block_captures_weak,
261 diag::note_exits_block_captures_weak);
262 break;
Akira Hatanaka7275da02018-02-28 07:15:55 +0000263 case QualType::DK_nontrivial_c_struct:
264 Diags = ScopePair(diag::note_enters_block_captures_non_trivial_c_struct,
265 diag::note_exits_block_captures_non_trivial_c_struct);
266 break;
Fariborz Jahanian256d39d2011-07-11 18:04:54 +0000267 case QualType::DK_none:
Richard Smithfe2750d2011-10-20 21:42:12 +0000268 llvm_unreachable("non-lifetime captured variable");
Fariborz Jahanian256d39d2011-07-11 18:04:54 +0000269 }
270 SourceLocation Loc = D->getLocation();
271 if (Loc.isInvalid())
272 Loc = BDecl->getLocation();
Hubert Tong64c2f5a2015-06-04 22:53:21 +0000273 Scopes.push_back(GotoScope(ParentScope,
Fariborz Jahanian256d39d2011-07-11 18:04:54 +0000274 Diags.first, Diags.second, Loc));
275 ParentScope = Scopes.size()-1;
276 }
277}
278
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000279/// BuildScopeInformation - The statements from CI to CE are known to form a
280/// coherent VLA scope with a specified parent node. Walk through the
281/// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
282/// walking the AST as needed.
Richard Smith8b65f102016-06-21 20:10:11 +0000283void JumpScopeChecker::BuildScopeInformation(Stmt *S,
284 unsigned &origParentScope) {
Fariborz Jahanian256d39d2011-07-11 18:04:54 +0000285 // If this is a statement, rather than an expression, scopes within it don't
286 // propagate out into the enclosing scope. Otherwise we have to worry
287 // about block literals, which have the lifetime of their enclosing statement.
288 unsigned independentParentScope = origParentScope;
Hubert Tong64c2f5a2015-06-04 22:53:21 +0000289 unsigned &ParentScope = ((isa<Expr>(S) && !isa<StmtExpr>(S))
Fariborz Jahanian256d39d2011-07-11 18:04:54 +0000290 ? origParentScope : independentParentScope);
291
Richard Smitha547eb22016-07-14 00:11:03 +0000292 unsigned StmtsToSkip = 0u;
Hubert Tong64c2f5a2015-06-04 22:53:21 +0000293
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000294 // If we found a label, remember that it is in ParentScope scope.
John McCallcf819ab2010-05-12 00:58:13 +0000295 switch (S->getStmtClass()) {
John McCallcf819ab2010-05-12 00:58:13 +0000296 case Stmt::AddrLabelExprClass:
297 IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel());
298 break;
299
Akira Hatanaka39013772017-04-19 17:54:08 +0000300 case Stmt::ObjCForCollectionStmtClass: {
301 auto *CS = cast<ObjCForCollectionStmt>(S);
302 unsigned Diag = diag::note_protected_by_objc_fast_enumeration;
303 unsigned NewParentScope = Scopes.size();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000304 Scopes.push_back(GotoScope(ParentScope, Diag, 0, S->getBeginLoc()));
Akira Hatanaka39013772017-04-19 17:54:08 +0000305 BuildScopeInformation(CS->getBody(), NewParentScope);
306 return;
307 }
308
John McCallcf819ab2010-05-12 00:58:13 +0000309 case Stmt::IndirectGotoStmtClass:
John McCall9de91602010-10-28 08:53:48 +0000310 // "goto *&&lbl;" is a special case which we treat as equivalent
311 // to a normal goto. In addition, we don't calculate scope in the
312 // operand (to avoid recording the address-of-label use), which
313 // works only because of the restricted set of expressions which
314 // we detect as constant targets.
315 if (cast<IndirectGotoStmt>(S)->getConstantTarget()) {
316 LabelAndGotoScopes[S] = ParentScope;
317 Jumps.push_back(S);
318 return;
319 }
320
John McCallcf819ab2010-05-12 00:58:13 +0000321 LabelAndGotoScopes[S] = ParentScope;
Jennifer Yub8fee672019-06-03 15:57:25 +0000322 IndirectJumps.push_back(S);
John McCallcf819ab2010-05-12 00:58:13 +0000323 break;
324
John McCallcf819ab2010-05-12 00:58:13 +0000325 case Stmt::SwitchStmtClass:
Richard Smitha547eb22016-07-14 00:11:03 +0000326 // Evaluate the C++17 init stmt and condition variable
327 // before entering the scope of the switch statement.
328 if (Stmt *Init = cast<SwitchStmt>(S)->getInit()) {
329 BuildScopeInformation(Init, ParentScope);
330 ++StmtsToSkip;
331 }
Douglas Gregor27b98ea2010-06-21 23:44:13 +0000332 if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) {
333 BuildScopeInformation(Var, ParentScope);
Richard Smitha547eb22016-07-14 00:11:03 +0000334 ++StmtsToSkip;
Douglas Gregor27b98ea2010-06-21 23:44:13 +0000335 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000336 LLVM_FALLTHROUGH;
Hubert Tong64c2f5a2015-06-04 22:53:21 +0000337
Douglas Gregor27b98ea2010-06-21 23:44:13 +0000338 case Stmt::GotoStmtClass:
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000339 // Remember both what scope a goto is in as well as the fact that we have
340 // it. This makes the second scan not have to walk the AST again.
341 LabelAndGotoScopes[S] = ParentScope;
342 Jumps.push_back(S);
John McCallcf819ab2010-05-12 00:58:13 +0000343 break;
344
Jennifer Yub8fee672019-06-03 15:57:25 +0000345 case Stmt::GCCAsmStmtClass:
346 if (auto *GS = dyn_cast<GCCAsmStmt>(S))
347 if (GS->isAsmGoto()) {
348 // Remember both what scope a goto is in as well as the fact that we
349 // have it. This makes the second scan not have to walk the AST again.
350 LabelAndGotoScopes[S] = ParentScope;
351 AsmJumps.push_back(GS);
352 for (auto *E : GS->labels())
353 AsmJumpTargets.push_back(E->getLabel());
354 }
355 break;
356
Richard Smithb130fe72016-06-23 19:16:49 +0000357 case Stmt::IfStmtClass: {
358 IfStmt *IS = cast<IfStmt>(S);
Erik Pilkington5cd57172016-08-16 17:44:11 +0000359 if (!(IS->isConstexpr() || IS->isObjCAvailabilityCheck()))
Richard Smithb130fe72016-06-23 19:16:49 +0000360 break;
361
Erik Pilkington5cd57172016-08-16 17:44:11 +0000362 unsigned Diag = IS->isConstexpr() ? diag::note_protected_by_constexpr_if
363 : diag::note_protected_by_if_available;
364
Richard Smithb130fe72016-06-23 19:16:49 +0000365 if (VarDecl *Var = IS->getConditionVariable())
366 BuildScopeInformation(Var, ParentScope);
367
368 // Cannot jump into the middle of the condition.
369 unsigned NewParentScope = Scopes.size();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000370 Scopes.push_back(GotoScope(ParentScope, Diag, 0, IS->getBeginLoc()));
Richard Smithb130fe72016-06-23 19:16:49 +0000371 BuildScopeInformation(IS->getCond(), NewParentScope);
372
373 // Jumps into either arm of an 'if constexpr' are not allowed.
374 NewParentScope = Scopes.size();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000375 Scopes.push_back(GotoScope(ParentScope, Diag, 0, IS->getBeginLoc()));
Richard Smithb130fe72016-06-23 19:16:49 +0000376 BuildScopeInformation(IS->getThen(), NewParentScope);
377 if (Stmt *Else = IS->getElse()) {
378 NewParentScope = Scopes.size();
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000379 Scopes.push_back(GotoScope(ParentScope, Diag, 0, IS->getBeginLoc()));
Richard Smithb130fe72016-06-23 19:16:49 +0000380 BuildScopeInformation(Else, NewParentScope);
381 }
382 return;
383 }
384
Eli Friedman1e95d4b2012-10-31 23:55:28 +0000385 case Stmt::CXXTryStmtClass: {
386 CXXTryStmt *TS = cast<CXXTryStmt>(S);
Richard Smith8b65f102016-06-21 20:10:11 +0000387 {
388 unsigned NewParentScope = Scopes.size();
389 Scopes.push_back(GotoScope(ParentScope,
390 diag::note_protected_by_cxx_try,
391 diag::note_exits_cxx_try,
392 TS->getSourceRange().getBegin()));
393 if (Stmt *TryBlock = TS->getTryBlock())
394 BuildScopeInformation(TryBlock, NewParentScope);
395 }
Eli Friedman1e95d4b2012-10-31 23:55:28 +0000396
397 // Jump from the catch into the try is not allowed either.
398 for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) {
399 CXXCatchStmt *CS = TS->getHandler(I);
Richard Smith8b65f102016-06-21 20:10:11 +0000400 unsigned NewParentScope = Scopes.size();
Eli Friedman1e95d4b2012-10-31 23:55:28 +0000401 Scopes.push_back(GotoScope(ParentScope,
402 diag::note_protected_by_cxx_catch,
403 diag::note_exits_cxx_catch,
404 CS->getSourceRange().getBegin()));
Richard Smith8b65f102016-06-21 20:10:11 +0000405 BuildScopeInformation(CS->getHandlerBlock(), NewParentScope);
Eli Friedman1e95d4b2012-10-31 23:55:28 +0000406 }
407 return;
408 }
409
Nico Weberb14f8722015-02-03 17:06:08 +0000410 case Stmt::SEHTryStmtClass: {
411 SEHTryStmt *TS = cast<SEHTryStmt>(S);
Richard Smith8b65f102016-06-21 20:10:11 +0000412 {
413 unsigned NewParentScope = Scopes.size();
414 Scopes.push_back(GotoScope(ParentScope,
415 diag::note_protected_by_seh_try,
416 diag::note_exits_seh_try,
417 TS->getSourceRange().getBegin()));
418 if (Stmt *TryBlock = TS->getTryBlock())
419 BuildScopeInformation(TryBlock, NewParentScope);
420 }
Nico Weberb14f8722015-02-03 17:06:08 +0000421
422 // Jump from __except or __finally into the __try are not allowed either.
423 if (SEHExceptStmt *Except = TS->getExceptHandler()) {
Richard Smith8b65f102016-06-21 20:10:11 +0000424 unsigned NewParentScope = Scopes.size();
Nico Weberb14f8722015-02-03 17:06:08 +0000425 Scopes.push_back(GotoScope(ParentScope,
426 diag::note_protected_by_seh_except,
427 diag::note_exits_seh_except,
428 Except->getSourceRange().getBegin()));
Richard Smith8b65f102016-06-21 20:10:11 +0000429 BuildScopeInformation(Except->getBlock(), NewParentScope);
Nico Weberb14f8722015-02-03 17:06:08 +0000430 } else if (SEHFinallyStmt *Finally = TS->getFinallyHandler()) {
Richard Smith8b65f102016-06-21 20:10:11 +0000431 unsigned NewParentScope = Scopes.size();
Nico Weberb14f8722015-02-03 17:06:08 +0000432 Scopes.push_back(GotoScope(ParentScope,
433 diag::note_protected_by_seh_finally,
434 diag::note_exits_seh_finally,
435 Finally->getSourceRange().getBegin()));
Richard Smith8b65f102016-06-21 20:10:11 +0000436 BuildScopeInformation(Finally->getBlock(), NewParentScope);
Nico Weberb14f8722015-02-03 17:06:08 +0000437 }
438
439 return;
440 }
Reid Kleckner1d59f992015-01-22 01:36:17 +0000441
Richard Smith8b65f102016-06-21 20:10:11 +0000442 case Stmt::DeclStmtClass: {
443 // If this is a declstmt with a VLA definition, it defines a scope from here
444 // to the end of the containing context.
445 DeclStmt *DS = cast<DeclStmt>(S);
446 // The decl statement creates a scope if any of the decls in it are VLAs
447 // or have the cleanup attribute.
448 for (auto *I : DS->decls())
449 BuildScopeInformation(I, origParentScope);
450 return;
451 }
452
453 case Stmt::ObjCAtTryStmtClass: {
454 // Disallow jumps into any part of an @try statement by pushing a scope and
455 // walking all sub-stmts in that scope.
456 ObjCAtTryStmt *AT = cast<ObjCAtTryStmt>(S);
457 // Recursively walk the AST for the @try part.
458 {
459 unsigned NewParentScope = Scopes.size();
460 Scopes.push_back(GotoScope(ParentScope,
461 diag::note_protected_by_objc_try,
462 diag::note_exits_objc_try,
463 AT->getAtTryLoc()));
464 if (Stmt *TryPart = AT->getTryBody())
465 BuildScopeInformation(TryPart, NewParentScope);
466 }
467
468 // Jump from the catch to the finally or try is not valid.
469 for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) {
470 ObjCAtCatchStmt *AC = AT->getCatchStmt(I);
471 unsigned NewParentScope = Scopes.size();
472 Scopes.push_back(GotoScope(ParentScope,
473 diag::note_protected_by_objc_catch,
474 diag::note_exits_objc_catch,
475 AC->getAtCatchLoc()));
476 // @catches are nested and it isn't
477 BuildScopeInformation(AC->getCatchBody(), NewParentScope);
478 }
479
480 // Jump from the finally to the try or catch is not valid.
481 if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
482 unsigned NewParentScope = Scopes.size();
483 Scopes.push_back(GotoScope(ParentScope,
484 diag::note_protected_by_objc_finally,
485 diag::note_exits_objc_finally,
486 AF->getAtFinallyLoc()));
487 BuildScopeInformation(AF, NewParentScope);
488 }
489
490 return;
491 }
492
493 case Stmt::ObjCAtSynchronizedStmtClass: {
494 // Disallow jumps into the protected statement of an @synchronized, but
495 // allow jumps into the object expression it protects.
496 ObjCAtSynchronizedStmt *AS = cast<ObjCAtSynchronizedStmt>(S);
497 // Recursively walk the AST for the @synchronized object expr, it is
498 // evaluated in the normal scope.
499 BuildScopeInformation(AS->getSynchExpr(), ParentScope);
500
501 // Recursively walk the AST for the @synchronized part, protected by a new
502 // scope.
503 unsigned NewParentScope = Scopes.size();
504 Scopes.push_back(GotoScope(ParentScope,
505 diag::note_protected_by_objc_synchronized,
506 diag::note_exits_objc_synchronized,
507 AS->getAtSynchronizedLoc()));
508 BuildScopeInformation(AS->getSynchBody(), NewParentScope);
509 return;
510 }
511
512 case Stmt::ObjCAutoreleasePoolStmtClass: {
513 // Disallow jumps into the protected statement of an @autoreleasepool.
514 ObjCAutoreleasePoolStmt *AS = cast<ObjCAutoreleasePoolStmt>(S);
515 // Recursively walk the AST for the @autoreleasepool part, protected by a
516 // new scope.
517 unsigned NewParentScope = Scopes.size();
518 Scopes.push_back(GotoScope(ParentScope,
519 diag::note_protected_by_objc_autoreleasepool,
520 diag::note_exits_objc_autoreleasepool,
521 AS->getAtLoc()));
522 BuildScopeInformation(AS->getSubStmt(), NewParentScope);
523 return;
524 }
525
526 case Stmt::ExprWithCleanupsClass: {
527 // Disallow jumps past full-expressions that use blocks with
528 // non-trivial cleanups of their captures. This is theoretically
529 // implementable but a lot of work which we haven't felt up to doing.
530 ExprWithCleanups *EWC = cast<ExprWithCleanups>(S);
531 for (unsigned i = 0, e = EWC->getNumObjects(); i != e; ++i) {
532 const BlockDecl *BDecl = EWC->getObject(i);
533 for (const auto &CI : BDecl->captures()) {
534 VarDecl *variable = CI.getVariable();
535 BuildScopeInformation(variable, BDecl, origParentScope);
536 }
537 }
538 break;
539 }
540
541 case Stmt::MaterializeTemporaryExprClass: {
542 // Disallow jumps out of scopes containing temporaries lifetime-extended to
543 // automatic storage duration.
544 MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
545 if (MTE->getStorageDuration() == SD_Automatic) {
546 SmallVector<const Expr *, 4> CommaLHS;
547 SmallVector<SubobjectAdjustment, 4> Adjustments;
548 const Expr *ExtendedObject =
549 MTE->GetTemporaryExpr()->skipRValueSubobjectAdjustments(
550 CommaLHS, Adjustments);
551 if (ExtendedObject->getType().isDestructedType()) {
552 Scopes.push_back(GotoScope(ParentScope, 0,
553 diag::note_exits_temporary_dtor,
554 ExtendedObject->getExprLoc()));
555 origParentScope = Scopes.size()-1;
556 }
557 }
558 break;
559 }
560
561 case Stmt::CaseStmtClass:
562 case Stmt::DefaultStmtClass:
563 case Stmt::LabelStmtClass:
564 LabelAndGotoScopes[S] = ParentScope;
565 break;
566
John McCallcf819ab2010-05-12 00:58:13 +0000567 default:
568 break;
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000569 }
Mike Stump11289f42009-09-09 15:08:12 +0000570
Benjamin Kramer642f1732015-07-02 21:03:14 +0000571 for (Stmt *SubStmt : S->children()) {
Richard Smitha547eb22016-07-14 00:11:03 +0000572 if (!SubStmt)
573 continue;
574 if (StmtsToSkip) {
575 --StmtsToSkip;
Douglas Gregor27b98ea2010-06-21 23:44:13 +0000576 continue;
577 }
Hubert Tong64c2f5a2015-06-04 22:53:21 +0000578
John McCall4a33fa92010-08-02 23:33:14 +0000579 // Cases, labels, and defaults aren't "scope parents". It's also
580 // important to handle these iteratively instead of recursively in
581 // order to avoid blowing out the stack.
582 while (true) {
583 Stmt *Next;
Vitaly Buka28a1b8c2016-10-26 02:00:00 +0000584 if (SwitchCase *SC = dyn_cast<SwitchCase>(SubStmt))
585 Next = SC->getSubStmt();
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000586 else if (LabelStmt *LS = dyn_cast<LabelStmt>(SubStmt))
587 Next = LS->getSubStmt();
John McCall4a33fa92010-08-02 23:33:14 +0000588 else
589 break;
590
591 LabelAndGotoScopes[SubStmt] = ParentScope;
592 SubStmt = Next;
593 }
594
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000595 // Recursively walk the AST.
596 BuildScopeInformation(SubStmt, ParentScope);
597 }
598}
599
600/// VerifyJumps - Verify each element of the Jumps array to see if they are
601/// valid, emitting diagnostics if not.
602void JumpScopeChecker::VerifyJumps() {
603 while (!Jumps.empty()) {
604 Stmt *Jump = Jumps.pop_back_val();
Mike Stump11289f42009-09-09 15:08:12 +0000605
606 // With a goto,
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000607 if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
Ehsan Akhgari31097582014-09-22 02:21:54 +0000608 // The label may not have a statement if it's coming from inline MS ASM.
609 if (GS->getLabel()->getStmt()) {
610 CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(),
611 diag::err_goto_into_protected_scope,
612 diag::ext_goto_into_protected_scope,
613 diag::warn_cxx98_compat_goto_into_protected_scope);
614 }
615 CheckGotoStmt(GS);
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000616 continue;
617 }
Mike Stump11289f42009-09-09 15:08:12 +0000618
John McCall9de91602010-10-28 08:53:48 +0000619 // We only get indirect gotos here when they have a constant target.
620 if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000621 LabelDecl *Target = IGS->getConstantTarget();
622 CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(),
Francois Pichet2f550192011-09-16 23:15:32 +0000623 diag::err_goto_into_protected_scope,
Richard Smith1b98ccc2014-07-19 01:39:17 +0000624 diag::ext_goto_into_protected_scope,
Richard Smithfe2750d2011-10-20 21:42:12 +0000625 diag::warn_cxx98_compat_goto_into_protected_scope);
John McCall9de91602010-10-28 08:53:48 +0000626 continue;
627 }
628
John McCallcf819ab2010-05-12 00:58:13 +0000629 SwitchStmt *SS = cast<SwitchStmt>(Jump);
630 for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
631 SC = SC->getNextSwitchCase()) {
Alp Tokere265cf12014-05-09 08:40:10 +0000632 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(SC)))
633 continue;
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +0000634 SourceLocation Loc;
635 if (CaseStmt *CS = dyn_cast<CaseStmt>(SC))
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000636 Loc = CS->getBeginLoc();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +0000637 else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC))
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000638 Loc = DS->getBeginLoc();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +0000639 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000640 Loc = SC->getBeginLoc();
Erik Verbruggen11a2ecc2012-12-25 14:51:39 +0000641 CheckJump(SS, SC, Loc, diag::err_switch_into_protected_scope, 0,
Richard Smithfe2750d2011-10-20 21:42:12 +0000642 diag::warn_cxx98_compat_switch_into_protected_scope);
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000643 }
644 }
645}
646
Jennifer Yub8fee672019-06-03 15:57:25 +0000647/// VerifyIndirectOrAsmJumps - Verify whether any possible indirect goto or
648/// asm goto jump might cross a protection boundary. Unlike direct jumps,
649/// indirect or asm goto jumps count cleanups as protection boundaries:
650/// since there's no way to know where the jump is going, we can't implicitly
651/// run the right cleanups the way we can with direct jumps.
652/// Thus, an indirect/asm jump is "trivial" if it bypasses no
653/// initializations and no teardowns. More formally, an indirect/asm jump
John McCall42f9f1f2010-05-12 02:37:54 +0000654/// from A to B is trivial if the path out from A to DCA(A,B) is
655/// trivial and the path in from DCA(A,B) to B is trivial, where
656/// DCA(A,B) is the deepest common ancestor of A and B.
657/// Jump-triviality is transitive but asymmetric.
658///
John McCallcf819ab2010-05-12 00:58:13 +0000659/// A path in is trivial if none of the entered scopes have an InDiag.
660/// A path out is trivial is none of the exited scopes have an OutDiag.
John McCall42f9f1f2010-05-12 02:37:54 +0000661///
662/// Under these definitions, this function checks that the indirect
663/// jump between A and B is trivial for every indirect goto statement A
664/// and every label B whose address was taken in the function.
Jennifer Yub8fee672019-06-03 15:57:25 +0000665void JumpScopeChecker::VerifyIndirectOrAsmJumps(bool IsAsmGoto) {
666 SmallVector<Stmt*, 4> GotoJumps = IsAsmGoto ? AsmJumps : IndirectJumps;
667 if (GotoJumps.empty())
668 return;
669 SmallVector<LabelDecl *, 4> JumpTargets =
670 IsAsmGoto ? AsmJumpTargets : IndirectJumpTargets;
John McCallcf819ab2010-05-12 00:58:13 +0000671 // If there aren't any address-of-label expressions in this function,
672 // complain about the first indirect goto.
Jennifer Yub8fee672019-06-03 15:57:25 +0000673 if (JumpTargets.empty()) {
674 assert(!IsAsmGoto &&"only indirect goto can get here");
675 S.Diag(GotoJumps[0]->getBeginLoc(),
John McCallcf819ab2010-05-12 00:58:13 +0000676 diag::err_indirect_goto_without_addrlabel);
677 return;
678 }
John McCall42f9f1f2010-05-12 02:37:54 +0000679 // Collect a single representative of every scope containing an
Jennifer Yub8fee672019-06-03 15:57:25 +0000680 // indirect or asm goto. For most code bases, this substantially cuts
John McCall42f9f1f2010-05-12 02:37:54 +0000681 // down on the number of jump sites we'll have to consider later.
Jennifer Yub8fee672019-06-03 15:57:25 +0000682 typedef std::pair<unsigned, Stmt*> JumpScope;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000683 SmallVector<JumpScope, 32> JumpScopes;
John McCallcf819ab2010-05-12 00:58:13 +0000684 {
Jennifer Yub8fee672019-06-03 15:57:25 +0000685 llvm::DenseMap<unsigned, Stmt*> JumpScopesMap;
686 for (SmallVectorImpl<Stmt *>::iterator I = GotoJumps.begin(),
687 E = GotoJumps.end();
688 I != E; ++I) {
689 Stmt *IG = *I;
Alp Tokere265cf12014-05-09 08:40:10 +0000690 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(IG)))
691 continue;
John McCallcf819ab2010-05-12 00:58:13 +0000692 unsigned IGScope = LabelAndGotoScopes[IG];
Jennifer Yub8fee672019-06-03 15:57:25 +0000693 Stmt *&Entry = JumpScopesMap[IGScope];
John McCallcf819ab2010-05-12 00:58:13 +0000694 if (!Entry) Entry = IG;
695 }
696 JumpScopes.reserve(JumpScopesMap.size());
Jennifer Yub8fee672019-06-03 15:57:25 +0000697 for (llvm::DenseMap<unsigned, Stmt *>::iterator I = JumpScopesMap.begin(),
698 E = JumpScopesMap.end();
699 I != E; ++I)
John McCallcf819ab2010-05-12 00:58:13 +0000700 JumpScopes.push_back(*I);
701 }
702
John McCall42f9f1f2010-05-12 02:37:54 +0000703 // Collect a single representative of every scope containing a
704 // label whose address was taken somewhere in the function.
705 // For most code bases, there will be only one such scope.
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000706 llvm::DenseMap<unsigned, LabelDecl*> TargetScopes;
Jennifer Yub8fee672019-06-03 15:57:25 +0000707 for (SmallVectorImpl<LabelDecl *>::iterator I = JumpTargets.begin(),
708 E = JumpTargets.end();
John McCallcf819ab2010-05-12 00:58:13 +0000709 I != E; ++I) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000710 LabelDecl *TheLabel = *I;
Alp Tokere265cf12014-05-09 08:40:10 +0000711 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(TheLabel->getStmt())))
712 continue;
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000713 unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()];
714 LabelDecl *&Target = TargetScopes[LabelScope];
John McCallcf819ab2010-05-12 00:58:13 +0000715 if (!Target) Target = TheLabel;
716 }
717
John McCall42f9f1f2010-05-12 02:37:54 +0000718 // For each target scope, make sure it's trivially reachable from
719 // every scope containing a jump site.
720 //
721 // A path between scopes always consists of exitting zero or more
722 // scopes, then entering zero or more scopes. We build a set of
723 // of scopes S from which the target scope can be trivially
724 // entered, then verify that every jump scope can be trivially
725 // exitted to reach a scope in S.
John McCallcf819ab2010-05-12 00:58:13 +0000726 llvm::BitVector Reachable(Scopes.size(), false);
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000727 for (llvm::DenseMap<unsigned,LabelDecl*>::iterator
John McCallcf819ab2010-05-12 00:58:13 +0000728 TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) {
729 unsigned TargetScope = TI->first;
Chris Lattnerc8e630e2011-02-17 07:39:24 +0000730 LabelDecl *TargetLabel = TI->second;
John McCallcf819ab2010-05-12 00:58:13 +0000731
732 Reachable.reset();
733
734 // Mark all the enclosing scopes from which you can safely jump
John McCall42f9f1f2010-05-12 02:37:54 +0000735 // into the target scope. 'Min' will end up being the index of
736 // the shallowest such scope.
John McCallcf819ab2010-05-12 00:58:13 +0000737 unsigned Min = TargetScope;
738 while (true) {
739 Reachable.set(Min);
740
741 // Don't go beyond the outermost scope.
742 if (Min == 0) break;
743
John McCall42f9f1f2010-05-12 02:37:54 +0000744 // Stop if we can't trivially enter the current scope.
John McCallcf819ab2010-05-12 00:58:13 +0000745 if (Scopes[Min].InDiag) break;
746
747 Min = Scopes[Min].ParentScope;
748 }
749
750 // Walk through all the jump sites, checking that they can trivially
751 // reach this label scope.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000752 for (SmallVectorImpl<JumpScope>::iterator
John McCallcf819ab2010-05-12 00:58:13 +0000753 I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) {
754 unsigned Scope = I->first;
755
756 // Walk out the "scope chain" for this scope, looking for a scope
John McCall42f9f1f2010-05-12 02:37:54 +0000757 // we've marked reachable. For well-formed code this amortizes
758 // to O(JumpScopes.size() / Scopes.size()): we only iterate
759 // when we see something unmarked, and in well-formed code we
760 // mark everything we iterate past.
John McCallcf819ab2010-05-12 00:58:13 +0000761 bool IsReachable = false;
762 while (true) {
763 if (Reachable.test(Scope)) {
764 // If we find something reachable, mark all the scopes we just
765 // walked through as reachable.
766 for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope)
767 Reachable.set(S);
768 IsReachable = true;
769 break;
770 }
771
772 // Don't walk out if we've reached the top-level scope or we've
773 // gotten shallower than the shallowest reachable scope.
774 if (Scope == 0 || Scope < Min) break;
775
776 // Don't walk out through an out-diagnostic.
777 if (Scopes[Scope].OutDiag) break;
778
779 Scope = Scopes[Scope].ParentScope;
780 }
781
782 // Only diagnose if we didn't find something.
783 if (IsReachable) continue;
784
Jennifer Yub8fee672019-06-03 15:57:25 +0000785 DiagnoseIndirectOrAsmJump(I->second, I->first, TargetLabel, TargetScope);
John McCallcf819ab2010-05-12 00:58:13 +0000786 }
787 }
788}
789
Richard Smithfe2750d2011-10-20 21:42:12 +0000790/// Return true if a particular error+note combination must be downgraded to a
791/// warning in Microsoft mode.
792static bool IsMicrosoftJumpWarning(unsigned JumpDiag, unsigned InDiagNote) {
793 return (JumpDiag == diag::err_goto_into_protected_scope &&
794 (InDiagNote == diag::note_protected_by_variable_init ||
795 InDiagNote == diag::note_protected_by_variable_nontriv_destructor));
796}
797
798/// Return true if a particular note should be downgraded to a compatibility
799/// warning in C++11 mode.
800static bool IsCXX98CompatWarning(Sema &S, unsigned InDiagNote) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000801 return S.getLangOpts().CPlusPlus11 &&
Richard Smithfe2750d2011-10-20 21:42:12 +0000802 InDiagNote == diag::note_protected_by_variable_non_pod;
803}
804
805/// Produce primary diagnostic for an indirect jump statement.
Jennifer Yub8fee672019-06-03 15:57:25 +0000806static void DiagnoseIndirectOrAsmJumpStmt(Sema &S, Stmt *Jump,
807 LabelDecl *Target, bool &Diagnosed) {
Richard Smithfe2750d2011-10-20 21:42:12 +0000808 if (Diagnosed)
809 return;
Jennifer Yub8fee672019-06-03 15:57:25 +0000810 bool IsAsmGoto = isa<GCCAsmStmt>(Jump);
811 S.Diag(Jump->getBeginLoc(), diag::err_indirect_goto_in_protected_scope)
812 << IsAsmGoto;
813 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target)
814 << IsAsmGoto;
Richard Smithfe2750d2011-10-20 21:42:12 +0000815 Diagnosed = true;
816}
817
818/// Produce note diagnostics for a jump into a protected scope.
Bill Wendling8ac06af2012-02-22 09:38:11 +0000819void JumpScopeChecker::NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes) {
Alp Tokere265cf12014-05-09 08:40:10 +0000820 if (CHECK_PERMISSIVE(ToScopes.empty()))
821 return;
Richard Smithfe2750d2011-10-20 21:42:12 +0000822 for (unsigned I = 0, E = ToScopes.size(); I != E; ++I)
823 if (Scopes[ToScopes[I]].InDiag)
824 S.Diag(Scopes[ToScopes[I]].Loc, Scopes[ToScopes[I]].InDiag);
825}
826
John McCall42f9f1f2010-05-12 02:37:54 +0000827/// Diagnose an indirect jump which is known to cross scopes.
Jennifer Yub8fee672019-06-03 15:57:25 +0000828void JumpScopeChecker::DiagnoseIndirectOrAsmJump(Stmt *Jump, unsigned JumpScope,
829 LabelDecl *Target,
830 unsigned TargetScope) {
Alp Tokere265cf12014-05-09 08:40:10 +0000831 if (CHECK_PERMISSIVE(JumpScope == TargetScope))
832 return;
John McCallcf819ab2010-05-12 00:58:13 +0000833
John McCall42f9f1f2010-05-12 02:37:54 +0000834 unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope);
Richard Smithfe2750d2011-10-20 21:42:12 +0000835 bool Diagnosed = false;
John McCallcf819ab2010-05-12 00:58:13 +0000836
John McCall42f9f1f2010-05-12 02:37:54 +0000837 // Walk out the scope chain until we reach the common ancestor.
838 for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope)
Richard Smithfe2750d2011-10-20 21:42:12 +0000839 if (Scopes[I].OutDiag) {
Jennifer Yub8fee672019-06-03 15:57:25 +0000840 DiagnoseIndirectOrAsmJumpStmt(S, Jump, Target, Diagnosed);
John McCall42f9f1f2010-05-12 02:37:54 +0000841 S.Diag(Scopes[I].Loc, Scopes[I].OutDiag);
Richard Smithfe2750d2011-10-20 21:42:12 +0000842 }
843
844 SmallVector<unsigned, 10> ToScopesCXX98Compat;
John McCallcf819ab2010-05-12 00:58:13 +0000845
846 // Now walk into the scopes containing the label whose address was taken.
John McCall42f9f1f2010-05-12 02:37:54 +0000847 for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope)
Richard Smithfe2750d2011-10-20 21:42:12 +0000848 if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
849 ToScopesCXX98Compat.push_back(I);
850 else if (Scopes[I].InDiag) {
Jennifer Yub8fee672019-06-03 15:57:25 +0000851 DiagnoseIndirectOrAsmJumpStmt(S, Jump, Target, Diagnosed);
John McCall42f9f1f2010-05-12 02:37:54 +0000852 S.Diag(Scopes[I].Loc, Scopes[I].InDiag);
Richard Smithfe2750d2011-10-20 21:42:12 +0000853 }
John McCallcf819ab2010-05-12 00:58:13 +0000854
Richard Smithfe2750d2011-10-20 21:42:12 +0000855 // Diagnose this jump if it would be ill-formed in C++98.
856 if (!Diagnosed && !ToScopesCXX98Compat.empty()) {
Jennifer Yub8fee672019-06-03 15:57:25 +0000857 bool IsAsmGoto = isa<GCCAsmStmt>(Jump);
858 S.Diag(Jump->getBeginLoc(),
859 diag::warn_cxx98_compat_indirect_goto_in_protected_scope)
860 << IsAsmGoto;
861 S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target)
862 << IsAsmGoto;
Richard Smithfe2750d2011-10-20 21:42:12 +0000863 NoteJumpIntoScopes(ToScopesCXX98Compat);
864 }
Francois Pichet051f5e52011-09-13 10:26:51 +0000865}
866
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000867/// CheckJump - Validate that the specified jump statement is valid: that it is
868/// jumping within or out of its current scope, not into a deeper one.
Francois Pichet051f5e52011-09-13 10:26:51 +0000869void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
Richard Smithfe2750d2011-10-20 21:42:12 +0000870 unsigned JumpDiagError, unsigned JumpDiagWarning,
871 unsigned JumpDiagCXX98Compat) {
Alp Tokere265cf12014-05-09 08:40:10 +0000872 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(From)))
873 return;
874 if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(To)))
875 return;
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000876
Alp Tokere265cf12014-05-09 08:40:10 +0000877 unsigned FromScope = LabelAndGotoScopes[From];
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000878 unsigned ToScope = LabelAndGotoScopes[To];
Mike Stump11289f42009-09-09 15:08:12 +0000879
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000880 // Common case: exactly the same scope, which is fine.
881 if (FromScope == ToScope) return;
Mike Stump11289f42009-09-09 15:08:12 +0000882
Nico Webereb0cfb52015-03-09 04:27:56 +0000883 // Warn on gotos out of __finally blocks.
884 if (isa<GotoStmt>(From) || isa<IndirectGotoStmt>(From)) {
885 // If FromScope > ToScope, FromScope is more nested and the jump goes to a
886 // less nested scope. Check if it crosses a __finally along the way.
887 for (unsigned I = FromScope; I > ToScope; I = Scopes[I].ParentScope) {
888 if (Scopes[I].InDiag == diag::note_protected_by_seh_finally) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000889 S.Diag(From->getBeginLoc(), diag::warn_jump_out_of_seh_finally);
Nico Webereb0cfb52015-03-09 04:27:56 +0000890 break;
891 }
892 }
893 }
894
John McCall42f9f1f2010-05-12 02:37:54 +0000895 unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope);
Mike Stump11289f42009-09-09 15:08:12 +0000896
John McCall42f9f1f2010-05-12 02:37:54 +0000897 // It's okay to jump out from a nested scope.
898 if (CommonScope == ToScope) return;
Mike Stump11289f42009-09-09 15:08:12 +0000899
John McCall42f9f1f2010-05-12 02:37:54 +0000900 // Pull out (and reverse) any scopes we might need to diagnose skipping.
Richard Smithfe2750d2011-10-20 21:42:12 +0000901 SmallVector<unsigned, 10> ToScopesCXX98Compat;
Francois Pichet051f5e52011-09-13 10:26:51 +0000902 SmallVector<unsigned, 10> ToScopesError;
903 SmallVector<unsigned, 10> ToScopesWarning;
904 for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope) {
Alp Tokerbfa39342014-01-14 12:51:41 +0000905 if (S.getLangOpts().MSVCCompat && JumpDiagWarning != 0 &&
Francois Pichet051f5e52011-09-13 10:26:51 +0000906 IsMicrosoftJumpWarning(JumpDiagError, Scopes[I].InDiag))
907 ToScopesWarning.push_back(I);
Richard Smithfe2750d2011-10-20 21:42:12 +0000908 else if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
909 ToScopesCXX98Compat.push_back(I);
Francois Pichet051f5e52011-09-13 10:26:51 +0000910 else if (Scopes[I].InDiag)
911 ToScopesError.push_back(I);
912 }
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000913
Francois Pichet051f5e52011-09-13 10:26:51 +0000914 // Handle warnings.
915 if (!ToScopesWarning.empty()) {
916 S.Diag(DiagLoc, JumpDiagWarning);
Richard Smithfe2750d2011-10-20 21:42:12 +0000917 NoteJumpIntoScopes(ToScopesWarning);
Francois Pichet051f5e52011-09-13 10:26:51 +0000918 }
John McCallcf819ab2010-05-12 00:58:13 +0000919
Francois Pichet051f5e52011-09-13 10:26:51 +0000920 // Handle errors.
921 if (!ToScopesError.empty()) {
922 S.Diag(DiagLoc, JumpDiagError);
Richard Smithfe2750d2011-10-20 21:42:12 +0000923 NoteJumpIntoScopes(ToScopesError);
924 }
925
926 // Handle -Wc++98-compat warnings if the jump is well-formed.
927 if (ToScopesError.empty() && !ToScopesCXX98Compat.empty()) {
928 S.Diag(DiagLoc, JumpDiagCXX98Compat);
929 NoteJumpIntoScopes(ToScopesCXX98Compat);
Francois Pichet051f5e52011-09-13 10:26:51 +0000930 }
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000931}
932
Ehsan Akhgari31097582014-09-22 02:21:54 +0000933void JumpScopeChecker::CheckGotoStmt(GotoStmt *GS) {
934 if (GS->getLabel()->isMSAsmLabel()) {
935 S.Diag(GS->getGotoLoc(), diag::err_goto_ms_asm_label)
936 << GS->getLabel()->getIdentifier();
937 S.Diag(GS->getLabel()->getLocation(), diag::note_goto_ms_asm_label)
938 << GS->getLabel()->getIdentifier();
939 }
940}
941
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000942void Sema::DiagnoseInvalidJumps(Stmt *Body) {
Douglas Gregor120f6a62009-11-17 06:14:37 +0000943 (void)JumpScopeChecker(Body, *this);
Chris Lattner1a1fdbd2009-04-19 04:46:21 +0000944}