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