#include "clang/Analysis/CloneDetection.h"
#include "clang/AST/Attr.h"
#include "clang/AST/DataCollection.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/Support/MD5.h"
#include "llvm/Support/Path.h"
using namespace clang;
StmtSequence::StmtSequence(const CompoundStmt *Stmt, const Decl *D,
unsigned StartIndex, unsigned EndIndex)
: S(Stmt), D(D), StartIndex(StartIndex), EndIndex(EndIndex) {
assert(Stmt && "Stmt must not be a nullptr");
assert(StartIndex < EndIndex && "Given array should not be empty");
assert(EndIndex <= Stmt->size() && "Given array too big for this Stmt");
}
StmtSequence::StmtSequence(const Stmt *Stmt, const Decl *D)
: S(Stmt), D(D), StartIndex(0), EndIndex(0) {}
StmtSequence::StmtSequence()
: S(nullptr), D(nullptr), StartIndex(0), EndIndex(0) {}
bool StmtSequence::contains(const StmtSequence &Other) const {
if (D != Other.D)
return false;
const SourceManager &SM = getASTContext().getSourceManager();
bool StartIsInBounds =
SM.isBeforeInTranslationUnit(getBeginLoc(), Other.getBeginLoc()) ||
getBeginLoc() == Other.getBeginLoc();
if (!StartIsInBounds)
return false;
bool EndIsInBounds =
SM.isBeforeInTranslationUnit(Other.getEndLoc(), getEndLoc()) ||
Other.getEndLoc() == getEndLoc();
return EndIsInBounds;
}
StmtSequence::iterator StmtSequence::begin() const {
if (!holdsSequence()) {
return &S;
}
auto CS = cast<CompoundStmt>(S);
return CS->body_begin() + StartIndex;
}
StmtSequence::iterator StmtSequence::end() const {
if (!holdsSequence()) {
return reinterpret_cast<StmtSequence::iterator>(&S) + 1;
}
auto CS = cast<CompoundStmt>(S);
return CS->body_begin() + EndIndex;
}
ASTContext &StmtSequence::getASTContext() const {
assert(D);
return D->getASTContext();
}
SourceLocation StmtSequence::getBeginLoc() const {
return front()->getBeginLoc();
}
SourceLocation StmtSequence::getEndLoc() const { return back()->getEndLoc(); }
SourceRange StmtSequence::getSourceRange() const {
return SourceRange(getBeginLoc(), getEndLoc());
}
void CloneDetector::analyzeCodeBody(const Decl *D) {
assert(D);
assert(D->hasBody());
Sequences.push_back(StmtSequence(D->getBody(), D));
}
static bool containsAnyInGroup(StmtSequence &Seq,
CloneDetector::CloneGroup &Group) {
for (StmtSequence &GroupSeq : Group) {
if (Seq.contains(GroupSeq))
return true;
}
return false;
}
static bool containsGroup(CloneDetector::CloneGroup &Group,
CloneDetector::CloneGroup &OtherGroup) {
if (Group.size() < OtherGroup.size())
return false;
for (StmtSequence &Stmt : Group) {
if (!containsAnyInGroup(Stmt, OtherGroup))
return false;
}
return true;
}
void OnlyLargestCloneConstraint::constrain(
std::vector<CloneDetector::CloneGroup> &Result) {
std::vector<unsigned> IndexesToRemove;
for (unsigned i = 0; i < Result.size(); ++i) {
for (unsigned j = 0; j < Result.size(); ++j) {
if (i == j)
continue;
if (containsGroup(Result[j], Result[i])) {
IndexesToRemove.push_back(i);
break;
}
}
}
for (unsigned I : llvm::reverse(IndexesToRemove))
Result.erase(Result.begin() + I);
}
bool FilenamePatternConstraint::isAutoGenerated(
const CloneDetector::CloneGroup &Group) {
if (IgnoredFilesPattern.empty() || Group.empty() ||
!IgnoredFilesRegex->isValid())
return false;
for (const StmtSequence &S : Group) {
const SourceManager &SM = S.getASTContext().getSourceManager();
StringRef Filename = llvm::sys::path::filename(
SM.getFilename(S.getContainingDecl()->getLocation()));
if (IgnoredFilesRegex->match(Filename))
return true;
}
return false;
}
namespace {
template <class T>
class CloneTypeIIStmtDataCollector
: public ConstStmtVisitor<CloneTypeIIStmtDataCollector<T>> {
ASTContext &Context;
T &DataConsumer;
template <class Ty> void addData(const Ty &Data) {
data_collection::addDataToConsumer(DataConsumer, Data);
}
public:
CloneTypeIIStmtDataCollector(const Stmt *S, ASTContext &Context,
T &DataConsumer)
: Context(Context), DataConsumer(DataConsumer) {
this->Visit(S);
}
#define DEF_ADD_DATA(CLASS, CODE) \
template <class = void> void Visit##CLASS(const CLASS *S) { \
CODE; \
ConstStmtVisitor<CloneTypeIIStmtDataCollector<T>>::Visit##CLASS(S); \
}
#include "clang/AST/StmtDataCollectors.inc"
#define SKIP(CLASS) \
void Visit##CLASS(const CLASS *S) { \
ConstStmtVisitor<CloneTypeIIStmtDataCollector<T>>::Visit##CLASS(S); \
}
SKIP(DeclRefExpr)
SKIP(MemberExpr)
SKIP(IntegerLiteral)
SKIP(FloatingLiteral)
SKIP(StringLiteral)
SKIP(CXXBoolLiteralExpr)
SKIP(CharacterLiteral)
#undef SKIP
};
}
static size_t createHash(llvm::MD5 &Hash) {
size_t HashCode;
llvm::MD5::MD5Result HashResult;
Hash.final(HashResult);
std::memcpy(&HashCode, &HashResult,
std::min(sizeof(HashCode), sizeof(HashResult)));
return HashCode;
}
static size_t
saveHash(const Stmt *S, const Decl *D,
std::vector<std::pair<size_t, StmtSequence>> &StmtsByHash) {
llvm::MD5 Hash;
ASTContext &Context = D->getASTContext();
CloneTypeIIStmtDataCollector<llvm::MD5>(S, Context, Hash);
auto CS = dyn_cast<CompoundStmt>(S);
SmallVector<size_t, 8> ChildHashes;
for (const Stmt *Child : S->children()) {
if (Child == nullptr) {
ChildHashes.push_back(0);
continue;
}
size_t ChildHash = saveHash(Child, D, StmtsByHash);
Hash.update(
StringRef(reinterpret_cast<char *>(&ChildHash), sizeof(ChildHash)));
ChildHashes.push_back(ChildHash);
}
if (CS) {
for (unsigned Pos = 0; Pos < CS->size(); ++Pos) {
llvm::MD5 Hash;
for (unsigned Length = 1; Length <= CS->size() - Pos; ++Length) {
size_t ChildHash = ChildHashes[Pos + Length - 1];
Hash.update(
StringRef(reinterpret_cast<char *>(&ChildHash), sizeof(ChildHash)));
if (Length > 1) {
llvm::MD5 SubHash = Hash;
StmtsByHash.push_back(std::make_pair(
createHash(SubHash), StmtSequence(CS, D, Pos, Pos + Length)));
}
}
}
}
size_t HashCode = createHash(Hash);
StmtsByHash.push_back(std::make_pair(HashCode, StmtSequence(S, D)));
return HashCode;
}
namespace {
class FoldingSetNodeIDWrapper {
llvm::FoldingSetNodeID &FS;
public:
FoldingSetNodeIDWrapper(llvm::FoldingSetNodeID &FS) : FS(FS) {}
void update(StringRef Str) { FS.AddString(Str); }
};
}
static void CollectStmtSequenceData(const StmtSequence &Sequence,
FoldingSetNodeIDWrapper &OutputData) {
for (const Stmt *S : Sequence) {
CloneTypeIIStmtDataCollector<FoldingSetNodeIDWrapper>(
S, Sequence.getASTContext(), OutputData);
for (const Stmt *Child : S->children()) {
if (!Child)
continue;
CollectStmtSequenceData(StmtSequence(Child, Sequence.getContainingDecl()),
OutputData);
}
}
}
static bool areSequencesClones(const StmtSequence &LHS,
const StmtSequence &RHS) {
llvm::FoldingSetNodeID DataLHS, DataRHS;
FoldingSetNodeIDWrapper LHSWrapper(DataLHS);
FoldingSetNodeIDWrapper RHSWrapper(DataRHS);
CollectStmtSequenceData(LHS, LHSWrapper);
CollectStmtSequenceData(RHS, RHSWrapper);
return DataLHS == DataRHS;
}
void RecursiveCloneTypeIIHashConstraint::constrain(
std::vector<CloneDetector::CloneGroup> &Sequences) {
std::vector<CloneDetector::CloneGroup> Result;
for (CloneDetector::CloneGroup &Group : Sequences) {
if (Group.empty())
continue;
std::vector<std::pair<size_t, StmtSequence>> StmtsByHash;
for (const StmtSequence &S : Group) {
saveHash(S.front(), S.getContainingDecl(), StmtsByHash);
}
llvm::stable_sort(StmtsByHash, llvm::less_first());
for (unsigned i = 0; i < StmtsByHash.size() - 1; ++i) {
const auto Current = StmtsByHash[i];
CloneDetector::CloneGroup NewGroup;
size_t PrototypeHash = Current.first;
for (; i < StmtsByHash.size(); ++i) {
if (PrototypeHash != StmtsByHash[i].first) {
assert(i != 0);
--i;
break;
}
NewGroup.push_back(StmtsByHash[i].second);
}
Result.push_back(NewGroup);
}
}
Sequences = Result;
}
void RecursiveCloneTypeIIVerifyConstraint::constrain(
std::vector<CloneDetector::CloneGroup> &Sequences) {
CloneConstraint::splitCloneGroups(
Sequences, [](const StmtSequence &A, const StmtSequence &B) {
return areSequencesClones(A, B);
});
}
size_t MinComplexityConstraint::calculateStmtComplexity(
const StmtSequence &Seq, std::size_t Limit,
const std::string &ParentMacroStack) {
if (Seq.empty())
return 0;
size_t Complexity = 1;
ASTContext &Context = Seq.getASTContext();
std::string MacroStack =
data_collection::getMacroStack(Seq.getBeginLoc(), Context);
if (!ParentMacroStack.empty() && MacroStack == ParentMacroStack) {
Complexity = 0;
}
if (Seq.holdsSequence()) {
for (const Stmt *S : Seq) {
Complexity += calculateStmtComplexity(
StmtSequence(S, Seq.getContainingDecl()), Limit, MacroStack);
if (Complexity >= Limit)
return Limit;
}
} else {
for (const Stmt *S : Seq.front()->children()) {
Complexity += calculateStmtComplexity(
StmtSequence(S, Seq.getContainingDecl()), Limit, MacroStack);
if (Complexity >= Limit)
return Limit;
}
}
return Complexity;
}
void MatchingVariablePatternConstraint::constrain(
std::vector<CloneDetector::CloneGroup> &CloneGroups) {
CloneConstraint::splitCloneGroups(
CloneGroups, [](const StmtSequence &A, const StmtSequence &B) {
VariablePattern PatternA(A);
VariablePattern PatternB(B);
return PatternA.countPatternDifferences(PatternB) == 0;
});
}
void CloneConstraint::splitCloneGroups(
std::vector<CloneDetector::CloneGroup> &CloneGroups,
llvm::function_ref<bool(const StmtSequence &, const StmtSequence &)>
Compare) {
std::vector<CloneDetector::CloneGroup> Result;
for (auto &HashGroup : CloneGroups) {
std::vector<char> Indexes;
Indexes.resize(HashGroup.size());
for (unsigned i = 0; i < HashGroup.size(); ++i) {
if (Indexes[i])
continue;
StmtSequence Prototype = HashGroup[i];
CloneDetector::CloneGroup PotentialGroup = {Prototype};
++Indexes[i];
for (unsigned j = i + 1; j < HashGroup.size(); ++j) {
if (Indexes[j])
continue;
const StmtSequence &Candidate = HashGroup[j];
if (!Compare(Prototype, Candidate))
continue;
PotentialGroup.push_back(Candidate);
++Indexes[j];
}
Result.push_back(PotentialGroup);
}
assert(llvm::all_of(Indexes, [](char c) { return c == 1; }));
}
CloneGroups = Result;
}
void VariablePattern::addVariableOccurence(const VarDecl *VarDecl,
const Stmt *Mention) {
for (size_t KindIndex = 0; KindIndex < Variables.size(); ++KindIndex) {
if (Variables[KindIndex] == VarDecl) {
Occurences.emplace_back(KindIndex, Mention);
return;
}
}
Occurences.emplace_back(Variables.size(), Mention);
Variables.push_back(VarDecl);
}
void VariablePattern::addVariables(const Stmt *S) {
if (!S)
return;
if (auto D = dyn_cast<DeclRefExpr>(S)) {
if (auto VD = dyn_cast<VarDecl>(D->getDecl()->getCanonicalDecl()))
addVariableOccurence(VD, D);
}
for (const Stmt *Child : S->children()) {
addVariables(Child);
}
}
unsigned VariablePattern::countPatternDifferences(
const VariablePattern &Other,
VariablePattern::SuspiciousClonePair *FirstMismatch) {
unsigned NumberOfDifferences = 0;
assert(Other.Occurences.size() == Occurences.size());
for (unsigned i = 0; i < Occurences.size(); ++i) {
auto ThisOccurence = Occurences[i];
auto OtherOccurence = Other.Occurences[i];
if (ThisOccurence.KindID == OtherOccurence.KindID)
continue;
++NumberOfDifferences;
if (FirstMismatch == nullptr)
continue;
if (NumberOfDifferences != 1)
continue;
const VarDecl *FirstSuggestion = nullptr;
if (OtherOccurence.KindID < Variables.size())
FirstSuggestion = Variables[OtherOccurence.KindID];
FirstMismatch->FirstCloneInfo =
VariablePattern::SuspiciousClonePair::SuspiciousCloneInfo(
Variables[ThisOccurence.KindID], ThisOccurence.Mention,
FirstSuggestion);
const VarDecl *SecondSuggestion = nullptr;
if (ThisOccurence.KindID < Other.Variables.size())
SecondSuggestion = Other.Variables[ThisOccurence.KindID];
FirstMismatch->SecondCloneInfo =
VariablePattern::SuspiciousClonePair::SuspiciousCloneInfo(
Other.Variables[OtherOccurence.KindID], OtherOccurence.Mention,
SecondSuggestion);
if (!FirstMismatch->FirstCloneInfo.Suggestion)
std::swap(FirstMismatch->FirstCloneInfo, FirstMismatch->SecondCloneInfo);
assert(FirstMismatch->FirstCloneInfo.Suggestion);
}
return NumberOfDifferences;
}