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