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