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