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