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