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