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