Home | History | Annotate | Download | only in Sema
      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"
     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   /// GotoScope - This is a record that we use to keep track of all of the
     36   /// scopes that are introduced by VLAs and other things that scope jumps like
     37   /// gotos.  This scope tree has nothing to do with the source scope tree,
     38   /// because you can have multiple VLA scopes per compound statement, and most
     39   /// compound statements don't introduce any scopes.
     40   struct GotoScope {
     41     /// ParentScope - The index in ScopeMap of the parent scope.  This is 0 for
     42     /// the parent scope is the function body.
     43     unsigned ParentScope;
     44 
     45     /// InDiag - The note to emit if there is a jump into this scope.
     46     unsigned InDiag;
     47 
     48     /// OutDiag - The note to emit if there is an indirect jump out
     49     /// of this scope.  Direct jumps always clean up their current scope
     50     /// in an orderly way.
     51     unsigned OutDiag;
     52 
     53     /// Loc - Location to emit the diagnostic.
     54     SourceLocation Loc;
     55 
     56     GotoScope(unsigned parentScope, unsigned InDiag, unsigned OutDiag,
     57               SourceLocation L)
     58       : ParentScope(parentScope), InDiag(InDiag), OutDiag(OutDiag), Loc(L) {}
     59   };
     60 
     61   SmallVector<GotoScope, 48> Scopes;
     62   llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
     63   SmallVector<Stmt*, 16> Jumps;
     64 
     65   SmallVector<IndirectGotoStmt*, 4> IndirectJumps;
     66   SmallVector<LabelDecl*, 4> IndirectJumpTargets;
     67 public:
     68   JumpScopeChecker(Stmt *Body, Sema &S);
     69 private:
     70   void BuildScopeInformation(Decl *D, unsigned &ParentScope);
     71   void BuildScopeInformation(VarDecl *D, const BlockDecl *BDecl,
     72                              unsigned &ParentScope);
     73   void BuildScopeInformation(Stmt *S, unsigned &origParentScope);
     74 
     75   void VerifyJumps();
     76   void VerifyIndirectJumps();
     77   void NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes);
     78   void DiagnoseIndirectJump(IndirectGotoStmt *IG, unsigned IGScope,
     79                             LabelDecl *Target, unsigned TargetScope);
     80   void CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
     81                  unsigned JumpDiag, unsigned JumpDiagWarning,
     82                  unsigned JumpDiagCXX98Compat);
     83 
     84   unsigned GetDeepestCommonScope(unsigned A, unsigned B);
     85 };
     86 } // end anonymous namespace
     87 
     88 
     89 JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s) : S(s) {
     90   // Add a scope entry for function scope.
     91   Scopes.push_back(GotoScope(~0U, ~0U, ~0U, SourceLocation()));
     92 
     93   // Build information for the top level compound statement, so that we have a
     94   // defined scope record for every "goto" and label.
     95   unsigned BodyParentScope = 0;
     96   BuildScopeInformation(Body, BodyParentScope);
     97 
     98   // Check that all jumps we saw are kosher.
     99   VerifyJumps();
    100   VerifyIndirectJumps();
    101 }
    102 
    103 /// GetDeepestCommonScope - Finds the innermost scope enclosing the
    104 /// two scopes.
    105 unsigned JumpScopeChecker::GetDeepestCommonScope(unsigned A, unsigned B) {
    106   while (A != B) {
    107     // Inner scopes are created after outer scopes and therefore have
    108     // higher indices.
    109     if (A < B) {
    110       assert(Scopes[B].ParentScope < B);
    111       B = Scopes[B].ParentScope;
    112     } else {
    113       assert(Scopes[A].ParentScope < A);
    114       A = Scopes[A].ParentScope;
    115     }
    116   }
    117   return A;
    118 }
    119 
    120 typedef std::pair<unsigned,unsigned> ScopePair;
    121 
    122 /// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a
    123 /// diagnostic that should be emitted if control goes over it. If not, return 0.
    124 static ScopePair GetDiagForGotoScopeDecl(ASTContext &Context, const Decl *D) {
    125   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
    126     unsigned InDiag = 0;
    127     if (VD->getType()->isVariablyModifiedType())
    128       InDiag = diag::note_protected_by_vla;
    129 
    130     if (VD->hasAttr<BlocksAttr>())
    131       return ScopePair(diag::note_protected_by___block,
    132                        diag::note_exits___block);
    133 
    134     if (VD->hasAttr<CleanupAttr>())
    135       return ScopePair(diag::note_protected_by_cleanup,
    136                        diag::note_exits_cleanup);
    137 
    138     if (Context.getLangOpts().ObjCAutoRefCount && VD->hasLocalStorage()) {
    139       switch (VD->getType().getObjCLifetime()) {
    140       case Qualifiers::OCL_None:
    141       case Qualifiers::OCL_ExplicitNone:
    142       case Qualifiers::OCL_Autoreleasing:
    143         break;
    144 
    145       case Qualifiers::OCL_Strong:
    146       case Qualifiers::OCL_Weak:
    147         return ScopePair(diag::note_protected_by_objc_ownership,
    148                          diag::note_exits_objc_ownership);
    149       }
    150     }
    151 
    152     if (Context.getLangOpts().CPlusPlus && VD->hasLocalStorage()) {
    153       // C++11 [stmt.dcl]p3:
    154       //   A program that jumps from a point where a variable with automatic
    155       //   storage duration is not in scope to a point where it is in scope
    156       //   is ill-formed unless the variable has scalar type, class type with
    157       //   a trivial default constructor and a trivial destructor, a
    158       //   cv-qualified version of one of these types, or an array of one of
    159       //   the preceding types and is declared without an initializer.
    160 
    161       // C++03 [stmt.dcl.p3:
    162       //   A program that jumps from a point where a local variable
    163       //   with automatic storage duration is not in scope to a point
    164       //   where it is in scope is ill-formed unless the variable has
    165       //   POD type and is declared without an initializer.
    166 
    167       const Expr *Init = VD->getInit();
    168       if (!Init)
    169         return ScopePair(InDiag, 0);
    170 
    171       const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Init);
    172       if (EWC)
    173         Init = EWC->getSubExpr();
    174 
    175       const MaterializeTemporaryExpr *M = NULL;
    176       Init = Init->findMaterializedTemporary(M);
    177 
    178       SmallVector<const Expr *, 2> CommaLHSs;
    179       SmallVector<SubobjectAdjustment, 2> Adjustments;
    180       Init = Init->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
    181 
    182       QualType QT = Init->getType();
    183       if (QT.isNull())
    184         return ScopePair(diag::note_protected_by_variable_init, 0);
    185 
    186       const Type *T = QT.getTypePtr();
    187       if (T->isArrayType())
    188         T = T->getBaseElementTypeUnsafe();
    189 
    190       const CXXRecordDecl *Record = T->getAsCXXRecordDecl();
    191       if (!Record)
    192         return ScopePair(diag::note_protected_by_variable_init, 0);
    193 
    194       // If we need to call a non trivial destructor for this variable,
    195       // record an out diagnostic.
    196       unsigned OutDiag = 0;
    197       if (!Init->isGLValue() && !Record->hasTrivialDestructor())
    198         OutDiag = diag::note_exits_dtor;
    199 
    200       if (const CXXConstructExpr *cce = dyn_cast<CXXConstructExpr>(Init)) {
    201         const CXXConstructorDecl *ctor = cce->getConstructor();
    202         // For a variable declared without an initializer, we will have
    203         // call-style initialization and the initializer will be the
    204         // CXXConstructExpr with no intervening nodes.
    205         if (ctor->isTrivial() && ctor->isDefaultConstructor() &&
    206             VD->getInit() == Init && VD->getInitStyle() == VarDecl::CallInit) {
    207           if (OutDiag)
    208             InDiag = diag::note_protected_by_variable_nontriv_destructor;
    209           else if (!Record->isPOD())
    210             InDiag = diag::note_protected_by_variable_non_pod;
    211           return ScopePair(InDiag, OutDiag);
    212         }
    213       }
    214 
    215       return ScopePair(diag::note_protected_by_variable_init, OutDiag);
    216     }
    217 
    218     return ScopePair(InDiag, 0);
    219   }
    220 
    221   if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
    222     if (TD->getUnderlyingType()->isVariablyModifiedType())
    223       return ScopePair(diag::note_protected_by_vla_typedef, 0);
    224   }
    225 
    226   if (const TypeAliasDecl *TD = dyn_cast<TypeAliasDecl>(D)) {
    227     if (TD->getUnderlyingType()->isVariablyModifiedType())
    228       return ScopePair(diag::note_protected_by_vla_type_alias, 0);
    229   }
    230 
    231   return ScopePair(0U, 0U);
    232 }
    233 
    234 /// \brief Build scope information for a declaration that is part of a DeclStmt.
    235 void 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.Context, D);
    238   if (Diags.first || Diags.second) {
    239     Scopes.push_back(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>(D))
    247     if (Expr *Init = VD->getInit())
    248       BuildScopeInformation(Init, ParentScope);
    249 }
    250 
    251 /// \brief Build scope information for a captured block literal variables.
    252 void 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_none:
    277         llvm_unreachable("non-lifetime captured variable");
    278     }
    279     SourceLocation Loc = D->getLocation();
    280     if (Loc.isInvalid())
    281       Loc = BDecl->getLocation();
    282     Scopes.push_back(GotoScope(ParentScope,
    283                                Diags.first, Diags.second, Loc));
    284     ParentScope = Scopes.size()-1;
    285   }
    286 }
    287 
    288 /// BuildScopeInformation - The statements from CI to CE are known to form a
    289 /// coherent VLA scope with a specified parent node.  Walk through the
    290 /// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
    291 /// walking the AST as needed.
    292 void JumpScopeChecker::BuildScopeInformation(Stmt *S, unsigned &origParentScope) {
    293   // If this is a statement, rather than an expression, scopes within it don't
    294   // propagate out into the enclosing scope.  Otherwise we have to worry
    295   // about block literals, which have the lifetime of their enclosing statement.
    296   unsigned independentParentScope = origParentScope;
    297   unsigned &ParentScope = ((isa<Expr>(S) && !isa<StmtExpr>(S))
    298                             ? origParentScope : independentParentScope);
    299 
    300   bool SkipFirstSubStmt = false;
    301 
    302   // If we found a label, remember that it is in ParentScope scope.
    303   switch (S->getStmtClass()) {
    304   case Stmt::AddrLabelExprClass:
    305     IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel());
    306     break;
    307 
    308   case Stmt::IndirectGotoStmtClass:
    309     // "goto *&&lbl;" is a special case which we treat as equivalent
    310     // to a normal goto.  In addition, we don't calculate scope in the
    311     // operand (to avoid recording the address-of-label use), which
    312     // works only because of the restricted set of expressions which
    313     // we detect as constant targets.
    314     if (cast<IndirectGotoStmt>(S)->getConstantTarget()) {
    315       LabelAndGotoScopes[S] = ParentScope;
    316       Jumps.push_back(S);
    317       return;
    318     }
    319 
    320     LabelAndGotoScopes[S] = ParentScope;
    321     IndirectJumps.push_back(cast<IndirectGotoStmt>(S));
    322     break;
    323 
    324   case Stmt::SwitchStmtClass:
    325     // Evaluate the condition variable before entering the scope of the switch
    326     // statement.
    327     if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) {
    328       BuildScopeInformation(Var, ParentScope);
    329       SkipFirstSubStmt = true;
    330     }
    331     // Fall through
    332 
    333   case Stmt::GotoStmtClass:
    334     // Remember both what scope a goto is in as well as the fact that we have
    335     // it.  This makes the second scan not have to walk the AST again.
    336     LabelAndGotoScopes[S] = ParentScope;
    337     Jumps.push_back(S);
    338     break;
    339 
    340   case Stmt::CXXTryStmtClass: {
    341     CXXTryStmt *TS = cast<CXXTryStmt>(S);
    342     unsigned newParentScope;
    343     Scopes.push_back(GotoScope(ParentScope,
    344                                diag::note_protected_by_cxx_try,
    345                                diag::note_exits_cxx_try,
    346                                TS->getSourceRange().getBegin()));
    347     if (Stmt *TryBlock = TS->getTryBlock())
    348       BuildScopeInformation(TryBlock, (newParentScope = Scopes.size()-1));
    349 
    350     // Jump from the catch into the try is not allowed either.
    351     for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) {
    352       CXXCatchStmt *CS = TS->getHandler(I);
    353       Scopes.push_back(GotoScope(ParentScope,
    354                                  diag::note_protected_by_cxx_catch,
    355                                  diag::note_exits_cxx_catch,
    356                                  CS->getSourceRange().getBegin()));
    357       BuildScopeInformation(CS->getHandlerBlock(),
    358                             (newParentScope = Scopes.size()-1));
    359     }
    360     return;
    361   }
    362 
    363   default:
    364     break;
    365   }
    366 
    367   for (Stmt::child_range CI = S->children(); CI; ++CI) {
    368     if (SkipFirstSubStmt) {
    369       SkipFirstSubStmt = false;
    370       continue;
    371     }
    372 
    373     Stmt *SubStmt = *CI;
    374     if (SubStmt == 0) continue;
    375 
    376     // Cases, labels, and defaults aren't "scope parents".  It's also
    377     // important to handle these iteratively instead of recursively in
    378     // order to avoid blowing out the stack.
    379     while (true) {
    380       Stmt *Next;
    381       if (CaseStmt *CS = dyn_cast<CaseStmt>(SubStmt))
    382         Next = CS->getSubStmt();
    383       else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SubStmt))
    384         Next = DS->getSubStmt();
    385       else if (LabelStmt *LS = dyn_cast<LabelStmt>(SubStmt))
    386         Next = LS->getSubStmt();
    387       else
    388         break;
    389 
    390       LabelAndGotoScopes[SubStmt] = ParentScope;
    391       SubStmt = Next;
    392     }
    393 
    394     // If this is a declstmt with a VLA definition, it defines a scope from here
    395     // to the end of the containing context.
    396     if (DeclStmt *DS = dyn_cast<DeclStmt>(SubStmt)) {
    397       // The decl statement creates a scope if any of the decls in it are VLAs
    398       // or have the cleanup attribute.
    399       for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
    400            I != E; ++I)
    401         BuildScopeInformation(*I, ParentScope);
    402       continue;
    403     }
    404     // Disallow jumps into any part of an @try statement by pushing a scope and
    405     // walking all sub-stmts in that scope.
    406     if (ObjCAtTryStmt *AT = dyn_cast<ObjCAtTryStmt>(SubStmt)) {
    407       unsigned newParentScope;
    408       // Recursively walk the AST for the @try part.
    409       Scopes.push_back(GotoScope(ParentScope,
    410                                  diag::note_protected_by_objc_try,
    411                                  diag::note_exits_objc_try,
    412                                  AT->getAtTryLoc()));
    413       if (Stmt *TryPart = AT->getTryBody())
    414         BuildScopeInformation(TryPart, (newParentScope = Scopes.size()-1));
    415 
    416       // Jump from the catch to the finally or try is not valid.
    417       for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) {
    418         ObjCAtCatchStmt *AC = AT->getCatchStmt(I);
    419         Scopes.push_back(GotoScope(ParentScope,
    420                                    diag::note_protected_by_objc_catch,
    421                                    diag::note_exits_objc_catch,
    422                                    AC->getAtCatchLoc()));
    423         // @catches are nested and it isn't
    424         BuildScopeInformation(AC->getCatchBody(),
    425                               (newParentScope = Scopes.size()-1));
    426       }
    427 
    428       // Jump from the finally to the try or catch is not valid.
    429       if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
    430         Scopes.push_back(GotoScope(ParentScope,
    431                                    diag::note_protected_by_objc_finally,
    432                                    diag::note_exits_objc_finally,
    433                                    AF->getAtFinallyLoc()));
    434         BuildScopeInformation(AF, (newParentScope = Scopes.size()-1));
    435       }
    436 
    437       continue;
    438     }
    439 
    440     unsigned newParentScope;
    441     // Disallow jumps into the protected statement of an @synchronized, but
    442     // allow jumps into the object expression it protects.
    443     if (ObjCAtSynchronizedStmt *AS = dyn_cast<ObjCAtSynchronizedStmt>(SubStmt)){
    444       // Recursively walk the AST for the @synchronized object expr, it is
    445       // evaluated in the normal scope.
    446       BuildScopeInformation(AS->getSynchExpr(), ParentScope);
    447 
    448       // Recursively walk the AST for the @synchronized part, protected by a new
    449       // scope.
    450       Scopes.push_back(GotoScope(ParentScope,
    451                                  diag::note_protected_by_objc_synchronized,
    452                                  diag::note_exits_objc_synchronized,
    453                                  AS->getAtSynchronizedLoc()));
    454       BuildScopeInformation(AS->getSynchBody(),
    455                             (newParentScope = Scopes.size()-1));
    456       continue;
    457     }
    458 
    459     // Disallow jumps into the protected statement of an @autoreleasepool.
    460     if (ObjCAutoreleasePoolStmt *AS = dyn_cast<ObjCAutoreleasePoolStmt>(SubStmt)){
    461       // Recursively walk the AST for the @autoreleasepool part, protected by a new
    462       // scope.
    463       Scopes.push_back(GotoScope(ParentScope,
    464                                  diag::note_protected_by_objc_autoreleasepool,
    465                                  diag::note_exits_objc_autoreleasepool,
    466                                  AS->getAtLoc()));
    467       BuildScopeInformation(AS->getSubStmt(), (newParentScope = Scopes.size()-1));
    468       continue;
    469     }
    470 
    471     // Disallow jumps past full-expressions that use blocks with
    472     // non-trivial cleanups of their captures.  This is theoretically
    473     // implementable but a lot of work which we haven't felt up to doing.
    474     if (ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(SubStmt)) {
    475       for (unsigned i = 0, e = EWC->getNumObjects(); i != e; ++i) {
    476         const BlockDecl *BDecl = EWC->getObject(i);
    477         for (BlockDecl::capture_const_iterator ci = BDecl->capture_begin(),
    478              ce = BDecl->capture_end(); ci != ce; ++ci) {
    479           VarDecl *variable = ci->getVariable();
    480           BuildScopeInformation(variable, BDecl, ParentScope);
    481         }
    482       }
    483     }
    484 
    485     // Recursively walk the AST.
    486     BuildScopeInformation(SubStmt, ParentScope);
    487   }
    488 }
    489 
    490 /// VerifyJumps - Verify each element of the Jumps array to see if they are
    491 /// valid, emitting diagnostics if not.
    492 void JumpScopeChecker::VerifyJumps() {
    493   while (!Jumps.empty()) {
    494     Stmt *Jump = Jumps.pop_back_val();
    495 
    496     // With a goto,
    497     if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
    498       CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(),
    499                 diag::err_goto_into_protected_scope,
    500                 diag::warn_goto_into_protected_scope,
    501                 diag::warn_cxx98_compat_goto_into_protected_scope);
    502       continue;
    503     }
    504 
    505     // We only get indirect gotos here when they have a constant target.
    506     if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) {
    507       LabelDecl *Target = IGS->getConstantTarget();
    508       CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(),
    509                 diag::err_goto_into_protected_scope,
    510                 diag::warn_goto_into_protected_scope,
    511                 diag::warn_cxx98_compat_goto_into_protected_scope);
    512       continue;
    513     }
    514 
    515     SwitchStmt *SS = cast<SwitchStmt>(Jump);
    516     for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
    517          SC = SC->getNextSwitchCase()) {
    518       assert(LabelAndGotoScopes.count(SC) && "Case not visited?");
    519       SourceLocation Loc;
    520       if (CaseStmt *CS = dyn_cast<CaseStmt>(SC))
    521         Loc = CS->getLocStart();
    522       else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC))
    523         Loc = DS->getLocStart();
    524       else
    525         Loc = SC->getLocStart();
    526       CheckJump(SS, SC, Loc, diag::err_switch_into_protected_scope, 0,
    527                 diag::warn_cxx98_compat_switch_into_protected_scope);
    528     }
    529   }
    530 }
    531 
    532 /// VerifyIndirectJumps - Verify whether any possible indirect jump
    533 /// might cross a protection boundary.  Unlike direct jumps, indirect
    534 /// jumps count cleanups as protection boundaries:  since there's no
    535 /// way to know where the jump is going, we can't implicitly run the
    536 /// right cleanups the way we can with direct jumps.
    537 ///
    538 /// Thus, an indirect jump is "trivial" if it bypasses no
    539 /// initializations and no teardowns.  More formally, an indirect jump
    540 /// from A to B is trivial if the path out from A to DCA(A,B) is
    541 /// trivial and the path in from DCA(A,B) to B is trivial, where
    542 /// DCA(A,B) is the deepest common ancestor of A and B.
    543 /// Jump-triviality is transitive but asymmetric.
    544 ///
    545 /// A path in is trivial if none of the entered scopes have an InDiag.
    546 /// A path out is trivial is none of the exited scopes have an OutDiag.
    547 ///
    548 /// Under these definitions, this function checks that the indirect
    549 /// jump between A and B is trivial for every indirect goto statement A
    550 /// and every label B whose address was taken in the function.
    551 void JumpScopeChecker::VerifyIndirectJumps() {
    552   if (IndirectJumps.empty()) return;
    553 
    554   // If there aren't any address-of-label expressions in this function,
    555   // complain about the first indirect goto.
    556   if (IndirectJumpTargets.empty()) {
    557     S.Diag(IndirectJumps[0]->getGotoLoc(),
    558            diag::err_indirect_goto_without_addrlabel);
    559     return;
    560   }
    561 
    562   // Collect a single representative of every scope containing an
    563   // indirect goto.  For most code bases, this substantially cuts
    564   // down on the number of jump sites we'll have to consider later.
    565   typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope;
    566   SmallVector<JumpScope, 32> JumpScopes;
    567   {
    568     llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap;
    569     for (SmallVectorImpl<IndirectGotoStmt*>::iterator
    570            I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) {
    571       IndirectGotoStmt *IG = *I;
    572       assert(LabelAndGotoScopes.count(IG) &&
    573              "indirect jump didn't get added to scopes?");
    574       unsigned IGScope = LabelAndGotoScopes[IG];
    575       IndirectGotoStmt *&Entry = JumpScopesMap[IGScope];
    576       if (!Entry) Entry = IG;
    577     }
    578     JumpScopes.reserve(JumpScopesMap.size());
    579     for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator
    580            I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I)
    581       JumpScopes.push_back(*I);
    582   }
    583 
    584   // Collect a single representative of every scope containing a
    585   // label whose address was taken somewhere in the function.
    586   // For most code bases, there will be only one such scope.
    587   llvm::DenseMap<unsigned, LabelDecl*> TargetScopes;
    588   for (SmallVectorImpl<LabelDecl*>::iterator
    589          I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end();
    590        I != E; ++I) {
    591     LabelDecl *TheLabel = *I;
    592     assert(LabelAndGotoScopes.count(TheLabel->getStmt()) &&
    593            "Referenced label didn't get added to scopes?");
    594     unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()];
    595     LabelDecl *&Target = TargetScopes[LabelScope];
    596     if (!Target) Target = TheLabel;
    597   }
    598 
    599   // For each target scope, make sure it's trivially reachable from
    600   // every scope containing a jump site.
    601   //
    602   // A path between scopes always consists of exitting zero or more
    603   // scopes, then entering zero or more scopes.  We build a set of
    604   // of scopes S from which the target scope can be trivially
    605   // entered, then verify that every jump scope can be trivially
    606   // exitted to reach a scope in S.
    607   llvm::BitVector Reachable(Scopes.size(), false);
    608   for (llvm::DenseMap<unsigned,LabelDecl*>::iterator
    609          TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) {
    610     unsigned TargetScope = TI->first;
    611     LabelDecl *TargetLabel = TI->second;
    612 
    613     Reachable.reset();
    614 
    615     // Mark all the enclosing scopes from which you can safely jump
    616     // into the target scope.  'Min' will end up being the index of
    617     // the shallowest such scope.
    618     unsigned Min = TargetScope;
    619     while (true) {
    620       Reachable.set(Min);
    621 
    622       // Don't go beyond the outermost scope.
    623       if (Min == 0) break;
    624 
    625       // Stop if we can't trivially enter the current scope.
    626       if (Scopes[Min].InDiag) break;
    627 
    628       Min = Scopes[Min].ParentScope;
    629     }
    630 
    631     // Walk through all the jump sites, checking that they can trivially
    632     // reach this label scope.
    633     for (SmallVectorImpl<JumpScope>::iterator
    634            I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) {
    635       unsigned Scope = I->first;
    636 
    637       // Walk out the "scope chain" for this scope, looking for a scope
    638       // we've marked reachable.  For well-formed code this amortizes
    639       // to O(JumpScopes.size() / Scopes.size()):  we only iterate
    640       // when we see something unmarked, and in well-formed code we
    641       // mark everything we iterate past.
    642       bool IsReachable = false;
    643       while (true) {
    644         if (Reachable.test(Scope)) {
    645           // If we find something reachable, mark all the scopes we just
    646           // walked through as reachable.
    647           for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope)
    648             Reachable.set(S);
    649           IsReachable = true;
    650           break;
    651         }
    652 
    653         // Don't walk out if we've reached the top-level scope or we've
    654         // gotten shallower than the shallowest reachable scope.
    655         if (Scope == 0 || Scope < Min) break;
    656 
    657         // Don't walk out through an out-diagnostic.
    658         if (Scopes[Scope].OutDiag) break;
    659 
    660         Scope = Scopes[Scope].ParentScope;
    661       }
    662 
    663       // Only diagnose if we didn't find something.
    664       if (IsReachable) continue;
    665 
    666       DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope);
    667     }
    668   }
    669 }
    670 
    671 /// Return true if a particular error+note combination must be downgraded to a
    672 /// warning in Microsoft mode.
    673 static bool IsMicrosoftJumpWarning(unsigned JumpDiag, unsigned InDiagNote) {
    674   return (JumpDiag == diag::err_goto_into_protected_scope &&
    675          (InDiagNote == diag::note_protected_by_variable_init ||
    676           InDiagNote == diag::note_protected_by_variable_nontriv_destructor));
    677 }
    678 
    679 /// Return true if a particular note should be downgraded to a compatibility
    680 /// warning in C++11 mode.
    681 static bool IsCXX98CompatWarning(Sema &S, unsigned InDiagNote) {
    682   return S.getLangOpts().CPlusPlus11 &&
    683          InDiagNote == diag::note_protected_by_variable_non_pod;
    684 }
    685 
    686 /// Produce primary diagnostic for an indirect jump statement.
    687 static void DiagnoseIndirectJumpStmt(Sema &S, IndirectGotoStmt *Jump,
    688                                      LabelDecl *Target, bool &Diagnosed) {
    689   if (Diagnosed)
    690     return;
    691   S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
    692   S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
    693   Diagnosed = true;
    694 }
    695 
    696 /// Produce note diagnostics for a jump into a protected scope.
    697 void JumpScopeChecker::NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes) {
    698   assert(!ToScopes.empty());
    699   for (unsigned I = 0, E = ToScopes.size(); I != E; ++I)
    700     if (Scopes[ToScopes[I]].InDiag)
    701       S.Diag(Scopes[ToScopes[I]].Loc, Scopes[ToScopes[I]].InDiag);
    702 }
    703 
    704 /// Diagnose an indirect jump which is known to cross scopes.
    705 void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump,
    706                                             unsigned JumpScope,
    707                                             LabelDecl *Target,
    708                                             unsigned TargetScope) {
    709   assert(JumpScope != TargetScope);
    710 
    711   unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope);
    712   bool Diagnosed = false;
    713 
    714   // Walk out the scope chain until we reach the common ancestor.
    715   for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope)
    716     if (Scopes[I].OutDiag) {
    717       DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
    718       S.Diag(Scopes[I].Loc, Scopes[I].OutDiag);
    719     }
    720 
    721   SmallVector<unsigned, 10> ToScopesCXX98Compat;
    722 
    723   // Now walk into the scopes containing the label whose address was taken.
    724   for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope)
    725     if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
    726       ToScopesCXX98Compat.push_back(I);
    727     else if (Scopes[I].InDiag) {
    728       DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
    729       S.Diag(Scopes[I].Loc, Scopes[I].InDiag);
    730     }
    731 
    732   // Diagnose this jump if it would be ill-formed in C++98.
    733   if (!Diagnosed && !ToScopesCXX98Compat.empty()) {
    734     S.Diag(Jump->getGotoLoc(),
    735            diag::warn_cxx98_compat_indirect_goto_in_protected_scope);
    736     S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
    737     NoteJumpIntoScopes(ToScopesCXX98Compat);
    738   }
    739 }
    740 
    741 /// CheckJump - Validate that the specified jump statement is valid: that it is
    742 /// jumping within or out of its current scope, not into a deeper one.
    743 void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
    744                                unsigned JumpDiagError, unsigned JumpDiagWarning,
    745                                  unsigned JumpDiagCXX98Compat) {
    746   assert(LabelAndGotoScopes.count(From) && "Jump didn't get added to scopes?");
    747   unsigned FromScope = LabelAndGotoScopes[From];
    748 
    749   assert(LabelAndGotoScopes.count(To) && "Jump didn't get added to scopes?");
    750   unsigned ToScope = LabelAndGotoScopes[To];
    751 
    752   // Common case: exactly the same scope, which is fine.
    753   if (FromScope == ToScope) return;
    754 
    755   unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope);
    756 
    757   // It's okay to jump out from a nested scope.
    758   if (CommonScope == ToScope) return;
    759 
    760   // Pull out (and reverse) any scopes we might need to diagnose skipping.
    761   SmallVector<unsigned, 10> ToScopesCXX98Compat;
    762   SmallVector<unsigned, 10> ToScopesError;
    763   SmallVector<unsigned, 10> ToScopesWarning;
    764   for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope) {
    765     if (S.getLangOpts().MicrosoftMode && JumpDiagWarning != 0 &&
    766         IsMicrosoftJumpWarning(JumpDiagError, Scopes[I].InDiag))
    767       ToScopesWarning.push_back(I);
    768     else if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
    769       ToScopesCXX98Compat.push_back(I);
    770     else if (Scopes[I].InDiag)
    771       ToScopesError.push_back(I);
    772   }
    773 
    774   // Handle warnings.
    775   if (!ToScopesWarning.empty()) {
    776     S.Diag(DiagLoc, JumpDiagWarning);
    777     NoteJumpIntoScopes(ToScopesWarning);
    778   }
    779 
    780   // Handle errors.
    781   if (!ToScopesError.empty()) {
    782     S.Diag(DiagLoc, JumpDiagError);
    783     NoteJumpIntoScopes(ToScopesError);
    784   }
    785 
    786   // Handle -Wc++98-compat warnings if the jump is well-formed.
    787   if (ToScopesError.empty() && !ToScopesCXX98Compat.empty()) {
    788     S.Diag(DiagLoc, JumpDiagCXX98Compat);
    789     NoteJumpIntoScopes(ToScopesCXX98Compat);
    790   }
    791 }
    792 
    793 void Sema::DiagnoseInvalidJumps(Stmt *Body) {
    794   (void)JumpScopeChecker(Body, *this);
    795 }
    796