17330f729Sjoerg //===--- CloneDetection.cpp - Finds code clones in an AST -------*- C++ -*-===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg ///
97330f729Sjoerg /// This file implements classes for searching and analyzing source code clones.
107330f729Sjoerg ///
117330f729Sjoerg //===----------------------------------------------------------------------===//
127330f729Sjoerg
137330f729Sjoerg #include "clang/Analysis/CloneDetection.h"
14*e038c9c4Sjoerg #include "clang/AST/Attr.h"
157330f729Sjoerg #include "clang/AST/DataCollection.h"
167330f729Sjoerg #include "clang/AST/DeclTemplate.h"
17*e038c9c4Sjoerg #include "clang/Basic/SourceManager.h"
187330f729Sjoerg #include "llvm/Support/MD5.h"
197330f729Sjoerg #include "llvm/Support/Path.h"
207330f729Sjoerg
217330f729Sjoerg using namespace clang;
227330f729Sjoerg
StmtSequence(const CompoundStmt * Stmt,const Decl * D,unsigned StartIndex,unsigned EndIndex)237330f729Sjoerg StmtSequence::StmtSequence(const CompoundStmt *Stmt, const Decl *D,
247330f729Sjoerg unsigned StartIndex, unsigned EndIndex)
257330f729Sjoerg : S(Stmt), D(D), StartIndex(StartIndex), EndIndex(EndIndex) {
267330f729Sjoerg assert(Stmt && "Stmt must not be a nullptr");
277330f729Sjoerg assert(StartIndex < EndIndex && "Given array should not be empty");
287330f729Sjoerg assert(EndIndex <= Stmt->size() && "Given array too big for this Stmt");
297330f729Sjoerg }
307330f729Sjoerg
StmtSequence(const Stmt * Stmt,const Decl * D)317330f729Sjoerg StmtSequence::StmtSequence(const Stmt *Stmt, const Decl *D)
327330f729Sjoerg : S(Stmt), D(D), StartIndex(0), EndIndex(0) {}
337330f729Sjoerg
StmtSequence()347330f729Sjoerg StmtSequence::StmtSequence()
357330f729Sjoerg : S(nullptr), D(nullptr), StartIndex(0), EndIndex(0) {}
367330f729Sjoerg
contains(const StmtSequence & Other) const377330f729Sjoerg bool StmtSequence::contains(const StmtSequence &Other) const {
387330f729Sjoerg // If both sequences reside in different declarations, they can never contain
397330f729Sjoerg // each other.
407330f729Sjoerg if (D != Other.D)
417330f729Sjoerg return false;
427330f729Sjoerg
437330f729Sjoerg const SourceManager &SM = getASTContext().getSourceManager();
447330f729Sjoerg
457330f729Sjoerg // Otherwise check if the start and end locations of the current sequence
467330f729Sjoerg // surround the other sequence.
477330f729Sjoerg bool StartIsInBounds =
487330f729Sjoerg SM.isBeforeInTranslationUnit(getBeginLoc(), Other.getBeginLoc()) ||
497330f729Sjoerg getBeginLoc() == Other.getBeginLoc();
507330f729Sjoerg if (!StartIsInBounds)
517330f729Sjoerg return false;
527330f729Sjoerg
537330f729Sjoerg bool EndIsInBounds =
547330f729Sjoerg SM.isBeforeInTranslationUnit(Other.getEndLoc(), getEndLoc()) ||
557330f729Sjoerg Other.getEndLoc() == getEndLoc();
567330f729Sjoerg return EndIsInBounds;
577330f729Sjoerg }
587330f729Sjoerg
begin() const597330f729Sjoerg StmtSequence::iterator StmtSequence::begin() const {
607330f729Sjoerg if (!holdsSequence()) {
617330f729Sjoerg return &S;
627330f729Sjoerg }
637330f729Sjoerg auto CS = cast<CompoundStmt>(S);
647330f729Sjoerg return CS->body_begin() + StartIndex;
657330f729Sjoerg }
667330f729Sjoerg
end() const677330f729Sjoerg StmtSequence::iterator StmtSequence::end() const {
687330f729Sjoerg if (!holdsSequence()) {
697330f729Sjoerg return reinterpret_cast<StmtSequence::iterator>(&S) + 1;
707330f729Sjoerg }
717330f729Sjoerg auto CS = cast<CompoundStmt>(S);
727330f729Sjoerg return CS->body_begin() + EndIndex;
737330f729Sjoerg }
747330f729Sjoerg
getASTContext() const757330f729Sjoerg ASTContext &StmtSequence::getASTContext() const {
767330f729Sjoerg assert(D);
777330f729Sjoerg return D->getASTContext();
787330f729Sjoerg }
797330f729Sjoerg
getBeginLoc() const807330f729Sjoerg SourceLocation StmtSequence::getBeginLoc() const {
817330f729Sjoerg return front()->getBeginLoc();
827330f729Sjoerg }
837330f729Sjoerg
getEndLoc() const847330f729Sjoerg SourceLocation StmtSequence::getEndLoc() const { return back()->getEndLoc(); }
857330f729Sjoerg
getSourceRange() const867330f729Sjoerg SourceRange StmtSequence::getSourceRange() const {
877330f729Sjoerg return SourceRange(getBeginLoc(), getEndLoc());
887330f729Sjoerg }
897330f729Sjoerg
analyzeCodeBody(const Decl * D)907330f729Sjoerg void CloneDetector::analyzeCodeBody(const Decl *D) {
917330f729Sjoerg assert(D);
927330f729Sjoerg assert(D->hasBody());
937330f729Sjoerg
947330f729Sjoerg Sequences.push_back(StmtSequence(D->getBody(), D));
957330f729Sjoerg }
967330f729Sjoerg
977330f729Sjoerg /// Returns true if and only if \p Stmt contains at least one other
987330f729Sjoerg /// sequence in the \p Group.
containsAnyInGroup(StmtSequence & Seq,CloneDetector::CloneGroup & Group)997330f729Sjoerg static bool containsAnyInGroup(StmtSequence &Seq,
1007330f729Sjoerg CloneDetector::CloneGroup &Group) {
1017330f729Sjoerg for (StmtSequence &GroupSeq : Group) {
1027330f729Sjoerg if (Seq.contains(GroupSeq))
1037330f729Sjoerg return true;
1047330f729Sjoerg }
1057330f729Sjoerg return false;
1067330f729Sjoerg }
1077330f729Sjoerg
1087330f729Sjoerg /// Returns true if and only if all sequences in \p OtherGroup are
1097330f729Sjoerg /// contained by a sequence in \p Group.
containsGroup(CloneDetector::CloneGroup & Group,CloneDetector::CloneGroup & OtherGroup)1107330f729Sjoerg static bool containsGroup(CloneDetector::CloneGroup &Group,
1117330f729Sjoerg CloneDetector::CloneGroup &OtherGroup) {
1127330f729Sjoerg // We have less sequences in the current group than we have in the other,
1137330f729Sjoerg // so we will never fulfill the requirement for returning true. This is only
1147330f729Sjoerg // possible because we know that a sequence in Group can contain at most
1157330f729Sjoerg // one sequence in OtherGroup.
1167330f729Sjoerg if (Group.size() < OtherGroup.size())
1177330f729Sjoerg return false;
1187330f729Sjoerg
1197330f729Sjoerg for (StmtSequence &Stmt : Group) {
1207330f729Sjoerg if (!containsAnyInGroup(Stmt, OtherGroup))
1217330f729Sjoerg return false;
1227330f729Sjoerg }
1237330f729Sjoerg return true;
1247330f729Sjoerg }
1257330f729Sjoerg
constrain(std::vector<CloneDetector::CloneGroup> & Result)1267330f729Sjoerg void OnlyLargestCloneConstraint::constrain(
1277330f729Sjoerg std::vector<CloneDetector::CloneGroup> &Result) {
1287330f729Sjoerg std::vector<unsigned> IndexesToRemove;
1297330f729Sjoerg
1307330f729Sjoerg // Compare every group in the result with the rest. If one groups contains
1317330f729Sjoerg // another group, we only need to return the bigger group.
1327330f729Sjoerg // Note: This doesn't scale well, so if possible avoid calling any heavy
1337330f729Sjoerg // function from this loop to minimize the performance impact.
1347330f729Sjoerg for (unsigned i = 0; i < Result.size(); ++i) {
1357330f729Sjoerg for (unsigned j = 0; j < Result.size(); ++j) {
1367330f729Sjoerg // Don't compare a group with itself.
1377330f729Sjoerg if (i == j)
1387330f729Sjoerg continue;
1397330f729Sjoerg
1407330f729Sjoerg if (containsGroup(Result[j], Result[i])) {
1417330f729Sjoerg IndexesToRemove.push_back(i);
1427330f729Sjoerg break;
1437330f729Sjoerg }
1447330f729Sjoerg }
1457330f729Sjoerg }
1467330f729Sjoerg
1477330f729Sjoerg // Erasing a list of indexes from the vector should be done with decreasing
1487330f729Sjoerg // indexes. As IndexesToRemove is constructed with increasing values, we just
1497330f729Sjoerg // reverse iterate over it to get the desired order.
1507330f729Sjoerg for (auto I = IndexesToRemove.rbegin(); I != IndexesToRemove.rend(); ++I) {
1517330f729Sjoerg Result.erase(Result.begin() + *I);
1527330f729Sjoerg }
1537330f729Sjoerg }
1547330f729Sjoerg
isAutoGenerated(const CloneDetector::CloneGroup & Group)1557330f729Sjoerg bool FilenamePatternConstraint::isAutoGenerated(
1567330f729Sjoerg const CloneDetector::CloneGroup &Group) {
1577330f729Sjoerg if (IgnoredFilesPattern.empty() || Group.empty() ||
1587330f729Sjoerg !IgnoredFilesRegex->isValid())
1597330f729Sjoerg return false;
1607330f729Sjoerg
1617330f729Sjoerg for (const StmtSequence &S : Group) {
1627330f729Sjoerg const SourceManager &SM = S.getASTContext().getSourceManager();
1637330f729Sjoerg StringRef Filename = llvm::sys::path::filename(
1647330f729Sjoerg SM.getFilename(S.getContainingDecl()->getLocation()));
1657330f729Sjoerg if (IgnoredFilesRegex->match(Filename))
1667330f729Sjoerg return true;
1677330f729Sjoerg }
1687330f729Sjoerg
1697330f729Sjoerg return false;
1707330f729Sjoerg }
1717330f729Sjoerg
1727330f729Sjoerg /// This class defines what a type II code clone is: If it collects for two
1737330f729Sjoerg /// statements the same data, then those two statements are considered to be
1747330f729Sjoerg /// clones of each other.
1757330f729Sjoerg ///
1767330f729Sjoerg /// All collected data is forwarded to the given data consumer of the type T.
1777330f729Sjoerg /// The data consumer class needs to provide a member method with the signature:
1787330f729Sjoerg /// update(StringRef Str)
1797330f729Sjoerg namespace {
1807330f729Sjoerg template <class T>
1817330f729Sjoerg class CloneTypeIIStmtDataCollector
1827330f729Sjoerg : public ConstStmtVisitor<CloneTypeIIStmtDataCollector<T>> {
1837330f729Sjoerg ASTContext &Context;
1847330f729Sjoerg /// The data sink to which all data is forwarded.
1857330f729Sjoerg T &DataConsumer;
1867330f729Sjoerg
addData(const Ty & Data)1877330f729Sjoerg template <class Ty> void addData(const Ty &Data) {
1887330f729Sjoerg data_collection::addDataToConsumer(DataConsumer, Data);
1897330f729Sjoerg }
1907330f729Sjoerg
1917330f729Sjoerg public:
CloneTypeIIStmtDataCollector(const Stmt * S,ASTContext & Context,T & DataConsumer)1927330f729Sjoerg CloneTypeIIStmtDataCollector(const Stmt *S, ASTContext &Context,
1937330f729Sjoerg T &DataConsumer)
1947330f729Sjoerg : Context(Context), DataConsumer(DataConsumer) {
1957330f729Sjoerg this->Visit(S);
1967330f729Sjoerg }
1977330f729Sjoerg
1987330f729Sjoerg // Define a visit method for each class to collect data and subsequently visit
1997330f729Sjoerg // all parent classes. This uses a template so that custom visit methods by us
2007330f729Sjoerg // take precedence.
2017330f729Sjoerg #define DEF_ADD_DATA(CLASS, CODE) \
2027330f729Sjoerg template <class = void> void Visit##CLASS(const CLASS *S) { \
2037330f729Sjoerg CODE; \
2047330f729Sjoerg ConstStmtVisitor<CloneTypeIIStmtDataCollector<T>>::Visit##CLASS(S); \
2057330f729Sjoerg }
2067330f729Sjoerg
2077330f729Sjoerg #include "clang/AST/StmtDataCollectors.inc"
2087330f729Sjoerg
2097330f729Sjoerg // Type II clones ignore variable names and literals, so let's skip them.
2107330f729Sjoerg #define SKIP(CLASS) \
2117330f729Sjoerg void Visit##CLASS(const CLASS *S) { \
2127330f729Sjoerg ConstStmtVisitor<CloneTypeIIStmtDataCollector<T>>::Visit##CLASS(S); \
2137330f729Sjoerg }
2147330f729Sjoerg SKIP(DeclRefExpr)
2157330f729Sjoerg SKIP(MemberExpr)
2167330f729Sjoerg SKIP(IntegerLiteral)
2177330f729Sjoerg SKIP(FloatingLiteral)
2187330f729Sjoerg SKIP(StringLiteral)
2197330f729Sjoerg SKIP(CXXBoolLiteralExpr)
2207330f729Sjoerg SKIP(CharacterLiteral)
2217330f729Sjoerg #undef SKIP
2227330f729Sjoerg };
2237330f729Sjoerg } // end anonymous namespace
2247330f729Sjoerg
createHash(llvm::MD5 & Hash)2257330f729Sjoerg static size_t createHash(llvm::MD5 &Hash) {
2267330f729Sjoerg size_t HashCode;
2277330f729Sjoerg
2287330f729Sjoerg // Create the final hash code for the current Stmt.
2297330f729Sjoerg llvm::MD5::MD5Result HashResult;
2307330f729Sjoerg Hash.final(HashResult);
2317330f729Sjoerg
2327330f729Sjoerg // Copy as much as possible of the generated hash code to the Stmt's hash
2337330f729Sjoerg // code.
2347330f729Sjoerg std::memcpy(&HashCode, &HashResult,
2357330f729Sjoerg std::min(sizeof(HashCode), sizeof(HashResult)));
2367330f729Sjoerg
2377330f729Sjoerg return HashCode;
2387330f729Sjoerg }
2397330f729Sjoerg
2407330f729Sjoerg /// Generates and saves a hash code for the given Stmt.
2417330f729Sjoerg /// \param S The given Stmt.
2427330f729Sjoerg /// \param D The Decl containing S.
2437330f729Sjoerg /// \param StmtsByHash Output parameter that will contain the hash codes for
2447330f729Sjoerg /// each StmtSequence in the given Stmt.
2457330f729Sjoerg /// \return The hash code of the given Stmt.
2467330f729Sjoerg ///
2477330f729Sjoerg /// If the given Stmt is a CompoundStmt, this method will also generate
2487330f729Sjoerg /// hashes for all possible StmtSequences in the children of this Stmt.
2497330f729Sjoerg static size_t
saveHash(const Stmt * S,const Decl * D,std::vector<std::pair<size_t,StmtSequence>> & StmtsByHash)2507330f729Sjoerg saveHash(const Stmt *S, const Decl *D,
2517330f729Sjoerg std::vector<std::pair<size_t, StmtSequence>> &StmtsByHash) {
2527330f729Sjoerg llvm::MD5 Hash;
2537330f729Sjoerg ASTContext &Context = D->getASTContext();
2547330f729Sjoerg
2557330f729Sjoerg CloneTypeIIStmtDataCollector<llvm::MD5>(S, Context, Hash);
2567330f729Sjoerg
2577330f729Sjoerg auto CS = dyn_cast<CompoundStmt>(S);
2587330f729Sjoerg SmallVector<size_t, 8> ChildHashes;
2597330f729Sjoerg
2607330f729Sjoerg for (const Stmt *Child : S->children()) {
2617330f729Sjoerg if (Child == nullptr) {
2627330f729Sjoerg ChildHashes.push_back(0);
2637330f729Sjoerg continue;
2647330f729Sjoerg }
2657330f729Sjoerg size_t ChildHash = saveHash(Child, D, StmtsByHash);
2667330f729Sjoerg Hash.update(
2677330f729Sjoerg StringRef(reinterpret_cast<char *>(&ChildHash), sizeof(ChildHash)));
2687330f729Sjoerg ChildHashes.push_back(ChildHash);
2697330f729Sjoerg }
2707330f729Sjoerg
2717330f729Sjoerg if (CS) {
2727330f729Sjoerg // If we're in a CompoundStmt, we hash all possible combinations of child
2737330f729Sjoerg // statements to find clones in those subsequences.
2747330f729Sjoerg // We first go through every possible starting position of a subsequence.
2757330f729Sjoerg for (unsigned Pos = 0; Pos < CS->size(); ++Pos) {
2767330f729Sjoerg // Then we try all possible lengths this subsequence could have and
2777330f729Sjoerg // reuse the same hash object to make sure we only hash every child
2787330f729Sjoerg // hash exactly once.
2797330f729Sjoerg llvm::MD5 Hash;
2807330f729Sjoerg for (unsigned Length = 1; Length <= CS->size() - Pos; ++Length) {
2817330f729Sjoerg // Grab the current child hash and put it into our hash. We do
2827330f729Sjoerg // -1 on the index because we start counting the length at 1.
2837330f729Sjoerg size_t ChildHash = ChildHashes[Pos + Length - 1];
2847330f729Sjoerg Hash.update(
2857330f729Sjoerg StringRef(reinterpret_cast<char *>(&ChildHash), sizeof(ChildHash)));
2867330f729Sjoerg // If we have at least two elements in our subsequence, we can start
2877330f729Sjoerg // saving it.
2887330f729Sjoerg if (Length > 1) {
2897330f729Sjoerg llvm::MD5 SubHash = Hash;
2907330f729Sjoerg StmtsByHash.push_back(std::make_pair(
2917330f729Sjoerg createHash(SubHash), StmtSequence(CS, D, Pos, Pos + Length)));
2927330f729Sjoerg }
2937330f729Sjoerg }
2947330f729Sjoerg }
2957330f729Sjoerg }
2967330f729Sjoerg
2977330f729Sjoerg size_t HashCode = createHash(Hash);
2987330f729Sjoerg StmtsByHash.push_back(std::make_pair(HashCode, StmtSequence(S, D)));
2997330f729Sjoerg return HashCode;
3007330f729Sjoerg }
3017330f729Sjoerg
3027330f729Sjoerg namespace {
3037330f729Sjoerg /// Wrapper around FoldingSetNodeID that it can be used as the template
3047330f729Sjoerg /// argument of the StmtDataCollector.
3057330f729Sjoerg class FoldingSetNodeIDWrapper {
3067330f729Sjoerg
3077330f729Sjoerg llvm::FoldingSetNodeID &FS;
3087330f729Sjoerg
3097330f729Sjoerg public:
FoldingSetNodeIDWrapper(llvm::FoldingSetNodeID & FS)3107330f729Sjoerg FoldingSetNodeIDWrapper(llvm::FoldingSetNodeID &FS) : FS(FS) {}
3117330f729Sjoerg
update(StringRef Str)3127330f729Sjoerg void update(StringRef Str) { FS.AddString(Str); }
3137330f729Sjoerg };
3147330f729Sjoerg } // end anonymous namespace
3157330f729Sjoerg
3167330f729Sjoerg /// Writes the relevant data from all statements and child statements
3177330f729Sjoerg /// in the given StmtSequence into the given FoldingSetNodeID.
CollectStmtSequenceData(const StmtSequence & Sequence,FoldingSetNodeIDWrapper & OutputData)3187330f729Sjoerg static void CollectStmtSequenceData(const StmtSequence &Sequence,
3197330f729Sjoerg FoldingSetNodeIDWrapper &OutputData) {
3207330f729Sjoerg for (const Stmt *S : Sequence) {
3217330f729Sjoerg CloneTypeIIStmtDataCollector<FoldingSetNodeIDWrapper>(
3227330f729Sjoerg S, Sequence.getASTContext(), OutputData);
3237330f729Sjoerg
3247330f729Sjoerg for (const Stmt *Child : S->children()) {
3257330f729Sjoerg if (!Child)
3267330f729Sjoerg continue;
3277330f729Sjoerg
3287330f729Sjoerg CollectStmtSequenceData(StmtSequence(Child, Sequence.getContainingDecl()),
3297330f729Sjoerg OutputData);
3307330f729Sjoerg }
3317330f729Sjoerg }
3327330f729Sjoerg }
3337330f729Sjoerg
3347330f729Sjoerg /// Returns true if both sequences are clones of each other.
areSequencesClones(const StmtSequence & LHS,const StmtSequence & RHS)3357330f729Sjoerg static bool areSequencesClones(const StmtSequence &LHS,
3367330f729Sjoerg const StmtSequence &RHS) {
3377330f729Sjoerg // We collect the data from all statements in the sequence as we did before
3387330f729Sjoerg // when generating a hash value for each sequence. But this time we don't
3397330f729Sjoerg // hash the collected data and compare the whole data set instead. This
3407330f729Sjoerg // prevents any false-positives due to hash code collisions.
3417330f729Sjoerg llvm::FoldingSetNodeID DataLHS, DataRHS;
3427330f729Sjoerg FoldingSetNodeIDWrapper LHSWrapper(DataLHS);
3437330f729Sjoerg FoldingSetNodeIDWrapper RHSWrapper(DataRHS);
3447330f729Sjoerg
3457330f729Sjoerg CollectStmtSequenceData(LHS, LHSWrapper);
3467330f729Sjoerg CollectStmtSequenceData(RHS, RHSWrapper);
3477330f729Sjoerg
3487330f729Sjoerg return DataLHS == DataRHS;
3497330f729Sjoerg }
3507330f729Sjoerg
constrain(std::vector<CloneDetector::CloneGroup> & Sequences)3517330f729Sjoerg void RecursiveCloneTypeIIHashConstraint::constrain(
3527330f729Sjoerg std::vector<CloneDetector::CloneGroup> &Sequences) {
3537330f729Sjoerg // FIXME: Maybe we can do this in-place and don't need this additional vector.
3547330f729Sjoerg std::vector<CloneDetector::CloneGroup> Result;
3557330f729Sjoerg
3567330f729Sjoerg for (CloneDetector::CloneGroup &Group : Sequences) {
3577330f729Sjoerg // We assume in the following code that the Group is non-empty, so we
3587330f729Sjoerg // skip all empty groups.
3597330f729Sjoerg if (Group.empty())
3607330f729Sjoerg continue;
3617330f729Sjoerg
3627330f729Sjoerg std::vector<std::pair<size_t, StmtSequence>> StmtsByHash;
3637330f729Sjoerg
3647330f729Sjoerg // Generate hash codes for all children of S and save them in StmtsByHash.
3657330f729Sjoerg for (const StmtSequence &S : Group) {
3667330f729Sjoerg saveHash(S.front(), S.getContainingDecl(), StmtsByHash);
3677330f729Sjoerg }
3687330f729Sjoerg
3697330f729Sjoerg // Sort hash_codes in StmtsByHash.
3707330f729Sjoerg llvm::stable_sort(StmtsByHash, llvm::less_first());
3717330f729Sjoerg
3727330f729Sjoerg // Check for each StmtSequence if its successor has the same hash value.
3737330f729Sjoerg // We don't check the last StmtSequence as it has no successor.
3747330f729Sjoerg // Note: The 'size - 1 ' in the condition is safe because we check for an
3757330f729Sjoerg // empty Group vector at the beginning of this function.
3767330f729Sjoerg for (unsigned i = 0; i < StmtsByHash.size() - 1; ++i) {
3777330f729Sjoerg const auto Current = StmtsByHash[i];
3787330f729Sjoerg
3797330f729Sjoerg // It's likely that we just found a sequence of StmtSequences that
3807330f729Sjoerg // represent a CloneGroup, so we create a new group and start checking and
3817330f729Sjoerg // adding the StmtSequences in this sequence.
3827330f729Sjoerg CloneDetector::CloneGroup NewGroup;
3837330f729Sjoerg
3847330f729Sjoerg size_t PrototypeHash = Current.first;
3857330f729Sjoerg
3867330f729Sjoerg for (; i < StmtsByHash.size(); ++i) {
3877330f729Sjoerg // A different hash value means we have reached the end of the sequence.
3887330f729Sjoerg if (PrototypeHash != StmtsByHash[i].first) {
3897330f729Sjoerg // The current sequence could be the start of a new CloneGroup. So we
3907330f729Sjoerg // decrement i so that we visit it again in the outer loop.
3917330f729Sjoerg // Note: i can never be 0 at this point because we are just comparing
3927330f729Sjoerg // the hash of the Current StmtSequence with itself in the 'if' above.
3937330f729Sjoerg assert(i != 0);
3947330f729Sjoerg --i;
3957330f729Sjoerg break;
3967330f729Sjoerg }
3977330f729Sjoerg // Same hash value means we should add the StmtSequence to the current
3987330f729Sjoerg // group.
3997330f729Sjoerg NewGroup.push_back(StmtsByHash[i].second);
4007330f729Sjoerg }
4017330f729Sjoerg
4027330f729Sjoerg // We created a new clone group with matching hash codes and move it to
4037330f729Sjoerg // the result vector.
4047330f729Sjoerg Result.push_back(NewGroup);
4057330f729Sjoerg }
4067330f729Sjoerg }
4077330f729Sjoerg // Sequences is the output parameter, so we copy our result into it.
4087330f729Sjoerg Sequences = Result;
4097330f729Sjoerg }
4107330f729Sjoerg
constrain(std::vector<CloneDetector::CloneGroup> & Sequences)4117330f729Sjoerg void RecursiveCloneTypeIIVerifyConstraint::constrain(
4127330f729Sjoerg std::vector<CloneDetector::CloneGroup> &Sequences) {
4137330f729Sjoerg CloneConstraint::splitCloneGroups(
4147330f729Sjoerg Sequences, [](const StmtSequence &A, const StmtSequence &B) {
4157330f729Sjoerg return areSequencesClones(A, B);
4167330f729Sjoerg });
4177330f729Sjoerg }
4187330f729Sjoerg
calculateStmtComplexity(const StmtSequence & Seq,std::size_t Limit,const std::string & ParentMacroStack)4197330f729Sjoerg size_t MinComplexityConstraint::calculateStmtComplexity(
4207330f729Sjoerg const StmtSequence &Seq, std::size_t Limit,
4217330f729Sjoerg const std::string &ParentMacroStack) {
4227330f729Sjoerg if (Seq.empty())
4237330f729Sjoerg return 0;
4247330f729Sjoerg
4257330f729Sjoerg size_t Complexity = 1;
4267330f729Sjoerg
4277330f729Sjoerg ASTContext &Context = Seq.getASTContext();
4287330f729Sjoerg
4297330f729Sjoerg // Look up what macros expanded into the current statement.
4307330f729Sjoerg std::string MacroStack =
4317330f729Sjoerg data_collection::getMacroStack(Seq.getBeginLoc(), Context);
4327330f729Sjoerg
4337330f729Sjoerg // First, check if ParentMacroStack is not empty which means we are currently
4347330f729Sjoerg // dealing with a parent statement which was expanded from a macro.
4357330f729Sjoerg // If this parent statement was expanded from the same macros as this
4367330f729Sjoerg // statement, we reduce the initial complexity of this statement to zero.
4377330f729Sjoerg // This causes that a group of statements that were generated by a single
4387330f729Sjoerg // macro expansion will only increase the total complexity by one.
4397330f729Sjoerg // Note: This is not the final complexity of this statement as we still
4407330f729Sjoerg // add the complexity of the child statements to the complexity value.
4417330f729Sjoerg if (!ParentMacroStack.empty() && MacroStack == ParentMacroStack) {
4427330f729Sjoerg Complexity = 0;
4437330f729Sjoerg }
4447330f729Sjoerg
4457330f729Sjoerg // Iterate over the Stmts in the StmtSequence and add their complexity values
4467330f729Sjoerg // to the current complexity value.
4477330f729Sjoerg if (Seq.holdsSequence()) {
4487330f729Sjoerg for (const Stmt *S : Seq) {
4497330f729Sjoerg Complexity += calculateStmtComplexity(
4507330f729Sjoerg StmtSequence(S, Seq.getContainingDecl()), Limit, MacroStack);
4517330f729Sjoerg if (Complexity >= Limit)
4527330f729Sjoerg return Limit;
4537330f729Sjoerg }
4547330f729Sjoerg } else {
4557330f729Sjoerg for (const Stmt *S : Seq.front()->children()) {
4567330f729Sjoerg Complexity += calculateStmtComplexity(
4577330f729Sjoerg StmtSequence(S, Seq.getContainingDecl()), Limit, MacroStack);
4587330f729Sjoerg if (Complexity >= Limit)
4597330f729Sjoerg return Limit;
4607330f729Sjoerg }
4617330f729Sjoerg }
4627330f729Sjoerg return Complexity;
4637330f729Sjoerg }
4647330f729Sjoerg
constrain(std::vector<CloneDetector::CloneGroup> & CloneGroups)4657330f729Sjoerg void MatchingVariablePatternConstraint::constrain(
4667330f729Sjoerg std::vector<CloneDetector::CloneGroup> &CloneGroups) {
4677330f729Sjoerg CloneConstraint::splitCloneGroups(
4687330f729Sjoerg CloneGroups, [](const StmtSequence &A, const StmtSequence &B) {
4697330f729Sjoerg VariablePattern PatternA(A);
4707330f729Sjoerg VariablePattern PatternB(B);
4717330f729Sjoerg return PatternA.countPatternDifferences(PatternB) == 0;
4727330f729Sjoerg });
4737330f729Sjoerg }
4747330f729Sjoerg
splitCloneGroups(std::vector<CloneDetector::CloneGroup> & CloneGroups,llvm::function_ref<bool (const StmtSequence &,const StmtSequence &)> Compare)4757330f729Sjoerg void CloneConstraint::splitCloneGroups(
4767330f729Sjoerg std::vector<CloneDetector::CloneGroup> &CloneGroups,
4777330f729Sjoerg llvm::function_ref<bool(const StmtSequence &, const StmtSequence &)>
4787330f729Sjoerg Compare) {
4797330f729Sjoerg std::vector<CloneDetector::CloneGroup> Result;
4807330f729Sjoerg for (auto &HashGroup : CloneGroups) {
4817330f729Sjoerg // Contains all indexes in HashGroup that were already added to a
4827330f729Sjoerg // CloneGroup.
4837330f729Sjoerg std::vector<char> Indexes;
4847330f729Sjoerg Indexes.resize(HashGroup.size());
4857330f729Sjoerg
4867330f729Sjoerg for (unsigned i = 0; i < HashGroup.size(); ++i) {
4877330f729Sjoerg // Skip indexes that are already part of a CloneGroup.
4887330f729Sjoerg if (Indexes[i])
4897330f729Sjoerg continue;
4907330f729Sjoerg
4917330f729Sjoerg // Pick the first unhandled StmtSequence and consider it as the
4927330f729Sjoerg // beginning
4937330f729Sjoerg // of a new CloneGroup for now.
4947330f729Sjoerg // We don't add i to Indexes because we never iterate back.
4957330f729Sjoerg StmtSequence Prototype = HashGroup[i];
4967330f729Sjoerg CloneDetector::CloneGroup PotentialGroup = {Prototype};
4977330f729Sjoerg ++Indexes[i];
4987330f729Sjoerg
4997330f729Sjoerg // Check all following StmtSequences for clones.
5007330f729Sjoerg for (unsigned j = i + 1; j < HashGroup.size(); ++j) {
5017330f729Sjoerg // Skip indexes that are already part of a CloneGroup.
5027330f729Sjoerg if (Indexes[j])
5037330f729Sjoerg continue;
5047330f729Sjoerg
5057330f729Sjoerg // If a following StmtSequence belongs to our CloneGroup, we add it.
5067330f729Sjoerg const StmtSequence &Candidate = HashGroup[j];
5077330f729Sjoerg
5087330f729Sjoerg if (!Compare(Prototype, Candidate))
5097330f729Sjoerg continue;
5107330f729Sjoerg
5117330f729Sjoerg PotentialGroup.push_back(Candidate);
5127330f729Sjoerg // Make sure we never visit this StmtSequence again.
5137330f729Sjoerg ++Indexes[j];
5147330f729Sjoerg }
5157330f729Sjoerg
5167330f729Sjoerg // Otherwise, add it to the result and continue searching for more
5177330f729Sjoerg // groups.
5187330f729Sjoerg Result.push_back(PotentialGroup);
5197330f729Sjoerg }
5207330f729Sjoerg
5217330f729Sjoerg assert(llvm::all_of(Indexes, [](char c) { return c == 1; }));
5227330f729Sjoerg }
5237330f729Sjoerg CloneGroups = Result;
5247330f729Sjoerg }
5257330f729Sjoerg
addVariableOccurence(const VarDecl * VarDecl,const Stmt * Mention)5267330f729Sjoerg void VariablePattern::addVariableOccurence(const VarDecl *VarDecl,
5277330f729Sjoerg const Stmt *Mention) {
5287330f729Sjoerg // First check if we already reference this variable
5297330f729Sjoerg for (size_t KindIndex = 0; KindIndex < Variables.size(); ++KindIndex) {
5307330f729Sjoerg if (Variables[KindIndex] == VarDecl) {
5317330f729Sjoerg // If yes, add a new occurrence that points to the existing entry in
5327330f729Sjoerg // the Variables vector.
5337330f729Sjoerg Occurences.emplace_back(KindIndex, Mention);
5347330f729Sjoerg return;
5357330f729Sjoerg }
5367330f729Sjoerg }
5377330f729Sjoerg // If this variable wasn't already referenced, add it to the list of
5387330f729Sjoerg // referenced variables and add a occurrence that points to this new entry.
5397330f729Sjoerg Occurences.emplace_back(Variables.size(), Mention);
5407330f729Sjoerg Variables.push_back(VarDecl);
5417330f729Sjoerg }
5427330f729Sjoerg
addVariables(const Stmt * S)5437330f729Sjoerg void VariablePattern::addVariables(const Stmt *S) {
5447330f729Sjoerg // Sometimes we get a nullptr (such as from IfStmts which often have nullptr
5457330f729Sjoerg // children). We skip such statements as they don't reference any
5467330f729Sjoerg // variables.
5477330f729Sjoerg if (!S)
5487330f729Sjoerg return;
5497330f729Sjoerg
5507330f729Sjoerg // Check if S is a reference to a variable. If yes, add it to the pattern.
5517330f729Sjoerg if (auto D = dyn_cast<DeclRefExpr>(S)) {
5527330f729Sjoerg if (auto VD = dyn_cast<VarDecl>(D->getDecl()->getCanonicalDecl()))
5537330f729Sjoerg addVariableOccurence(VD, D);
5547330f729Sjoerg }
5557330f729Sjoerg
5567330f729Sjoerg // Recursively check all children of the given statement.
5577330f729Sjoerg for (const Stmt *Child : S->children()) {
5587330f729Sjoerg addVariables(Child);
5597330f729Sjoerg }
5607330f729Sjoerg }
5617330f729Sjoerg
countPatternDifferences(const VariablePattern & Other,VariablePattern::SuspiciousClonePair * FirstMismatch)5627330f729Sjoerg unsigned VariablePattern::countPatternDifferences(
5637330f729Sjoerg const VariablePattern &Other,
5647330f729Sjoerg VariablePattern::SuspiciousClonePair *FirstMismatch) {
5657330f729Sjoerg unsigned NumberOfDifferences = 0;
5667330f729Sjoerg
5677330f729Sjoerg assert(Other.Occurences.size() == Occurences.size());
5687330f729Sjoerg for (unsigned i = 0; i < Occurences.size(); ++i) {
5697330f729Sjoerg auto ThisOccurence = Occurences[i];
5707330f729Sjoerg auto OtherOccurence = Other.Occurences[i];
5717330f729Sjoerg if (ThisOccurence.KindID == OtherOccurence.KindID)
5727330f729Sjoerg continue;
5737330f729Sjoerg
5747330f729Sjoerg ++NumberOfDifferences;
5757330f729Sjoerg
5767330f729Sjoerg // If FirstMismatch is not a nullptr, we need to store information about
5777330f729Sjoerg // the first difference between the two patterns.
5787330f729Sjoerg if (FirstMismatch == nullptr)
5797330f729Sjoerg continue;
5807330f729Sjoerg
5817330f729Sjoerg // Only proceed if we just found the first difference as we only store
5827330f729Sjoerg // information about the first difference.
5837330f729Sjoerg if (NumberOfDifferences != 1)
5847330f729Sjoerg continue;
5857330f729Sjoerg
5867330f729Sjoerg const VarDecl *FirstSuggestion = nullptr;
5877330f729Sjoerg // If there is a variable available in the list of referenced variables
5887330f729Sjoerg // which wouldn't break the pattern if it is used in place of the
5897330f729Sjoerg // current variable, we provide this variable as the suggested fix.
5907330f729Sjoerg if (OtherOccurence.KindID < Variables.size())
5917330f729Sjoerg FirstSuggestion = Variables[OtherOccurence.KindID];
5927330f729Sjoerg
5937330f729Sjoerg // Store information about the first clone.
5947330f729Sjoerg FirstMismatch->FirstCloneInfo =
5957330f729Sjoerg VariablePattern::SuspiciousClonePair::SuspiciousCloneInfo(
5967330f729Sjoerg Variables[ThisOccurence.KindID], ThisOccurence.Mention,
5977330f729Sjoerg FirstSuggestion);
5987330f729Sjoerg
5997330f729Sjoerg // Same as above but with the other clone. We do this for both clones as
6007330f729Sjoerg // we don't know which clone is the one containing the unintended
6017330f729Sjoerg // pattern error.
6027330f729Sjoerg const VarDecl *SecondSuggestion = nullptr;
6037330f729Sjoerg if (ThisOccurence.KindID < Other.Variables.size())
6047330f729Sjoerg SecondSuggestion = Other.Variables[ThisOccurence.KindID];
6057330f729Sjoerg
6067330f729Sjoerg // Store information about the second clone.
6077330f729Sjoerg FirstMismatch->SecondCloneInfo =
6087330f729Sjoerg VariablePattern::SuspiciousClonePair::SuspiciousCloneInfo(
6097330f729Sjoerg Other.Variables[OtherOccurence.KindID], OtherOccurence.Mention,
6107330f729Sjoerg SecondSuggestion);
6117330f729Sjoerg
6127330f729Sjoerg // SuspiciousClonePair guarantees that the first clone always has a
6137330f729Sjoerg // suggested variable associated with it. As we know that one of the two
6147330f729Sjoerg // clones in the pair always has suggestion, we swap the two clones
6157330f729Sjoerg // in case the first clone has no suggested variable which means that
6167330f729Sjoerg // the second clone has a suggested variable and should be first.
6177330f729Sjoerg if (!FirstMismatch->FirstCloneInfo.Suggestion)
6187330f729Sjoerg std::swap(FirstMismatch->FirstCloneInfo, FirstMismatch->SecondCloneInfo);
6197330f729Sjoerg
6207330f729Sjoerg // This ensures that we always have at least one suggestion in a pair.
6217330f729Sjoerg assert(FirstMismatch->FirstCloneInfo.Suggestion);
6227330f729Sjoerg }
6237330f729Sjoerg
6247330f729Sjoerg return NumberOfDifferences;
6257330f729Sjoerg }
626