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(argumentCountIs(0), 150 callee(cxxMethodDecl(hasAnyName("begin", "cbegin")))) 151 .bind(BeginCallName); 152 153 DeclarationMatcher InitDeclMatcher = 154 varDecl(hasInitializer(anyOf(ignoringParenImpCasts(BeginCallMatcher), 155 materializeTemporaryExpr( 156 ignoringParenImpCasts(BeginCallMatcher)), 157 hasDescendant(BeginCallMatcher)))) 158 .bind(InitVarName); 159 160 DeclarationMatcher EndDeclMatcher = 161 varDecl(hasInitializer(anything())).bind(EndVarName); 162 163 StatementMatcher EndCallMatcher = cxxMemberCallExpr( 164 argumentCountIs(0), callee(cxxMethodDecl(hasAnyName("end", "cend")))); 165 166 StatementMatcher IteratorBoundMatcher = 167 expr(anyOf(ignoringParenImpCasts( 168 declRefExpr(to(varDecl().bind(ConditionEndVarName)))), 169 ignoringParenImpCasts(expr(EndCallMatcher).bind(EndCallName)), 170 materializeTemporaryExpr(ignoringParenImpCasts( 171 expr(EndCallMatcher).bind(EndCallName))))); 172 173 StatementMatcher IteratorComparisonMatcher = expr( 174 ignoringParenImpCasts(declRefExpr(to(varDecl().bind(ConditionVarName))))); 175 176 auto OverloadedNEQMatcher = ignoringImplicit( 177 cxxOperatorCallExpr(hasOverloadedOperatorName("!="), argumentCountIs(2), 178 hasArgument(0, IteratorComparisonMatcher), 179 hasArgument(1, IteratorBoundMatcher))); 180 181 // This matcher tests that a declaration is a CXXRecordDecl that has an 182 // overloaded operator*(). If the operator*() returns by value instead of by 183 // reference then the return type is tagged with DerefByValueResultName. 184 internal::Matcher<VarDecl> TestDerefReturnsByValue = 185 hasType(hasUnqualifiedDesugaredType( 186 recordType(hasDeclaration(cxxRecordDecl(hasMethod(cxxMethodDecl( 187 hasOverloadedOperatorName("*"), 188 anyOf( 189 // Tag the return type if it's by value. 190 returns(qualType(unless(hasCanonicalType(referenceType()))) 191 .bind(DerefByValueResultName)), 192 returns( 193 // Skip loops where the iterator's operator* returns an 194 // rvalue reference. This is just weird. 195 qualType(unless(hasCanonicalType(rValueReferenceType()))) 196 .bind(DerefByRefResultName)))))))))); 197 198 return forStmt( 199 unless(isInTemplateInstantiation()), 200 hasLoopInit(anyOf(declStmt(declCountIs(2), 201 containsDeclaration(0, InitDeclMatcher), 202 containsDeclaration(1, EndDeclMatcher)), 203 declStmt(hasSingleDecl(InitDeclMatcher)))), 204 hasCondition( 205 anyOf(binaryOperator(hasOperatorName("!="), 206 hasLHS(IteratorComparisonMatcher), 207 hasRHS(IteratorBoundMatcher)), 208 binaryOperator(hasOperatorName("!="), 209 hasLHS(IteratorBoundMatcher), 210 hasRHS(IteratorComparisonMatcher)), 211 OverloadedNEQMatcher)), 212 hasIncrement(anyOf( 213 unaryOperator(hasOperatorName("++"), 214 hasUnaryOperand(declRefExpr( 215 to(varDecl(hasType(pointsTo(AnyType()))) 216 .bind(IncrementVarName))))), 217 cxxOperatorCallExpr( 218 hasOverloadedOperatorName("++"), 219 hasArgument( 220 0, declRefExpr(to(varDecl(TestDerefReturnsByValue) 221 .bind(IncrementVarName)))))))) 222 .bind(LoopNameIterator); 223 } 224 225 /// The matcher used for array-like containers (pseudoarrays). 226 /// 227 /// This matcher is more flexible than array-based loops. It will match 228 /// loops of the following textual forms (regardless of whether the 229 /// iterator type is actually a pointer type or a class type): 230 /// 231 /// Assuming f, g, and h are of type containerType::iterator, 232 /// \code 233 /// for (int i = 0, j = container.size(); f < g; ++h) { ... } 234 /// for (int i = 0; f < container.size(); ++h) { ... } 235 /// \endcode 236 /// The following string identifiers are bound to the parts of the AST: 237 /// InitVarName: 'i' (as a VarDecl) 238 /// ConditionVarName: 'f' (as a VarDecl) 239 /// LoopName: The entire for loop (as a ForStmt) 240 /// In the first example only: 241 /// EndVarName: 'j' (as a VarDecl) 242 /// ConditionEndVarName: 'g' (as a VarDecl) 243 /// In the second example only: 244 /// EndCallName: 'container.size()' (as a CXXMemberCallExpr) 245 /// 246 /// Client code will need to make sure that: 247 /// - The index variables 'i', 'f', and 'h' are the same. 248 /// - The containers on which 'size()' is called is the container indexed. 249 /// - The index variable is only used in overloaded operator[] or 250 /// container.at(). 251 /// - If the end iterator variable 'g' is defined, it is the same as 'j'. 252 /// - The container's iterators would not be invalidated during the loop. 253 StatementMatcher makePseudoArrayLoopMatcher() { 254 // Test that the incoming type has a record declaration that has methods 255 // called 'begin' and 'end'. If the incoming type is const, then make sure 256 // these methods are also marked const. 257 // 258 // FIXME: To be completely thorough this matcher should also ensure the 259 // return type of begin/end is an iterator that dereferences to the same as 260 // what operator[] or at() returns. Such a test isn't likely to fail except 261 // for pathological cases. 262 // 263 // FIXME: Also, a record doesn't necessarily need begin() and end(). Free 264 // functions called begin() and end() taking the container as an argument 265 // are also allowed. 266 TypeMatcher RecordWithBeginEnd = qualType(anyOf( 267 qualType( 268 isConstQualified(), 269 hasUnqualifiedDesugaredType(recordType(hasDeclaration(cxxRecordDecl( 270 hasMethod(cxxMethodDecl(hasName("begin"), isConst())), 271 hasMethod(cxxMethodDecl(hasName("end"), 272 isConst())))) // hasDeclaration 273 ))), // qualType 274 qualType(unless(isConstQualified()), 275 hasUnqualifiedDesugaredType(recordType(hasDeclaration( 276 cxxRecordDecl(hasMethod(hasName("begin")), 277 hasMethod(hasName("end"))))))) // qualType 278 )); 279 280 StatementMatcher SizeCallMatcher = cxxMemberCallExpr( 281 argumentCountIs(0), callee(cxxMethodDecl(hasAnyName("size", "length"))), 282 on(anyOf(hasType(pointsTo(RecordWithBeginEnd)), 283 hasType(RecordWithBeginEnd)))); 284 285 StatementMatcher EndInitMatcher = 286 expr(anyOf(ignoringParenImpCasts(expr(SizeCallMatcher).bind(EndCallName)), 287 explicitCastExpr(hasSourceExpression(ignoringParenImpCasts( 288 expr(SizeCallMatcher).bind(EndCallName)))))); 289 290 DeclarationMatcher EndDeclMatcher = 291 varDecl(hasInitializer(EndInitMatcher)).bind(EndVarName); 292 293 StatementMatcher IndexBoundMatcher = 294 expr(anyOf(ignoringParenImpCasts(declRefExpr(to( 295 varDecl(hasType(isInteger())).bind(ConditionEndVarName)))), 296 EndInitMatcher)); 297 298 return forStmt( 299 unless(isInTemplateInstantiation()), 300 hasLoopInit( 301 anyOf(declStmt(declCountIs(2), 302 containsDeclaration(0, InitToZeroMatcher()), 303 containsDeclaration(1, EndDeclMatcher)), 304 declStmt(hasSingleDecl(InitToZeroMatcher())))), 305 hasCondition(anyOf( 306 binaryOperator(hasOperatorName("<"), 307 hasLHS(IntegerComparisonMatcher()), 308 hasRHS(IndexBoundMatcher)), 309 binaryOperator(hasOperatorName(">"), hasLHS(IndexBoundMatcher), 310 hasRHS(IntegerComparisonMatcher())))), 311 hasIncrement(unaryOperator(hasOperatorName("++"), 312 hasUnaryOperand(IncrementVarMatcher())))) 313 .bind(LoopNamePseudoArray); 314 } 315 316 /// Determine whether Init appears to be an initializing an iterator. 317 /// 318 /// If it is, returns the object whose begin() or end() method is called, and 319 /// the output parameter isArrow is set to indicate whether the initialization 320 /// is called via . or ->. 321 static const Expr *getContainerFromBeginEndCall(const Expr *Init, bool IsBegin, 322 bool *IsArrow) { 323 // FIXME: Maybe allow declaration/initialization outside of the for loop. 324 const auto *TheCall = 325 dyn_cast_or_null<CXXMemberCallExpr>(digThroughConstructors(Init)); 326 if (!TheCall || TheCall->getNumArgs() != 0) 327 return nullptr; 328 329 const auto *Member = dyn_cast<MemberExpr>(TheCall->getCallee()); 330 if (!Member) 331 return nullptr; 332 StringRef Name = Member->getMemberDecl()->getName(); 333 StringRef TargetName = IsBegin ? "begin" : "end"; 334 StringRef ConstTargetName = IsBegin ? "cbegin" : "cend"; 335 if (Name != TargetName && Name != ConstTargetName) 336 return nullptr; 337 338 const Expr *SourceExpr = Member->getBase(); 339 if (!SourceExpr) 340 return nullptr; 341 342 *IsArrow = Member->isArrow(); 343 return SourceExpr; 344 } 345 346 /// Determines the container whose begin() and end() functions are called 347 /// for an iterator-based loop. 348 /// 349 /// BeginExpr must be a member call to a function named "begin()", and EndExpr 350 /// must be a member. 351 static const Expr *findContainer(ASTContext *Context, const Expr *BeginExpr, 352 const Expr *EndExpr, 353 bool *ContainerNeedsDereference) { 354 // Now that we know the loop variable and test expression, make sure they are 355 // valid. 356 bool BeginIsArrow = false; 357 bool EndIsArrow = false; 358 const Expr *BeginContainerExpr = 359 getContainerFromBeginEndCall(BeginExpr, /*IsBegin=*/true, &BeginIsArrow); 360 if (!BeginContainerExpr) 361 return nullptr; 362 363 const Expr *EndContainerExpr = 364 getContainerFromBeginEndCall(EndExpr, /*IsBegin=*/false, &EndIsArrow); 365 // Disallow loops that try evil things like this (note the dot and arrow): 366 // for (IteratorType It = Obj.begin(), E = Obj->end(); It != E; ++It) { } 367 if (!EndContainerExpr || BeginIsArrow != EndIsArrow || 368 !areSameExpr(Context, EndContainerExpr, BeginContainerExpr)) 369 return nullptr; 370 371 *ContainerNeedsDereference = BeginIsArrow; 372 return BeginContainerExpr; 373 } 374 375 /// Obtain the original source code text from a SourceRange. 376 static StringRef getStringFromRange(SourceManager &SourceMgr, 377 const LangOptions &LangOpts, 378 SourceRange Range) { 379 if (SourceMgr.getFileID(Range.getBegin()) != 380 SourceMgr.getFileID(Range.getEnd())) { 381 return StringRef(); // Empty string. 382 } 383 384 return Lexer::getSourceText(CharSourceRange(Range, true), SourceMgr, 385 LangOpts); 386 } 387 388 /// If the given expression is actually a DeclRefExpr or a MemberExpr, 389 /// find and return the underlying ValueDecl; otherwise, return NULL. 390 static const ValueDecl *getReferencedVariable(const Expr *E) { 391 if (const DeclRefExpr *DRE = getDeclRef(E)) 392 return dyn_cast<VarDecl>(DRE->getDecl()); 393 if (const auto *Mem = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts())) 394 return dyn_cast<FieldDecl>(Mem->getMemberDecl()); 395 return nullptr; 396 } 397 398 /// Returns true when the given expression is a member expression 399 /// whose base is `this` (implicitly or not). 400 static bool isDirectMemberExpr(const Expr *E) { 401 if (const auto *Member = dyn_cast<MemberExpr>(E->IgnoreParenImpCasts())) 402 return isa<CXXThisExpr>(Member->getBase()->IgnoreParenImpCasts()); 403 return false; 404 } 405 406 /// Given an expression that represents an usage of an element from the 407 /// containter that we are iterating over, returns false when it can be 408 /// guaranteed this element cannot be modified as a result of this usage. 409 static bool canBeModified(ASTContext *Context, const Expr *E) { 410 if (E->getType().isConstQualified()) 411 return false; 412 auto Parents = Context->getParents(*E); 413 if (Parents.size() != 1) 414 return true; 415 if (const auto *Cast = Parents[0].get<ImplicitCastExpr>()) { 416 if ((Cast->getCastKind() == CK_NoOp && 417 Cast->getType() == E->getType().withConst()) || 418 (Cast->getCastKind() == CK_LValueToRValue && 419 !Cast->getType().isNull() && Cast->getType()->isFundamentalType())) 420 return false; 421 } 422 // FIXME: Make this function more generic. 423 return true; 424 } 425 426 /// Returns true when it can be guaranteed that the elements of the 427 /// container are not being modified. 428 static bool usagesAreConst(ASTContext *Context, const UsageResult &Usages) { 429 for (const Usage &U : Usages) { 430 // Lambda captures are just redeclarations (VarDecl) of the same variable, 431 // not expressions. If we want to know if a variable that is captured by 432 // reference can be modified in an usage inside the lambda's body, we need 433 // to find the expression corresponding to that particular usage, later in 434 // this loop. 435 if (U.Kind != Usage::UK_CaptureByCopy && U.Kind != Usage::UK_CaptureByRef && 436 canBeModified(Context, U.Expression)) 437 return false; 438 } 439 return true; 440 } 441 442 /// Returns true if the elements of the container are never accessed 443 /// by reference. 444 static bool usagesReturnRValues(const UsageResult &Usages) { 445 for (const auto &U : Usages) { 446 if (U.Expression && !U.Expression->isRValue()) 447 return false; 448 } 449 return true; 450 } 451 452 /// Returns true if the container is const-qualified. 453 static bool containerIsConst(const Expr *ContainerExpr, bool Dereference) { 454 if (const auto *VDec = getReferencedVariable(ContainerExpr)) { 455 QualType CType = VDec->getType(); 456 if (Dereference) { 457 if (!CType->isPointerType()) 458 return false; 459 CType = CType->getPointeeType(); 460 } 461 // If VDec is a reference to a container, Dereference is false, 462 // but we still need to check the const-ness of the underlying container 463 // type. 464 CType = CType.getNonReferenceType(); 465 return CType.isConstQualified(); 466 } 467 return false; 468 } 469 470 LoopConvertCheck::RangeDescriptor::RangeDescriptor() 471 : ContainerNeedsDereference(false), DerefByConstRef(false), 472 DerefByValue(false) {} 473 474 LoopConvertCheck::LoopConvertCheck(StringRef Name, ClangTidyContext *Context) 475 : ClangTidyCheck(Name, Context), TUInfo(new TUTrackingInfo), 476 MaxCopySize(Options.get("MaxCopySize", 16ULL)), 477 MinConfidence(Options.get("MinConfidence", getConfidenceMapping(), 478 Confidence::CL_Reasonable)), 479 NamingStyle(Options.get("NamingStyle", getStyleMapping(), 480 VariableNamer::NS_CamelCase)) {} 481 482 void LoopConvertCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { 483 Options.store(Opts, "MaxCopySize", std::to_string(MaxCopySize)); 484 Options.store(Opts, "MinConfidence", MinConfidence, getConfidenceMapping()); 485 Options.store(Opts, "NamingStyle", NamingStyle, getStyleMapping()); 486 } 487 488 void LoopConvertCheck::registerMatchers(MatchFinder *Finder) { 489 Finder->addMatcher(traverse(ast_type_traits::TK_AsIs, makeArrayLoopMatcher()), 490 this); 491 Finder->addMatcher( 492 traverse(ast_type_traits::TK_AsIs, makeIteratorLoopMatcher()), this); 493 Finder->addMatcher( 494 traverse(ast_type_traits::TK_AsIs, 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 std::string VarName; 529 bool VarNameFromAlias = (Usages.size() == 1) && AliasDecl; 530 bool AliasVarIsRef = false; 531 bool CanCopy = true; 532 std::vector<FixItHint> FixIts; 533 if (VarNameFromAlias) { 534 const auto *AliasVar = cast<VarDecl>(AliasDecl->getSingleDecl()); 535 VarName = AliasVar->getName().str(); 536 537 // Use the type of the alias if it's not the same 538 QualType AliasVarType = AliasVar->getType(); 539 assert(!AliasVarType.isNull() && "Type in VarDecl is null"); 540 if (AliasVarType->isReferenceType()) { 541 AliasVarType = AliasVarType.getNonReferenceType(); 542 AliasVarIsRef = true; 543 } 544 if (Descriptor.ElemType.isNull() || 545 !Context->hasSameUnqualifiedType(AliasVarType, Descriptor.ElemType)) 546 Descriptor.ElemType = AliasVarType; 547 548 // We keep along the entire DeclStmt to keep the correct range here. 549 SourceRange ReplaceRange = AliasDecl->getSourceRange(); 550 551 std::string ReplacementText; 552 if (AliasUseRequired) { 553 ReplacementText = VarName; 554 } else if (AliasFromForInit) { 555 // FIXME: Clang includes the location of the ';' but only for DeclStmt's 556 // in a for loop's init clause. Need to put this ';' back while removing 557 // the declaration of the alias variable. This is probably a bug. 558 ReplacementText = ";"; 559 } else { 560 // Avoid leaving empty lines or trailing whitespaces. 561 getAliasRange(Context->getSourceManager(), ReplaceRange); 562 } 563 564 FixIts.push_back(FixItHint::CreateReplacement( 565 CharSourceRange::getTokenRange(ReplaceRange), ReplacementText)); 566 // No further replacements are made to the loop, since the iterator or index 567 // was used exactly once - in the initialization of AliasVar. 568 } else { 569 VariableNamer Namer(&TUInfo->getGeneratedDecls(), 570 &TUInfo->getParentFinder().getStmtToParentStmtMap(), 571 Loop, IndexVar, MaybeContainer, Context, NamingStyle); 572 VarName = Namer.createIndexName(); 573 // First, replace all usages of the array subscript expression with our new 574 // variable. 575 for (const auto &Usage : Usages) { 576 std::string ReplaceText; 577 SourceRange Range = Usage.Range; 578 if (Usage.Expression) { 579 // If this is an access to a member through the arrow operator, after 580 // the replacement it must be accessed through the '.' operator. 581 ReplaceText = Usage.Kind == Usage::UK_MemberThroughArrow ? VarName + "." 582 : VarName; 583 auto Parents = Context->getParents(*Usage.Expression); 584 if (Parents.size() == 1) { 585 if (const auto *Paren = Parents[0].get<ParenExpr>()) { 586 // Usage.Expression will be replaced with the new index variable, 587 // and parenthesis around a simple DeclRefExpr can always be 588 // removed. 589 Range = Paren->getSourceRange(); 590 } else if (const auto *UOP = Parents[0].get<UnaryOperator>()) { 591 // If we are taking the address of the loop variable, then we must 592 // not use a copy, as it would mean taking the address of the loop's 593 // local index instead. 594 // FIXME: This won't catch cases where the address is taken outside 595 // of the loop's body (for instance, in a function that got the 596 // loop's index as a const reference parameter), or where we take 597 // the address of a member (like "&Arr[i].A.B.C"). 598 if (UOP->getOpcode() == UO_AddrOf) 599 CanCopy = false; 600 } 601 } 602 } else { 603 // The Usage expression is only null in case of lambda captures (which 604 // are VarDecl). If the index is captured by value, add '&' to capture 605 // by reference instead. 606 ReplaceText = 607 Usage.Kind == Usage::UK_CaptureByCopy ? "&" + VarName : VarName; 608 } 609 TUInfo->getReplacedVars().insert(std::make_pair(Loop, IndexVar)); 610 FixIts.push_back(FixItHint::CreateReplacement( 611 CharSourceRange::getTokenRange(Range), ReplaceText)); 612 } 613 } 614 615 // Now, we need to construct the new range expression. 616 SourceRange ParenRange(Loop->getLParenLoc(), Loop->getRParenLoc()); 617 618 QualType Type = Context->getAutoDeductType(); 619 if (!Descriptor.ElemType.isNull() && Descriptor.ElemType->isFundamentalType()) 620 Type = Descriptor.ElemType.getUnqualifiedType(); 621 Type = Type.getDesugaredType(*Context); 622 623 // If the new variable name is from the aliased variable, then the reference 624 // type for the new variable should only be used if the aliased variable was 625 // declared as a reference. 626 bool IsCheapToCopy = 627 !Descriptor.ElemType.isNull() && 628 Descriptor.ElemType.isTriviallyCopyableType(*Context) && 629 // TypeInfo::Width is in bits. 630 Context->getTypeInfo(Descriptor.ElemType).Width <= 8 * MaxCopySize; 631 bool UseCopy = CanCopy && ((VarNameFromAlias && !AliasVarIsRef) || 632 (Descriptor.DerefByConstRef && IsCheapToCopy)); 633 634 if (!UseCopy) { 635 if (Descriptor.DerefByConstRef) { 636 Type = Context->getLValueReferenceType(Context->getConstType(Type)); 637 } else if (Descriptor.DerefByValue) { 638 if (!IsCheapToCopy) 639 Type = Context->getRValueReferenceType(Type); 640 } else { 641 Type = Context->getLValueReferenceType(Type); 642 } 643 } 644 645 StringRef MaybeDereference = Descriptor.ContainerNeedsDereference ? "*" : ""; 646 std::string TypeString = Type.getAsString(getLangOpts()); 647 std::string Range = ("(" + TypeString + " " + VarName + " : " + 648 MaybeDereference + Descriptor.ContainerString + ")") 649 .str(); 650 FixIts.push_back(FixItHint::CreateReplacement( 651 CharSourceRange::getTokenRange(ParenRange), Range)); 652 diag(Loop->getForLoc(), "use range-based for loop instead") << FixIts; 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 TraversalKindScope RAII(*Context, ast_type_traits::TK_AsIs); 902 const UsageResult &Usages = Finder.getUsages(); 903 determineRangeDescriptor(Context, Nodes, Loop, FixerKind, ContainerExpr, 904 Usages, Descriptor); 905 906 // Ensure that we do not try to move an expression dependent on a local 907 // variable declared inside the loop outside of it. 908 // FIXME: Determine when the external dependency isn't an expression converted 909 // by another loop. 910 TUInfo->getParentFinder().gatherAncestors(*Context); 911 DependencyFinderASTVisitor DependencyFinder( 912 &TUInfo->getParentFinder().getStmtToParentStmtMap(), 913 &TUInfo->getParentFinder().getDeclToParentStmtMap(), 914 &TUInfo->getReplacedVars(), Loop); 915 916 if (DependencyFinder.dependsOnInsideVariable(ContainerExpr) || 917 Descriptor.ContainerString.empty() || Usages.empty() || 918 ConfidenceLevel.getLevel() < MinConfidence) 919 return; 920 921 doConversion(Context, LoopVar, getReferencedVariable(ContainerExpr), Usages, 922 Finder.getAliasDecl(), Finder.aliasUseRequired(), 923 Finder.aliasFromForInit(), Loop, Descriptor); 924 } 925 926 } // namespace modernize 927 } // namespace tidy 928 } // namespace clang 929