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