1 //===--- LoopConvertCheck.cpp - clang-tidy---------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "LoopConvertCheck.h" 10 #include "clang/AST/ASTContext.h" 11 #include "clang/ASTMatchers/ASTMatchFinder.h" 12 #include "clang/Basic/LLVM.h" 13 #include "clang/Basic/LangOptions.h" 14 #include "clang/Basic/SourceLocation.h" 15 #include "clang/Basic/SourceManager.h" 16 #include "clang/Lex/Lexer.h" 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/ADT/StringSwitch.h" 21 #include "llvm/Support/Casting.h" 22 #include <cassert> 23 #include <cstring> 24 #include <utility> 25 26 using namespace clang::ast_matchers; 27 using namespace llvm; 28 29 namespace clang { 30 namespace tidy { 31 32 template <> struct OptionEnumMapping<modernize::Confidence::Level> { 33 static llvm::ArrayRef<std::pair<modernize::Confidence::Level, StringRef>> 34 getEnumMapping() { 35 static constexpr std::pair<modernize::Confidence::Level, StringRef> 36 Mapping[] = {{modernize::Confidence::CL_Reasonable, "reasonable"}, 37 {modernize::Confidence::CL_Safe, "safe"}, 38 {modernize::Confidence::CL_Risky, "risky"}}; 39 return makeArrayRef(Mapping); 40 } 41 }; 42 43 template <> struct OptionEnumMapping<modernize::VariableNamer::NamingStyle> { 44 static llvm::ArrayRef< 45 std::pair<modernize::VariableNamer::NamingStyle, StringRef>> 46 getEnumMapping() { 47 static constexpr std::pair<modernize::VariableNamer::NamingStyle, StringRef> 48 Mapping[] = {{modernize::VariableNamer::NS_CamelCase, "CamelCase"}, 49 {modernize::VariableNamer::NS_CamelBack, "camelBack"}, 50 {modernize::VariableNamer::NS_LowerCase, "lower_case"}, 51 {modernize::VariableNamer::NS_UpperCase, "UPPER_CASE"}}; 52 return makeArrayRef(Mapping); 53 } 54 }; 55 56 namespace modernize { 57 58 static const char LoopNameArray[] = "forLoopArray"; 59 static const char LoopNameIterator[] = "forLoopIterator"; 60 static const char LoopNamePseudoArray[] = "forLoopPseudoArray"; 61 static const char ConditionBoundName[] = "conditionBound"; 62 static const char ConditionVarName[] = "conditionVar"; 63 static const char IncrementVarName[] = "incrementVar"; 64 static const char InitVarName[] = "initVar"; 65 static const char BeginCallName[] = "beginCall"; 66 static const char EndCallName[] = "endCall"; 67 static const char ConditionEndVarName[] = "conditionEndVar"; 68 static const char EndVarName[] = "endVar"; 69 static const char DerefByValueResultName[] = "derefByValueResult"; 70 static const char DerefByRefResultName[] = "derefByRefResult"; 71 72 // shared matchers 73 static const TypeMatcher AnyType() { return anything(); } 74 75 static const StatementMatcher IntegerComparisonMatcher() { 76 return expr(ignoringParenImpCasts( 77 declRefExpr(to(varDecl(hasType(isInteger())).bind(ConditionVarName))))); 78 } 79 80 static const DeclarationMatcher InitToZeroMatcher() { 81 return varDecl( 82 hasInitializer(ignoringParenImpCasts(integerLiteral(equals(0))))) 83 .bind(InitVarName); 84 } 85 86 static const StatementMatcher IncrementVarMatcher() { 87 return declRefExpr(to(varDecl(hasType(isInteger())).bind(IncrementVarName))); 88 } 89 90 /// The matcher for loops over arrays. 91 /// 92 /// In this general example, assuming 'j' and 'k' are of integral type: 93 /// \code 94 /// for (int i = 0; j < 3 + 2; ++k) { ... } 95 /// \endcode 96 /// The following string identifiers are bound to these parts of the AST: 97 /// ConditionVarName: 'j' (as a VarDecl) 98 /// ConditionBoundName: '3 + 2' (as an Expr) 99 /// InitVarName: 'i' (as a VarDecl) 100 /// IncrementVarName: 'k' (as a VarDecl) 101 /// LoopName: The entire for loop (as a ForStmt) 102 /// 103 /// Client code will need to make sure that: 104 /// - The three index variables identified by the matcher are the same 105 /// VarDecl. 106 /// - The index variable is only used as an array index. 107 /// - All arrays indexed by the loop are the same. 108 StatementMatcher makeArrayLoopMatcher() { 109 StatementMatcher ArrayBoundMatcher = 110 expr(hasType(isInteger())).bind(ConditionBoundName); 111 112 return forStmt( 113 unless(isInTemplateInstantiation()), 114 hasLoopInit(declStmt(hasSingleDecl(InitToZeroMatcher()))), 115 hasCondition(anyOf( 116 binaryOperator(hasOperatorName("<"), 117 hasLHS(IntegerComparisonMatcher()), 118 hasRHS(ArrayBoundMatcher)), 119 binaryOperator(hasOperatorName(">"), hasLHS(ArrayBoundMatcher), 120 hasRHS(IntegerComparisonMatcher())))), 121 hasIncrement(unaryOperator(hasOperatorName("++"), 122 hasUnaryOperand(IncrementVarMatcher())))) 123 .bind(LoopNameArray); 124 } 125 126 /// The matcher used for iterator-based for loops. 127 /// 128 /// This matcher is more flexible than array-based loops. It will match 129 /// catch loops of the following textual forms (regardless of whether the 130 /// iterator type is actually a pointer type or a class type): 131 /// 132 /// Assuming f, g, and h are of type containerType::iterator, 133 /// \code 134 /// for (containerType::iterator it = container.begin(), 135 /// e = createIterator(); f != g; ++h) { ... } 136 /// for (containerType::iterator it = container.begin(); 137 /// f != anotherContainer.end(); ++h) { ... } 138 /// \endcode 139 /// The following string identifiers are bound to the parts of the AST: 140 /// InitVarName: 'it' (as a VarDecl) 141 /// ConditionVarName: 'f' (as a VarDecl) 142 /// LoopName: The entire for loop (as a ForStmt) 143 /// In the first example only: 144 /// EndVarName: 'e' (as a VarDecl) 145 /// ConditionEndVarName: 'g' (as a VarDecl) 146 /// In the second example only: 147 /// EndCallName: 'container.end()' (as a CXXMemberCallExpr) 148 /// 149 /// Client code will need to make sure that: 150 /// - The iterator variables 'it', 'f', and 'h' are the same. 151 /// - The two containers on which 'begin' and 'end' are called are the same. 152 /// - If the end iterator variable 'g' is defined, it is the same as 'f'. 153 StatementMatcher makeIteratorLoopMatcher() { 154 StatementMatcher BeginCallMatcher = 155 cxxMemberCallExpr(argumentCountIs(0), 156 callee(cxxMethodDecl(hasAnyName("begin", "cbegin")))) 157 .bind(BeginCallName); 158 159 DeclarationMatcher InitDeclMatcher = 160 varDecl(hasInitializer(anyOf(ignoringParenImpCasts(BeginCallMatcher), 161 materializeTemporaryExpr( 162 ignoringParenImpCasts(BeginCallMatcher)), 163 hasDescendant(BeginCallMatcher)))) 164 .bind(InitVarName); 165 166 DeclarationMatcher EndDeclMatcher = 167 varDecl(hasInitializer(anything())).bind(EndVarName); 168 169 StatementMatcher EndCallMatcher = cxxMemberCallExpr( 170 argumentCountIs(0), callee(cxxMethodDecl(hasAnyName("end", "cend")))); 171 172 StatementMatcher IteratorBoundMatcher = 173 expr(anyOf(ignoringParenImpCasts( 174 declRefExpr(to(varDecl().bind(ConditionEndVarName)))), 175 ignoringParenImpCasts(expr(EndCallMatcher).bind(EndCallName)), 176 materializeTemporaryExpr(ignoringParenImpCasts( 177 expr(EndCallMatcher).bind(EndCallName))))); 178 179 StatementMatcher IteratorComparisonMatcher = expr( 180 ignoringParenImpCasts(declRefExpr(to(varDecl().bind(ConditionVarName))))); 181 182 auto OverloadedNEQMatcher = ignoringImplicit( 183 cxxOperatorCallExpr(hasOverloadedOperatorName("!="), argumentCountIs(2), 184 hasArgument(0, IteratorComparisonMatcher), 185 hasArgument(1, IteratorBoundMatcher))); 186 187 // This matcher tests that a declaration is a CXXRecordDecl that has an 188 // overloaded operator*(). If the operator*() returns by value instead of by 189 // reference then the return type is tagged with DerefByValueResultName. 190 internal::Matcher<VarDecl> TestDerefReturnsByValue = 191 hasType(hasUnqualifiedDesugaredType( 192 recordType(hasDeclaration(cxxRecordDecl(hasMethod(cxxMethodDecl( 193 hasOverloadedOperatorName("*"), 194 anyOf( 195 // Tag the return type if it's by value. 196 returns(qualType(unless(hasCanonicalType(referenceType()))) 197 .bind(DerefByValueResultName)), 198 returns( 199 // Skip loops where the iterator's operator* returns an 200 // rvalue reference. This is just weird. 201 qualType(unless(hasCanonicalType(rValueReferenceType()))) 202 .bind(DerefByRefResultName)))))))))); 203 204 return forStmt( 205 unless(isInTemplateInstantiation()), 206 hasLoopInit(anyOf(declStmt(declCountIs(2), 207 containsDeclaration(0, InitDeclMatcher), 208 containsDeclaration(1, EndDeclMatcher)), 209 declStmt(hasSingleDecl(InitDeclMatcher)))), 210 hasCondition( 211 anyOf(binaryOperator(hasOperatorName("!="), 212 hasLHS(IteratorComparisonMatcher), 213 hasRHS(IteratorBoundMatcher)), 214 binaryOperator(hasOperatorName("!="), 215 hasLHS(IteratorBoundMatcher), 216 hasRHS(IteratorComparisonMatcher)), 217 OverloadedNEQMatcher)), 218 hasIncrement(anyOf( 219 unaryOperator(hasOperatorName("++"), 220 hasUnaryOperand(declRefExpr( 221 to(varDecl(hasType(pointsTo(AnyType()))) 222 .bind(IncrementVarName))))), 223 cxxOperatorCallExpr( 224 hasOverloadedOperatorName("++"), 225 hasArgument( 226 0, declRefExpr(to(varDecl(TestDerefReturnsByValue) 227 .bind(IncrementVarName)))))))) 228 .bind(LoopNameIterator); 229 } 230 231 /// The matcher used for array-like containers (pseudoarrays). 232 /// 233 /// This matcher is more flexible than array-based loops. It will match 234 /// loops of the following textual forms (regardless of whether the 235 /// iterator type is actually a pointer type or a class type): 236 /// 237 /// Assuming f, g, and h are of type containerType::iterator, 238 /// \code 239 /// for (int i = 0, j = container.size(); f < g; ++h) { ... } 240 /// for (int i = 0; f < container.size(); ++h) { ... } 241 /// \endcode 242 /// The following string identifiers are bound to the parts of the AST: 243 /// InitVarName: 'i' (as a VarDecl) 244 /// ConditionVarName: 'f' (as a VarDecl) 245 /// LoopName: The entire for loop (as a ForStmt) 246 /// In the first example only: 247 /// EndVarName: 'j' (as a VarDecl) 248 /// ConditionEndVarName: 'g' (as a VarDecl) 249 /// In the second example only: 250 /// EndCallName: 'container.size()' (as a CXXMemberCallExpr) 251 /// 252 /// Client code will need to make sure that: 253 /// - The index variables 'i', 'f', and 'h' are the same. 254 /// - The containers on which 'size()' is called is the container indexed. 255 /// - The index variable is only used in overloaded operator[] or 256 /// container.at(). 257 /// - If the end iterator variable 'g' is defined, it is the same as 'j'. 258 /// - The container's iterators would not be invalidated during the loop. 259 StatementMatcher makePseudoArrayLoopMatcher() { 260 // Test that the incoming type has a record declaration that has methods 261 // called 'begin' and 'end'. If the incoming type is const, then make sure 262 // these methods are also marked const. 263 // 264 // FIXME: To be completely thorough this matcher should also ensure the 265 // return type of begin/end is an iterator that dereferences to the same as 266 // what operator[] or at() returns. Such a test isn't likely to fail except 267 // for pathological cases. 268 // 269 // FIXME: Also, a record doesn't necessarily need begin() and end(). Free 270 // functions called begin() and end() taking the container as an argument 271 // are also allowed. 272 TypeMatcher RecordWithBeginEnd = qualType(anyOf( 273 qualType( 274 isConstQualified(), 275 hasUnqualifiedDesugaredType(recordType(hasDeclaration(cxxRecordDecl( 276 hasMethod(cxxMethodDecl(hasName("begin"), isConst())), 277 hasMethod(cxxMethodDecl(hasName("end"), 278 isConst())))) // hasDeclaration 279 ))), // qualType 280 qualType(unless(isConstQualified()), 281 hasUnqualifiedDesugaredType(recordType(hasDeclaration( 282 cxxRecordDecl(hasMethod(hasName("begin")), 283 hasMethod(hasName("end"))))))) // qualType 284 )); 285 286 StatementMatcher SizeCallMatcher = cxxMemberCallExpr( 287 argumentCountIs(0), callee(cxxMethodDecl(hasAnyName("size", "length"))), 288 on(anyOf(hasType(pointsTo(RecordWithBeginEnd)), 289 hasType(RecordWithBeginEnd)))); 290 291 StatementMatcher EndInitMatcher = 292 expr(anyOf(ignoringParenImpCasts(expr(SizeCallMatcher).bind(EndCallName)), 293 explicitCastExpr(hasSourceExpression(ignoringParenImpCasts( 294 expr(SizeCallMatcher).bind(EndCallName)))))); 295 296 DeclarationMatcher EndDeclMatcher = 297 varDecl(hasInitializer(EndInitMatcher)).bind(EndVarName); 298 299 StatementMatcher IndexBoundMatcher = 300 expr(anyOf(ignoringParenImpCasts(declRefExpr(to( 301 varDecl(hasType(isInteger())).bind(ConditionEndVarName)))), 302 EndInitMatcher)); 303 304 return forStmt( 305 unless(isInTemplateInstantiation()), 306 hasLoopInit( 307 anyOf(declStmt(declCountIs(2), 308 containsDeclaration(0, InitToZeroMatcher()), 309 containsDeclaration(1, EndDeclMatcher)), 310 declStmt(hasSingleDecl(InitToZeroMatcher())))), 311 hasCondition(anyOf( 312 binaryOperator(hasOperatorName("<"), 313 hasLHS(IntegerComparisonMatcher()), 314 hasRHS(IndexBoundMatcher)), 315 binaryOperator(hasOperatorName(">"), hasLHS(IndexBoundMatcher), 316 hasRHS(IntegerComparisonMatcher())))), 317 hasIncrement(unaryOperator(hasOperatorName("++"), 318 hasUnaryOperand(IncrementVarMatcher())))) 319 .bind(LoopNamePseudoArray); 320 } 321 322 /// Determine whether Init appears to be an initializing an iterator. 323 /// 324 /// If it is, returns the object whose begin() or end() method is called, and 325 /// the output parameter isArrow is set to indicate whether the initialization 326 /// is called via . or ->. 327 static const Expr *getContainerFromBeginEndCall(const Expr *Init, bool IsBegin, 328 bool *IsArrow) { 329 // FIXME: Maybe allow declaration/initialization outside of the for loop. 330 const auto *TheCall = 331 dyn_cast_or_null<CXXMemberCallExpr>(digThroughConstructors(Init)); 332 if (!TheCall || TheCall->getNumArgs() != 0) 333 return nullptr; 334 335 const auto *Member = dyn_cast<MemberExpr>(TheCall->getCallee()); 336 if (!Member) 337 return nullptr; 338 StringRef Name = Member->getMemberDecl()->getName(); 339 StringRef TargetName = IsBegin ? "begin" : "end"; 340 StringRef ConstTargetName = IsBegin ? "cbegin" : "cend"; 341 if (Name != TargetName && Name != ConstTargetName) 342 return nullptr; 343 344 const Expr *SourceExpr = Member->getBase(); 345 if (!SourceExpr) 346 return nullptr; 347 348 *IsArrow = Member->isArrow(); 349 return SourceExpr; 350 } 351 352 /// Determines the container whose begin() and end() functions are called 353 /// for an iterator-based loop. 354 /// 355 /// BeginExpr must be a member call to a function named "begin()", and EndExpr 356 /// must be a member. 357 static const Expr *findContainer(ASTContext *Context, const Expr *BeginExpr, 358 const Expr *EndExpr, 359 bool *ContainerNeedsDereference) { 360 // Now that we know the loop variable and test expression, make sure they are 361 // valid. 362 bool BeginIsArrow = false; 363 bool EndIsArrow = false; 364 const Expr *BeginContainerExpr = 365 getContainerFromBeginEndCall(BeginExpr, /*IsBegin=*/true, &BeginIsArrow); 366 if (!BeginContainerExpr) 367 return nullptr; 368 369 const Expr *EndContainerExpr = 370 getContainerFromBeginEndCall(EndExpr, /*IsBegin=*/false, &EndIsArrow); 371 // Disallow loops that try evil things like this (note the dot and arrow): 372 // for (IteratorType It = Obj.begin(), E = Obj->end(); It != E; ++It) { } 373 if (!EndContainerExpr || BeginIsArrow != EndIsArrow || 374 !areSameExpr(Context, EndContainerExpr, BeginContainerExpr)) 375 return nullptr; 376 377 *ContainerNeedsDereference = BeginIsArrow; 378 return BeginContainerExpr; 379 } 380 381 /// Obtain the original source code text from a SourceRange. 382 static StringRef getStringFromRange(SourceManager &SourceMgr, 383 const LangOptions &LangOpts, 384 SourceRange Range) { 385 if (SourceMgr.getFileID(Range.getBegin()) != 386 SourceMgr.getFileID(Range.getEnd())) { 387 return StringRef(); // Empty string. 388 } 389 390 return Lexer::getSourceText(CharSourceRange(Range, true), SourceMgr, 391 LangOpts); 392 } 393 394 /// If the given expression is actually a DeclRefExpr or a MemberExpr, 395 /// find and return the underlying ValueDecl; otherwise, return NULL. 396 static const ValueDecl *getReferencedVariable(const Expr *E) { 397 if (const DeclRefExpr *DRE = getDeclRef(E)) 398 return dyn_cast<VarDecl>(DRE->getDecl()); 399 if (const auto *Mem = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts())) 400 return dyn_cast<FieldDecl>(Mem->getMemberDecl()); 401 return nullptr; 402 } 403 404 /// Returns true when the given expression is a member expression 405 /// whose base is `this` (implicitly or not). 406 static bool isDirectMemberExpr(const Expr *E) { 407 if (const auto *Member = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts())) 408 return isa<CXXThisExpr>(Member->getBase()->IgnoreParenImpCasts()); 409 return false; 410 } 411 412 /// Given an expression that represents an usage of an element from the 413 /// containter that we are iterating over, returns false when it can be 414 /// guaranteed this element cannot be modified as a result of this usage. 415 static bool canBeModified(ASTContext *Context, const Expr *E) { 416 if (E->getType().isConstQualified()) 417 return false; 418 auto Parents = Context->getParents(*E); 419 if (Parents.size() != 1) 420 return true; 421 if (const auto *Cast = Parents[0].get<ImplicitCastExpr>()) { 422 if ((Cast->getCastKind() == CK_NoOp && 423 Cast->getType() == E->getType().withConst()) || 424 (Cast->getCastKind() == CK_LValueToRValue && 425 !Cast->getType().isNull() && Cast->getType()->isFundamentalType())) 426 return false; 427 } 428 // FIXME: Make this function more generic. 429 return true; 430 } 431 432 /// Returns true when it can be guaranteed that the elements of the 433 /// container are not being modified. 434 static bool usagesAreConst(ASTContext *Context, const UsageResult &Usages) { 435 for (const Usage &U : Usages) { 436 // Lambda captures are just redeclarations (VarDecl) of the same variable, 437 // not expressions. If we want to know if a variable that is captured by 438 // reference can be modified in an usage inside the lambda's body, we need 439 // to find the expression corresponding to that particular usage, later in 440 // this loop. 441 if (U.Kind != Usage::UK_CaptureByCopy && U.Kind != Usage::UK_CaptureByRef && 442 canBeModified(Context, U.Expression)) 443 return false; 444 } 445 return true; 446 } 447 448 /// Returns true if the elements of the container are never accessed 449 /// by reference. 450 static bool usagesReturnRValues(const UsageResult &Usages) { 451 for (const auto &U : Usages) { 452 if (U.Expression && !U.Expression->isRValue()) 453 return false; 454 } 455 return true; 456 } 457 458 /// Returns true if the container is const-qualified. 459 static bool containerIsConst(const Expr *ContainerExpr, bool Dereference) { 460 if (const auto *VDec = getReferencedVariable(ContainerExpr)) { 461 QualType CType = VDec->getType(); 462 if (Dereference) { 463 if (!CType->isPointerType()) 464 return false; 465 CType = CType->getPointeeType(); 466 } 467 // If VDec is a reference to a container, Dereference is false, 468 // but we still need to check the const-ness of the underlying container 469 // type. 470 CType = CType.getNonReferenceType(); 471 return CType.isConstQualified(); 472 } 473 return false; 474 } 475 476 LoopConvertCheck::RangeDescriptor::RangeDescriptor() 477 : ContainerNeedsDereference(false), DerefByConstRef(false), 478 DerefByValue(false) {} 479 480 LoopConvertCheck::LoopConvertCheck(StringRef Name, ClangTidyContext *Context) 481 : ClangTidyCheck(Name, Context), TUInfo(new TUTrackingInfo), 482 MaxCopySize(Options.get("MaxCopySize", 16ULL)), 483 MinConfidence(Options.get("MinConfidence", Confidence::CL_Reasonable)), 484 NamingStyle(Options.get("NamingStyle", VariableNamer::NS_CamelCase)) {} 485 486 void LoopConvertCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { 487 Options.store(Opts, "MaxCopySize", std::to_string(MaxCopySize)); 488 Options.store(Opts, "MinConfidence", MinConfidence); 489 Options.store(Opts, "NamingStyle", NamingStyle); 490 } 491 492 void LoopConvertCheck::registerMatchers(MatchFinder *Finder) { 493 Finder->addMatcher(traverse(ast_type_traits::TK_AsIs, makeArrayLoopMatcher()), 494 this); 495 Finder->addMatcher( 496 traverse(ast_type_traits::TK_AsIs, makeIteratorLoopMatcher()), this); 497 Finder->addMatcher( 498 traverse(ast_type_traits::TK_AsIs, makePseudoArrayLoopMatcher()), this); 499 } 500 501 /// Given the range of a single declaration, such as: 502 /// \code 503 /// unsigned &ThisIsADeclarationThatCanSpanSeveralLinesOfCode = 504 /// InitializationValues[I]; 505 /// next_instruction; 506 /// \endcode 507 /// Finds the range that has to be erased to remove this declaration without 508 /// leaving empty lines, by extending the range until the beginning of the 509 /// next instruction. 510 /// 511 /// We need to delete a potential newline after the deleted alias, as 512 /// clang-format will leave empty lines untouched. For all other formatting we 513 /// rely on clang-format to fix it. 514 void LoopConvertCheck::getAliasRange(SourceManager &SM, SourceRange &Range) { 515 bool Invalid = false; 516 const char *TextAfter = 517 SM.getCharacterData(Range.getEnd().getLocWithOffset(1), &Invalid); 518 if (Invalid) 519 return; 520 unsigned Offset = std::strspn(TextAfter, " \t\r\n"); 521 Range = 522 SourceRange(Range.getBegin(), Range.getEnd().getLocWithOffset(Offset)); 523 } 524 525 /// Computes the changes needed to convert a given for loop, and 526 /// applies them. 527 void LoopConvertCheck::doConversion( 528 ASTContext *Context, const VarDecl *IndexVar, 529 const ValueDecl *MaybeContainer, const UsageResult &Usages, 530 const DeclStmt *AliasDecl, bool AliasUseRequired, bool AliasFromForInit, 531 const ForStmt *Loop, RangeDescriptor Descriptor) { 532 std::string VarName; 533 bool VarNameFromAlias = (Usages.size() == 1) && AliasDecl; 534 bool AliasVarIsRef = false; 535 bool CanCopy = true; 536 std::vector<FixItHint> FixIts; 537 if (VarNameFromAlias) { 538 const auto *AliasVar = cast<VarDecl>(AliasDecl->getSingleDecl()); 539 VarName = AliasVar->getName().str(); 540 541 // Use the type of the alias if it's not the same 542 QualType AliasVarType = AliasVar->getType(); 543 assert(!AliasVarType.isNull() && "Type in VarDecl is null"); 544 if (AliasVarType->isReferenceType()) { 545 AliasVarType = AliasVarType.getNonReferenceType(); 546 AliasVarIsRef = true; 547 } 548 if (Descriptor.ElemType.isNull() || 549 !Context->hasSameUnqualifiedType(AliasVarType, Descriptor.ElemType)) 550 Descriptor.ElemType = AliasVarType; 551 552 // We keep along the entire DeclStmt to keep the correct range here. 553 SourceRange ReplaceRange = AliasDecl->getSourceRange(); 554 555 std::string ReplacementText; 556 if (AliasUseRequired) { 557 ReplacementText = VarName; 558 } else if (AliasFromForInit) { 559 // FIXME: Clang includes the location of the ';' but only for DeclStmt's 560 // in a for loop's init clause. Need to put this ';' back while removing 561 // the declaration of the alias variable. This is probably a bug. 562 ReplacementText = ";"; 563 } else { 564 // Avoid leaving empty lines or trailing whitespaces. 565 getAliasRange(Context->getSourceManager(), ReplaceRange); 566 } 567 568 FixIts.push_back(FixItHint::CreateReplacement( 569 CharSourceRange::getTokenRange(ReplaceRange), ReplacementText)); 570 // No further replacements are made to the loop, since the iterator or index 571 // was used exactly once - in the initialization of AliasVar. 572 } else { 573 VariableNamer Namer(&TUInfo->getGeneratedDecls(), 574 &TUInfo->getParentFinder().getStmtToParentStmtMap(), 575 Loop, IndexVar, MaybeContainer, Context, NamingStyle); 576 VarName = Namer.createIndexName(); 577 // First, replace all usages of the array subscript expression with our new 578 // variable. 579 for (const auto &Usage : Usages) { 580 std::string ReplaceText; 581 SourceRange Range = Usage.Range; 582 if (Usage.Expression) { 583 // If this is an access to a member through the arrow operator, after 584 // the replacement it must be accessed through the '.' operator. 585 ReplaceText = Usage.Kind == Usage::UK_MemberThroughArrow ? VarName + "." 586 : VarName; 587 auto Parents = Context->getParents(*Usage.Expression); 588 if (Parents.size() == 1) { 589 if (const auto *Paren = Parents[0].get<ParenExpr>()) { 590 // Usage.Expression will be replaced with the new index variable, 591 // and parenthesis around a simple DeclRefExpr can always be 592 // removed. 593 Range = Paren->getSourceRange(); 594 } else if (const auto *UOP = Parents[0].get<UnaryOperator>()) { 595 // If we are taking the address of the loop variable, then we must 596 // not use a copy, as it would mean taking the address of the loop's 597 // local index instead. 598 // FIXME: This won't catch cases where the address is taken outside 599 // of the loop's body (for instance, in a function that got the 600 // loop's index as a const reference parameter), or where we take 601 // the address of a member (like "&Arr[i].A.B.C"). 602 if (UOP->getOpcode() == UO_AddrOf) 603 CanCopy = false; 604 } 605 } 606 } else { 607 // The Usage expression is only null in case of lambda captures (which 608 // are VarDecl). If the index is captured by value, add '&' to capture 609 // by reference instead. 610 ReplaceText = 611 Usage.Kind == Usage::UK_CaptureByCopy ? "&" + VarName : VarName; 612 } 613 TUInfo->getReplacedVars().insert(std::make_pair(Loop, IndexVar)); 614 FixIts.push_back(FixItHint::CreateReplacement( 615 CharSourceRange::getTokenRange(Range), ReplaceText)); 616 } 617 } 618 619 // Now, we need to construct the new range expression. 620 SourceRange ParenRange(Loop->getLParenLoc(), Loop->getRParenLoc()); 621 622 QualType Type = Context->getAutoDeductType(); 623 if (!Descriptor.ElemType.isNull() && Descriptor.ElemType->isFundamentalType()) 624 Type = Descriptor.ElemType.getUnqualifiedType(); 625 Type = Type.getDesugaredType(*Context); 626 627 // If the new variable name is from the aliased variable, then the reference 628 // type for the new variable should only be used if the aliased variable was 629 // declared as a reference. 630 bool IsCheapToCopy = 631 !Descriptor.ElemType.isNull() && 632 Descriptor.ElemType.isTriviallyCopyableType(*Context) && 633 // TypeInfo::Width is in bits. 634 Context->getTypeInfo(Descriptor.ElemType).Width <= 8 * MaxCopySize; 635 bool UseCopy = CanCopy && ((VarNameFromAlias && !AliasVarIsRef) || 636 (Descriptor.DerefByConstRef && IsCheapToCopy)); 637 638 if (!UseCopy) { 639 if (Descriptor.DerefByConstRef) { 640 Type = Context->getLValueReferenceType(Context->getConstType(Type)); 641 } else if (Descriptor.DerefByValue) { 642 if (!IsCheapToCopy) 643 Type = Context->getRValueReferenceType(Type); 644 } else { 645 Type = Context->getLValueReferenceType(Type); 646 } 647 } 648 649 StringRef MaybeDereference = Descriptor.ContainerNeedsDereference ? "*" : ""; 650 std::string TypeString = Type.getAsString(getLangOpts()); 651 std::string Range = ("(" + TypeString + " " + VarName + " : " + 652 MaybeDereference + Descriptor.ContainerString + ")") 653 .str(); 654 FixIts.push_back(FixItHint::CreateReplacement( 655 CharSourceRange::getTokenRange(ParenRange), Range)); 656 diag(Loop->getForLoc(), "use range-based for loop instead") << FixIts; 657 TUInfo->getGeneratedDecls().insert(make_pair(Loop, VarName)); 658 } 659 660 /// Returns a string which refers to the container iterated over. 661 StringRef LoopConvertCheck::getContainerString(ASTContext *Context, 662 const ForStmt *Loop, 663 const Expr *ContainerExpr) { 664 StringRef ContainerString; 665 ContainerExpr = ContainerExpr->IgnoreParenImpCasts(); 666 if (isa<CXXThisExpr>(ContainerExpr)) { 667 ContainerString = "this"; 668 } else { 669 // For CXXOperatorCallExpr (e.g. vector_ptr->size()), its first argument is 670 // the class object (vector_ptr) we are targeting. 671 if (const auto* E = dyn_cast<CXXOperatorCallExpr>(ContainerExpr)) 672 ContainerExpr = E->getArg(0); 673 ContainerString = 674 getStringFromRange(Context->getSourceManager(), Context->getLangOpts(), 675 ContainerExpr->getSourceRange()); 676 } 677 678 return ContainerString; 679 } 680 681 /// Determines what kind of 'auto' must be used after converting a for 682 /// loop that iterates over an array or pseudoarray. 683 void LoopConvertCheck::getArrayLoopQualifiers(ASTContext *Context, 684 const BoundNodes &Nodes, 685 const Expr *ContainerExpr, 686 const UsageResult &Usages, 687 RangeDescriptor &Descriptor) { 688 // On arrays and pseudoarrays, we must figure out the qualifiers from the 689 // usages. 690 if (usagesAreConst(Context, Usages) || 691 containerIsConst(ContainerExpr, Descriptor.ContainerNeedsDereference)) { 692 Descriptor.DerefByConstRef = true; 693 } 694 if (usagesReturnRValues(Usages)) { 695 // If the index usages (dereference, subscript, at, ...) return rvalues, 696 // then we should not use a reference, because we need to keep the code 697 // correct if it mutates the returned objects. 698 Descriptor.DerefByValue = true; 699 } 700 // Try to find the type of the elements on the container, to check if 701 // they are trivially copyable. 702 for (const Usage &U : Usages) { 703 if (!U.Expression || U.Expression->getType().isNull()) 704 continue; 705 QualType Type = U.Expression->getType().getCanonicalType(); 706 if (U.Kind == Usage::UK_MemberThroughArrow) { 707 if (!Type->isPointerType()) { 708 continue; 709 } 710 Type = Type->getPointeeType(); 711 } 712 Descriptor.ElemType = Type; 713 } 714 } 715 716 /// Determines what kind of 'auto' must be used after converting an 717 /// iterator based for loop. 718 void LoopConvertCheck::getIteratorLoopQualifiers(ASTContext *Context, 719 const BoundNodes &Nodes, 720 RangeDescriptor &Descriptor) { 721 // The matchers for iterator loops provide bound nodes to obtain this 722 // information. 723 const auto *InitVar = Nodes.getNodeAs<VarDecl>(InitVarName); 724 QualType CanonicalInitVarType = InitVar->getType().getCanonicalType(); 725 const auto *DerefByValueType = 726 Nodes.getNodeAs<QualType>(DerefByValueResultName); 727 Descriptor.DerefByValue = DerefByValueType; 728 729 if (Descriptor.DerefByValue) { 730 // If the dereference operator returns by value then test for the 731 // canonical const qualification of the init variable type. 732 Descriptor.DerefByConstRef = CanonicalInitVarType.isConstQualified(); 733 Descriptor.ElemType = *DerefByValueType; 734 } else { 735 if (const auto *DerefType = 736 Nodes.getNodeAs<QualType>(DerefByRefResultName)) { 737 // A node will only be bound with DerefByRefResultName if we're dealing 738 // with a user-defined iterator type. Test the const qualification of 739 // the reference type. 740 auto ValueType = DerefType->getNonReferenceType(); 741 742 Descriptor.DerefByConstRef = ValueType.isConstQualified(); 743 Descriptor.ElemType = ValueType; 744 } else { 745 // By nature of the matcher this case is triggered only for built-in 746 // iterator types (i.e. pointers). 747 assert(isa<PointerType>(CanonicalInitVarType) && 748 "Non-class iterator type is not a pointer type"); 749 750 // We test for const qualification of the pointed-at type. 751 Descriptor.DerefByConstRef = 752 CanonicalInitVarType->getPointeeType().isConstQualified(); 753 Descriptor.ElemType = CanonicalInitVarType->getPointeeType(); 754 } 755 } 756 } 757 758 /// Determines the parameters needed to build the range replacement. 759 void LoopConvertCheck::determineRangeDescriptor( 760 ASTContext *Context, const BoundNodes &Nodes, const ForStmt *Loop, 761 LoopFixerKind FixerKind, const Expr *ContainerExpr, 762 const UsageResult &Usages, RangeDescriptor &Descriptor) { 763 Descriptor.ContainerString = 764 std::string(getContainerString(Context, Loop, ContainerExpr)); 765 766 if (FixerKind == LFK_Iterator) 767 getIteratorLoopQualifiers(Context, Nodes, Descriptor); 768 else 769 getArrayLoopQualifiers(Context, Nodes, ContainerExpr, Usages, Descriptor); 770 } 771 772 /// Check some of the conditions that must be met for the loop to be 773 /// convertible. 774 bool LoopConvertCheck::isConvertible(ASTContext *Context, 775 const ast_matchers::BoundNodes &Nodes, 776 const ForStmt *Loop, 777 LoopFixerKind FixerKind) { 778 // If we already modified the range of this for loop, don't do any further 779 // updates on this iteration. 780 if (TUInfo->getReplacedVars().count(Loop)) 781 return false; 782 783 // Check that we have exactly one index variable and at most one end variable. 784 const auto *LoopVar = Nodes.getNodeAs<VarDecl>(IncrementVarName); 785 const auto *CondVar = Nodes.getNodeAs<VarDecl>(ConditionVarName); 786 const auto *InitVar = Nodes.getNodeAs<VarDecl>(InitVarName); 787 if (!areSameVariable(LoopVar, CondVar) || !areSameVariable(LoopVar, InitVar)) 788 return false; 789 const auto *EndVar = Nodes.getNodeAs<VarDecl>(EndVarName); 790 const auto *ConditionEndVar = Nodes.getNodeAs<VarDecl>(ConditionEndVarName); 791 if (EndVar && !areSameVariable(EndVar, ConditionEndVar)) 792 return false; 793 794 // FIXME: Try to put most of this logic inside a matcher. 795 if (FixerKind == LFK_Iterator) { 796 QualType InitVarType = InitVar->getType(); 797 QualType CanonicalInitVarType = InitVarType.getCanonicalType(); 798 799 const auto *BeginCall = Nodes.getNodeAs<CXXMemberCallExpr>(BeginCallName); 800 assert(BeginCall && "Bad Callback. No begin call expression"); 801 QualType CanonicalBeginType = 802 BeginCall->getMethodDecl()->getReturnType().getCanonicalType(); 803 if (CanonicalBeginType->isPointerType() && 804 CanonicalInitVarType->isPointerType()) { 805 // If the initializer and the variable are both pointers check if the 806 // un-qualified pointee types match, otherwise we don't use auto. 807 if (!Context->hasSameUnqualifiedType( 808 CanonicalBeginType->getPointeeType(), 809 CanonicalInitVarType->getPointeeType())) 810 return false; 811 } 812 } else if (FixerKind == LFK_PseudoArray) { 813 // This call is required to obtain the container. 814 const auto *EndCall = Nodes.getNodeAs<CXXMemberCallExpr>(EndCallName); 815 if (!EndCall || !dyn_cast<MemberExpr>(EndCall->getCallee())) 816 return false; 817 } 818 return true; 819 } 820 821 void LoopConvertCheck::check(const MatchFinder::MatchResult &Result) { 822 const BoundNodes &Nodes = Result.Nodes; 823 Confidence ConfidenceLevel(Confidence::CL_Safe); 824 ASTContext *Context = Result.Context; 825 826 const ForStmt *Loop; 827 LoopFixerKind FixerKind; 828 RangeDescriptor Descriptor; 829 830 if ((Loop = Nodes.getNodeAs<ForStmt>(LoopNameArray))) { 831 FixerKind = LFK_Array; 832 } else if ((Loop = Nodes.getNodeAs<ForStmt>(LoopNameIterator))) { 833 FixerKind = LFK_Iterator; 834 } else { 835 Loop = Nodes.getNodeAs<ForStmt>(LoopNamePseudoArray); 836 assert(Loop && "Bad Callback. No for statement"); 837 FixerKind = LFK_PseudoArray; 838 } 839 840 if (!isConvertible(Context, Nodes, Loop, FixerKind)) 841 return; 842 843 const auto *LoopVar = Nodes.getNodeAs<VarDecl>(IncrementVarName); 844 const auto *EndVar = Nodes.getNodeAs<VarDecl>(EndVarName); 845 846 // If the loop calls end()/size() after each iteration, lower our confidence 847 // level. 848 if (FixerKind != LFK_Array && !EndVar) 849 ConfidenceLevel.lowerTo(Confidence::CL_Reasonable); 850 851 // If the end comparison isn't a variable, we can try to work with the 852 // expression the loop variable is being tested against instead. 853 const auto *EndCall = Nodes.getNodeAs<CXXMemberCallExpr>(EndCallName); 854 const auto *BoundExpr = Nodes.getNodeAs<Expr>(ConditionBoundName); 855 856 // Find container expression of iterators and pseudoarrays, and determine if 857 // this expression needs to be dereferenced to obtain the container. 858 // With array loops, the container is often discovered during the 859 // ForLoopIndexUseVisitor traversal. 860 const Expr *ContainerExpr = nullptr; 861 if (FixerKind == LFK_Iterator) { 862 ContainerExpr = findContainer(Context, LoopVar->getInit(), 863 EndVar ? EndVar->getInit() : EndCall, 864 &Descriptor.ContainerNeedsDereference); 865 } else if (FixerKind == LFK_PseudoArray) { 866 ContainerExpr = EndCall->getImplicitObjectArgument(); 867 Descriptor.ContainerNeedsDereference = 868 dyn_cast<MemberExpr>(EndCall->getCallee())->isArrow(); 869 } 870 871 // We must know the container or an array length bound. 872 if (!ContainerExpr && !BoundExpr) 873 return; 874 875 ForLoopIndexUseVisitor Finder(Context, LoopVar, EndVar, ContainerExpr, 876 BoundExpr, 877 Descriptor.ContainerNeedsDereference); 878 879 // Find expressions and variables on which the container depends. 880 if (ContainerExpr) { 881 ComponentFinderASTVisitor ComponentFinder; 882 ComponentFinder.findExprComponents(ContainerExpr->IgnoreParenImpCasts()); 883 Finder.addComponents(ComponentFinder.getComponents()); 884 } 885 886 // Find usages of the loop index. If they are not used in a convertible way, 887 // stop here. 888 if (!Finder.findAndVerifyUsages(Loop->getBody())) 889 return; 890 ConfidenceLevel.lowerTo(Finder.getConfidenceLevel()); 891 892 // Obtain the container expression, if we don't have it yet. 893 if (FixerKind == LFK_Array) { 894 ContainerExpr = Finder.getContainerIndexed()->IgnoreParenImpCasts(); 895 896 // Very few loops are over expressions that generate arrays rather than 897 // array variables. Consider loops over arrays that aren't just represented 898 // by a variable to be risky conversions. 899 if (!getReferencedVariable(ContainerExpr) && 900 !isDirectMemberExpr(ContainerExpr)) 901 ConfidenceLevel.lowerTo(Confidence::CL_Risky); 902 } 903 904 // Find out which qualifiers we have to use in the loop range. 905 TraversalKindScope RAII(*Context, ast_type_traits::TK_AsIs); 906 const UsageResult &Usages = Finder.getUsages(); 907 determineRangeDescriptor(Context, Nodes, Loop, FixerKind, ContainerExpr, 908 Usages, Descriptor); 909 910 // Ensure that we do not try to move an expression dependent on a local 911 // variable declared inside the loop outside of it. 912 // FIXME: Determine when the external dependency isn't an expression converted 913 // by another loop. 914 TUInfo->getParentFinder().gatherAncestors(*Context); 915 DependencyFinderASTVisitor DependencyFinder( 916 &TUInfo->getParentFinder().getStmtToParentStmtMap(), 917 &TUInfo->getParentFinder().getDeclToParentStmtMap(), 918 &TUInfo->getReplacedVars(), Loop); 919 920 if (DependencyFinder.dependsOnInsideVariable(ContainerExpr) || 921 Descriptor.ContainerString.empty() || Usages.empty() || 922 ConfidenceLevel.getLevel() < MinConfidence) 923 return; 924 925 doConversion(Context, LoopVar, getReferencedVariable(ContainerExpr), Usages, 926 Finder.getAliasDecl(), Finder.aliasUseRequired(), 927 Finder.aliasFromForInit(), Loop, Descriptor); 928 } 929 930 } // namespace modernize 931 } // namespace tidy 932 } // namespace clang 933