clang API Documentation

JumpDiagnostics.cpp
Go to the documentation of this file.
00001 //===--- JumpDiagnostics.cpp - Protected scope jump analysis ------*- C++ -*-=//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the JumpScopeChecker class, which is used to diagnose
00011 // jumps that enter a protected scope in an invalid way.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "clang/Sema/SemaInternal.h"
00016 #include "clang/AST/DeclCXX.h"
00017 #include "clang/AST/Expr.h"
00018 #include "clang/AST/ExprCXX.h"
00019 #include "clang/AST/StmtCXX.h"
00020 #include "clang/AST/StmtObjC.h"
00021 #include "llvm/ADT/BitVector.h"
00022 using namespace clang;
00023 
00024 namespace {
00025 
00026 /// JumpScopeChecker - This object is used by Sema to diagnose invalid jumps
00027 /// into VLA and other protected scopes.  For example, this rejects:
00028 ///    goto L;
00029 ///    int a[n];
00030 ///  L:
00031 ///
00032 class JumpScopeChecker {
00033   Sema &S;
00034 
00035   /// Permissive - True when recovering from errors, in which case precautions
00036   /// are taken to handle incomplete scope information.
00037   const bool Permissive;
00038 
00039   /// GotoScope - This is a record that we use to keep track of all of the
00040   /// scopes that are introduced by VLAs and other things that scope jumps like
00041   /// gotos.  This scope tree has nothing to do with the source scope tree,
00042   /// because you can have multiple VLA scopes per compound statement, and most
00043   /// compound statements don't introduce any scopes.
00044   struct GotoScope {
00045     /// ParentScope - The index in ScopeMap of the parent scope.  This is 0 for
00046     /// the parent scope is the function body.
00047     unsigned ParentScope;
00048 
00049     /// InDiag - The note to emit if there is a jump into this scope.
00050     unsigned InDiag;
00051 
00052     /// OutDiag - The note to emit if there is an indirect jump out
00053     /// of this scope.  Direct jumps always clean up their current scope
00054     /// in an orderly way.
00055     unsigned OutDiag;
00056 
00057     /// Loc - Location to emit the diagnostic.
00058     SourceLocation Loc;
00059 
00060     GotoScope(unsigned parentScope, unsigned InDiag, unsigned OutDiag,
00061               SourceLocation L)
00062       : ParentScope(parentScope), InDiag(InDiag), OutDiag(OutDiag), Loc(L) {}
00063   };
00064 
00065   SmallVector<GotoScope, 48> Scopes;
00066   llvm::DenseMap<Stmt*, unsigned> LabelAndGotoScopes;
00067   SmallVector<Stmt*, 16> Jumps;
00068 
00069   SmallVector<IndirectGotoStmt*, 4> IndirectJumps;
00070   SmallVector<LabelDecl*, 4> IndirectJumpTargets;
00071 public:
00072   JumpScopeChecker(Stmt *Body, Sema &S);
00073 private:
00074   void BuildScopeInformation(Decl *D, unsigned &ParentScope);
00075   void BuildScopeInformation(VarDecl *D, const BlockDecl *BDecl, 
00076                              unsigned &ParentScope);
00077   void BuildScopeInformation(Stmt *S, unsigned &origParentScope);
00078   
00079   void VerifyJumps();
00080   void VerifyIndirectJumps();
00081   void NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes);
00082   void DiagnoseIndirectJump(IndirectGotoStmt *IG, unsigned IGScope,
00083                             LabelDecl *Target, unsigned TargetScope);
00084   void CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
00085                  unsigned JumpDiag, unsigned JumpDiagWarning,
00086                  unsigned JumpDiagCXX98Compat);
00087   void CheckGotoStmt(GotoStmt *GS);
00088 
00089   unsigned GetDeepestCommonScope(unsigned A, unsigned B);
00090 };
00091 } // end anonymous namespace
00092 
00093 #define CHECK_PERMISSIVE(x) (assert(Permissive || !(x)), (Permissive && (x)))
00094 
00095 JumpScopeChecker::JumpScopeChecker(Stmt *Body, Sema &s)
00096     : S(s), Permissive(s.hasAnyUnrecoverableErrorsInThisFunction()) {
00097   // Add a scope entry for function scope.
00098   Scopes.push_back(GotoScope(~0U, ~0U, ~0U, SourceLocation()));
00099 
00100   // Build information for the top level compound statement, so that we have a
00101   // defined scope record for every "goto" and label.
00102   unsigned BodyParentScope = 0;
00103   BuildScopeInformation(Body, BodyParentScope);
00104 
00105   // Check that all jumps we saw are kosher.
00106   VerifyJumps();
00107   VerifyIndirectJumps();
00108 }
00109 
00110 /// GetDeepestCommonScope - Finds the innermost scope enclosing the
00111 /// two scopes.
00112 unsigned JumpScopeChecker::GetDeepestCommonScope(unsigned A, unsigned B) {
00113   while (A != B) {
00114     // Inner scopes are created after outer scopes and therefore have
00115     // higher indices.
00116     if (A < B) {
00117       assert(Scopes[B].ParentScope < B);
00118       B = Scopes[B].ParentScope;
00119     } else {
00120       assert(Scopes[A].ParentScope < A);
00121       A = Scopes[A].ParentScope;
00122     }
00123   }
00124   return A;
00125 }
00126 
00127 typedef std::pair<unsigned,unsigned> ScopePair;
00128 
00129 /// GetDiagForGotoScopeDecl - If this decl induces a new goto scope, return a
00130 /// diagnostic that should be emitted if control goes over it. If not, return 0.
00131 static ScopePair GetDiagForGotoScopeDecl(Sema &S, const Decl *D) {
00132   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
00133     unsigned InDiag = 0;
00134     unsigned OutDiag = 0;
00135 
00136     if (VD->getType()->isVariablyModifiedType())
00137       InDiag = diag::note_protected_by_vla;
00138 
00139     if (VD->hasAttr<BlocksAttr>())
00140       return ScopePair(diag::note_protected_by___block,
00141                        diag::note_exits___block);
00142 
00143     if (VD->hasAttr<CleanupAttr>())
00144       return ScopePair(diag::note_protected_by_cleanup,
00145                        diag::note_exits_cleanup);
00146 
00147     if (VD->hasLocalStorage()) {
00148       switch (VD->getType().isDestructedType()) {
00149       case QualType::DK_objc_strong_lifetime:
00150       case QualType::DK_objc_weak_lifetime:
00151         return ScopePair(diag::note_protected_by_objc_ownership,
00152                          diag::note_exits_objc_ownership);
00153 
00154       case QualType::DK_cxx_destructor:
00155         OutDiag = diag::note_exits_dtor;
00156         break;
00157 
00158       case QualType::DK_none:
00159         break;
00160       }
00161     }
00162 
00163     const Expr *Init = VD->getInit();
00164     if (S.Context.getLangOpts().CPlusPlus && VD->hasLocalStorage() && Init) {
00165       // C++11 [stmt.dcl]p3:
00166       //   A program that jumps from a point where a variable with automatic
00167       //   storage duration is not in scope to a point where it is in scope
00168       //   is ill-formed unless the variable has scalar type, class type with
00169       //   a trivial default constructor and a trivial destructor, a 
00170       //   cv-qualified version of one of these types, or an array of one of
00171       //   the preceding types and is declared without an initializer.
00172 
00173       // C++03 [stmt.dcl.p3:
00174       //   A program that jumps from a point where a local variable
00175       //   with automatic storage duration is not in scope to a point
00176       //   where it is in scope is ill-formed unless the variable has
00177       //   POD type and is declared without an initializer.
00178 
00179       InDiag = diag::note_protected_by_variable_init;
00180 
00181       // For a variable of (array of) class type declared without an
00182       // initializer, we will have call-style initialization and the initializer
00183       // will be the CXXConstructExpr with no intervening nodes.
00184       if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
00185         const CXXConstructorDecl *Ctor = CCE->getConstructor();
00186         if (Ctor->isTrivial() && Ctor->isDefaultConstructor() &&
00187             VD->getInitStyle() == VarDecl::CallInit) {
00188           if (OutDiag)
00189             InDiag = diag::note_protected_by_variable_nontriv_destructor;
00190           else if (!Ctor->getParent()->isPOD())
00191             InDiag = diag::note_protected_by_variable_non_pod;
00192           else
00193             InDiag = 0;
00194         }
00195       }
00196     }
00197 
00198     return ScopePair(InDiag, OutDiag);
00199   }
00200 
00201   if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
00202     if (TD->getUnderlyingType()->isVariablyModifiedType())
00203       return ScopePair(isa<TypedefDecl>(TD)
00204                            ? diag::note_protected_by_vla_typedef
00205                            : diag::note_protected_by_vla_type_alias,
00206                        0);
00207   }
00208 
00209   return ScopePair(0U, 0U);
00210 }
00211 
00212 /// \brief Build scope information for a declaration that is part of a DeclStmt.
00213 void JumpScopeChecker::BuildScopeInformation(Decl *D, unsigned &ParentScope) {
00214   // If this decl causes a new scope, push and switch to it.
00215   std::pair<unsigned,unsigned> Diags = GetDiagForGotoScopeDecl(S, D);
00216   if (Diags.first || Diags.second) {
00217     Scopes.push_back(GotoScope(ParentScope, Diags.first, Diags.second,
00218                                D->getLocation()));
00219     ParentScope = Scopes.size()-1;
00220   }
00221   
00222   // If the decl has an initializer, walk it with the potentially new
00223   // scope we just installed.
00224   if (VarDecl *VD = dyn_cast<VarDecl>(D))
00225     if (Expr *Init = VD->getInit())
00226       BuildScopeInformation(Init, ParentScope);
00227 }
00228 
00229 /// \brief Build scope information for a captured block literal variables.
00230 void JumpScopeChecker::BuildScopeInformation(VarDecl *D, 
00231                                              const BlockDecl *BDecl, 
00232                                              unsigned &ParentScope) {
00233   // exclude captured __block variables; there's no destructor
00234   // associated with the block literal for them.
00235   if (D->hasAttr<BlocksAttr>())
00236     return;
00237   QualType T = D->getType();
00238   QualType::DestructionKind destructKind = T.isDestructedType();
00239   if (destructKind != QualType::DK_none) {
00240     std::pair<unsigned,unsigned> Diags;
00241     switch (destructKind) {
00242       case QualType::DK_cxx_destructor:
00243         Diags = ScopePair(diag::note_enters_block_captures_cxx_obj,
00244                           diag::note_exits_block_captures_cxx_obj);
00245         break;
00246       case QualType::DK_objc_strong_lifetime:
00247         Diags = ScopePair(diag::note_enters_block_captures_strong,
00248                           diag::note_exits_block_captures_strong);
00249         break;
00250       case QualType::DK_objc_weak_lifetime:
00251         Diags = ScopePair(diag::note_enters_block_captures_weak,
00252                           diag::note_exits_block_captures_weak);
00253         break;
00254       case QualType::DK_none:
00255         llvm_unreachable("non-lifetime captured variable");
00256     }
00257     SourceLocation Loc = D->getLocation();
00258     if (Loc.isInvalid())
00259       Loc = BDecl->getLocation();
00260     Scopes.push_back(GotoScope(ParentScope, 
00261                                Diags.first, Diags.second, Loc));
00262     ParentScope = Scopes.size()-1;
00263   }
00264 }
00265 
00266 /// BuildScopeInformation - The statements from CI to CE are known to form a
00267 /// coherent VLA scope with a specified parent node.  Walk through the
00268 /// statements, adding any labels or gotos to LabelAndGotoScopes and recursively
00269 /// walking the AST as needed.
00270 void JumpScopeChecker::BuildScopeInformation(Stmt *S, unsigned &origParentScope) {
00271   // If this is a statement, rather than an expression, scopes within it don't
00272   // propagate out into the enclosing scope.  Otherwise we have to worry
00273   // about block literals, which have the lifetime of their enclosing statement.
00274   unsigned independentParentScope = origParentScope;
00275   unsigned &ParentScope = ((isa<Expr>(S) && !isa<StmtExpr>(S)) 
00276                             ? origParentScope : independentParentScope);
00277 
00278   bool SkipFirstSubStmt = false;
00279   
00280   // If we found a label, remember that it is in ParentScope scope.
00281   switch (S->getStmtClass()) {
00282   case Stmt::AddrLabelExprClass:
00283     IndirectJumpTargets.push_back(cast<AddrLabelExpr>(S)->getLabel());
00284     break;
00285 
00286   case Stmt::IndirectGotoStmtClass:
00287     // "goto *&&lbl;" is a special case which we treat as equivalent
00288     // to a normal goto.  In addition, we don't calculate scope in the
00289     // operand (to avoid recording the address-of-label use), which
00290     // works only because of the restricted set of expressions which
00291     // we detect as constant targets.
00292     if (cast<IndirectGotoStmt>(S)->getConstantTarget()) {
00293       LabelAndGotoScopes[S] = ParentScope;
00294       Jumps.push_back(S);
00295       return;
00296     }
00297 
00298     LabelAndGotoScopes[S] = ParentScope;
00299     IndirectJumps.push_back(cast<IndirectGotoStmt>(S));
00300     break;
00301 
00302   case Stmt::SwitchStmtClass:
00303     // Evaluate the condition variable before entering the scope of the switch
00304     // statement.
00305     if (VarDecl *Var = cast<SwitchStmt>(S)->getConditionVariable()) {
00306       BuildScopeInformation(Var, ParentScope);
00307       SkipFirstSubStmt = true;
00308     }
00309     // Fall through
00310       
00311   case Stmt::GotoStmtClass:
00312     // Remember both what scope a goto is in as well as the fact that we have
00313     // it.  This makes the second scan not have to walk the AST again.
00314     LabelAndGotoScopes[S] = ParentScope;
00315     Jumps.push_back(S);
00316     break;
00317 
00318   case Stmt::CXXTryStmtClass: {
00319     CXXTryStmt *TS = cast<CXXTryStmt>(S);
00320     unsigned newParentScope;
00321     Scopes.push_back(GotoScope(ParentScope,
00322                                diag::note_protected_by_cxx_try,
00323                                diag::note_exits_cxx_try,
00324                                TS->getSourceRange().getBegin()));
00325     if (Stmt *TryBlock = TS->getTryBlock())
00326       BuildScopeInformation(TryBlock, (newParentScope = Scopes.size()-1));
00327 
00328     // Jump from the catch into the try is not allowed either.
00329     for (unsigned I = 0, E = TS->getNumHandlers(); I != E; ++I) {
00330       CXXCatchStmt *CS = TS->getHandler(I);
00331       Scopes.push_back(GotoScope(ParentScope,
00332                                  diag::note_protected_by_cxx_catch,
00333                                  diag::note_exits_cxx_catch,
00334                                  CS->getSourceRange().getBegin()));
00335       BuildScopeInformation(CS->getHandlerBlock(), 
00336                             (newParentScope = Scopes.size()-1));
00337     }
00338     return;
00339   }
00340 
00341   default:
00342     break;
00343   }
00344 
00345   for (Stmt::child_range CI = S->children(); CI; ++CI) {
00346     if (SkipFirstSubStmt) {
00347       SkipFirstSubStmt = false;
00348       continue;
00349     }
00350     
00351     Stmt *SubStmt = *CI;
00352     if (!SubStmt) continue;
00353 
00354     // Cases, labels, and defaults aren't "scope parents".  It's also
00355     // important to handle these iteratively instead of recursively in
00356     // order to avoid blowing out the stack.
00357     while (true) {
00358       Stmt *Next;
00359       if (CaseStmt *CS = dyn_cast<CaseStmt>(SubStmt))
00360         Next = CS->getSubStmt();
00361       else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SubStmt))
00362         Next = DS->getSubStmt();
00363       else if (LabelStmt *LS = dyn_cast<LabelStmt>(SubStmt))
00364         Next = LS->getSubStmt();
00365       else
00366         break;
00367 
00368       LabelAndGotoScopes[SubStmt] = ParentScope;
00369       SubStmt = Next;
00370     }
00371 
00372     // If this is a declstmt with a VLA definition, it defines a scope from here
00373     // to the end of the containing context.
00374     if (DeclStmt *DS = dyn_cast<DeclStmt>(SubStmt)) {
00375       // The decl statement creates a scope if any of the decls in it are VLAs
00376       // or have the cleanup attribute.
00377       for (auto *I : DS->decls())
00378         BuildScopeInformation(I, ParentScope);
00379       continue;
00380     }
00381     // Disallow jumps into any part of an @try statement by pushing a scope and
00382     // walking all sub-stmts in that scope.
00383     if (ObjCAtTryStmt *AT = dyn_cast<ObjCAtTryStmt>(SubStmt)) {
00384       unsigned newParentScope;
00385       // Recursively walk the AST for the @try part.
00386       Scopes.push_back(GotoScope(ParentScope,
00387                                  diag::note_protected_by_objc_try,
00388                                  diag::note_exits_objc_try,
00389                                  AT->getAtTryLoc()));
00390       if (Stmt *TryPart = AT->getTryBody())
00391         BuildScopeInformation(TryPart, (newParentScope = Scopes.size()-1));
00392 
00393       // Jump from the catch to the finally or try is not valid.
00394       for (unsigned I = 0, N = AT->getNumCatchStmts(); I != N; ++I) {
00395         ObjCAtCatchStmt *AC = AT->getCatchStmt(I);
00396         Scopes.push_back(GotoScope(ParentScope,
00397                                    diag::note_protected_by_objc_catch,
00398                                    diag::note_exits_objc_catch,
00399                                    AC->getAtCatchLoc()));
00400         // @catches are nested and it isn't
00401         BuildScopeInformation(AC->getCatchBody(), 
00402                               (newParentScope = Scopes.size()-1));
00403       }
00404 
00405       // Jump from the finally to the try or catch is not valid.
00406       if (ObjCAtFinallyStmt *AF = AT->getFinallyStmt()) {
00407         Scopes.push_back(GotoScope(ParentScope,
00408                                    diag::note_protected_by_objc_finally,
00409                                    diag::note_exits_objc_finally,
00410                                    AF->getAtFinallyLoc()));
00411         BuildScopeInformation(AF, (newParentScope = Scopes.size()-1));
00412       }
00413 
00414       continue;
00415     }
00416     
00417     unsigned newParentScope;
00418     // Disallow jumps into the protected statement of an @synchronized, but
00419     // allow jumps into the object expression it protects.
00420     if (ObjCAtSynchronizedStmt *AS = dyn_cast<ObjCAtSynchronizedStmt>(SubStmt)){
00421       // Recursively walk the AST for the @synchronized object expr, it is
00422       // evaluated in the normal scope.
00423       BuildScopeInformation(AS->getSynchExpr(), ParentScope);
00424 
00425       // Recursively walk the AST for the @synchronized part, protected by a new
00426       // scope.
00427       Scopes.push_back(GotoScope(ParentScope,
00428                                  diag::note_protected_by_objc_synchronized,
00429                                  diag::note_exits_objc_synchronized,
00430                                  AS->getAtSynchronizedLoc()));
00431       BuildScopeInformation(AS->getSynchBody(), 
00432                             (newParentScope = Scopes.size()-1));
00433       continue;
00434     }
00435 
00436     // Disallow jumps into the protected statement of an @autoreleasepool.
00437     if (ObjCAutoreleasePoolStmt *AS = dyn_cast<ObjCAutoreleasePoolStmt>(SubStmt)){
00438       // Recursively walk the AST for the @autoreleasepool part, protected by a new
00439       // scope.
00440       Scopes.push_back(GotoScope(ParentScope,
00441                                  diag::note_protected_by_objc_autoreleasepool,
00442                                  diag::note_exits_objc_autoreleasepool,
00443                                  AS->getAtLoc()));
00444       BuildScopeInformation(AS->getSubStmt(), (newParentScope = Scopes.size()-1));
00445       continue;
00446     }
00447 
00448     // Disallow jumps past full-expressions that use blocks with
00449     // non-trivial cleanups of their captures.  This is theoretically
00450     // implementable but a lot of work which we haven't felt up to doing.
00451     if (ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(SubStmt)) {
00452       for (unsigned i = 0, e = EWC->getNumObjects(); i != e; ++i) {
00453         const BlockDecl *BDecl = EWC->getObject(i);
00454         for (const auto &CI : BDecl->captures()) {
00455           VarDecl *variable = CI.getVariable();
00456           BuildScopeInformation(variable, BDecl, ParentScope);
00457         }
00458       }
00459     }
00460 
00461     // Disallow jumps out of scopes containing temporaries lifetime-extended to
00462     // automatic storage duration.
00463     if (MaterializeTemporaryExpr *MTE =
00464             dyn_cast<MaterializeTemporaryExpr>(SubStmt)) {
00465       if (MTE->getStorageDuration() == SD_Automatic) {
00466         SmallVector<const Expr *, 4> CommaLHS;
00467         SmallVector<SubobjectAdjustment, 4> Adjustments;
00468         const Expr *ExtendedObject =
00469             MTE->GetTemporaryExpr()->skipRValueSubobjectAdjustments(
00470                 CommaLHS, Adjustments);
00471         if (ExtendedObject->getType().isDestructedType()) {
00472           Scopes.push_back(GotoScope(ParentScope, 0,
00473                                      diag::note_exits_temporary_dtor,
00474                                      ExtendedObject->getExprLoc()));
00475           ParentScope = Scopes.size()-1;
00476         }
00477       }
00478     }
00479 
00480     // Recursively walk the AST.
00481     BuildScopeInformation(SubStmt, ParentScope);
00482   }
00483 }
00484 
00485 /// VerifyJumps - Verify each element of the Jumps array to see if they are
00486 /// valid, emitting diagnostics if not.
00487 void JumpScopeChecker::VerifyJumps() {
00488   while (!Jumps.empty()) {
00489     Stmt *Jump = Jumps.pop_back_val();
00490 
00491     // With a goto,
00492     if (GotoStmt *GS = dyn_cast<GotoStmt>(Jump)) {
00493       // The label may not have a statement if it's coming from inline MS ASM.
00494       if (GS->getLabel()->getStmt()) {
00495         CheckJump(GS, GS->getLabel()->getStmt(), GS->getGotoLoc(),
00496                   diag::err_goto_into_protected_scope,
00497                   diag::ext_goto_into_protected_scope,
00498                   diag::warn_cxx98_compat_goto_into_protected_scope);
00499       }
00500       CheckGotoStmt(GS);
00501       continue;
00502     }
00503 
00504     // We only get indirect gotos here when they have a constant target.
00505     if (IndirectGotoStmt *IGS = dyn_cast<IndirectGotoStmt>(Jump)) {
00506       LabelDecl *Target = IGS->getConstantTarget();
00507       CheckJump(IGS, Target->getStmt(), IGS->getGotoLoc(),
00508                 diag::err_goto_into_protected_scope,
00509                 diag::ext_goto_into_protected_scope,
00510                 diag::warn_cxx98_compat_goto_into_protected_scope);
00511       continue;
00512     }
00513 
00514     SwitchStmt *SS = cast<SwitchStmt>(Jump);
00515     for (SwitchCase *SC = SS->getSwitchCaseList(); SC;
00516          SC = SC->getNextSwitchCase()) {
00517       if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(SC)))
00518         continue;
00519       SourceLocation Loc;
00520       if (CaseStmt *CS = dyn_cast<CaseStmt>(SC))
00521         Loc = CS->getLocStart();
00522       else if (DefaultStmt *DS = dyn_cast<DefaultStmt>(SC))
00523         Loc = DS->getLocStart();
00524       else
00525         Loc = SC->getLocStart();
00526       CheckJump(SS, SC, Loc, diag::err_switch_into_protected_scope, 0,
00527                 diag::warn_cxx98_compat_switch_into_protected_scope);
00528     }
00529   }
00530 }
00531 
00532 /// VerifyIndirectJumps - Verify whether any possible indirect jump
00533 /// might cross a protection boundary.  Unlike direct jumps, indirect
00534 /// jumps count cleanups as protection boundaries:  since there's no
00535 /// way to know where the jump is going, we can't implicitly run the
00536 /// right cleanups the way we can with direct jumps.
00537 ///
00538 /// Thus, an indirect jump is "trivial" if it bypasses no
00539 /// initializations and no teardowns.  More formally, an indirect jump
00540 /// from A to B is trivial if the path out from A to DCA(A,B) is
00541 /// trivial and the path in from DCA(A,B) to B is trivial, where
00542 /// DCA(A,B) is the deepest common ancestor of A and B.
00543 /// Jump-triviality is transitive but asymmetric.
00544 ///
00545 /// A path in is trivial if none of the entered scopes have an InDiag.
00546 /// A path out is trivial is none of the exited scopes have an OutDiag.
00547 ///
00548 /// Under these definitions, this function checks that the indirect
00549 /// jump between A and B is trivial for every indirect goto statement A
00550 /// and every label B whose address was taken in the function.
00551 void JumpScopeChecker::VerifyIndirectJumps() {
00552   if (IndirectJumps.empty()) return;
00553 
00554   // If there aren't any address-of-label expressions in this function,
00555   // complain about the first indirect goto.
00556   if (IndirectJumpTargets.empty()) {
00557     S.Diag(IndirectJumps[0]->getGotoLoc(),
00558            diag::err_indirect_goto_without_addrlabel);
00559     return;
00560   }
00561 
00562   // Collect a single representative of every scope containing an
00563   // indirect goto.  For most code bases, this substantially cuts
00564   // down on the number of jump sites we'll have to consider later.
00565   typedef std::pair<unsigned, IndirectGotoStmt*> JumpScope;
00566   SmallVector<JumpScope, 32> JumpScopes;
00567   {
00568     llvm::DenseMap<unsigned, IndirectGotoStmt*> JumpScopesMap;
00569     for (SmallVectorImpl<IndirectGotoStmt*>::iterator
00570            I = IndirectJumps.begin(), E = IndirectJumps.end(); I != E; ++I) {
00571       IndirectGotoStmt *IG = *I;
00572       if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(IG)))
00573         continue;
00574       unsigned IGScope = LabelAndGotoScopes[IG];
00575       IndirectGotoStmt *&Entry = JumpScopesMap[IGScope];
00576       if (!Entry) Entry = IG;
00577     }
00578     JumpScopes.reserve(JumpScopesMap.size());
00579     for (llvm::DenseMap<unsigned, IndirectGotoStmt*>::iterator
00580            I = JumpScopesMap.begin(), E = JumpScopesMap.end(); I != E; ++I)
00581       JumpScopes.push_back(*I);
00582   }
00583 
00584   // Collect a single representative of every scope containing a
00585   // label whose address was taken somewhere in the function.
00586   // For most code bases, there will be only one such scope.
00587   llvm::DenseMap<unsigned, LabelDecl*> TargetScopes;
00588   for (SmallVectorImpl<LabelDecl*>::iterator
00589          I = IndirectJumpTargets.begin(), E = IndirectJumpTargets.end();
00590        I != E; ++I) {
00591     LabelDecl *TheLabel = *I;
00592     if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(TheLabel->getStmt())))
00593       continue;
00594     unsigned LabelScope = LabelAndGotoScopes[TheLabel->getStmt()];
00595     LabelDecl *&Target = TargetScopes[LabelScope];
00596     if (!Target) Target = TheLabel;
00597   }
00598 
00599   // For each target scope, make sure it's trivially reachable from
00600   // every scope containing a jump site.
00601   //
00602   // A path between scopes always consists of exitting zero or more
00603   // scopes, then entering zero or more scopes.  We build a set of
00604   // of scopes S from which the target scope can be trivially
00605   // entered, then verify that every jump scope can be trivially
00606   // exitted to reach a scope in S.
00607   llvm::BitVector Reachable(Scopes.size(), false);
00608   for (llvm::DenseMap<unsigned,LabelDecl*>::iterator
00609          TI = TargetScopes.begin(), TE = TargetScopes.end(); TI != TE; ++TI) {
00610     unsigned TargetScope = TI->first;
00611     LabelDecl *TargetLabel = TI->second;
00612 
00613     Reachable.reset();
00614 
00615     // Mark all the enclosing scopes from which you can safely jump
00616     // into the target scope.  'Min' will end up being the index of
00617     // the shallowest such scope.
00618     unsigned Min = TargetScope;
00619     while (true) {
00620       Reachable.set(Min);
00621 
00622       // Don't go beyond the outermost scope.
00623       if (Min == 0) break;
00624 
00625       // Stop if we can't trivially enter the current scope.
00626       if (Scopes[Min].InDiag) break;
00627 
00628       Min = Scopes[Min].ParentScope;
00629     }
00630 
00631     // Walk through all the jump sites, checking that they can trivially
00632     // reach this label scope.
00633     for (SmallVectorImpl<JumpScope>::iterator
00634            I = JumpScopes.begin(), E = JumpScopes.end(); I != E; ++I) {
00635       unsigned Scope = I->first;
00636 
00637       // Walk out the "scope chain" for this scope, looking for a scope
00638       // we've marked reachable.  For well-formed code this amortizes
00639       // to O(JumpScopes.size() / Scopes.size()):  we only iterate
00640       // when we see something unmarked, and in well-formed code we
00641       // mark everything we iterate past.
00642       bool IsReachable = false;
00643       while (true) {
00644         if (Reachable.test(Scope)) {
00645           // If we find something reachable, mark all the scopes we just
00646           // walked through as reachable.
00647           for (unsigned S = I->first; S != Scope; S = Scopes[S].ParentScope)
00648             Reachable.set(S);
00649           IsReachable = true;
00650           break;
00651         }
00652 
00653         // Don't walk out if we've reached the top-level scope or we've
00654         // gotten shallower than the shallowest reachable scope.
00655         if (Scope == 0 || Scope < Min) break;
00656 
00657         // Don't walk out through an out-diagnostic.
00658         if (Scopes[Scope].OutDiag) break;
00659 
00660         Scope = Scopes[Scope].ParentScope;
00661       }
00662 
00663       // Only diagnose if we didn't find something.
00664       if (IsReachable) continue;
00665 
00666       DiagnoseIndirectJump(I->second, I->first, TargetLabel, TargetScope);
00667     }
00668   }
00669 }
00670 
00671 /// Return true if a particular error+note combination must be downgraded to a
00672 /// warning in Microsoft mode.
00673 static bool IsMicrosoftJumpWarning(unsigned JumpDiag, unsigned InDiagNote) {
00674   return (JumpDiag == diag::err_goto_into_protected_scope &&
00675          (InDiagNote == diag::note_protected_by_variable_init ||
00676           InDiagNote == diag::note_protected_by_variable_nontriv_destructor));
00677 }
00678 
00679 /// Return true if a particular note should be downgraded to a compatibility
00680 /// warning in C++11 mode.
00681 static bool IsCXX98CompatWarning(Sema &S, unsigned InDiagNote) {
00682   return S.getLangOpts().CPlusPlus11 &&
00683          InDiagNote == diag::note_protected_by_variable_non_pod;
00684 }
00685 
00686 /// Produce primary diagnostic for an indirect jump statement.
00687 static void DiagnoseIndirectJumpStmt(Sema &S, IndirectGotoStmt *Jump,
00688                                      LabelDecl *Target, bool &Diagnosed) {
00689   if (Diagnosed)
00690     return;
00691   S.Diag(Jump->getGotoLoc(), diag::err_indirect_goto_in_protected_scope);
00692   S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
00693   Diagnosed = true;
00694 }
00695 
00696 /// Produce note diagnostics for a jump into a protected scope.
00697 void JumpScopeChecker::NoteJumpIntoScopes(ArrayRef<unsigned> ToScopes) {
00698   if (CHECK_PERMISSIVE(ToScopes.empty()))
00699     return;
00700   for (unsigned I = 0, E = ToScopes.size(); I != E; ++I)
00701     if (Scopes[ToScopes[I]].InDiag)
00702       S.Diag(Scopes[ToScopes[I]].Loc, Scopes[ToScopes[I]].InDiag);
00703 }
00704 
00705 /// Diagnose an indirect jump which is known to cross scopes.
00706 void JumpScopeChecker::DiagnoseIndirectJump(IndirectGotoStmt *Jump,
00707                                             unsigned JumpScope,
00708                                             LabelDecl *Target,
00709                                             unsigned TargetScope) {
00710   if (CHECK_PERMISSIVE(JumpScope == TargetScope))
00711     return;
00712 
00713   unsigned Common = GetDeepestCommonScope(JumpScope, TargetScope);
00714   bool Diagnosed = false;
00715 
00716   // Walk out the scope chain until we reach the common ancestor.
00717   for (unsigned I = JumpScope; I != Common; I = Scopes[I].ParentScope)
00718     if (Scopes[I].OutDiag) {
00719       DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
00720       S.Diag(Scopes[I].Loc, Scopes[I].OutDiag);
00721     }
00722 
00723   SmallVector<unsigned, 10> ToScopesCXX98Compat;
00724 
00725   // Now walk into the scopes containing the label whose address was taken.
00726   for (unsigned I = TargetScope; I != Common; I = Scopes[I].ParentScope)
00727     if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
00728       ToScopesCXX98Compat.push_back(I);
00729     else if (Scopes[I].InDiag) {
00730       DiagnoseIndirectJumpStmt(S, Jump, Target, Diagnosed);
00731       S.Diag(Scopes[I].Loc, Scopes[I].InDiag);
00732     }
00733 
00734   // Diagnose this jump if it would be ill-formed in C++98.
00735   if (!Diagnosed && !ToScopesCXX98Compat.empty()) {
00736     S.Diag(Jump->getGotoLoc(),
00737            diag::warn_cxx98_compat_indirect_goto_in_protected_scope);
00738     S.Diag(Target->getStmt()->getIdentLoc(), diag::note_indirect_goto_target);
00739     NoteJumpIntoScopes(ToScopesCXX98Compat);
00740   }
00741 }
00742 
00743 /// CheckJump - Validate that the specified jump statement is valid: that it is
00744 /// jumping within or out of its current scope, not into a deeper one.
00745 void JumpScopeChecker::CheckJump(Stmt *From, Stmt *To, SourceLocation DiagLoc,
00746                                unsigned JumpDiagError, unsigned JumpDiagWarning,
00747                                  unsigned JumpDiagCXX98Compat) {
00748   if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(From)))
00749     return;
00750   if (CHECK_PERMISSIVE(!LabelAndGotoScopes.count(To)))
00751     return;
00752 
00753   unsigned FromScope = LabelAndGotoScopes[From];
00754   unsigned ToScope = LabelAndGotoScopes[To];
00755 
00756   // Common case: exactly the same scope, which is fine.
00757   if (FromScope == ToScope) return;
00758 
00759   unsigned CommonScope = GetDeepestCommonScope(FromScope, ToScope);
00760 
00761   // It's okay to jump out from a nested scope.
00762   if (CommonScope == ToScope) return;
00763 
00764   // Pull out (and reverse) any scopes we might need to diagnose skipping.
00765   SmallVector<unsigned, 10> ToScopesCXX98Compat;
00766   SmallVector<unsigned, 10> ToScopesError;
00767   SmallVector<unsigned, 10> ToScopesWarning;
00768   for (unsigned I = ToScope; I != CommonScope; I = Scopes[I].ParentScope) {
00769     if (S.getLangOpts().MSVCCompat && JumpDiagWarning != 0 &&
00770         IsMicrosoftJumpWarning(JumpDiagError, Scopes[I].InDiag))
00771       ToScopesWarning.push_back(I);
00772     else if (IsCXX98CompatWarning(S, Scopes[I].InDiag))
00773       ToScopesCXX98Compat.push_back(I);
00774     else if (Scopes[I].InDiag)
00775       ToScopesError.push_back(I);
00776   }
00777 
00778   // Handle warnings.
00779   if (!ToScopesWarning.empty()) {
00780     S.Diag(DiagLoc, JumpDiagWarning);
00781     NoteJumpIntoScopes(ToScopesWarning);
00782   }
00783 
00784   // Handle errors.
00785   if (!ToScopesError.empty()) {
00786     S.Diag(DiagLoc, JumpDiagError);
00787     NoteJumpIntoScopes(ToScopesError);
00788   }
00789 
00790   // Handle -Wc++98-compat warnings if the jump is well-formed.
00791   if (ToScopesError.empty() && !ToScopesCXX98Compat.empty()) {
00792     S.Diag(DiagLoc, JumpDiagCXX98Compat);
00793     NoteJumpIntoScopes(ToScopesCXX98Compat);
00794   }
00795 }
00796 
00797 void JumpScopeChecker::CheckGotoStmt(GotoStmt *GS) {
00798   if (GS->getLabel()->isMSAsmLabel()) {
00799     S.Diag(GS->getGotoLoc(), diag::err_goto_ms_asm_label)
00800         << GS->getLabel()->getIdentifier();
00801     S.Diag(GS->getLabel()->getLocation(), diag::note_goto_ms_asm_label)
00802         << GS->getLabel()->getIdentifier();
00803   }
00804 }
00805 
00806 void Sema::DiagnoseInvalidJumps(Stmt *Body) {
00807   (void)JumpScopeChecker(Body, *this);
00808 }