xref: /aosp_15_r20/external/clang/lib/Sema/JumpDiagnostics.cpp (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li //===--- JumpDiagnostics.cpp - Protected scope jump analysis ------*- C++ -*-=//
2*67e74705SXin Li //
3*67e74705SXin Li //                     The LLVM Compiler Infrastructure
4*67e74705SXin Li //
5*67e74705SXin Li // This file is distributed under the University of Illinois Open Source
6*67e74705SXin Li // License. See LICENSE.TXT for details.
7*67e74705SXin Li //
8*67e74705SXin Li //===----------------------------------------------------------------------===//
9*67e74705SXin Li //
10*67e74705SXin Li // This file implements the JumpScopeChecker class, which is used to diagnose
11*67e74705SXin Li // jumps that enter a protected scope in an invalid way.
12*67e74705SXin Li //
13*67e74705SXin Li //===----------------------------------------------------------------------===//
14*67e74705SXin Li 
15*67e74705SXin Li #include "clang/Sema/SemaInternal.h"
16*67e74705SXin Li #include "clang/AST/DeclCXX.h"
17*67e74705SXin Li #include "clang/AST/Expr.h"
18*67e74705SXin Li #include "clang/AST/ExprCXX.h"
19*67e74705SXin Li #include "clang/AST/StmtCXX.h"
20*67e74705SXin Li #include "clang/AST/StmtObjC.h"
21*67e74705SXin Li #include "llvm/ADT/BitVector.h"
22*67e74705SXin Li using namespace clang;
23*67e74705SXin Li 
24*67e74705SXin Li namespace {
25*67e74705SXin Li 
26*67e74705SXin Li /// JumpScopeChecker - This object is used by Sema to diagnose invalid jumps
27*67e74705SXin Li /// into VLA and other protected scopes.  For example, this rejects:
28*67e74705SXin Li ///    goto L;
29*67e74705SXin Li ///    int a[n];
30*67e74705SXin Li ///  L:
31*67e74705SXin Li ///
32*67e74705SXin Li class JumpScopeChecker {
33*67e74705SXin Li   Sema &S;
34*67e74705SXin Li 
35*67e74705SXin Li   /// Permissive - True when recovering from errors, in which case precautions
36*67e74705SXin Li   /// are taken to handle incomplete scope information.
37*67e74705SXin Li   const bool Permissive;
38*67e74705SXin Li 
39*67e74705SXin Li   /// GotoScope - This is a record that we use to keep track of all of the
40*67e74705SXin Li   /// scopes that are introduced by VLAs and other things that scope jumps like
41*67e74705SXin Li   /// gotos.  This scope tree has nothing to do with the source scope tree,
42*67e74705SXin Li   /// because you can have multiple VLA scopes per compound statement, and most
43*67e74705SXin Li   /// compound statements don't introduce any scopes.
44*67e74705SXin Li   struct GotoScope {
45*67e74705SXin Li     /// ParentScope - The index in ScopeMap of the parent scope.  This is 0 for
46*67e74705SXin Li     /// the parent scope is the function body.
47*67e74705SXin Li     unsigned ParentScope;
48*67e74705SXin Li 
49*67e74705SXin Li     /// InDiag - The note to emit if there is a jump into this scope.
50*67e74705SXin Li     unsigned InDiag;
51*67e74705SXin Li 
52*67e74705SXin Li     /// OutDiag - The note to emit if there is an indirect jump out
53*67e74705SXin Li     /// of this scope.  Direct jumps always clean up their current scope
54*67e74705SXin Li     /// in an orderly way.
55*67e74705SXin Li     unsigned OutDiag;
56*67e74705SXin Li 
57*67e74705SXin Li     /// Loc - Location to emit the diagnostic.
58*67e74705SXin Li     SourceLocation Loc;
59*67e74705SXin Li 
GotoScope__anond2936c7b0111::JumpScopeChecker::GotoScope60*67e74705SXin Li     GotoScope(unsigned parentScope, unsigned InDiag, unsigned OutDiag,
61*67e74705SXin Li               SourceLocation L)
62*67e74705SXin Li       : ParentScope(parentScope), InDiag(InDiag), OutDiag(OutDiag), Loc(L) {}
63*67e74705SXin Li   };
64*67e74705SXin Li 
65*67e74705SXin Li   SmallVector<GotoScope, 48> Scopes;
66*67e74705SXin Li   llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
67*67e74705SXin Li   SmallVector<Stmt*, 16> Jumps;
68*67e74705SXin Li 
69*67e74705SXin Li   SmallVector<IndirectGotoStmt*, 4> IndirectJumps;
70*67e74705SXin Li   SmallVector<LabelDecl*, 4> IndirectJumpTargets;
71*67e74705SXin Li public:
72*67e74705SXin Li   JumpScopeChecker(Stmt *Body, Sema &S);
73*67e74705SXin Li private:
74*67e74705SXin Li   void BuildScopeInformation(Decl *D, unsigned &ParentScope);
75*67e74705SXin Li   void BuildScopeInformation(VarDecl *D, const BlockDecl *BDecl,
76*67e74705SXin Li                              unsigned &ParentScope);
77*67e74705SXin Li   void BuildScopeInformation(Stmt *S, unsigned &origParentScope);
78*67e74705SXin Li 
79*67e74705SXin Li   void VerifyJumps();
80*67e74705SXin Li   void VerifyIndirectJumps();
81*67e74705SXin Li   void NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes);
82*67e74705SXin Li   void DiagnoseIndirectJump(IndirectGotoStmt *IG, unsigned IGScope,
83*67e74705SXin Li                             LabelDecl *Target, unsigned TargetScope);
84*67e74705SXin Li   void CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
85*67e74705SXin Li                  unsigned JumpDiag, unsigned JumpDiagWarning,
86*67e74705SXin Li                  unsigned JumpDiagCXX98Compat);
87*67e74705SXin Li   void CheckGotoStmt(GotoStmt *GS);
88*67e74705SXin Li 
89*67e74705SXin Li   unsigned GetDeepestCommonScope(unsigned A, unsigned B);
90*67e74705SXin Li };
91*67e74705SXin Li } // end anonymous namespace
92*67e74705SXin Li 
93*67e74705SXin Li #define CHECK_PERMISSIVE(x) (assert(Permissive || !(x)), (Permissive && (x)))
94*67e74705SXin Li 
JumpScopeChecker(Stmt * Body,Sema & s)95*67e74705SXin Li JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s)
96*67e74705SXin Li     : S(s), Permissive(s.hasAnyUnrecoverableErrorsInThisFunction()) {
97*67e74705SXin Li   // Add a scope entry for function scope.
98*67e74705SXin Li   Scopes.push_back(GotoScope(~0U, ~0U, ~0U, SourceLocation()));
99*67e74705SXin Li 
100*67e74705SXin Li   // Build information for the top level compound statement, so that we have a
101*67e74705SXin Li   // defined scope record for every "goto" and label.
102*67e74705SXin Li   unsigned BodyParentScope = 0;
103*67e74705SXin Li   BuildScopeInformation(Body, BodyParentScope);
104*67e74705SXin Li 
105*67e74705SXin Li   // Check that all jumps we saw are kosher.
106*67e74705SXin Li   VerifyJumps();
107*67e74705SXin Li   VerifyIndirectJumps();
108*67e74705SXin Li }
109*67e74705SXin Li 
110*67e74705SXin Li /// GetDeepestCommonScope - Finds the innermost scope enclosing the
111*67e74705SXin Li /// two scopes.
GetDeepestCommonScope(unsigned A,unsigned B)112*67e74705SXin Li unsigned JumpScopeChecker::GetDeepestCommonScope(unsigned A, unsigned B) {
113*67e74705SXin Li   while (A != B) {
114*67e74705SXin Li     // Inner scopes are created after outer scopes and therefore have
115*67e74705SXin Li     // higher indices.
116*67e74705SXin Li     if (A < B) {
117*67e74705SXin Li       assert(Scopes[B].ParentScope < B);
118*67e74705SXin Li       B = Scopes[B].ParentScope;
119*67e74705SXin Li     } else {
120*67e74705SXin Li       assert(Scopes[A].ParentScope < A);
121*67e74705SXin Li       A = Scopes[A].ParentScope;
122*67e74705SXin Li     }
123*67e74705SXin Li   }
124*67e74705SXin Li   return A;
125*67e74705SXin Li }
126*67e74705SXin Li 
127*67e74705SXin Li typedef std::pair<unsigned,unsigned> ScopePair;
128*67e74705SXin Li 
129*67e74705SXin Li /// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a
130*67e74705SXin Li /// diagnostic that should be emitted if control goes over it. If not, return 0.
GetDiagForGotoScopeDecl(Sema & S,const Decl * D)131*67e74705SXin Li static ScopePair GetDiagForGotoScopeDecl(Sema &S, const Decl *D) {
132*67e74705SXin Li   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
133*67e74705SXin Li     unsigned InDiag = 0;
134*67e74705SXin Li     unsigned OutDiag = 0;
135*67e74705SXin Li 
136*67e74705SXin Li     if (VD->getType()->isVariablyModifiedType())
137*67e74705SXin Li       InDiag = diag::note_protected_by_vla;
138*67e74705SXin Li 
139*67e74705SXin Li     if (VD->hasAttr<BlocksAttr>())
140*67e74705SXin Li       return ScopePair(diag::note_protected_by___block,
141*67e74705SXin Li                        diag::note_exits___block);
142*67e74705SXin Li 
143*67e74705SXin Li     if (VD->hasAttr<CleanupAttr>())
144*67e74705SXin Li       return ScopePair(diag::note_protected_by_cleanup,
145*67e74705SXin Li                        diag::note_exits_cleanup);
146*67e74705SXin Li 
147*67e74705SXin Li     if (VD->hasLocalStorage()) {
148*67e74705SXin Li       switch (VD->getType().isDestructedType()) {
149*67e74705SXin Li       case QualType::DK_objc_strong_lifetime:
150*67e74705SXin Li         return ScopePair(diag::note_protected_by_objc_strong_init,
151*67e74705SXin Li                          diag::note_exits_objc_strong);
152*67e74705SXin Li 
153*67e74705SXin Li       case QualType::DK_objc_weak_lifetime:
154*67e74705SXin Li         return ScopePair(diag::note_protected_by_objc_weak_init,
155*67e74705SXin Li                          diag::note_exits_objc_weak);
156*67e74705SXin Li 
157*67e74705SXin Li       case QualType::DK_cxx_destructor:
158*67e74705SXin Li         OutDiag = diag::note_exits_dtor;
159*67e74705SXin Li         break;
160*67e74705SXin Li 
161*67e74705SXin Li       case QualType::DK_none:
162*67e74705SXin Li         break;
163*67e74705SXin Li       }
164*67e74705SXin Li     }
165*67e74705SXin Li 
166*67e74705SXin Li     const Expr *Init = VD->getInit();
167*67e74705SXin Li     if (S.Context.getLangOpts().CPlusPlus && VD->hasLocalStorage() && Init) {
168*67e74705SXin Li       // C++11 [stmt.dcl]p3:
169*67e74705SXin Li       //   A program that jumps from a point where a variable with automatic
170*67e74705SXin Li       //   storage duration is not in scope to a point where it is in scope
171*67e74705SXin Li       //   is ill-formed unless the variable has scalar type, class type with
172*67e74705SXin Li       //   a trivial default constructor and a trivial destructor, a
173*67e74705SXin Li       //   cv-qualified version of one of these types, or an array of one of
174*67e74705SXin Li       //   the preceding types and is declared without an initializer.
175*67e74705SXin Li 
176*67e74705SXin Li       // C++03 [stmt.dcl.p3:
177*67e74705SXin Li       //   A program that jumps from a point where a local variable
178*67e74705SXin Li       //   with automatic storage duration is not in scope to a point
179*67e74705SXin Li       //   where it is in scope is ill-formed unless the variable has
180*67e74705SXin Li       //   POD type and is declared without an initializer.
181*67e74705SXin Li 
182*67e74705SXin Li       InDiag = diag::note_protected_by_variable_init;
183*67e74705SXin Li 
184*67e74705SXin Li       // For a variable of (array of) class type declared without an
185*67e74705SXin Li       // initializer, we will have call-style initialization and the initializer
186*67e74705SXin Li       // will be the CXXConstructExpr with no intervening nodes.
187*67e74705SXin Li       if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
188*67e74705SXin Li         const CXXConstructorDecl *Ctor = CCE->getConstructor();
189*67e74705SXin Li         if (Ctor->isTrivial() && Ctor->isDefaultConstructor() &&
190*67e74705SXin Li             VD->getInitStyle() == VarDecl::CallInit) {
191*67e74705SXin Li           if (OutDiag)
192*67e74705SXin Li             InDiag = diag::note_protected_by_variable_nontriv_destructor;
193*67e74705SXin Li           else if (!Ctor->getParent()->isPOD())
194*67e74705SXin Li             InDiag = diag::note_protected_by_variable_non_pod;
195*67e74705SXin Li           else
196*67e74705SXin Li             InDiag = 0;
197*67e74705SXin Li         }
198*67e74705SXin Li       }
199*67e74705SXin Li     }
200*67e74705SXin Li 
201*67e74705SXin Li     return ScopePair(InDiag, OutDiag);
202*67e74705SXin Li   }
203*67e74705SXin Li 
204*67e74705SXin Li   if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
205*67e74705SXin Li     if (TD->getUnderlyingType()->isVariablyModifiedType())
206*67e74705SXin Li       return ScopePair(isa<TypedefDecl>(TD)
207*67e74705SXin Li                            ? diag::note_protected_by_vla_typedef
208*67e74705SXin Li                            : diag::note_protected_by_vla_type_alias,
209*67e74705SXin Li                        0);
210*67e74705SXin Li   }
211*67e74705SXin Li 
212*67e74705SXin Li   return ScopePair(0U, 0U);
213*67e74705SXin Li }
214*67e74705SXin Li 
215*67e74705SXin Li /// \brief Build scope information for a declaration that is part of a DeclStmt.
BuildScopeInformation(Decl * D,unsigned & ParentScope)216*67e74705SXin Li void JumpScopeChecker::BuildScopeInformation(Decl *D, unsigned &ParentScope) {
217*67e74705SXin Li   // If this decl causes a new scope, push and switch to it.
218*67e74705SXin Li   std::pair<unsigned,unsigned> Diags = GetDiagForGotoScopeDecl(S, D);
219*67e74705SXin Li   if (Diags.first || Diags.second) {
220*67e74705SXin Li     Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second,
221*67e74705SXin Li                                D->getLocation()));
222*67e74705SXin Li     ParentScope = Scopes.size()-1;
223*67e74705SXin Li   }
224*67e74705SXin Li 
225*67e74705SXin Li   // If the decl has an initializer, walk it with the potentially new
226*67e74705SXin Li   // scope we just installed.
227*67e74705SXin Li   if (VarDecl *VD = dyn_cast<VarDecl>(D))
228*67e74705SXin Li     if (Expr *Init = VD->getInit())
229*67e74705SXin Li       BuildScopeInformation(Init, ParentScope);
230*67e74705SXin Li }
231*67e74705SXin Li 
232*67e74705SXin Li /// \brief Build scope information for a captured block literal variables.
BuildScopeInformation(VarDecl * D,const BlockDecl * BDecl,unsigned & ParentScope)233*67e74705SXin Li void JumpScopeChecker::BuildScopeInformation(VarDecl *D,
234*67e74705SXin Li                                              const BlockDecl *BDecl,
235*67e74705SXin Li                                              unsigned &ParentScope) {
236*67e74705SXin Li   // exclude captured __block variables; there's no destructor
237*67e74705SXin Li   // associated with the block literal for them.
238*67e74705SXin Li   if (D->hasAttr<BlocksAttr>())
239*67e74705SXin Li     return;
240*67e74705SXin Li   QualType T = D->getType();
241*67e74705SXin Li   QualType::DestructionKind destructKind = T.isDestructedType();
242*67e74705SXin Li   if (destructKind != QualType::DK_none) {
243*67e74705SXin Li     std::pair<unsigned,unsigned> Diags;
244*67e74705SXin Li     switch (destructKind) {
245*67e74705SXin Li       case QualType::DK_cxx_destructor:
246*67e74705SXin Li         Diags = ScopePair(diag::note_enters_block_captures_cxx_obj,
247*67e74705SXin Li                           diag::note_exits_block_captures_cxx_obj);
248*67e74705SXin Li         break;
249*67e74705SXin Li       case QualType::DK_objc_strong_lifetime:
250*67e74705SXin Li         Diags = ScopePair(diag::note_enters_block_captures_strong,
251*67e74705SXin Li                           diag::note_exits_block_captures_strong);
252*67e74705SXin Li         break;
253*67e74705SXin Li       case QualType::DK_objc_weak_lifetime:
254*67e74705SXin Li         Diags = ScopePair(diag::note_enters_block_captures_weak,
255*67e74705SXin Li                           diag::note_exits_block_captures_weak);
256*67e74705SXin Li         break;
257*67e74705SXin Li       case QualType::DK_none:
258*67e74705SXin Li         llvm_unreachable("non-lifetime captured variable");
259*67e74705SXin Li     }
260*67e74705SXin Li     SourceLocation Loc = D->getLocation();
261*67e74705SXin Li     if (Loc.isInvalid())
262*67e74705SXin Li       Loc = BDecl->getLocation();
263*67e74705SXin Li     Scopes.push_back(GotoScope(ParentScope,
264*67e74705SXin Li                                Diags.first, Diags.second, Loc));
265*67e74705SXin Li     ParentScope = Scopes.size()-1;
266*67e74705SXin Li   }
267*67e74705SXin Li }
268*67e74705SXin Li 
269*67e74705SXin Li /// BuildScopeInformation - The statements from CI to CE are known to form a
270*67e74705SXin Li /// coherent VLA scope with a specified parent node.  Walk through the
271*67e74705SXin Li /// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
272*67e74705SXin Li /// walking the AST as needed.
BuildScopeInformation(Stmt * S,unsigned & origParentScope)273*67e74705SXin Li void JumpScopeChecker::BuildScopeInformation(Stmt *S,
274*67e74705SXin Li                                              unsigned &origParentScope) {
275*67e74705SXin Li   // If this is a statement, rather than an expression, scopes within it don't
276*67e74705SXin Li   // propagate out into the enclosing scope.  Otherwise we have to worry
277*67e74705SXin Li   // about block literals, which have the lifetime of their enclosing statement.
278*67e74705SXin Li   unsigned independentParentScope = origParentScope;
279*67e74705SXin Li   unsigned &ParentScope = ((isa<Expr>(S) && !isa<StmtExpr>(S))
280*67e74705SXin Li                             ? origParentScope : independentParentScope);
281*67e74705SXin Li 
282*67e74705SXin Li   unsigned StmtsToSkip = 0u;
283*67e74705SXin Li 
284*67e74705SXin Li   // If we found a label, remember that it is in ParentScope scope.
285*67e74705SXin Li   switch (S->getStmtClass()) {
286*67e74705SXin Li   case Stmt::AddrLabelExprClass:
287*67e74705SXin Li     IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel());
288*67e74705SXin Li     break;
289*67e74705SXin Li 
290*67e74705SXin Li   case Stmt::IndirectGotoStmtClass:
291*67e74705SXin Li     // "goto *&&lbl;" is a special case which we treat as equivalent
292*67e74705SXin Li     // to a normal goto.  In addition, we don't calculate scope in the
293*67e74705SXin Li     // operand (to avoid recording the address-of-label use), which
294*67e74705SXin Li     // works only because of the restricted set of expressions which
295*67e74705SXin Li     // we detect as constant targets.
296*67e74705SXin Li     if (cast<IndirectGotoStmt>(S)->getConstantTarget()) {
297*67e74705SXin Li       LabelAndGotoScopes[S] = ParentScope;
298*67e74705SXin Li       Jumps.push_back(S);
299*67e74705SXin Li       return;
300*67e74705SXin Li     }
301*67e74705SXin Li 
302*67e74705SXin Li     LabelAndGotoScopes[S] = ParentScope;
303*67e74705SXin Li     IndirectJumps.push_back(cast<IndirectGotoStmt>(S));
304*67e74705SXin Li     break;
305*67e74705SXin Li 
306*67e74705SXin Li   case Stmt::SwitchStmtClass:
307*67e74705SXin Li     // Evaluate the C++17 init stmt and condition variable
308*67e74705SXin Li     // before entering the scope of the switch statement.
309*67e74705SXin Li     if (Stmt *Init = cast<SwitchStmt>(S)->getInit()) {
310*67e74705SXin Li       BuildScopeInformation(Init, ParentScope);
311*67e74705SXin Li       ++StmtsToSkip;
312*67e74705SXin Li     }
313*67e74705SXin Li     if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) {
314*67e74705SXin Li       BuildScopeInformation(Var, ParentScope);
315*67e74705SXin Li       ++StmtsToSkip;
316*67e74705SXin Li     }
317*67e74705SXin Li     // Fall through
318*67e74705SXin Li 
319*67e74705SXin Li   case Stmt::GotoStmtClass:
320*67e74705SXin Li     // Remember both what scope a goto is in as well as the fact that we have
321*67e74705SXin Li     // it.  This makes the second scan not have to walk the AST again.
322*67e74705SXin Li     LabelAndGotoScopes[S] = ParentScope;
323*67e74705SXin Li     Jumps.push_back(S);
324*67e74705SXin Li     break;
325*67e74705SXin Li 
326*67e74705SXin Li   case Stmt::IfStmtClass: {
327*67e74705SXin Li     IfStmt *IS = cast<IfStmt>(S);
328*67e74705SXin Li     if (!IS->isConstexpr())
329*67e74705SXin Li       break;
330*67e74705SXin Li 
331*67e74705SXin Li     if (VarDecl *Var = IS->getConditionVariable())
332*67e74705SXin Li       BuildScopeInformation(Var, ParentScope);
333*67e74705SXin Li 
334*67e74705SXin Li     // Cannot jump into the middle of the condition.
335*67e74705SXin Li     unsigned NewParentScope = Scopes.size();
336*67e74705SXin Li     Scopes.push_back(GotoScope(ParentScope,
337*67e74705SXin Li                                diag::note_protected_by_constexpr_if, 0,
338*67e74705SXin Li                                IS->getLocStart()));
339*67e74705SXin Li     BuildScopeInformation(IS->getCond(), NewParentScope);
340*67e74705SXin Li 
341*67e74705SXin Li     // Jumps into either arm of an 'if constexpr' are not allowed.
342*67e74705SXin Li     NewParentScope = Scopes.size();
343*67e74705SXin Li     Scopes.push_back(GotoScope(ParentScope,
344*67e74705SXin Li                                diag::note_protected_by_constexpr_if, 0,
345*67e74705SXin Li                                IS->getLocStart()));
346*67e74705SXin Li     BuildScopeInformation(IS->getThen(), NewParentScope);
347*67e74705SXin Li     if (Stmt *Else = IS->getElse()) {
348*67e74705SXin Li       NewParentScope = Scopes.size();
349*67e74705SXin Li       Scopes.push_back(GotoScope(ParentScope,
350*67e74705SXin Li                                  diag::note_protected_by_constexpr_if, 0,
351*67e74705SXin Li                                  IS->getLocStart()));
352*67e74705SXin Li       BuildScopeInformation(Else, NewParentScope);
353*67e74705SXin Li     }
354*67e74705SXin Li     return;
355*67e74705SXin Li   }
356*67e74705SXin Li 
357*67e74705SXin Li   case Stmt::CXXTryStmtClass: {
358*67e74705SXin Li     CXXTryStmt *TS = cast<CXXTryStmt>(S);
359*67e74705SXin Li     {
360*67e74705SXin Li       unsigned NewParentScope = Scopes.size();
361*67e74705SXin Li       Scopes.push_back(GotoScope(ParentScope,
362*67e74705SXin Li                                  diag::note_protected_by_cxx_try,
363*67e74705SXin Li                                  diag::note_exits_cxx_try,
364*67e74705SXin Li                                  TS->getSourceRange().getBegin()));
365*67e74705SXin Li       if (Stmt *TryBlock = TS->getTryBlock())
366*67e74705SXin Li         BuildScopeInformation(TryBlock, NewParentScope);
367*67e74705SXin Li     }
368*67e74705SXin Li 
369*67e74705SXin Li     // Jump from the catch into the try is not allowed either.
370*67e74705SXin Li     for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) {
371*67e74705SXin Li       CXXCatchStmt *CS = TS->getHandler(I);
372*67e74705SXin Li       unsigned NewParentScope = Scopes.size();
373*67e74705SXin Li       Scopes.push_back(GotoScope(ParentScope,
374*67e74705SXin Li                                  diag::note_protected_by_cxx_catch,
375*67e74705SXin Li                                  diag::note_exits_cxx_catch,
376*67e74705SXin Li                                  CS->getSourceRange().getBegin()));
377*67e74705SXin Li       BuildScopeInformation(CS->getHandlerBlock(), NewParentScope);
378*67e74705SXin Li     }
379*67e74705SXin Li     return;
380*67e74705SXin Li   }
381*67e74705SXin Li 
382*67e74705SXin Li   case Stmt::SEHTryStmtClass: {
383*67e74705SXin Li     SEHTryStmt *TS = cast<SEHTryStmt>(S);
384*67e74705SXin Li     {
385*67e74705SXin Li       unsigned NewParentScope = Scopes.size();
386*67e74705SXin Li       Scopes.push_back(GotoScope(ParentScope,
387*67e74705SXin Li                                  diag::note_protected_by_seh_try,
388*67e74705SXin Li                                  diag::note_exits_seh_try,
389*67e74705SXin Li                                  TS->getSourceRange().getBegin()));
390*67e74705SXin Li       if (Stmt *TryBlock = TS->getTryBlock())
391*67e74705SXin Li         BuildScopeInformation(TryBlock, NewParentScope);
392*67e74705SXin Li     }
393*67e74705SXin Li 
394*67e74705SXin Li     // Jump from __except or __finally into the __try are not allowed either.
395*67e74705SXin Li     if (SEHExceptStmt *Except = TS->getExceptHandler()) {
396*67e74705SXin Li       unsigned NewParentScope = Scopes.size();
397*67e74705SXin Li       Scopes.push_back(GotoScope(ParentScope,
398*67e74705SXin Li                                  diag::note_protected_by_seh_except,
399*67e74705SXin Li                                  diag::note_exits_seh_except,
400*67e74705SXin Li                                  Except->getSourceRange().getBegin()));
401*67e74705SXin Li       BuildScopeInformation(Except->getBlock(), NewParentScope);
402*67e74705SXin Li     } else if (SEHFinallyStmt *Finally = TS->getFinallyHandler()) {
403*67e74705SXin Li       unsigned NewParentScope = Scopes.size();
404*67e74705SXin Li       Scopes.push_back(GotoScope(ParentScope,
405*67e74705SXin Li                                  diag::note_protected_by_seh_finally,
406*67e74705SXin Li                                  diag::note_exits_seh_finally,
407*67e74705SXin Li                                  Finally->getSourceRange().getBegin()));
408*67e74705SXin Li       BuildScopeInformation(Finally->getBlock(), NewParentScope);
409*67e74705SXin Li     }
410*67e74705SXin Li 
411*67e74705SXin Li     return;
412*67e74705SXin Li   }
413*67e74705SXin Li 
414*67e74705SXin Li   case Stmt::DeclStmtClass: {
415*67e74705SXin Li     // If this is a declstmt with a VLA definition, it defines a scope from here
416*67e74705SXin Li     // to the end of the containing context.
417*67e74705SXin Li     DeclStmt *DS = cast<DeclStmt>(S);
418*67e74705SXin Li     // The decl statement creates a scope if any of the decls in it are VLAs
419*67e74705SXin Li     // or have the cleanup attribute.
420*67e74705SXin Li     for (auto *I : DS->decls())
421*67e74705SXin Li       BuildScopeInformation(I, origParentScope);
422*67e74705SXin Li     return;
423*67e74705SXin Li   }
424*67e74705SXin Li 
425*67e74705SXin Li   case Stmt::ObjCAtTryStmtClass: {
426*67e74705SXin Li     // Disallow jumps into any part of an @try statement by pushing a scope and
427*67e74705SXin Li     // walking all sub-stmts in that scope.
428*67e74705SXin Li     ObjCAtTryStmt *AT = cast<ObjCAtTryStmt>(S);
429*67e74705SXin Li     // Recursively walk the AST for the @try part.
430*67e74705SXin Li     {
431*67e74705SXin Li       unsigned NewParentScope = Scopes.size();
432*67e74705SXin Li       Scopes.push_back(GotoScope(ParentScope,
433*67e74705SXin Li                                  diag::note_protected_by_objc_try,
434*67e74705SXin Li                                  diag::note_exits_objc_try,
435*67e74705SXin Li                                  AT->getAtTryLoc()));
436*67e74705SXin Li       if (Stmt *TryPart = AT->getTryBody())
437*67e74705SXin Li         BuildScopeInformation(TryPart, NewParentScope);
438*67e74705SXin Li     }
439*67e74705SXin Li 
440*67e74705SXin Li     // Jump from the catch to the finally or try is not valid.
441*67e74705SXin Li     for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) {
442*67e74705SXin Li       ObjCAtCatchStmt *AC = AT->getCatchStmt(I);
443*67e74705SXin Li       unsigned NewParentScope = Scopes.size();
444*67e74705SXin Li       Scopes.push_back(GotoScope(ParentScope,
445*67e74705SXin Li                                  diag::note_protected_by_objc_catch,
446*67e74705SXin Li                                  diag::note_exits_objc_catch,
447*67e74705SXin Li                                  AC->getAtCatchLoc()));
448*67e74705SXin Li       // @catches are nested and it isn't
449*67e74705SXin Li       BuildScopeInformation(AC->getCatchBody(), NewParentScope);
450*67e74705SXin Li     }
451*67e74705SXin Li 
452*67e74705SXin Li     // Jump from the finally to the try or catch is not valid.
453*67e74705SXin Li     if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
454*67e74705SXin Li       unsigned NewParentScope = Scopes.size();
455*67e74705SXin Li       Scopes.push_back(GotoScope(ParentScope,
456*67e74705SXin Li                                  diag::note_protected_by_objc_finally,
457*67e74705SXin Li                                  diag::note_exits_objc_finally,
458*67e74705SXin Li                                  AF->getAtFinallyLoc()));
459*67e74705SXin Li       BuildScopeInformation(AF, NewParentScope);
460*67e74705SXin Li     }
461*67e74705SXin Li 
462*67e74705SXin Li     return;
463*67e74705SXin Li   }
464*67e74705SXin Li 
465*67e74705SXin Li   case Stmt::ObjCAtSynchronizedStmtClass: {
466*67e74705SXin Li     // Disallow jumps into the protected statement of an @synchronized, but
467*67e74705SXin Li     // allow jumps into the object expression it protects.
468*67e74705SXin Li     ObjCAtSynchronizedStmt *AS = cast<ObjCAtSynchronizedStmt>(S);
469*67e74705SXin Li     // Recursively walk the AST for the @synchronized object expr, it is
470*67e74705SXin Li     // evaluated in the normal scope.
471*67e74705SXin Li     BuildScopeInformation(AS->getSynchExpr(), ParentScope);
472*67e74705SXin Li 
473*67e74705SXin Li     // Recursively walk the AST for the @synchronized part, protected by a new
474*67e74705SXin Li     // scope.
475*67e74705SXin Li     unsigned NewParentScope = Scopes.size();
476*67e74705SXin Li     Scopes.push_back(GotoScope(ParentScope,
477*67e74705SXin Li                                diag::note_protected_by_objc_synchronized,
478*67e74705SXin Li                                diag::note_exits_objc_synchronized,
479*67e74705SXin Li                                AS->getAtSynchronizedLoc()));
480*67e74705SXin Li     BuildScopeInformation(AS->getSynchBody(), NewParentScope);
481*67e74705SXin Li     return;
482*67e74705SXin Li   }
483*67e74705SXin Li 
484*67e74705SXin Li   case Stmt::ObjCAutoreleasePoolStmtClass: {
485*67e74705SXin Li     // Disallow jumps into the protected statement of an @autoreleasepool.
486*67e74705SXin Li     ObjCAutoreleasePoolStmt *AS = cast<ObjCAutoreleasePoolStmt>(S);
487*67e74705SXin Li     // Recursively walk the AST for the @autoreleasepool part, protected by a
488*67e74705SXin Li     // new scope.
489*67e74705SXin Li     unsigned NewParentScope = Scopes.size();
490*67e74705SXin Li     Scopes.push_back(GotoScope(ParentScope,
491*67e74705SXin Li                                diag::note_protected_by_objc_autoreleasepool,
492*67e74705SXin Li                                diag::note_exits_objc_autoreleasepool,
493*67e74705SXin Li                                AS->getAtLoc()));
494*67e74705SXin Li     BuildScopeInformation(AS->getSubStmt(), NewParentScope);
495*67e74705SXin Li     return;
496*67e74705SXin Li   }
497*67e74705SXin Li 
498*67e74705SXin Li   case Stmt::ExprWithCleanupsClass: {
499*67e74705SXin Li     // Disallow jumps past full-expressions that use blocks with
500*67e74705SXin Li     // non-trivial cleanups of their captures.  This is theoretically
501*67e74705SXin Li     // implementable but a lot of work which we haven't felt up to doing.
502*67e74705SXin Li     ExprWithCleanups *EWC = cast<ExprWithCleanups>(S);
503*67e74705SXin Li     for (unsigned i = 0, e = EWC->getNumObjects(); i != e; ++i) {
504*67e74705SXin Li       const BlockDecl *BDecl = EWC->getObject(i);
505*67e74705SXin Li       for (const auto &CI : BDecl->captures()) {
506*67e74705SXin Li         VarDecl *variable = CI.getVariable();
507*67e74705SXin Li         BuildScopeInformation(variable, BDecl, origParentScope);
508*67e74705SXin Li       }
509*67e74705SXin Li     }
510*67e74705SXin Li     break;
511*67e74705SXin Li   }
512*67e74705SXin Li 
513*67e74705SXin Li   case Stmt::MaterializeTemporaryExprClass: {
514*67e74705SXin Li     // Disallow jumps out of scopes containing temporaries lifetime-extended to
515*67e74705SXin Li     // automatic storage duration.
516*67e74705SXin Li     MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(S);
517*67e74705SXin Li     if (MTE->getStorageDuration() == SD_Automatic) {
518*67e74705SXin Li       SmallVector<const Expr *, 4> CommaLHS;
519*67e74705SXin Li       SmallVector<SubobjectAdjustment, 4> Adjustments;
520*67e74705SXin Li       const Expr *ExtendedObject =
521*67e74705SXin Li           MTE->GetTemporaryExpr()->skipRValueSubobjectAdjustments(
522*67e74705SXin Li               CommaLHS, Adjustments);
523*67e74705SXin Li       if (ExtendedObject->getType().isDestructedType()) {
524*67e74705SXin Li         Scopes.push_back(GotoScope(ParentScope, 0,
525*67e74705SXin Li                                    diag::note_exits_temporary_dtor,
526*67e74705SXin Li                                    ExtendedObject->getExprLoc()));
527*67e74705SXin Li         origParentScope = Scopes.size()-1;
528*67e74705SXin Li       }
529*67e74705SXin Li     }
530*67e74705SXin Li     break;
531*67e74705SXin Li   }
532*67e74705SXin Li 
533*67e74705SXin Li   case Stmt::CaseStmtClass:
534*67e74705SXin Li   case Stmt::DefaultStmtClass:
535*67e74705SXin Li   case Stmt::LabelStmtClass:
536*67e74705SXin Li     LabelAndGotoScopes[S] = ParentScope;
537*67e74705SXin Li     break;
538*67e74705SXin Li 
539*67e74705SXin Li   default:
540*67e74705SXin Li     break;
541*67e74705SXin Li   }
542*67e74705SXin Li 
543*67e74705SXin Li   for (Stmt *SubStmt : S->children()) {
544*67e74705SXin Li     if (!SubStmt)
545*67e74705SXin Li         continue;
546*67e74705SXin Li     if (StmtsToSkip) {
547*67e74705SXin Li       --StmtsToSkip;
548*67e74705SXin Li       continue;
549*67e74705SXin Li     }
550*67e74705SXin Li 
551*67e74705SXin Li     // Cases, labels, and defaults aren't "scope parents".  It's also
552*67e74705SXin Li     // important to handle these iteratively instead of recursively in
553*67e74705SXin Li     // order to avoid blowing out the stack.
554*67e74705SXin Li     while (true) {
555*67e74705SXin Li       Stmt *Next;
556*67e74705SXin Li       if (CaseStmt *CS = dyn_cast<CaseStmt>(SubStmt))
557*67e74705SXin Li         Next = CS->getSubStmt();
558*67e74705SXin Li       else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SubStmt))
559*67e74705SXin Li         Next = DS->getSubStmt();
560*67e74705SXin Li       else if (LabelStmt *LS = dyn_cast<LabelStmt>(SubStmt))
561*67e74705SXin Li         Next = LS->getSubStmt();
562*67e74705SXin Li       else
563*67e74705SXin Li         break;
564*67e74705SXin Li 
565*67e74705SXin Li       LabelAndGotoScopes[SubStmt] = ParentScope;
566*67e74705SXin Li       SubStmt = Next;
567*67e74705SXin Li     }
568*67e74705SXin Li 
569*67e74705SXin Li     // Recursively walk the AST.
570*67e74705SXin Li     BuildScopeInformation(SubStmt, ParentScope);
571*67e74705SXin Li   }
572*67e74705SXin Li }
573*67e74705SXin Li 
574*67e74705SXin Li /// VerifyJumps - Verify each element of the Jumps array to see if they are
575*67e74705SXin Li /// valid, emitting diagnostics if not.
VerifyJumps()576*67e74705SXin Li void JumpScopeChecker::VerifyJumps() {
577*67e74705SXin Li   while (!Jumps.empty()) {
578*67e74705SXin Li     Stmt *Jump = Jumps.pop_back_val();
579*67e74705SXin Li 
580*67e74705SXin Li     // With a goto,
581*67e74705SXin Li     if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
582*67e74705SXin Li       // The label may not have a statement if it's coming from inline MS ASM.
583*67e74705SXin Li       if (GS->getLabel()->getStmt()) {
584*67e74705SXin Li         CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(),
585*67e74705SXin Li                   diag::err_goto_into_protected_scope,
586*67e74705SXin Li                   diag::ext_goto_into_protected_scope,
587*67e74705SXin Li                   diag::warn_cxx98_compat_goto_into_protected_scope);
588*67e74705SXin Li       }
589*67e74705SXin Li       CheckGotoStmt(GS);
590*67e74705SXin Li       continue;
591*67e74705SXin Li     }
592*67e74705SXin Li 
593*67e74705SXin Li     // We only get indirect gotos here when they have a constant target.
594*67e74705SXin Li     if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) {
595*67e74705SXin Li       LabelDecl *Target = IGS->getConstantTarget();
596*67e74705SXin Li       CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(),
597*67e74705SXin Li                 diag::err_goto_into_protected_scope,
598*67e74705SXin Li                 diag::ext_goto_into_protected_scope,
599*67e74705SXin Li                 diag::warn_cxx98_compat_goto_into_protected_scope);
600*67e74705SXin Li       continue;
601*67e74705SXin Li     }
602*67e74705SXin Li 
603*67e74705SXin Li     SwitchStmt *SS = cast<SwitchStmt>(Jump);
604*67e74705SXin Li     for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
605*67e74705SXin Li          SC = SC->getNextSwitchCase()) {
606*67e74705SXin Li       if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(SC)))
607*67e74705SXin Li         continue;
608*67e74705SXin Li       SourceLocation Loc;
609*67e74705SXin Li       if (CaseStmt *CS = dyn_cast<CaseStmt>(SC))
610*67e74705SXin Li         Loc = CS->getLocStart();
611*67e74705SXin Li       else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC))
612*67e74705SXin Li         Loc = DS->getLocStart();
613*67e74705SXin Li       else
614*67e74705SXin Li         Loc = SC->getLocStart();
615*67e74705SXin Li       CheckJump(SS, SC, Loc, diag::err_switch_into_protected_scope, 0,
616*67e74705SXin Li                 diag::warn_cxx98_compat_switch_into_protected_scope);
617*67e74705SXin Li     }
618*67e74705SXin Li   }
619*67e74705SXin Li }
620*67e74705SXin Li 
621*67e74705SXin Li /// VerifyIndirectJumps - Verify whether any possible indirect jump
622*67e74705SXin Li /// might cross a protection boundary.  Unlike direct jumps, indirect
623*67e74705SXin Li /// jumps count cleanups as protection boundaries:  since there's no
624*67e74705SXin Li /// way to know where the jump is going, we can't implicitly run the
625*67e74705SXin Li /// right cleanups the way we can with direct jumps.
626*67e74705SXin Li ///
627*67e74705SXin Li /// Thus, an indirect jump is "trivial" if it bypasses no
628*67e74705SXin Li /// initializations and no teardowns.  More formally, an indirect jump
629*67e74705SXin Li /// from A to B is trivial if the path out from A to DCA(A,B) is
630*67e74705SXin Li /// trivial and the path in from DCA(A,B) to B is trivial, where
631*67e74705SXin Li /// DCA(A,B) is the deepest common ancestor of A and B.
632*67e74705SXin Li /// Jump-triviality is transitive but asymmetric.
633*67e74705SXin Li ///
634*67e74705SXin Li /// A path in is trivial if none of the entered scopes have an InDiag.
635*67e74705SXin Li /// A path out is trivial is none of the exited scopes have an OutDiag.
636*67e74705SXin Li ///
637*67e74705SXin Li /// Under these definitions, this function checks that the indirect
638*67e74705SXin Li /// jump between A and B is trivial for every indirect goto statement A
639*67e74705SXin Li /// and every label B whose address was taken in the function.
VerifyIndirectJumps()640*67e74705SXin Li void JumpScopeChecker::VerifyIndirectJumps() {
641*67e74705SXin Li   if (IndirectJumps.empty()) return;
642*67e74705SXin Li 
643*67e74705SXin Li   // If there aren't any address-of-label expressions in this function,
644*67e74705SXin Li   // complain about the first indirect goto.
645*67e74705SXin Li   if (IndirectJumpTargets.empty()) {
646*67e74705SXin Li     S.Diag(IndirectJumps[0]->getGotoLoc(),
647*67e74705SXin Li            diag::err_indirect_goto_without_addrlabel);
648*67e74705SXin Li     return;
649*67e74705SXin Li   }
650*67e74705SXin Li 
651*67e74705SXin Li   // Collect a single representative of every scope containing an
652*67e74705SXin Li   // indirect goto.  For most code bases, this substantially cuts
653*67e74705SXin Li   // down on the number of jump sites we'll have to consider later.
654*67e74705SXin Li   typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope;
655*67e74705SXin Li   SmallVector<JumpScope, 32> JumpScopes;
656*67e74705SXin Li   {
657*67e74705SXin Li     llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap;
658*67e74705SXin Li     for (SmallVectorImpl<IndirectGotoStmt*>::iterator
659*67e74705SXin Li            I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) {
660*67e74705SXin Li       IndirectGotoStmt *IG = *I;
661*67e74705SXin Li       if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(IG)))
662*67e74705SXin Li         continue;
663*67e74705SXin Li       unsigned IGScope = LabelAndGotoScopes[IG];
664*67e74705SXin Li       IndirectGotoStmt *&Entry = JumpScopesMap[IGScope];
665*67e74705SXin Li       if (!Entry) Entry = IG;
666*67e74705SXin Li     }
667*67e74705SXin Li     JumpScopes.reserve(JumpScopesMap.size());
668*67e74705SXin Li     for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator
669*67e74705SXin Li            I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I)
670*67e74705SXin Li       JumpScopes.push_back(*I);
671*67e74705SXin Li   }
672*67e74705SXin Li 
673*67e74705SXin Li   // Collect a single representative of every scope containing a
674*67e74705SXin Li   // label whose address was taken somewhere in the function.
675*67e74705SXin Li   // For most code bases, there will be only one such scope.
676*67e74705SXin Li   llvm::DenseMap<unsigned, LabelDecl*> TargetScopes;
677*67e74705SXin Li   for (SmallVectorImpl<LabelDecl*>::iterator
678*67e74705SXin Li          I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end();
679*67e74705SXin Li        I != E; ++I) {
680*67e74705SXin Li     LabelDecl *TheLabel = *I;
681*67e74705SXin Li     if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(TheLabel->getStmt())))
682*67e74705SXin Li       continue;
683*67e74705SXin Li     unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()];
684*67e74705SXin Li     LabelDecl *&Target = TargetScopes[LabelScope];
685*67e74705SXin Li     if (!Target) Target = TheLabel;
686*67e74705SXin Li   }
687*67e74705SXin Li 
688*67e74705SXin Li   // For each target scope, make sure it's trivially reachable from
689*67e74705SXin Li   // every scope containing a jump site.
690*67e74705SXin Li   //
691*67e74705SXin Li   // A path between scopes always consists of exitting zero or more
692*67e74705SXin Li   // scopes, then entering zero or more scopes.  We build a set of
693*67e74705SXin Li   // of scopes S from which the target scope can be trivially
694*67e74705SXin Li   // entered, then verify that every jump scope can be trivially
695*67e74705SXin Li   // exitted to reach a scope in S.
696*67e74705SXin Li   llvm::BitVector Reachable(Scopes.size(), false);
697*67e74705SXin Li   for (llvm::DenseMap<unsigned,LabelDecl*>::iterator
698*67e74705SXin Li          TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) {
699*67e74705SXin Li     unsigned TargetScope = TI->first;
700*67e74705SXin Li     LabelDecl *TargetLabel = TI->second;
701*67e74705SXin Li 
702*67e74705SXin Li     Reachable.reset();
703*67e74705SXin Li 
704*67e74705SXin Li     // Mark all the enclosing scopes from which you can safely jump
705*67e74705SXin Li     // into the target scope.  'Min' will end up being the index of
706*67e74705SXin Li     // the shallowest such scope.
707*67e74705SXin Li     unsigned Min = TargetScope;
708*67e74705SXin Li     while (true) {
709*67e74705SXin Li       Reachable.set(Min);
710*67e74705SXin Li 
711*67e74705SXin Li       // Don't go beyond the outermost scope.
712*67e74705SXin Li       if (Min == 0) break;
713*67e74705SXin Li 
714*67e74705SXin Li       // Stop if we can't trivially enter the current scope.
715*67e74705SXin Li       if (Scopes[Min].InDiag) break;
716*67e74705SXin Li 
717*67e74705SXin Li       Min = Scopes[Min].ParentScope;
718*67e74705SXin Li     }
719*67e74705SXin Li 
720*67e74705SXin Li     // Walk through all the jump sites, checking that they can trivially
721*67e74705SXin Li     // reach this label scope.
722*67e74705SXin Li     for (SmallVectorImpl<JumpScope>::iterator
723*67e74705SXin Li            I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) {
724*67e74705SXin Li       unsigned Scope = I->first;
725*67e74705SXin Li 
726*67e74705SXin Li       // Walk out the "scope chain" for this scope, looking for a scope
727*67e74705SXin Li       // we've marked reachable.  For well-formed code this amortizes
728*67e74705SXin Li       // to O(JumpScopes.size() / Scopes.size()):  we only iterate
729*67e74705SXin Li       // when we see something unmarked, and in well-formed code we
730*67e74705SXin Li       // mark everything we iterate past.
731*67e74705SXin Li       bool IsReachable = false;
732*67e74705SXin Li       while (true) {
733*67e74705SXin Li         if (Reachable.test(Scope)) {
734*67e74705SXin Li           // If we find something reachable, mark all the scopes we just
735*67e74705SXin Li           // walked through as reachable.
736*67e74705SXin Li           for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope)
737*67e74705SXin Li             Reachable.set(S);
738*67e74705SXin Li           IsReachable = true;
739*67e74705SXin Li           break;
740*67e74705SXin Li         }
741*67e74705SXin Li 
742*67e74705SXin Li         // Don't walk out if we've reached the top-level scope or we've
743*67e74705SXin Li         // gotten shallower than the shallowest reachable scope.
744*67e74705SXin Li         if (Scope == 0 || Scope < Min) break;
745*67e74705SXin Li 
746*67e74705SXin Li         // Don't walk out through an out-diagnostic.
747*67e74705SXin Li         if (Scopes[Scope].OutDiag) break;
748*67e74705SXin Li 
749*67e74705SXin Li         Scope = Scopes[Scope].ParentScope;
750*67e74705SXin Li       }
751*67e74705SXin Li 
752*67e74705SXin Li       // Only diagnose if we didn't find something.
753*67e74705SXin Li       if (IsReachable) continue;
754*67e74705SXin Li 
755*67e74705SXin Li       DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope);
756*67e74705SXin Li     }
757*67e74705SXin Li   }
758*67e74705SXin Li }
759*67e74705SXin Li 
760*67e74705SXin Li /// Return true if a particular error+note combination must be downgraded to a
761*67e74705SXin Li /// warning in Microsoft mode.
IsMicrosoftJumpWarning(unsigned JumpDiag,unsigned InDiagNote)762*67e74705SXin Li static bool IsMicrosoftJumpWarning(unsigned JumpDiag, unsigned InDiagNote) {
763*67e74705SXin Li   return (JumpDiag == diag::err_goto_into_protected_scope &&
764*67e74705SXin Li          (InDiagNote == diag::note_protected_by_variable_init ||
765*67e74705SXin Li           InDiagNote == diag::note_protected_by_variable_nontriv_destructor));
766*67e74705SXin Li }
767*67e74705SXin Li 
768*67e74705SXin Li /// Return true if a particular note should be downgraded to a compatibility
769*67e74705SXin Li /// warning in C++11 mode.
IsCXX98CompatWarning(Sema & S,unsigned InDiagNote)770*67e74705SXin Li static bool IsCXX98CompatWarning(Sema &S, unsigned InDiagNote) {
771*67e74705SXin Li   return S.getLangOpts().CPlusPlus11 &&
772*67e74705SXin Li          InDiagNote == diag::note_protected_by_variable_non_pod;
773*67e74705SXin Li }
774*67e74705SXin Li 
775*67e74705SXin Li /// Produce primary diagnostic for an indirect jump statement.
DiagnoseIndirectJumpStmt(Sema & S,IndirectGotoStmt * Jump,LabelDecl * Target,bool & Diagnosed)776*67e74705SXin Li static void DiagnoseIndirectJumpStmt(Sema &S, IndirectGotoStmt *Jump,
777*67e74705SXin Li                                      LabelDecl *Target, bool &Diagnosed) {
778*67e74705SXin Li   if (Diagnosed)
779*67e74705SXin Li     return;
780*67e74705SXin Li   S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
781*67e74705SXin Li   S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
782*67e74705SXin Li   Diagnosed = true;
783*67e74705SXin Li }
784*67e74705SXin Li 
785*67e74705SXin Li /// Produce note diagnostics for a jump into a protected scope.
NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes)786*67e74705SXin Li void JumpScopeChecker::NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes) {
787*67e74705SXin Li   if (CHECK_PERMISSIVE(ToScopes.empty()))
788*67e74705SXin Li     return;
789*67e74705SXin Li   for (unsigned I = 0, E = ToScopes.size(); I != E; ++I)
790*67e74705SXin Li     if (Scopes[ToScopes[I]].InDiag)
791*67e74705SXin Li       S.Diag(Scopes[ToScopes[I]].Loc, Scopes[ToScopes[I]].InDiag);
792*67e74705SXin Li }
793*67e74705SXin Li 
794*67e74705SXin Li /// Diagnose an indirect jump which is known to cross scopes.
DiagnoseIndirectJump(IndirectGotoStmt * Jump,unsigned JumpScope,LabelDecl * Target,unsigned TargetScope)795*67e74705SXin Li void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump,
796*67e74705SXin Li                                             unsigned JumpScope,
797*67e74705SXin Li                                             LabelDecl *Target,
798*67e74705SXin Li                                             unsigned TargetScope) {
799*67e74705SXin Li   if (CHECK_PERMISSIVE(JumpScope == TargetScope))
800*67e74705SXin Li     return;
801*67e74705SXin Li 
802*67e74705SXin Li   unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope);
803*67e74705SXin Li   bool Diagnosed = false;
804*67e74705SXin Li 
805*67e74705SXin Li   // Walk out the scope chain until we reach the common ancestor.
806*67e74705SXin Li   for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope)
807*67e74705SXin Li     if (Scopes[I].OutDiag) {
808*67e74705SXin Li       DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
809*67e74705SXin Li       S.Diag(Scopes[I].Loc, Scopes[I].OutDiag);
810*67e74705SXin Li     }
811*67e74705SXin Li 
812*67e74705SXin Li   SmallVector<unsigned, 10> ToScopesCXX98Compat;
813*67e74705SXin Li 
814*67e74705SXin Li   // Now walk into the scopes containing the label whose address was taken.
815*67e74705SXin Li   for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope)
816*67e74705SXin Li     if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
817*67e74705SXin Li       ToScopesCXX98Compat.push_back(I);
818*67e74705SXin Li     else if (Scopes[I].InDiag) {
819*67e74705SXin Li       DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
820*67e74705SXin Li       S.Diag(Scopes[I].Loc, Scopes[I].InDiag);
821*67e74705SXin Li     }
822*67e74705SXin Li 
823*67e74705SXin Li   // Diagnose this jump if it would be ill-formed in C++98.
824*67e74705SXin Li   if (!Diagnosed && !ToScopesCXX98Compat.empty()) {
825*67e74705SXin Li     S.Diag(Jump->getGotoLoc(),
826*67e74705SXin Li            diag::warn_cxx98_compat_indirect_goto_in_protected_scope);
827*67e74705SXin Li     S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
828*67e74705SXin Li     NoteJumpIntoScopes(ToScopesCXX98Compat);
829*67e74705SXin Li   }
830*67e74705SXin Li }
831*67e74705SXin Li 
832*67e74705SXin Li /// CheckJump - Validate that the specified jump statement is valid: that it is
833*67e74705SXin Li /// jumping within or out of its current scope, not into a deeper one.
CheckJump(Stmt * From,Stmt * To,SourceLocation DiagLoc,unsigned JumpDiagError,unsigned JumpDiagWarning,unsigned JumpDiagCXX98Compat)834*67e74705SXin Li void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
835*67e74705SXin Li                                unsigned JumpDiagError, unsigned JumpDiagWarning,
836*67e74705SXin Li                                  unsigned JumpDiagCXX98Compat) {
837*67e74705SXin Li   if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(From)))
838*67e74705SXin Li     return;
839*67e74705SXin Li   if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(To)))
840*67e74705SXin Li     return;
841*67e74705SXin Li 
842*67e74705SXin Li   unsigned FromScope = LabelAndGotoScopes[From];
843*67e74705SXin Li   unsigned ToScope = LabelAndGotoScopes[To];
844*67e74705SXin Li 
845*67e74705SXin Li   // Common case: exactly the same scope, which is fine.
846*67e74705SXin Li   if (FromScope == ToScope) return;
847*67e74705SXin Li 
848*67e74705SXin Li   // Warn on gotos out of __finally blocks.
849*67e74705SXin Li   if (isa<GotoStmt>(From) || isa<IndirectGotoStmt>(From)) {
850*67e74705SXin Li     // If FromScope > ToScope, FromScope is more nested and the jump goes to a
851*67e74705SXin Li     // less nested scope.  Check if it crosses a __finally along the way.
852*67e74705SXin Li     for (unsigned I = FromScope; I > ToScope; I = Scopes[I].ParentScope) {
853*67e74705SXin Li       if (Scopes[I].InDiag == diag::note_protected_by_seh_finally) {
854*67e74705SXin Li         S.Diag(From->getLocStart(), diag::warn_jump_out_of_seh_finally);
855*67e74705SXin Li         break;
856*67e74705SXin Li       }
857*67e74705SXin Li     }
858*67e74705SXin Li   }
859*67e74705SXin Li 
860*67e74705SXin Li   unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope);
861*67e74705SXin Li 
862*67e74705SXin Li   // It's okay to jump out from a nested scope.
863*67e74705SXin Li   if (CommonScope == ToScope) return;
864*67e74705SXin Li 
865*67e74705SXin Li   // Pull out (and reverse) any scopes we might need to diagnose skipping.
866*67e74705SXin Li   SmallVector<unsigned, 10> ToScopesCXX98Compat;
867*67e74705SXin Li   SmallVector<unsigned, 10> ToScopesError;
868*67e74705SXin Li   SmallVector<unsigned, 10> ToScopesWarning;
869*67e74705SXin Li   for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope) {
870*67e74705SXin Li     if (S.getLangOpts().MSVCCompat && JumpDiagWarning != 0 &&
871*67e74705SXin Li         IsMicrosoftJumpWarning(JumpDiagError, Scopes[I].InDiag))
872*67e74705SXin Li       ToScopesWarning.push_back(I);
873*67e74705SXin Li     else if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
874*67e74705SXin Li       ToScopesCXX98Compat.push_back(I);
875*67e74705SXin Li     else if (Scopes[I].InDiag)
876*67e74705SXin Li       ToScopesError.push_back(I);
877*67e74705SXin Li   }
878*67e74705SXin Li 
879*67e74705SXin Li   // Handle warnings.
880*67e74705SXin Li   if (!ToScopesWarning.empty()) {
881*67e74705SXin Li     S.Diag(DiagLoc, JumpDiagWarning);
882*67e74705SXin Li     NoteJumpIntoScopes(ToScopesWarning);
883*67e74705SXin Li   }
884*67e74705SXin Li 
885*67e74705SXin Li   // Handle errors.
886*67e74705SXin Li   if (!ToScopesError.empty()) {
887*67e74705SXin Li     S.Diag(DiagLoc, JumpDiagError);
888*67e74705SXin Li     NoteJumpIntoScopes(ToScopesError);
889*67e74705SXin Li   }
890*67e74705SXin Li 
891*67e74705SXin Li   // Handle -Wc++98-compat warnings if the jump is well-formed.
892*67e74705SXin Li   if (ToScopesError.empty() && !ToScopesCXX98Compat.empty()) {
893*67e74705SXin Li     S.Diag(DiagLoc, JumpDiagCXX98Compat);
894*67e74705SXin Li     NoteJumpIntoScopes(ToScopesCXX98Compat);
895*67e74705SXin Li   }
896*67e74705SXin Li }
897*67e74705SXin Li 
CheckGotoStmt(GotoStmt * GS)898*67e74705SXin Li void JumpScopeChecker::CheckGotoStmt(GotoStmt *GS) {
899*67e74705SXin Li   if (GS->getLabel()->isMSAsmLabel()) {
900*67e74705SXin Li     S.Diag(GS->getGotoLoc(), diag::err_goto_ms_asm_label)
901*67e74705SXin Li         << GS->getLabel()->getIdentifier();
902*67e74705SXin Li     S.Diag(GS->getLabel()->getLocation(), diag::note_goto_ms_asm_label)
903*67e74705SXin Li         << GS->getLabel()->getIdentifier();
904*67e74705SXin Li   }
905*67e74705SXin Li }
906*67e74705SXin Li 
DiagnoseInvalidJumps(Stmt * Body)907*67e74705SXin Li void Sema::DiagnoseInvalidJumps(Stmt *Body) {
908*67e74705SXin Li   (void)JumpScopeChecker(Body, *this);
909*67e74705SXin Li }
910