blob: c331ddc25b1593064a39fbfdc5786f2dc3061c65 [file] [log] [blame]
Artem Dergachevba816322016-07-26 18:13:12 +00001//===--- CloneDetection.cpp - Finds code clones in an AST -------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// This file implements classes for searching and anlyzing source code clones.
11///
12//===----------------------------------------------------------------------===//
13
14#include "clang/Analysis/CloneDetection.h"
15
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/RecursiveASTVisitor.h"
18#include "clang/AST/Stmt.h"
Artem Dergachev78692ea2016-08-02 12:21:09 +000019#include "clang/AST/StmtVisitor.h"
Artem Dergachev51b9a0e2016-08-20 10:06:59 +000020#include "clang/Lex/Lexer.h"
Artem Dergachevba816322016-07-26 18:13:12 +000021#include "llvm/ADT/StringRef.h"
Artem Dergachev56574862016-08-20 17:35:53 +000022#include "llvm/Support/MD5.h"
Artem Dergachev51b9a0e2016-08-20 10:06:59 +000023#include "llvm/Support/raw_ostream.h"
Artem Dergachevba816322016-07-26 18:13:12 +000024
25using namespace clang;
26
27StmtSequence::StmtSequence(const CompoundStmt *Stmt, ASTContext &Context,
28 unsigned StartIndex, unsigned EndIndex)
29 : S(Stmt), Context(&Context), StartIndex(StartIndex), EndIndex(EndIndex) {
30 assert(Stmt && "Stmt must not be a nullptr");
31 assert(StartIndex < EndIndex && "Given array should not be empty");
32 assert(EndIndex <= Stmt->size() && "Given array too big for this Stmt");
33}
34
35StmtSequence::StmtSequence(const Stmt *Stmt, ASTContext &Context)
36 : S(Stmt), Context(&Context), StartIndex(0), EndIndex(0) {}
37
38StmtSequence::StmtSequence()
39 : S(nullptr), Context(nullptr), StartIndex(0), EndIndex(0) {}
40
41bool StmtSequence::contains(const StmtSequence &Other) const {
42 // If both sequences reside in different translation units, they can never
43 // contain each other.
44 if (Context != Other.Context)
45 return false;
46
47 const SourceManager &SM = Context->getSourceManager();
48
49 // Otherwise check if the start and end locations of the current sequence
50 // surround the other sequence.
51 bool StartIsInBounds =
52 SM.isBeforeInTranslationUnit(getStartLoc(), Other.getStartLoc()) ||
53 getStartLoc() == Other.getStartLoc();
54 if (!StartIsInBounds)
55 return false;
56
57 bool EndIsInBounds =
58 SM.isBeforeInTranslationUnit(Other.getEndLoc(), getEndLoc()) ||
59 Other.getEndLoc() == getEndLoc();
60 return EndIsInBounds;
61}
62
63StmtSequence::iterator StmtSequence::begin() const {
64 if (!holdsSequence()) {
65 return &S;
66 }
67 auto CS = cast<CompoundStmt>(S);
68 return CS->body_begin() + StartIndex;
69}
70
71StmtSequence::iterator StmtSequence::end() const {
72 if (!holdsSequence()) {
Vassil Vassilev5721e0f2016-08-09 10:00:23 +000073 return reinterpret_cast<StmtSequence::iterator>(&S) + 1;
Artem Dergachevba816322016-07-26 18:13:12 +000074 }
75 auto CS = cast<CompoundStmt>(S);
76 return CS->body_begin() + EndIndex;
77}
78
79SourceLocation StmtSequence::getStartLoc() const {
80 return front()->getLocStart();
81}
82
83SourceLocation StmtSequence::getEndLoc() const { return back()->getLocEnd(); }
84
85namespace {
Artem Dergachev7a0088b2016-08-04 19:37:00 +000086
87/// \brief Analyzes the pattern of the referenced variables in a statement.
88class VariablePattern {
89
90 /// \brief Describes an occurence of a variable reference in a statement.
91 struct VariableOccurence {
92 /// The index of the associated VarDecl in the Variables vector.
93 size_t KindID;
Artem Dergachev2fc19852016-08-18 12:29:41 +000094 /// The source range in the code where the variable was referenced.
95 SourceRange Range;
Artem Dergachev7a0088b2016-08-04 19:37:00 +000096
Artem Dergachev2fc19852016-08-18 12:29:41 +000097 VariableOccurence(size_t KindID, SourceRange Range)
98 : KindID(KindID), Range(Range) {}
Artem Dergachev7a0088b2016-08-04 19:37:00 +000099 };
100
101 /// All occurences of referenced variables in the order of appearance.
102 std::vector<VariableOccurence> Occurences;
103 /// List of referenced variables in the order of appearance.
104 /// Every item in this list is unique.
105 std::vector<const VarDecl *> Variables;
106
107 /// \brief Adds a new variable referenced to this pattern.
108 /// \param VarDecl The declaration of the variable that is referenced.
Artem Dergachev2fc19852016-08-18 12:29:41 +0000109 /// \param Range The SourceRange where this variable is referenced.
110 void addVariableOccurence(const VarDecl *VarDecl, SourceRange Range) {
Artem Dergachev7a0088b2016-08-04 19:37:00 +0000111 // First check if we already reference this variable
112 for (size_t KindIndex = 0; KindIndex < Variables.size(); ++KindIndex) {
113 if (Variables[KindIndex] == VarDecl) {
114 // If yes, add a new occurence that points to the existing entry in
115 // the Variables vector.
Artem Dergachev2fc19852016-08-18 12:29:41 +0000116 Occurences.emplace_back(KindIndex, Range);
Artem Dergachev7a0088b2016-08-04 19:37:00 +0000117 return;
118 }
119 }
120 // If this variable wasn't already referenced, add it to the list of
121 // referenced variables and add a occurence that points to this new entry.
Artem Dergachev2fc19852016-08-18 12:29:41 +0000122 Occurences.emplace_back(Variables.size(), Range);
Artem Dergachev7a0088b2016-08-04 19:37:00 +0000123 Variables.push_back(VarDecl);
124 }
125
126 /// \brief Adds each referenced variable from the given statement.
127 void addVariables(const Stmt *S) {
128 // Sometimes we get a nullptr (such as from IfStmts which often have nullptr
129 // children). We skip such statements as they don't reference any
130 // variables.
131 if (!S)
132 return;
133
134 // Check if S is a reference to a variable. If yes, add it to the pattern.
135 if (auto D = dyn_cast<DeclRefExpr>(S)) {
136 if (auto VD = dyn_cast<VarDecl>(D->getDecl()->getCanonicalDecl()))
Artem Dergachev2fc19852016-08-18 12:29:41 +0000137 addVariableOccurence(VD, D->getSourceRange());
Artem Dergachev7a0088b2016-08-04 19:37:00 +0000138 }
139
140 // Recursively check all children of the given statement.
141 for (const Stmt *Child : S->children()) {
142 addVariables(Child);
143 }
144 }
145
146public:
147 /// \brief Creates an VariablePattern object with information about the given
148 /// StmtSequence.
149 VariablePattern(const StmtSequence &Sequence) {
150 for (const Stmt *S : Sequence)
151 addVariables(S);
152 }
153
Artem Dergachev2fc19852016-08-18 12:29:41 +0000154 /// \brief Counts the differences between this pattern and the given one.
Artem Dergachev7a0088b2016-08-04 19:37:00 +0000155 /// \param Other The given VariablePattern to compare with.
Artem Dergachev2fc19852016-08-18 12:29:41 +0000156 /// \param FirstMismatch Output parameter that will be filled with information
157 /// about the first difference between the two patterns. This parameter
158 /// can be a nullptr, in which case it will be ignored.
159 /// \return Returns the number of differences between the pattern this object
160 /// is following and the given VariablePattern.
Artem Dergachev7a0088b2016-08-04 19:37:00 +0000161 ///
Artem Dergachev2fc19852016-08-18 12:29:41 +0000162 /// For example, the following statements all have the same pattern and this
163 /// function would return zero:
Artem Dergachev7a0088b2016-08-04 19:37:00 +0000164 ///
165 /// if (a < b) return a; return b;
166 /// if (x < y) return x; return y;
167 /// if (u2 < u1) return u2; return u1;
168 ///
Artem Dergachev2fc19852016-08-18 12:29:41 +0000169 /// But the following statement has a different pattern (note the changed
170 /// variables in the return statements) and would have two differences when
171 /// compared with one of the statements above.
Artem Dergachev7a0088b2016-08-04 19:37:00 +0000172 ///
173 /// if (a < b) return b; return a;
174 ///
175 /// This function should only be called if the related statements of the given
176 /// pattern and the statements of this objects are clones of each other.
Artem Dergachev2fc19852016-08-18 12:29:41 +0000177 unsigned countPatternDifferences(
178 const VariablePattern &Other,
179 CloneDetector::SuspiciousClonePair *FirstMismatch = nullptr) {
180 unsigned NumberOfDifferences = 0;
181
Artem Dergachev7a0088b2016-08-04 19:37:00 +0000182 assert(Other.Occurences.size() == Occurences.size());
183 for (unsigned i = 0; i < Occurences.size(); ++i) {
Artem Dergachev2fc19852016-08-18 12:29:41 +0000184 auto ThisOccurence = Occurences[i];
185 auto OtherOccurence = Other.Occurences[i];
186 if (ThisOccurence.KindID == OtherOccurence.KindID)
187 continue;
188
189 ++NumberOfDifferences;
190
191 // If FirstMismatch is not a nullptr, we need to store information about
192 // the first difference between the two patterns.
193 if (FirstMismatch == nullptr)
194 continue;
195
196 // Only proceed if we just found the first difference as we only store
197 // information about the first difference.
198 if (NumberOfDifferences != 1)
199 continue;
200
201 const VarDecl *FirstSuggestion = nullptr;
202 // If there is a variable available in the list of referenced variables
203 // which wouldn't break the pattern if it is used in place of the
204 // current variable, we provide this variable as the suggested fix.
205 if (OtherOccurence.KindID < Variables.size())
206 FirstSuggestion = Variables[OtherOccurence.KindID];
207
208 // Store information about the first clone.
209 FirstMismatch->FirstCloneInfo =
210 CloneDetector::SuspiciousClonePair::SuspiciousCloneInfo(
211 Variables[ThisOccurence.KindID], ThisOccurence.Range,
212 FirstSuggestion);
213
214 // Same as above but with the other clone. We do this for both clones as
215 // we don't know which clone is the one containing the unintended
216 // pattern error.
217 const VarDecl *SecondSuggestion = nullptr;
218 if (ThisOccurence.KindID < Other.Variables.size())
219 SecondSuggestion = Other.Variables[ThisOccurence.KindID];
220
221 // Store information about the second clone.
222 FirstMismatch->SecondCloneInfo =
223 CloneDetector::SuspiciousClonePair::SuspiciousCloneInfo(
224 Variables[ThisOccurence.KindID], OtherOccurence.Range,
225 SecondSuggestion);
226
227 // SuspiciousClonePair guarantees that the first clone always has a
228 // suggested variable associated with it. As we know that one of the two
229 // clones in the pair always has suggestion, we swap the two clones
230 // in case the first clone has no suggested variable which means that
231 // the second clone has a suggested variable and should be first.
232 if (!FirstMismatch->FirstCloneInfo.Suggestion)
233 std::swap(FirstMismatch->FirstCloneInfo,
234 FirstMismatch->SecondCloneInfo);
235
236 // This ensures that we always have at least one suggestion in a pair.
237 assert(FirstMismatch->FirstCloneInfo.Suggestion);
Artem Dergachev7a0088b2016-08-04 19:37:00 +0000238 }
Artem Dergachev2fc19852016-08-18 12:29:41 +0000239
240 return NumberOfDifferences;
Artem Dergachev7a0088b2016-08-04 19:37:00 +0000241 }
242};
243}
244
Artem Dergachev51b9a0e2016-08-20 10:06:59 +0000245/// \brief Prints the macro name that contains the given SourceLocation into
246/// the given raw_string_ostream.
247static void printMacroName(llvm::raw_string_ostream &MacroStack,
248 ASTContext &Context, SourceLocation Loc) {
249 MacroStack << Lexer::getImmediateMacroName(Loc, Context.getSourceManager(),
250 Context.getLangOpts());
251
252 // Add an empty space at the end as a padding to prevent
253 // that macro names concatenate to the names of other macros.
254 MacroStack << " ";
255}
256
257/// \brief Returns a string that represents all macro expansions that
258/// expanded into the given SourceLocation.
259///
260/// If 'getMacroStack(A) == getMacroStack(B)' is true, then the SourceLocations
261/// A and B are expanded from the same macros in the same order.
262static std::string getMacroStack(SourceLocation Loc, ASTContext &Context) {
263 std::string MacroStack;
264 llvm::raw_string_ostream MacroStackStream(MacroStack);
265 SourceManager &SM = Context.getSourceManager();
266
267 // Iterate over all macros that expanded into the given SourceLocation.
268 while (Loc.isMacroID()) {
269 // Add the macro name to the stream.
270 printMacroName(MacroStackStream, Context, Loc);
271 Loc = SM.getImmediateMacroCallerLoc(Loc);
272 }
273 MacroStackStream.flush();
274 return MacroStack;
275}
276
Artem Dergachev7a0088b2016-08-04 19:37:00 +0000277namespace {
Artem Dergachev78692ea2016-08-02 12:21:09 +0000278/// \brief Collects the data of a single Stmt.
279///
280/// This class defines what a code clone is: If it collects for two statements
281/// the same data, then those two statements are considered to be clones of each
282/// other.
Artem Dergachev56574862016-08-20 17:35:53 +0000283///
284/// All collected data is forwarded to the given data consumer of the type T.
285/// The data consumer class needs to provide a member method with the signature:
286/// update(StringRef Str)
287template <typename T>
288class StmtDataCollector : public ConstStmtVisitor<StmtDataCollector<T>> {
Artem Dergachev78692ea2016-08-02 12:21:09 +0000289
290 ASTContext &Context;
Artem Dergachev56574862016-08-20 17:35:53 +0000291 /// \brief The data sink to which all data is forwarded.
292 T &DataConsumer;
Artem Dergachev78692ea2016-08-02 12:21:09 +0000293
294public:
295 /// \brief Collects data of the given Stmt.
296 /// \param S The given statement.
297 /// \param Context The ASTContext of S.
Artem Dergachev56574862016-08-20 17:35:53 +0000298 /// \param D The data sink to which all data is forwarded.
299 StmtDataCollector(const Stmt *S, ASTContext &Context, T &DataConsumer)
300 : Context(Context), DataConsumer(DataConsumer) {
301 this->Visit(S);
Artem Dergachev78692ea2016-08-02 12:21:09 +0000302 }
303
304 // Below are utility methods for appending different data to the vector.
305
306 void addData(CloneDetector::DataPiece Integer) {
Artem Dergachev56574862016-08-20 17:35:53 +0000307 DataConsumer.update(
308 StringRef(reinterpret_cast<char *>(&Integer), sizeof(Integer)));
Artem Dergachev78692ea2016-08-02 12:21:09 +0000309 }
310
Artem Dergachev56574862016-08-20 17:35:53 +0000311 void addData(llvm::StringRef Str) { DataConsumer.update(Str); }
Artem Dergachev78692ea2016-08-02 12:21:09 +0000312
313 void addData(const QualType &QT) { addData(QT.getAsString()); }
314
315// The functions below collect the class specific data of each Stmt subclass.
316
317// Utility macro for defining a visit method for a given class. This method
318// calls back to the ConstStmtVisitor to visit all parent classes.
319#define DEF_ADD_DATA(CLASS, CODE) \
320 void Visit##CLASS(const CLASS *S) { \
321 CODE; \
322 ConstStmtVisitor<StmtDataCollector>::Visit##CLASS(S); \
323 }
324
Artem Dergachev51b9a0e2016-08-20 10:06:59 +0000325 DEF_ADD_DATA(Stmt, {
326 addData(S->getStmtClass());
327 // This ensures that macro generated code isn't identical to macro-generated
328 // code.
329 addData(getMacroStack(S->getLocStart(), Context));
330 addData(getMacroStack(S->getLocEnd(), Context));
331 })
Artem Dergachev78692ea2016-08-02 12:21:09 +0000332 DEF_ADD_DATA(Expr, { addData(S->getType()); })
333
334 //--- Builtin functionality ----------------------------------------------//
335 DEF_ADD_DATA(ArrayTypeTraitExpr, { addData(S->getTrait()); })
336 DEF_ADD_DATA(ExpressionTraitExpr, { addData(S->getTrait()); })
337 DEF_ADD_DATA(PredefinedExpr, { addData(S->getIdentType()); })
338 DEF_ADD_DATA(TypeTraitExpr, {
339 addData(S->getTrait());
340 for (unsigned i = 0; i < S->getNumArgs(); ++i)
341 addData(S->getArg(i)->getType());
342 })
343
344 //--- Calls --------------------------------------------------------------//
Artem Dergachevcad15142016-08-10 16:25:16 +0000345 DEF_ADD_DATA(CallExpr, {
346 // Function pointers don't have a callee and we just skip hashing it.
Artem Dergachev51838882016-08-20 09:57:21 +0000347 if (const FunctionDecl *D = S->getDirectCallee()) {
348 // If the function is a template instantiation, we also need to handle
349 // the template arguments as they are no included in the qualified name.
350 if (D->isTemplateInstantiation()) {
351 auto Args = D->getTemplateSpecializationArgs();
352 std::string ArgString;
353
354 // Print all template arguments into ArgString
355 llvm::raw_string_ostream OS(ArgString);
356 for (unsigned i = 0; i < Args->size(); ++i) {
357 Args->get(i).print(Context.getLangOpts(), OS);
358 // Add a padding character so that 'foo<X, XX>()' != 'foo<XX, X>()'.
359 OS << '\n';
360 }
361 OS.flush();
362
363 addData(ArgString);
364 }
365 addData(D->getQualifiedNameAsString());
366 }
Artem Dergachevcad15142016-08-10 16:25:16 +0000367 })
Artem Dergachev78692ea2016-08-02 12:21:09 +0000368
369 //--- Exceptions ---------------------------------------------------------//
370 DEF_ADD_DATA(CXXCatchStmt, { addData(S->getCaughtType()); })
371
372 //--- C++ OOP Stmts ------------------------------------------------------//
373 DEF_ADD_DATA(CXXDeleteExpr, {
374 addData(S->isArrayFormAsWritten());
375 addData(S->isGlobalDelete());
376 })
377
378 //--- Casts --------------------------------------------------------------//
379 DEF_ADD_DATA(ObjCBridgedCastExpr, { addData(S->getBridgeKind()); })
380
381 //--- Miscellaneous Exprs ------------------------------------------------//
382 DEF_ADD_DATA(BinaryOperator, { addData(S->getOpcode()); })
383 DEF_ADD_DATA(UnaryOperator, { addData(S->getOpcode()); })
384
385 //--- Control flow -------------------------------------------------------//
386 DEF_ADD_DATA(GotoStmt, { addData(S->getLabel()->getName()); })
387 DEF_ADD_DATA(IndirectGotoStmt, {
388 if (S->getConstantTarget())
389 addData(S->getConstantTarget()->getName());
390 })
391 DEF_ADD_DATA(LabelStmt, { addData(S->getDecl()->getName()); })
392 DEF_ADD_DATA(MSDependentExistsStmt, { addData(S->isIfExists()); })
393 DEF_ADD_DATA(AddrLabelExpr, { addData(S->getLabel()->getName()); })
394
395 //--- Objective-C --------------------------------------------------------//
396 DEF_ADD_DATA(ObjCIndirectCopyRestoreExpr, { addData(S->shouldCopy()); })
397 DEF_ADD_DATA(ObjCPropertyRefExpr, {
398 addData(S->isSuperReceiver());
399 addData(S->isImplicitProperty());
400 })
401 DEF_ADD_DATA(ObjCAtCatchStmt, { addData(S->hasEllipsis()); })
402
403 //--- Miscellaneous Stmts ------------------------------------------------//
404 DEF_ADD_DATA(CXXFoldExpr, {
405 addData(S->isRightFold());
406 addData(S->getOperator());
407 })
408 DEF_ADD_DATA(GenericSelectionExpr, {
409 for (unsigned i = 0; i < S->getNumAssocs(); ++i) {
410 addData(S->getAssocType(i));
411 }
412 })
413 DEF_ADD_DATA(LambdaExpr, {
414 for (const LambdaCapture &C : S->captures()) {
415 addData(C.isPackExpansion());
416 addData(C.getCaptureKind());
417 if (C.capturesVariable())
418 addData(C.getCapturedVar()->getType());
419 }
420 addData(S->isGenericLambda());
421 addData(S->isMutable());
422 })
423 DEF_ADD_DATA(DeclStmt, {
424 auto numDecls = std::distance(S->decl_begin(), S->decl_end());
425 addData(static_cast<CloneDetector::DataPiece>(numDecls));
426 for (const Decl *D : S->decls()) {
427 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
428 addData(VD->getType());
429 }
430 }
431 })
432 DEF_ADD_DATA(AsmStmt, {
433 addData(S->isSimple());
434 addData(S->isVolatile());
435 addData(S->generateAsmString(Context));
436 for (unsigned i = 0; i < S->getNumInputs(); ++i) {
437 addData(S->getInputConstraint(i));
438 }
439 for (unsigned i = 0; i < S->getNumOutputs(); ++i) {
440 addData(S->getOutputConstraint(i));
441 }
442 for (unsigned i = 0; i < S->getNumClobbers(); ++i) {
443 addData(S->getClobber(i));
444 }
445 })
446 DEF_ADD_DATA(AttributedStmt, {
447 for (const Attr *A : S->getAttrs()) {
448 addData(std::string(A->getSpelling()));
449 }
450 })
451};
452} // end anonymous namespace
453
454namespace {
Artem Dergachevba816322016-07-26 18:13:12 +0000455/// Generates CloneSignatures for a set of statements and stores the results in
456/// a CloneDetector object.
457class CloneSignatureGenerator {
458
459 CloneDetector &CD;
460 ASTContext &Context;
461
462 /// \brief Generates CloneSignatures for all statements in the given statement
463 /// tree and stores them in the CloneDetector.
464 ///
465 /// \param S The root of the given statement tree.
Artem Dergachev51b9a0e2016-08-20 10:06:59 +0000466 /// \param ParentMacroStack A string representing the macros that generated
467 /// the parent statement or an empty string if no
468 /// macros generated the parent statement.
469 /// See getMacroStack() for generating such a string.
Artem Dergachevba816322016-07-26 18:13:12 +0000470 /// \return The CloneSignature of the root statement.
Artem Dergachev51b9a0e2016-08-20 10:06:59 +0000471 CloneDetector::CloneSignature
472 generateSignatures(const Stmt *S, const std::string &ParentMacroStack) {
Artem Dergachevba816322016-07-26 18:13:12 +0000473 // Create an empty signature that will be filled in this method.
474 CloneDetector::CloneSignature Signature;
475
Artem Dergachev56574862016-08-20 17:35:53 +0000476 llvm::MD5 Hash;
477
478 // Collect all relevant data from S and hash it.
479 StmtDataCollector<llvm::MD5>(S, Context, Hash);
Artem Dergachevba816322016-07-26 18:13:12 +0000480
Artem Dergachev51b9a0e2016-08-20 10:06:59 +0000481 // Look up what macros expanded into the current statement.
482 std::string StartMacroStack = getMacroStack(S->getLocStart(), Context);
483 std::string EndMacroStack = getMacroStack(S->getLocEnd(), Context);
484
485 // First, check if ParentMacroStack is not empty which means we are currently
486 // dealing with a parent statement which was expanded from a macro.
487 // If this parent statement was expanded from the same macros as this
488 // statement, we reduce the initial complexity of this statement to zero.
489 // This causes that a group of statements that were generated by a single
490 // macro expansion will only increase the total complexity by one.
491 // Note: This is not the final complexity of this statement as we still
492 // add the complexity of the child statements to the complexity value.
493 if (!ParentMacroStack.empty() && (StartMacroStack == ParentMacroStack &&
494 EndMacroStack == ParentMacroStack)) {
495 Signature.Complexity = 0;
496 }
497
Artem Dergachevba816322016-07-26 18:13:12 +0000498 // Storage for the signatures of the direct child statements. This is only
499 // needed if the current statement is a CompoundStmt.
500 std::vector<CloneDetector::CloneSignature> ChildSignatures;
501 const CompoundStmt *CS = dyn_cast<const CompoundStmt>(S);
502
503 // The signature of a statement includes the signatures of its children.
504 // Therefore we create the signatures for every child and add them to the
505 // current signature.
506 for (const Stmt *Child : S->children()) {
507 // Some statements like 'if' can have nullptr children that we will skip.
508 if (!Child)
509 continue;
510
511 // Recursive call to create the signature of the child statement. This
512 // will also create and store all clone groups in this child statement.
Artem Dergachev51b9a0e2016-08-20 10:06:59 +0000513 // We pass only the StartMacroStack along to keep things simple.
514 auto ChildSignature = generateSignatures(Child, StartMacroStack);
Artem Dergachevba816322016-07-26 18:13:12 +0000515
516 // Add the collected data to the signature of the current statement.
Artem Dergachev56574862016-08-20 17:35:53 +0000517 Signature.Complexity += ChildSignature.Complexity;
518 Hash.update(StringRef(reinterpret_cast<char *>(&ChildSignature.Hash),
519 sizeof(ChildSignature.Hash)));
Artem Dergachevba816322016-07-26 18:13:12 +0000520
521 // If the current statement is a CompoundStatement, we need to store the
522 // signature for the generation of the sub-sequences.
523 if (CS)
524 ChildSignatures.push_back(ChildSignature);
525 }
526
527 // If the current statement is a CompoundStmt, we also need to create the
528 // clone groups from the sub-sequences inside the children.
529 if (CS)
530 handleSubSequences(CS, ChildSignatures);
531
Artem Dergachev56574862016-08-20 17:35:53 +0000532 // Create the final hash code for the current signature.
533 llvm::MD5::MD5Result HashResult;
534 Hash.final(HashResult);
535
536 // Copy as much of the generated hash code to the signature's hash code.
537 std::memcpy(&Signature.Hash, &HashResult,
538 std::min(sizeof(Signature.Hash), sizeof(HashResult)));
539
Artem Dergachevba816322016-07-26 18:13:12 +0000540 // Save the signature for the current statement in the CloneDetector object.
541 CD.add(StmtSequence(S, Context), Signature);
542
543 return Signature;
544 }
545
546 /// \brief Adds all possible sub-sequences in the child array of the given
547 /// CompoundStmt to the CloneDetector.
548 /// \param CS The given CompoundStmt.
549 /// \param ChildSignatures A list of calculated signatures for each child in
550 /// the given CompoundStmt.
551 void handleSubSequences(
552 const CompoundStmt *CS,
553 const std::vector<CloneDetector::CloneSignature> &ChildSignatures) {
554
555 // FIXME: This function has quadratic runtime right now. Check if skipping
556 // this function for too long CompoundStmts is an option.
557
558 // The length of the sub-sequence. We don't need to handle sequences with
559 // the length 1 as they are already handled in CollectData().
560 for (unsigned Length = 2; Length <= CS->size(); ++Length) {
561 // The start index in the body of the CompoundStmt. We increase the
562 // position until the end of the sub-sequence reaches the end of the
563 // CompoundStmt body.
564 for (unsigned Pos = 0; Pos <= CS->size() - Length; ++Pos) {
565 // Create an empty signature and add the signatures of all selected
566 // child statements to it.
567 CloneDetector::CloneSignature SubSignature;
Artem Dergachev56574862016-08-20 17:35:53 +0000568 llvm::MD5 SubHash;
Artem Dergachevba816322016-07-26 18:13:12 +0000569
570 for (unsigned i = Pos; i < Pos + Length; ++i) {
Artem Dergachev56574862016-08-20 17:35:53 +0000571 SubSignature.Complexity += ChildSignatures[i].Complexity;
572 size_t ChildHash = ChildSignatures[i].Hash;
573
574 SubHash.update(StringRef(reinterpret_cast<char *>(&ChildHash),
575 sizeof(ChildHash)));
Artem Dergachevba816322016-07-26 18:13:12 +0000576 }
577
Artem Dergachev56574862016-08-20 17:35:53 +0000578 // Create the final hash code for the current signature.
579 llvm::MD5::MD5Result HashResult;
580 SubHash.final(HashResult);
581
582 // Copy as much of the generated hash code to the signature's hash code.
583 std::memcpy(&SubSignature.Hash, &HashResult,
584 std::min(sizeof(SubSignature.Hash), sizeof(HashResult)));
585
Artem Dergachevba816322016-07-26 18:13:12 +0000586 // Save the signature together with the information about what children
587 // sequence we selected.
588 CD.add(StmtSequence(CS, Context, Pos, Pos + Length), SubSignature);
589 }
590 }
591 }
592
593public:
594 explicit CloneSignatureGenerator(CloneDetector &CD, ASTContext &Context)
595 : CD(CD), Context(Context) {}
596
597 /// \brief Generates signatures for all statements in the given function body.
Artem Dergachev51b9a0e2016-08-20 10:06:59 +0000598 void consumeCodeBody(const Stmt *S) { generateSignatures(S, ""); }
Artem Dergachevba816322016-07-26 18:13:12 +0000599};
600} // end anonymous namespace
601
602void CloneDetector::analyzeCodeBody(const Decl *D) {
603 assert(D);
604 assert(D->hasBody());
605 CloneSignatureGenerator Generator(*this, D->getASTContext());
606 Generator.consumeCodeBody(D->getBody());
607}
608
609void CloneDetector::add(const StmtSequence &S,
610 const CloneSignature &Signature) {
Artem Dergachev56574862016-08-20 17:35:53 +0000611 Sequences.push_back(std::make_pair(Signature, S));
Artem Dergachevba816322016-07-26 18:13:12 +0000612}
613
614namespace {
615/// \brief Returns true if and only if \p Stmt contains at least one other
616/// sequence in the \p Group.
Artem Dergachev7a0088b2016-08-04 19:37:00 +0000617bool containsAnyInGroup(StmtSequence &Stmt, CloneDetector::CloneGroup &Group) {
Artem Dergachevba816322016-07-26 18:13:12 +0000618 for (StmtSequence &GroupStmt : Group.Sequences) {
619 if (Stmt.contains(GroupStmt))
620 return true;
621 }
622 return false;
623}
624
625/// \brief Returns true if and only if all sequences in \p OtherGroup are
626/// contained by a sequence in \p Group.
627bool containsGroup(CloneDetector::CloneGroup &Group,
628 CloneDetector::CloneGroup &OtherGroup) {
629 // We have less sequences in the current group than we have in the other,
630 // so we will never fulfill the requirement for returning true. This is only
631 // possible because we know that a sequence in Group can contain at most
632 // one sequence in OtherGroup.
633 if (Group.Sequences.size() < OtherGroup.Sequences.size())
634 return false;
635
636 for (StmtSequence &Stmt : Group.Sequences) {
637 if (!containsAnyInGroup(Stmt, OtherGroup))
638 return false;
639 }
640 return true;
641}
642} // end anonymous namespace
643
Artem Dergachev56574862016-08-20 17:35:53 +0000644namespace {
645/// \brief Wrapper around FoldingSetNodeID that it can be used as the template
646/// argument of the StmtDataCollector.
647class FoldingSetNodeIDWrapper {
648
649 llvm::FoldingSetNodeID &FS;
650
651public:
652 FoldingSetNodeIDWrapper(llvm::FoldingSetNodeID &FS) : FS(FS) {}
653
654 void update(StringRef Str) { FS.AddString(Str); }
655};
656} // end anonymous namespace
657
658/// \brief Writes the relevant data from all statements and child statements
659/// in the given StmtSequence into the given FoldingSetNodeID.
660static void CollectStmtSequenceData(const StmtSequence &Sequence,
661 FoldingSetNodeIDWrapper &OutputData) {
662 for (const Stmt *S : Sequence) {
663 StmtDataCollector<FoldingSetNodeIDWrapper>(S, Sequence.getASTContext(),
664 OutputData);
665
666 for (const Stmt *Child : S->children()) {
667 if (!Child)
668 continue;
669
670 CollectStmtSequenceData(StmtSequence(Child, Sequence.getASTContext()),
671 OutputData);
672 }
673 }
674}
675
676/// \brief Returns true if both sequences are clones of each other.
677static bool areSequencesClones(const StmtSequence &LHS,
678 const StmtSequence &RHS) {
679 // We collect the data from all statements in the sequence as we did before
680 // when generating a hash value for each sequence. But this time we don't
681 // hash the collected data and compare the whole data set instead. This
682 // prevents any false-positives due to hash code collisions.
683 llvm::FoldingSetNodeID DataLHS, DataRHS;
684 FoldingSetNodeIDWrapper LHSWrapper(DataLHS);
685 FoldingSetNodeIDWrapper RHSWrapper(DataRHS);
686
687 CollectStmtSequenceData(LHS, LHSWrapper);
688 CollectStmtSequenceData(RHS, RHSWrapper);
689
690 return DataLHS == DataRHS;
691}
692
Artem Dergachev7a0088b2016-08-04 19:37:00 +0000693/// \brief Finds all actual clone groups in a single group of presumed clones.
Artem Dergachev56574862016-08-20 17:35:53 +0000694/// \param Result Output parameter to which all found groups are added.
695/// \param Group A group of presumed clones. The clones are allowed to have a
696/// different variable pattern and may not be actual clones of each
697/// other.
698/// \param CheckVariablePatterns If true, every clone in a group that was added
699/// to the output follows the same variable pattern as the other
700/// clones in its group.
Artem Dergachev7a0088b2016-08-04 19:37:00 +0000701static void createCloneGroups(std::vector<CloneDetector::CloneGroup> &Result,
Artem Dergachev56574862016-08-20 17:35:53 +0000702 const CloneDetector::CloneGroup &Group,
703 bool CheckVariablePattern) {
Artem Dergachev7a0088b2016-08-04 19:37:00 +0000704 // We remove the Sequences one by one, so a list is more appropriate.
705 std::list<StmtSequence> UnassignedSequences(Group.Sequences.begin(),
706 Group.Sequences.end());
707
708 // Search for clones as long as there could be clones in UnassignedSequences.
709 while (UnassignedSequences.size() > 1) {
710
711 // Pick the first Sequence as a protoype for a new clone group.
712 StmtSequence Prototype = UnassignedSequences.front();
713 UnassignedSequences.pop_front();
714
Artem Dergachev56574862016-08-20 17:35:53 +0000715 CloneDetector::CloneGroup FilteredGroup(Prototype, Group.Signature);
Artem Dergachev7a0088b2016-08-04 19:37:00 +0000716
717 // Analyze the variable pattern of the prototype. Every other StmtSequence
718 // needs to have the same pattern to get into the new clone group.
719 VariablePattern PrototypeFeatures(Prototype);
720
721 // Search all remaining StmtSequences for an identical variable pattern
722 // and assign them to our new clone group.
723 auto I = UnassignedSequences.begin(), E = UnassignedSequences.end();
724 while (I != E) {
Artem Dergachev56574862016-08-20 17:35:53 +0000725 // If the sequence doesn't fit to the prototype, we have encountered
726 // an unintended hash code collision and we skip it.
727 if (!areSequencesClones(Prototype, *I)) {
728 ++I;
729 continue;
730 }
Artem Dergachev2fc19852016-08-18 12:29:41 +0000731
Artem Dergachev56574862016-08-20 17:35:53 +0000732 // If we weren't asked to check for a matching variable pattern in clone
733 // groups we can add the sequence now to the new clone group.
734 // If we were asked to check for matching variable pattern, we first have
735 // to check that there are no differences between the two patterns and
736 // only proceed if they match.
737 if (!CheckVariablePattern ||
738 VariablePattern(*I).countPatternDifferences(PrototypeFeatures) == 0) {
Artem Dergachev7a0088b2016-08-04 19:37:00 +0000739 FilteredGroup.Sequences.push_back(*I);
740 I = UnassignedSequences.erase(I);
741 continue;
742 }
Artem Dergachev56574862016-08-20 17:35:53 +0000743
744 // We didn't found a matching variable pattern, so we continue with the
745 // next sequence.
Artem Dergachev7a0088b2016-08-04 19:37:00 +0000746 ++I;
747 }
748
749 // Add a valid clone group to the list of found clone groups.
750 if (!FilteredGroup.isValid())
751 continue;
752
753 Result.push_back(FilteredGroup);
754 }
755}
756
Artem Dergachevba816322016-07-26 18:13:12 +0000757void CloneDetector::findClones(std::vector<CloneGroup> &Result,
Artem Dergachev2fc19852016-08-18 12:29:41 +0000758 unsigned MinGroupComplexity,
759 bool CheckPatterns) {
Artem Dergachev56574862016-08-20 17:35:53 +0000760 // A shortcut (and necessary for the for-loop later in this function).
761 if (Sequences.empty())
762 return;
763
764 // We need to search for groups of StmtSequences with the same hash code to
765 // create our initial clone groups. By sorting all known StmtSequences by
766 // their hash value we make sure that StmtSequences with the same hash code
767 // are grouped together in the Sequences vector.
768 // Note: We stable sort here because the StmtSequences are added in the order
769 // in which they appear in the source file. We want to preserve that order
770 // because we also want to report them in that order in the CloneChecker.
771 std::stable_sort(Sequences.begin(), Sequences.end(),
772 [](std::pair<CloneSignature, StmtSequence> LHS,
773 std::pair<CloneSignature, StmtSequence> RHS) {
774 return LHS.first.Hash < RHS.first.Hash;
775 });
776
777 std::vector<CloneGroup> CloneGroups;
778
779 // Check for each CloneSignature if its successor has the same hash value.
780 // We don't check the last CloneSignature as it has no successor.
781 // Note: The 'size - 1' in the condition is safe because we check for an empty
782 // Sequences vector at the beginning of this function.
783 for (unsigned i = 0; i < Sequences.size() - 1; ++i) {
784 const auto Current = Sequences[i];
785 const auto Next = Sequences[i + 1];
786
787 if (Current.first.Hash != Next.first.Hash)
788 continue;
789
790 // It's likely that we just found an sequence of CloneSignatures that
791 // represent a CloneGroup, so we create a new group and start checking and
792 // adding the CloneSignatures in this sequence.
793 CloneGroup Group;
794 Group.Signature = Current.first;
795
796 for (; i < Sequences.size(); ++i) {
797 const auto &Signature = Sequences[i];
798
799 // A different hash value means we have reached the end of the sequence.
800 if (Current.first.Hash != Signature.first.Hash) {
801 // The current Signature could be the start of a new CloneGroup. So we
802 // decrement i so that we visit it again in the outer loop.
803 // Note: i can never be 0 at this point because we are just comparing
804 // the hash of the Current CloneSignature with itself in the 'if' above.
805 assert(i != 0);
806 --i;
807 break;
808 }
809
810 // Skip CloneSignatures that won't pass the complexity requirement.
811 if (Signature.first.Complexity < MinGroupComplexity)
812 continue;
813
814 Group.Sequences.push_back(Signature.second);
815 }
816
817 // There is a chance that we haven't found more than two fitting
818 // CloneSignature because not enough CloneSignatures passed the complexity
819 // requirement. As a CloneGroup with less than two members makes no sense,
820 // we ignore this CloneGroup and won't add it to the result.
821 if (!Group.isValid())
822 continue;
823
824 CloneGroups.push_back(Group);
825 }
826
Artem Dergachevba816322016-07-26 18:13:12 +0000827 // Add every valid clone group that fulfills the complexity requirement.
828 for (const CloneGroup &Group : CloneGroups) {
Artem Dergachev56574862016-08-20 17:35:53 +0000829 createCloneGroups(Result, Group, CheckPatterns);
Artem Dergachevba816322016-07-26 18:13:12 +0000830 }
831
832 std::vector<unsigned> IndexesToRemove;
833
834 // Compare every group in the result with the rest. If one groups contains
835 // another group, we only need to return the bigger group.
836 // Note: This doesn't scale well, so if possible avoid calling any heavy
837 // function from this loop to minimize the performance impact.
838 for (unsigned i = 0; i < Result.size(); ++i) {
839 for (unsigned j = 0; j < Result.size(); ++j) {
840 // Don't compare a group with itself.
841 if (i == j)
842 continue;
843
844 if (containsGroup(Result[j], Result[i])) {
845 IndexesToRemove.push_back(i);
846 break;
847 }
848 }
849 }
850
851 // Erasing a list of indexes from the vector should be done with decreasing
852 // indexes. As IndexesToRemove is constructed with increasing values, we just
853 // reverse iterate over it to get the desired order.
854 for (auto I = IndexesToRemove.rbegin(); I != IndexesToRemove.rend(); ++I) {
855 Result.erase(Result.begin() + *I);
856 }
857}
Artem Dergachev2fc19852016-08-18 12:29:41 +0000858
859void CloneDetector::findSuspiciousClones(
860 std::vector<CloneDetector::SuspiciousClonePair> &Result,
861 unsigned MinGroupComplexity) {
862 std::vector<CloneGroup> Clones;
863 // Reuse the normal search for clones but specify that the clone groups don't
864 // need to have a common referenced variable pattern so that we can manually
865 // search for the kind of pattern errors this function is supposed to find.
866 findClones(Clones, MinGroupComplexity, false);
867
868 for (const CloneGroup &Group : Clones) {
869 for (unsigned i = 0; i < Group.Sequences.size(); ++i) {
870 VariablePattern PatternA(Group.Sequences[i]);
871
872 for (unsigned j = i + 1; j < Group.Sequences.size(); ++j) {
873 VariablePattern PatternB(Group.Sequences[j]);
874
875 CloneDetector::SuspiciousClonePair ClonePair;
876 // For now, we only report clones which break the variable pattern just
877 // once because multiple differences in a pattern are an indicator that
878 // those differences are maybe intended (e.g. because it's actually
879 // a different algorithm).
880 // TODO: In very big clones even multiple variables can be unintended,
881 // so replacing this number with a percentage could better handle such
882 // cases. On the other hand it could increase the false-positive rate
883 // for all clones if the percentage is too high.
884 if (PatternA.countPatternDifferences(PatternB, &ClonePair) == 1) {
885 Result.push_back(ClonePair);
886 break;
887 }
888 }
889 }
890 }
891}