1 //===--- UseNullptrCheck.cpp - clang-tidy----------------------------------===// 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 #include "UseNullptrCheck.h" 11 #include "clang/AST/ASTContext.h" 12 #include "clang/AST/RecursiveASTVisitor.h" 13 #include "clang/ASTMatchers/ASTMatchFinder.h" 14 #include "clang/Lex/Lexer.h" 15 16 using namespace clang; 17 using namespace clang::ast_matchers; 18 using namespace llvm; 19 20 namespace clang { 21 namespace tidy { 22 namespace modernize { 23 namespace { 24 25 const char CastSequence[] = "sequence"; 26 27 /// \brief Matches cast expressions that have a cast kind of CK_NullToPointer 28 /// or CK_NullToMemberPointer. 29 /// 30 /// Given 31 /// \code 32 /// int *p = 0; 33 /// \endcode 34 /// implicitCastExpr(isNullToPointer()) matches the implicit cast clang adds 35 /// around \c 0. 36 AST_MATCHER(CastExpr, isNullToPointer) { 37 return Node.getCastKind() == CK_NullToPointer || 38 Node.getCastKind() == CK_NullToMemberPointer; 39 } 40 41 AST_MATCHER(Type, sugaredNullptrType) { 42 const Type *DesugaredType = Node.getUnqualifiedDesugaredType(); 43 if (const BuiltinType *BT = dyn_cast<BuiltinType>(DesugaredType)) 44 return BT->getKind() == BuiltinType::NullPtr; 45 return false; 46 } 47 48 /// \brief Create a matcher that finds implicit casts as well as the head of a 49 /// sequence of zero or more nested explicit casts that have an implicit cast 50 /// to null within. 51 /// Finding sequences of explict casts is necessary so that an entire sequence 52 /// can be replaced instead of just the inner-most implicit cast. 53 StatementMatcher makeCastSequenceMatcher() { 54 StatementMatcher ImplicitCastToNull = implicitCastExpr( 55 isNullToPointer(), 56 unless(hasSourceExpression(hasType(sugaredNullptrType())))); 57 58 return castExpr(anyOf(ImplicitCastToNull, 59 explicitCastExpr(hasDescendant(ImplicitCastToNull))), 60 unless(hasAncestor(explicitCastExpr()))) 61 .bind(CastSequence); 62 } 63 64 bool isReplaceableRange(SourceLocation StartLoc, SourceLocation EndLoc, 65 const SourceManager &SM) { 66 return SM.isWrittenInSameFile(StartLoc, EndLoc); 67 } 68 69 /// \brief Replaces the provided range with the text "nullptr", but only if 70 /// the start and end location are both in main file. 71 /// Returns true if and only if a replacement was made. 72 void replaceWithNullptr(ClangTidyCheck &Check, SourceManager &SM, 73 SourceLocation StartLoc, SourceLocation EndLoc) { 74 CharSourceRange Range(SourceRange(StartLoc, EndLoc), true); 75 // Add a space if nullptr follows an alphanumeric character. This happens 76 // whenever there is an c-style explicit cast to nullptr not surrounded by 77 // parentheses and right beside a return statement. 78 SourceLocation PreviousLocation = StartLoc.getLocWithOffset(-1); 79 bool NeedsSpace = isAlphanumeric(*SM.getCharacterData(PreviousLocation)); 80 Check.diag(Range.getBegin(), "use nullptr") << FixItHint::CreateReplacement( 81 Range, NeedsSpace ? " nullptr" : "nullptr"); 82 } 83 84 /// \brief Returns the name of the outermost macro. 85 /// 86 /// Given 87 /// \code 88 /// #define MY_NULL NULL 89 /// \endcode 90 /// If \p Loc points to NULL, this function will return the name MY_NULL. 91 StringRef getOutermostMacroName(SourceLocation Loc, const SourceManager &SM, 92 const LangOptions &LO) { 93 assert(Loc.isMacroID()); 94 SourceLocation OutermostMacroLoc; 95 96 while (Loc.isMacroID()) { 97 OutermostMacroLoc = Loc; 98 Loc = SM.getImmediateMacroCallerLoc(Loc); 99 } 100 101 return Lexer::getImmediateMacroName(OutermostMacroLoc, SM, LO); 102 } 103 104 /// \brief RecursiveASTVisitor for ensuring all nodes rooted at a given AST 105 /// subtree that have file-level source locations corresponding to a macro 106 /// argument have implicit NullTo(Member)Pointer nodes as ancestors. 107 class MacroArgUsageVisitor : public RecursiveASTVisitor<MacroArgUsageVisitor> { 108 public: 109 MacroArgUsageVisitor(SourceLocation CastLoc, const SourceManager &SM) 110 : CastLoc(CastLoc), SM(SM), Visited(false), CastFound(false), 111 InvalidFound(false) { 112 assert(CastLoc.isFileID()); 113 } 114 115 bool TraverseStmt(Stmt *S) { 116 bool VisitedPreviously = Visited; 117 118 if (!RecursiveASTVisitor<MacroArgUsageVisitor>::TraverseStmt(S)) 119 return false; 120 121 // The point at which VisitedPreviously is false and Visited is true is the 122 // root of a subtree containing nodes whose locations match CastLoc. It's 123 // at this point we test that the Implicit NullTo(Member)Pointer cast was 124 // found or not. 125 if (!VisitedPreviously) { 126 if (Visited && !CastFound) { 127 // Found nodes with matching SourceLocations but didn't come across a 128 // cast. This is an invalid macro arg use. Can stop traversal 129 // completely now. 130 InvalidFound = true; 131 return false; 132 } 133 // Reset state as we unwind back up the tree. 134 CastFound = false; 135 Visited = false; 136 } 137 return true; 138 } 139 140 bool VisitStmt(Stmt *S) { 141 if (SM.getFileLoc(S->getLocStart()) != CastLoc) 142 return true; 143 Visited = true; 144 145 const ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(S); 146 if (Cast && (Cast->getCastKind() == CK_NullToPointer || 147 Cast->getCastKind() == CK_NullToMemberPointer)) 148 CastFound = true; 149 150 return true; 151 } 152 153 bool TraverseInitListExpr(InitListExpr *S) { 154 // Only go through the semantic form of the InitListExpr, because 155 // ImplicitCast might not appear in the syntactic form, and this results in 156 // finding usages of the macro argument that don't have a ImplicitCast as an 157 // ancestor (thus invalidating the replacement) when they actually have. 158 return RecursiveASTVisitor<MacroArgUsageVisitor>:: 159 TraverseSynOrSemInitListExpr( 160 S->isSemanticForm() ? S : S->getSemanticForm()); 161 } 162 163 bool foundInvalid() const { return InvalidFound; } 164 165 private: 166 SourceLocation CastLoc; 167 const SourceManager &SM; 168 169 bool Visited; 170 bool CastFound; 171 bool InvalidFound; 172 }; 173 174 /// \brief Looks for implicit casts as well as sequences of 0 or more explicit 175 /// casts with an implicit null-to-pointer cast within. 176 /// 177 /// The matcher this visitor is used with will find a single implicit cast or a 178 /// top-most explicit cast (i.e. it has no explicit casts as an ancestor) where 179 /// an implicit cast is nested within. However, there is no guarantee that only 180 /// explicit casts exist between the found top-most explicit cast and the 181 /// possibly more than one nested implicit cast. This visitor finds all cast 182 /// sequences with an implicit cast to null within and creates a replacement 183 /// leaving the outermost explicit cast unchanged to avoid introducing 184 /// ambiguities. 185 class CastSequenceVisitor : public RecursiveASTVisitor<CastSequenceVisitor> { 186 public: 187 CastSequenceVisitor(ASTContext &Context, ArrayRef<StringRef> NullMacros, 188 ClangTidyCheck &check) 189 : SM(Context.getSourceManager()), Context(Context), 190 NullMacros(NullMacros), Check(check), FirstSubExpr(nullptr), 191 PruneSubtree(false) {} 192 193 bool TraverseStmt(Stmt *S) { 194 // Stop traversing down the tree if requested. 195 if (PruneSubtree) { 196 PruneSubtree = false; 197 return true; 198 } 199 return RecursiveASTVisitor<CastSequenceVisitor>::TraverseStmt(S); 200 } 201 202 // Only VisitStmt is overridden as we shouldn't find other base AST types 203 // within a cast expression. 204 bool VisitStmt(Stmt *S) { 205 CastExpr *C = dyn_cast<CastExpr>(S); 206 if (!C) { 207 FirstSubExpr = nullptr; 208 return true; 209 } 210 if (!FirstSubExpr) 211 FirstSubExpr = C->getSubExpr()->IgnoreParens(); 212 213 if (C->getCastKind() != CK_NullToPointer && 214 C->getCastKind() != CK_NullToMemberPointer) { 215 return true; 216 } 217 218 SourceLocation StartLoc = FirstSubExpr->getLocStart(); 219 SourceLocation EndLoc = FirstSubExpr->getLocEnd(); 220 221 // If the location comes from a macro arg expansion, *all* uses of that 222 // arg must be checked to result in NullTo(Member)Pointer casts. 223 // 224 // If the location comes from a macro body expansion, check to see if its 225 // coming from one of the allowed 'NULL' macros. 226 if (SM.isMacroArgExpansion(StartLoc) && SM.isMacroArgExpansion(EndLoc)) { 227 SourceLocation FileLocStart = SM.getFileLoc(StartLoc), 228 FileLocEnd = SM.getFileLoc(EndLoc); 229 SourceLocation ImmediateMarcoArgLoc, MacroLoc; 230 // Skip NULL macros used in macro. 231 if (!getMacroAndArgLocations(StartLoc, ImmediateMarcoArgLoc, MacroLoc) || 232 ImmediateMarcoArgLoc != FileLocStart) 233 return skipSubTree(); 234 235 if (isReplaceableRange(FileLocStart, FileLocEnd, SM) && 236 allArgUsesValid(C)) { 237 replaceWithNullptr(Check, SM, FileLocStart, FileLocEnd); 238 } 239 return skipSubTree(); 240 } 241 242 if (SM.isMacroBodyExpansion(StartLoc) && SM.isMacroBodyExpansion(EndLoc)) { 243 StringRef OutermostMacroName = 244 getOutermostMacroName(StartLoc, SM, Context.getLangOpts()); 245 246 // Check to see if the user wants to replace the macro being expanded. 247 if (std::find(NullMacros.begin(), NullMacros.end(), OutermostMacroName) == 248 NullMacros.end()) { 249 return skipSubTree(); 250 } 251 252 StartLoc = SM.getFileLoc(StartLoc); 253 EndLoc = SM.getFileLoc(EndLoc); 254 } 255 256 if (!isReplaceableRange(StartLoc, EndLoc, SM)) { 257 return skipSubTree(); 258 } 259 replaceWithNullptr(Check, SM, StartLoc, EndLoc); 260 261 return true; 262 } 263 264 private: 265 bool skipSubTree() { 266 PruneSubtree = true; 267 return true; 268 } 269 270 /// \brief Tests that all expansions of a macro arg, one of which expands to 271 /// result in \p CE, yield NullTo(Member)Pointer casts. 272 bool allArgUsesValid(const CastExpr *CE) { 273 SourceLocation CastLoc = CE->getLocStart(); 274 275 // Step 1: Get location of macro arg and location of the macro the arg was 276 // provided to. 277 SourceLocation ArgLoc, MacroLoc; 278 if (!getMacroAndArgLocations(CastLoc, ArgLoc, MacroLoc)) 279 return false; 280 281 // Step 2: Find the first ancestor that doesn't expand from this macro. 282 ast_type_traits::DynTypedNode ContainingAncestor; 283 if (!findContainingAncestor( 284 ast_type_traits::DynTypedNode::create<Stmt>(*CE), MacroLoc, 285 ContainingAncestor)) 286 return false; 287 288 // Step 3: 289 // Visit children of this containing parent looking for the least-descended 290 // nodes of the containing parent which are macro arg expansions that expand 291 // from the given arg location. 292 // Visitor needs: arg loc. 293 MacroArgUsageVisitor ArgUsageVisitor(SM.getFileLoc(CastLoc), SM); 294 if (const auto *D = ContainingAncestor.get<Decl>()) 295 ArgUsageVisitor.TraverseDecl(const_cast<Decl *>(D)); 296 else if (const auto *S = ContainingAncestor.get<Stmt>()) 297 ArgUsageVisitor.TraverseStmt(const_cast<Stmt *>(S)); 298 else 299 llvm_unreachable("Unhandled ContainingAncestor node type"); 300 301 return !ArgUsageVisitor.foundInvalid(); 302 } 303 304 /// \brief Given the SourceLocation for a macro arg expansion, finds the 305 /// non-macro SourceLocation of the macro the arg was passed to and the 306 /// non-macro SourceLocation of the argument in the arg list to that macro. 307 /// These results are returned via \c MacroLoc and \c ArgLoc respectively. 308 /// These values are undefined if the return value is false. 309 /// 310 /// \returns false if one of the returned SourceLocations would be a 311 /// SourceLocation pointing within the definition of another macro. 312 bool getMacroAndArgLocations(SourceLocation Loc, SourceLocation &ArgLoc, 313 SourceLocation &MacroLoc) { 314 assert(Loc.isMacroID() && "Only reasonble to call this on macros"); 315 316 ArgLoc = Loc; 317 318 // Find the location of the immediate macro expansion. 319 while (true) { 320 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(ArgLoc); 321 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(LocInfo.first); 322 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion(); 323 324 SourceLocation OldArgLoc = ArgLoc; 325 ArgLoc = Expansion.getExpansionLocStart(); 326 if (!Expansion.isMacroArgExpansion()) { 327 if (!MacroLoc.isFileID()) 328 return false; 329 330 StringRef Name = 331 Lexer::getImmediateMacroName(OldArgLoc, SM, Context.getLangOpts()); 332 return std::find(NullMacros.begin(), NullMacros.end(), Name) != 333 NullMacros.end(); 334 } 335 336 MacroLoc = SM.getExpansionRange(ArgLoc).first; 337 338 ArgLoc = Expansion.getSpellingLoc().getLocWithOffset(LocInfo.second); 339 if (ArgLoc.isFileID()) 340 return true; 341 342 // If spelling location resides in the same FileID as macro expansion 343 // location, it means there is no inner macro. 344 FileID MacroFID = SM.getFileID(MacroLoc); 345 if (SM.isInFileID(ArgLoc, MacroFID)) { 346 // Don't transform this case. If the characters that caused the 347 // null-conversion come from within a macro, they can't be changed. 348 return false; 349 } 350 } 351 352 llvm_unreachable("getMacroAndArgLocations"); 353 } 354 355 /// \brief Tests if TestMacroLoc is found while recursively unravelling 356 /// expansions starting at TestLoc. TestMacroLoc.isFileID() must be true. 357 /// Implementation is very similar to getMacroAndArgLocations() except in this 358 /// case, it's not assumed that TestLoc is expanded from a macro argument. 359 /// While unravelling expansions macro arguments are handled as with 360 /// getMacroAndArgLocations() but in this function macro body expansions are 361 /// also handled. 362 /// 363 /// False means either: 364 /// - TestLoc is not from a macro expansion. 365 /// - TestLoc is from a different macro expansion. 366 bool expandsFrom(SourceLocation TestLoc, SourceLocation TestMacroLoc) { 367 if (TestLoc.isFileID()) { 368 return false; 369 } 370 371 SourceLocation Loc = TestLoc, MacroLoc; 372 373 while (true) { 374 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 375 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(LocInfo.first); 376 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion(); 377 378 Loc = Expansion.getExpansionLocStart(); 379 380 if (!Expansion.isMacroArgExpansion()) { 381 if (Loc.isFileID()) { 382 return Loc == TestMacroLoc; 383 } 384 // Since Loc is still a macro ID and it's not an argument expansion, we 385 // don't need to do the work of handling an argument expansion. Simply 386 // keep recursively expanding until we hit a FileID or a macro arg 387 // expansion or a macro arg expansion. 388 continue; 389 } 390 391 MacroLoc = SM.getImmediateExpansionRange(Loc).first; 392 if (MacroLoc.isFileID() && MacroLoc == TestMacroLoc) { 393 // Match made. 394 return true; 395 } 396 397 Loc = Expansion.getSpellingLoc().getLocWithOffset(LocInfo.second); 398 if (Loc.isFileID()) { 399 // If we made it this far without finding a match, there is no match to 400 // be made. 401 return false; 402 } 403 } 404 405 llvm_unreachable("expandsFrom"); 406 } 407 408 /// \brief Given a starting point \c Start in the AST, find an ancestor that 409 /// doesn't expand from the macro called at file location \c MacroLoc. 410 /// 411 /// \pre MacroLoc.isFileID() 412 /// \returns true if such an ancestor was found, false otherwise. 413 bool findContainingAncestor(ast_type_traits::DynTypedNode Start, 414 SourceLocation MacroLoc, 415 ast_type_traits::DynTypedNode &Result) { 416 // Below we're only following the first parent back up the AST. This should 417 // be fine since for the statements we care about there should only be one 418 // parent, except for the case specified below. 419 420 assert(MacroLoc.isFileID()); 421 422 while (true) { 423 const auto &Parents = Context.getParents(Start); 424 if (Parents.empty()) 425 return false; 426 if (Parents.size() > 1) { 427 // If there are more than one parents, don't do the replacement unless 428 // they are InitListsExpr (semantic and syntactic form). In this case we 429 // can choose any one here, and the ASTVisitor will take care of 430 // traversing the right one. 431 for (const auto &Parent : Parents) { 432 if (!Parent.get<InitListExpr>()) 433 return false; 434 } 435 } 436 437 const ast_type_traits::DynTypedNode &Parent = Parents[0]; 438 439 SourceLocation Loc; 440 if (const auto *D = Parent.get<Decl>()) 441 Loc = D->getLocStart(); 442 else if (const auto *S = Parent.get<Stmt>()) 443 Loc = S->getLocStart(); 444 445 // TypeLoc and NestedNameSpecifierLoc are members of the parent map. Skip 446 // them and keep going up. 447 if (Loc.isValid()) { 448 if (!expandsFrom(Loc, MacroLoc)) { 449 Result = Parent; 450 return true; 451 } 452 } 453 Start = Parent; 454 } 455 456 llvm_unreachable("findContainingAncestor"); 457 } 458 459 private: 460 SourceManager &SM; 461 ASTContext &Context; 462 ArrayRef<StringRef> NullMacros; 463 ClangTidyCheck &Check; 464 Expr *FirstSubExpr; 465 bool PruneSubtree; 466 }; 467 468 } // namespace 469 470 UseNullptrCheck::UseNullptrCheck(StringRef Name, ClangTidyContext *Context) 471 : ClangTidyCheck(Name, Context), 472 NullMacrosStr(Options.get("NullMacros", "")) { 473 StringRef(NullMacrosStr).split(NullMacros, ","); 474 } 475 476 void UseNullptrCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { 477 Options.store(Opts, "NullMacros", NullMacrosStr); 478 } 479 480 void UseNullptrCheck::registerMatchers(MatchFinder *Finder) { 481 // Only register the matcher for C++. Because this checker is used for 482 // modernization, it is reasonable to run it on any C++ standard with the 483 // assumption the user is trying to modernize their codebase. 484 if (getLangOpts().CPlusPlus) 485 Finder->addMatcher(makeCastSequenceMatcher(), this); 486 } 487 488 void UseNullptrCheck::check(const MatchFinder::MatchResult &Result) { 489 const auto *NullCast = Result.Nodes.getNodeAs<CastExpr>(CastSequence); 490 assert(NullCast && "Bad Callback. No node provided"); 491 492 // Given an implicit null-ptr cast or an explicit cast with an implicit 493 // null-to-pointer cast within use CastSequenceVisitor to identify sequences 494 // of explicit casts that can be converted into 'nullptr'. 495 CastSequenceVisitor(*Result.Context, NullMacros, *this) 496 .TraverseStmt(const_cast<CastExpr *>(NullCast)); 497 } 498 499 } // namespace modernize 500 } // namespace tidy 501 } // namespace clang 502