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(traverse(ast_type_traits::TK_AsIs, makeArrayLoopMatcher()), 493 this); 494 Finder->addMatcher( 495 traverse(ast_type_traits::TK_AsIs, makeIteratorLoopMatcher()), this); 496 Finder->addMatcher( 497 traverse(ast_type_traits::TK_AsIs, makePseudoArrayLoopMatcher()), this); 498 } 499 500 /// Given the range of a single declaration, such as: 501 /// \code 502 /// unsigned &ThisIsADeclarationThatCanSpanSeveralLinesOfCode = 503 /// InitializationValues[I]; 504 /// next_instruction; 505 /// \endcode 506 /// Finds the range that has to be erased to remove this declaration without 507 /// leaving empty lines, by extending the range until the beginning of the 508 /// next instruction. 509 /// 510 /// We need to delete a potential newline after the deleted alias, as 511 /// clang-format will leave empty lines untouched. For all other formatting we 512 /// rely on clang-format to fix it. 513 void LoopConvertCheck::getAliasRange(SourceManager &SM, SourceRange &Range) { 514 bool Invalid = false; 515 const char *TextAfter = 516 SM.getCharacterData(Range.getEnd().getLocWithOffset(1), &Invalid); 517 if (Invalid) 518 return; 519 unsigned Offset = std::strspn(TextAfter, " \t\r\n"); 520 Range = 521 SourceRange(Range.getBegin(), Range.getEnd().getLocWithOffset(Offset)); 522 } 523 524 /// Computes the changes needed to convert a given for loop, and 525 /// applies them. 526 void LoopConvertCheck::doConversion( 527 ASTContext *Context, const VarDecl *IndexVar, 528 const ValueDecl *MaybeContainer, const UsageResult &Usages, 529 const DeclStmt *AliasDecl, bool AliasUseRequired, bool AliasFromForInit, 530 const ForStmt *Loop, RangeDescriptor Descriptor) { 531 std::string VarName; 532 bool VarNameFromAlias = (Usages.size() == 1) && AliasDecl; 533 bool AliasVarIsRef = false; 534 bool CanCopy = true; 535 std::vector<FixItHint> FixIts; 536 if (VarNameFromAlias) { 537 const auto *AliasVar = cast<VarDecl>(AliasDecl->getSingleDecl()); 538 VarName = AliasVar->getName().str(); 539 540 // Use the type of the alias if it's not the same 541 QualType AliasVarType = AliasVar->getType(); 542 assert(!AliasVarType.isNull() && "Type in VarDecl is null"); 543 if (AliasVarType->isReferenceType()) { 544 AliasVarType = AliasVarType.getNonReferenceType(); 545 AliasVarIsRef = true; 546 } 547 if (Descriptor.ElemType.isNull() || 548 !Context->hasSameUnqualifiedType(AliasVarType, Descriptor.ElemType)) 549 Descriptor.ElemType = AliasVarType; 550 551 // We keep along the entire DeclStmt to keep the correct range here. 552 SourceRange ReplaceRange = AliasDecl->getSourceRange(); 553 554 std::string ReplacementText; 555 if (AliasUseRequired) { 556 ReplacementText = VarName; 557 } else if (AliasFromForInit) { 558 // FIXME: Clang includes the location of the ';' but only for DeclStmt's 559 // in a for loop's init clause. Need to put this ';' back while removing 560 // the declaration of the alias variable. This is probably a bug. 561 ReplacementText = ";"; 562 } else { 563 // Avoid leaving empty lines or trailing whitespaces. 564 getAliasRange(Context->getSourceManager(), ReplaceRange); 565 } 566 567 FixIts.push_back(FixItHint::CreateReplacement( 568 CharSourceRange::getTokenRange(ReplaceRange), ReplacementText)); 569 // No further replacements are made to the loop, since the iterator or index 570 // was used exactly once - in the initialization of AliasVar. 571 } else { 572 VariableNamer Namer(&TUInfo->getGeneratedDecls(), 573 &TUInfo->getParentFinder().getStmtToParentStmtMap(), 574 Loop, IndexVar, MaybeContainer, Context, NamingStyle); 575 VarName = Namer.createIndexName(); 576 // First, replace all usages of the array subscript expression with our new 577 // variable. 578 for (const auto &Usage : Usages) { 579 std::string ReplaceText; 580 SourceRange Range = Usage.Range; 581 if (Usage.Expression) { 582 // If this is an access to a member through the arrow operator, after 583 // the replacement it must be accessed through the '.' operator. 584 ReplaceText = Usage.Kind == Usage::UK_MemberThroughArrow ? VarName + "." 585 : VarName; 586 auto Parents = Context->getParents(*Usage.Expression); 587 if (Parents.size() == 1) { 588 if (const auto *Paren = Parents[0].get<ParenExpr>()) { 589 // Usage.Expression will be replaced with the new index variable, 590 // and parenthesis around a simple DeclRefExpr can always be 591 // removed. 592 Range = Paren->getSourceRange(); 593 } else if (const auto *UOP = Parents[0].get<UnaryOperator>()) { 594 // If we are taking the address of the loop variable, then we must 595 // not use a copy, as it would mean taking the address of the loop's 596 // local index instead. 597 // FIXME: This won't catch cases where the address is taken outside 598 // of the loop's body (for instance, in a function that got the 599 // loop's index as a const reference parameter), or where we take 600 // the address of a member (like "&Arr[i].A.B.C"). 601 if (UOP->getOpcode() == UO_AddrOf) 602 CanCopy = false; 603 } 604 } 605 } else { 606 // The Usage expression is only null in case of lambda captures (which 607 // are VarDecl). If the index is captured by value, add '&' to capture 608 // by reference instead. 609 ReplaceText = 610 Usage.Kind == Usage::UK_CaptureByCopy ? "&" + VarName : VarName; 611 } 612 TUInfo->getReplacedVars().insert(std::make_pair(Loop, IndexVar)); 613 FixIts.push_back(FixItHint::CreateReplacement( 614 CharSourceRange::getTokenRange(Range), ReplaceText)); 615 } 616 } 617 618 // Now, we need to construct the new range expression. 619 SourceRange ParenRange(Loop->getLParenLoc(), Loop->getRParenLoc()); 620 621 QualType Type = Context->getAutoDeductType(); 622 if (!Descriptor.ElemType.isNull() && Descriptor.ElemType->isFundamentalType()) 623 Type = Descriptor.ElemType.getUnqualifiedType(); 624 Type = Type.getDesugaredType(*Context); 625 626 // If the new variable name is from the aliased variable, then the reference 627 // type for the new variable should only be used if the aliased variable was 628 // declared as a reference. 629 bool IsCheapToCopy = 630 !Descriptor.ElemType.isNull() && 631 Descriptor.ElemType.isTriviallyCopyableType(*Context) && 632 // TypeInfo::Width is in bits. 633 Context->getTypeInfo(Descriptor.ElemType).Width <= 8 * MaxCopySize; 634 bool UseCopy = CanCopy && ((VarNameFromAlias && !AliasVarIsRef) || 635 (Descriptor.DerefByConstRef && IsCheapToCopy)); 636 637 if (!UseCopy) { 638 if (Descriptor.DerefByConstRef) { 639 Type = Context->getLValueReferenceType(Context->getConstType(Type)); 640 } else if (Descriptor.DerefByValue) { 641 if (!IsCheapToCopy) 642 Type = Context->getRValueReferenceType(Type); 643 } else { 644 Type = Context->getLValueReferenceType(Type); 645 } 646 } 647 648 StringRef MaybeDereference = Descriptor.ContainerNeedsDereference ? "*" : ""; 649 std::string TypeString = Type.getAsString(getLangOpts()); 650 std::string Range = ("(" + TypeString + " " + VarName + " : " + 651 MaybeDereference + Descriptor.ContainerString + ")") 652 .str(); 653 FixIts.push_back(FixItHint::CreateReplacement( 654 CharSourceRange::getTokenRange(ParenRange), Range)); 655 diag(Loop->getForLoc(), "use range-based for loop instead") << FixIts; 656 TUInfo->getGeneratedDecls().insert(make_pair(Loop, VarName)); 657 } 658 659 /// Returns a string which refers to the container iterated over. 660 StringRef LoopConvertCheck::getContainerString(ASTContext *Context, 661 const ForStmt *Loop, 662 const Expr *ContainerExpr) { 663 StringRef ContainerString; 664 ContainerExpr = ContainerExpr->IgnoreParenImpCasts(); 665 if (isa<CXXThisExpr>(ContainerExpr)) { 666 ContainerString = "this"; 667 } else { 668 // For CXXOperatorCallExpr (e.g. vector_ptr->size()), its first argument is 669 // the class object (vector_ptr) we are targeting. 670 if (const auto* E = dyn_cast<CXXOperatorCallExpr>(ContainerExpr)) 671 ContainerExpr = E->getArg(0); 672 ContainerString = 673 getStringFromRange(Context->getSourceManager(), Context->getLangOpts(), 674 ContainerExpr->getSourceRange()); 675 } 676 677 return ContainerString; 678 } 679 680 /// Determines what kind of 'auto' must be used after converting a for 681 /// loop that iterates over an array or pseudoarray. 682 void LoopConvertCheck::getArrayLoopQualifiers(ASTContext *Context, 683 const BoundNodes &Nodes, 684 const Expr *ContainerExpr, 685 const UsageResult &Usages, 686 RangeDescriptor &Descriptor) { 687 // On arrays and pseudoarrays, we must figure out the qualifiers from the 688 // usages. 689 if (usagesAreConst(Context, Usages) || 690 containerIsConst(ContainerExpr, Descriptor.ContainerNeedsDereference)) { 691 Descriptor.DerefByConstRef = true; 692 } 693 if (usagesReturnRValues(Usages)) { 694 // If the index usages (dereference, subscript, at, ...) return rvalues, 695 // then we should not use a reference, because we need to keep the code 696 // correct if it mutates the returned objects. 697 Descriptor.DerefByValue = true; 698 } 699 // Try to find the type of the elements on the container, to check if 700 // they are trivially copyable. 701 for (const Usage &U : Usages) { 702 if (!U.Expression || U.Expression->getType().isNull()) 703 continue; 704 QualType Type = U.Expression->getType().getCanonicalType(); 705 if (U.Kind == Usage::UK_MemberThroughArrow) { 706 if (!Type->isPointerType()) { 707 continue; 708 } 709 Type = Type->getPointeeType(); 710 } 711 Descriptor.ElemType = Type; 712 } 713 } 714 715 /// Determines what kind of 'auto' must be used after converting an 716 /// iterator based for loop. 717 void LoopConvertCheck::getIteratorLoopQualifiers(ASTContext *Context, 718 const BoundNodes &Nodes, 719 RangeDescriptor &Descriptor) { 720 // The matchers for iterator loops provide bound nodes to obtain this 721 // information. 722 const auto *InitVar = Nodes.getNodeAs<VarDecl>(InitVarName); 723 QualType CanonicalInitVarType = InitVar->getType().getCanonicalType(); 724 const auto *DerefByValueType = 725 Nodes.getNodeAs<QualType>(DerefByValueResultName); 726 Descriptor.DerefByValue = DerefByValueType; 727 728 if (Descriptor.DerefByValue) { 729 // If the dereference operator returns by value then test for the 730 // canonical const qualification of the init variable type. 731 Descriptor.DerefByConstRef = CanonicalInitVarType.isConstQualified(); 732 Descriptor.ElemType = *DerefByValueType; 733 } else { 734 if (const auto *DerefType = 735 Nodes.getNodeAs<QualType>(DerefByRefResultName)) { 736 // A node will only be bound with DerefByRefResultName if we're dealing 737 // with a user-defined iterator type. Test the const qualification of 738 // the reference type. 739 auto ValueType = DerefType->getNonReferenceType(); 740 741 Descriptor.DerefByConstRef = ValueType.isConstQualified(); 742 Descriptor.ElemType = ValueType; 743 } else { 744 // By nature of the matcher this case is triggered only for built-in 745 // iterator types (i.e. pointers). 746 assert(isa<PointerType>(CanonicalInitVarType) && 747 "Non-class iterator type is not a pointer type"); 748 749 // We test for const qualification of the pointed-at type. 750 Descriptor.DerefByConstRef = 751 CanonicalInitVarType->getPointeeType().isConstQualified(); 752 Descriptor.ElemType = CanonicalInitVarType->getPointeeType(); 753 } 754 } 755 } 756 757 /// Determines the parameters needed to build the range replacement. 758 void LoopConvertCheck::determineRangeDescriptor( 759 ASTContext *Context, const BoundNodes &Nodes, const ForStmt *Loop, 760 LoopFixerKind FixerKind, const Expr *ContainerExpr, 761 const UsageResult &Usages, RangeDescriptor &Descriptor) { 762 Descriptor.ContainerString = 763 std::string(getContainerString(Context, Loop, ContainerExpr)); 764 765 if (FixerKind == LFK_Iterator) 766 getIteratorLoopQualifiers(Context, Nodes, Descriptor); 767 else 768 getArrayLoopQualifiers(Context, Nodes, ContainerExpr, Usages, Descriptor); 769 } 770 771 /// Check some of the conditions that must be met for the loop to be 772 /// convertible. 773 bool LoopConvertCheck::isConvertible(ASTContext *Context, 774 const ast_matchers::BoundNodes &Nodes, 775 const ForStmt *Loop, 776 LoopFixerKind FixerKind) { 777 // If we already modified the range of this for loop, don't do any further 778 // updates on this iteration. 779 if (TUInfo->getReplacedVars().count(Loop)) 780 return false; 781 782 // Check that we have exactly one index variable and at most one end variable. 783 const auto *LoopVar = Nodes.getNodeAs<VarDecl>(IncrementVarName); 784 const auto *CondVar = Nodes.getNodeAs<VarDecl>(ConditionVarName); 785 const auto *InitVar = Nodes.getNodeAs<VarDecl>(InitVarName); 786 if (!areSameVariable(LoopVar, CondVar) || !areSameVariable(LoopVar, InitVar)) 787 return false; 788 const auto *EndVar = Nodes.getNodeAs<VarDecl>(EndVarName); 789 const auto *ConditionEndVar = Nodes.getNodeAs<VarDecl>(ConditionEndVarName); 790 if (EndVar && !areSameVariable(EndVar, ConditionEndVar)) 791 return false; 792 793 // FIXME: Try to put most of this logic inside a matcher. 794 if (FixerKind == LFK_Iterator) { 795 QualType InitVarType = InitVar->getType(); 796 QualType CanonicalInitVarType = InitVarType.getCanonicalType(); 797 798 const auto *BeginCall = Nodes.getNodeAs<CXXMemberCallExpr>(BeginCallName); 799 assert(BeginCall && "Bad Callback. No begin call expression"); 800 QualType CanonicalBeginType = 801 BeginCall->getMethodDecl()->getReturnType().getCanonicalType(); 802 if (CanonicalBeginType->isPointerType() && 803 CanonicalInitVarType->isPointerType()) { 804 // If the initializer and the variable are both pointers check if the 805 // un-qualified pointee types match, otherwise we don't use auto. 806 if (!Context->hasSameUnqualifiedType( 807 CanonicalBeginType->getPointeeType(), 808 CanonicalInitVarType->getPointeeType())) 809 return false; 810 } 811 } else if (FixerKind == LFK_PseudoArray) { 812 // This call is required to obtain the container. 813 const auto *EndCall = Nodes.getNodeAs<CXXMemberCallExpr>(EndCallName); 814 if (!EndCall || !dyn_cast<MemberExpr>(EndCall->getCallee())) 815 return false; 816 } 817 return true; 818 } 819 820 void LoopConvertCheck::check(const MatchFinder::MatchResult &Result) { 821 const BoundNodes &Nodes = Result.Nodes; 822 Confidence ConfidenceLevel(Confidence::CL_Safe); 823 ASTContext *Context = Result.Context; 824 825 const ForStmt *Loop; 826 LoopFixerKind FixerKind; 827 RangeDescriptor Descriptor; 828 829 if ((Loop = Nodes.getNodeAs<ForStmt>(LoopNameArray))) { 830 FixerKind = LFK_Array; 831 } else if ((Loop = Nodes.getNodeAs<ForStmt>(LoopNameIterator))) { 832 FixerKind = LFK_Iterator; 833 } else { 834 Loop = Nodes.getNodeAs<ForStmt>(LoopNamePseudoArray); 835 assert(Loop && "Bad Callback. No for statement"); 836 FixerKind = LFK_PseudoArray; 837 } 838 839 if (!isConvertible(Context, Nodes, Loop, FixerKind)) 840 return; 841 842 const auto *LoopVar = Nodes.getNodeAs<VarDecl>(IncrementVarName); 843 const auto *EndVar = Nodes.getNodeAs<VarDecl>(EndVarName); 844 845 // If the loop calls end()/size() after each iteration, lower our confidence 846 // level. 847 if (FixerKind != LFK_Array && !EndVar) 848 ConfidenceLevel.lowerTo(Confidence::CL_Reasonable); 849 850 // If the end comparison isn't a variable, we can try to work with the 851 // expression the loop variable is being tested against instead. 852 const auto *EndCall = Nodes.getNodeAs<CXXMemberCallExpr>(EndCallName); 853 const auto *BoundExpr = Nodes.getNodeAs<Expr>(ConditionBoundName); 854 855 // Find container expression of iterators and pseudoarrays, and determine if 856 // this expression needs to be dereferenced to obtain the container. 857 // With array loops, the container is often discovered during the 858 // ForLoopIndexUseVisitor traversal. 859 const Expr *ContainerExpr = nullptr; 860 if (FixerKind == LFK_Iterator) { 861 ContainerExpr = findContainer(Context, LoopVar->getInit(), 862 EndVar ? EndVar->getInit() : EndCall, 863 &Descriptor.ContainerNeedsDereference); 864 } else if (FixerKind == LFK_PseudoArray) { 865 ContainerExpr = EndCall->getImplicitObjectArgument(); 866 Descriptor.ContainerNeedsDereference = 867 dyn_cast<MemberExpr>(EndCall->getCallee())->isArrow(); 868 } 869 870 // We must know the container or an array length bound. 871 if (!ContainerExpr && !BoundExpr) 872 return; 873 874 ForLoopIndexUseVisitor Finder(Context, LoopVar, EndVar, ContainerExpr, 875 BoundExpr, 876 Descriptor.ContainerNeedsDereference); 877 878 // Find expressions and variables on which the container depends. 879 if (ContainerExpr) { 880 ComponentFinderASTVisitor ComponentFinder; 881 ComponentFinder.findExprComponents(ContainerExpr->IgnoreParenImpCasts()); 882 Finder.addComponents(ComponentFinder.getComponents()); 883 } 884 885 // Find usages of the loop index. If they are not used in a convertible way, 886 // stop here. 887 if (!Finder.findAndVerifyUsages(Loop->getBody())) 888 return; 889 ConfidenceLevel.lowerTo(Finder.getConfidenceLevel()); 890 891 // Obtain the container expression, if we don't have it yet. 892 if (FixerKind == LFK_Array) { 893 ContainerExpr = Finder.getContainerIndexed()->IgnoreParenImpCasts(); 894 895 // Very few loops are over expressions that generate arrays rather than 896 // array variables. Consider loops over arrays that aren't just represented 897 // by a variable to be risky conversions. 898 if (!getReferencedVariable(ContainerExpr) && 899 !isDirectMemberExpr(ContainerExpr)) 900 ConfidenceLevel.lowerTo(Confidence::CL_Risky); 901 } 902 903 // Find out which qualifiers we have to use in the loop range. 904 TraversalKindScope RAII(*Context, ast_type_traits::TK_AsIs); 905 const UsageResult &Usages = Finder.getUsages(); 906 determineRangeDescriptor(Context, Nodes, Loop, FixerKind, ContainerExpr, 907 Usages, Descriptor); 908 909 // Ensure that we do not try to move an expression dependent on a local 910 // variable declared inside the loop outside of it. 911 // FIXME: Determine when the external dependency isn't an expression converted 912 // by another loop. 913 TUInfo->getParentFinder().gatherAncestors(*Context); 914 DependencyFinderASTVisitor DependencyFinder( 915 &TUInfo->getParentFinder().getStmtToParentStmtMap(), 916 &TUInfo->getParentFinder().getDeclToParentStmtMap(), 917 &TUInfo->getReplacedVars(), Loop); 918 919 if (DependencyFinder.dependsOnInsideVariable(ContainerExpr) || 920 Descriptor.ContainerString.empty() || Usages.empty() || 921 ConfidenceLevel.getLevel() < MinConfidence) 922 return; 923 924 doConversion(Context, LoopVar, getReferencedVariable(ContainerExpr), Usages, 925 Finder.getAliasDecl(), Finder.aliasUseRequired(), 926 Finder.aliasFromForInit(), Loop, Descriptor); 927 } 928 929 } // namespace modernize 930 } // namespace tidy 931 } // namespace clang 932