Debian Codegraph @

clang_delta/ExpressionDetector.cpp

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 //===----------------------------------------------------------------------===//
2 //
3 // Copyright (c) 2016, 2017, 2018, 2019 The University of Utah
4 // All rights reserved.
5 //
6 // This file is distributed under the University of Illinois Open Source
7 // License. See the file COPYING for details.
8 //
9 //===----------------------------------------------------------------------===//
10
11 #if HAVE_CONFIG_H
12 # include <config.h>
13 #endif
14
15 #include "ExpressionDetector.h"
16
17 #include "clang/AST/RecursiveASTVisitor.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/Basic/SourceManager.h"
20 #include "clang/Lex/Preprocessor.h"
21
22 #include "CommonStatementVisitor.h"
23 #include "TransformationManager.h"
24
25 using namespace clang;
26
27 static const char *DescriptionMsg =
28 "Insert a printf statement to print out the value of an expression. \
29 Currently, only expressions of type integer and floating point are \
30 considered valid. The transformation also injects a static control \
31 variable to ensure that the expression of interest will be printed \
32 only once.\n";
33
34 // Some known issues:
35 // (1) Because we don't have any array-bound analysis, this pass will
36 // turn the following code into one that would coredump:
37 // if (argc == 2 && !strcmp(argv[1], "xxx"))
38 // ==>
39 // int __creduce_expr_tmp_xxx = !strcmp(argv[1], "xxx");
40 // ...
41 // (2) we don't perform pointer analysis, the transformed program
42 // will produce different result from the original one, e.g.,
43 // int *x = &g;
44 // foo((*x) += 1 || g);
45 // ==>
46 // int *x = &g;
47 // int __creduce_expr_tmp_xxx = g;
48 // ...
49 // foo((*x) += 1 || __creduce_expr_tmp_xxx);
50
51 static RegisterTransformation<ExpressionDetector>
52 Trans("expression-detector", DescriptionMsg);
53
54 namespace {
55 class IncludesPPCallbacks : public PPCallbacks {
56 public:
57 IncludesPPCallbacks(SourceManager &M, const std::string &Name,
58 bool &H, SourceLocation &Loc)
59 : SrcManager(M), HeaderName(Name), HasHeader(H), HeaderLoc(Loc)
60 { }
61
62 virtual void InclusionDirective(SourceLocation HashLoc,
63 const Token &IncludeTok,
64 StringRef FileName, bool IsAngled,
•65 CharSourceRange FilenameRange,
66 #if LLVM_VERSION_MAJOR < 15
67 const FileEntry *File,
68 #elif LLVM_VERSION_MAJOR < 16
69 Optional<FileEntryRef> File,
70 #else
71 OptionalFileEntryRef File,
72 #endif
73 StringRef SearchPath, StringRef RelativePath,
•74 #if LLVM_VERSION_MAJOR < 19
75 const Module *Imported,
•76 #else
77 const Module *SuggestedModule, bool ModuleImported,
78 #endif
79 SrcMgr::CharacteristicKind FileType) override;
80
81 private:
82 SourceManager &SrcManager;
83
84 const std::string &HeaderName;
85
86 bool &HasHeader;
87
88 SourceLocation &HeaderLoc;
89 };
90
91 void IncludesPPCallbacks::InclusionDirective(SourceLocation HashLoc,
92 const Token &/*IncludeTok*/,
93 StringRef FileName,
•94 bool /*IsAngled*/,
95 CharSourceRange /*FilenameRange*/,
•96 #if LLVM_VERSION_MAJOR < 15
97 const FileEntry * /*File*/,
98 #elif LLVM_VERSION_MAJOR < 16
99 Optional<FileEntryRef> /*File*/,
100 #else
101 OptionalFileEntryRef /*File*/,
•102 #endif
103 StringRef /*SearchPath*/,
104 StringRef /*RelativePath*/,
•105 #if LLVM_VERSION_MAJOR < 19
106 const Module *Imported,
107 #else
108 const Module *SuggestedModule, bool ModuleImported,
109 #endif
110 SrcMgr::CharacteristicKind /*FileType*/)
111 {
112 if (!SrcManager.isInMainFile(HashLoc))
113 return;
114 // We may have multiple "#include <stdio.h>". Only handle the first one.
115 if (!HasHeader && FileName == HeaderName) {
116 HasHeader = true;
117 HeaderLoc = HashLoc;
118 }
119 }
120
121 // Collecting all tmp vars __creduce_expr_tmp_xxx within a statement
122 // generated by C-Reduce
123 class LocalTmpVarCollector : public RecursiveASTVisitor<LocalTmpVarCollector> {
124 public:
125 LocalTmpVarCollector(SmallVector<const VarDecl *, 4> &V, const std::string &P)
126 : TmpVars(V), Prefix(P)
127 { }
128
129 bool VisitDeclRefExpr(DeclRefExpr *DRE);
130
131 private:
132 SmallVector<const VarDecl *, 4> &TmpVars;
133
134 const std::string &Prefix;
135 };
136
137 bool LocalTmpVarCollector::VisitDeclRefExpr(DeclRefExpr *DRE)
138 {
139 const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl());
140 if (!VD)
141 return true;
•142 #if LLVM_VERSION_MAJOR < 18
143 if (VD->getName().startswith(Prefix))
•144 #else
145 if (VD->getName().starts_with(Prefix))
146 #endif
147 TmpVars.push_back(VD);
148 return true;
149 }
150
151 // For a given statement, collect all expressions, each of which is
152 // (1) either the sub-expression of an inc, dec or addrof operator; or
153 // (2) the LHS of a binary operator;
154 class LocalUOBOVisitor : public RecursiveASTVisitor<LocalUOBOVisitor> {
155 public:
156 explicit LocalUOBOVisitor(llvm::SmallPtrSet<const Expr *, 10> &ES)
157 : InvalidExprs(ES)
158 { }
159
160 bool VisitUnaryOperator(UnaryOperator *UO);
161
162 bool VisitBinaryOperator(BinaryOperator *BO);
163
164 private:
165 llvm::SmallPtrSet<const Expr *, 10> &InvalidExprs;
166 };
167
168 bool LocalUOBOVisitor::VisitUnaryOperator(UnaryOperator *UO)
169 {
170 if (!UO->isIncrementDecrementOp() && UO->getOpcode() != UO_AddrOf)
171 return true;
172
173 const Expr *E = UO->getSubExpr();
174 InvalidExprs.insert(E->IgnoreParenImpCasts());
175 return true;
176 }
177
178 bool LocalUOBOVisitor::VisitBinaryOperator(BinaryOperator *BO)
179 {
180 if (!BO->isAssignmentOp())
181 return true;
182 const Expr *E = BO->getLHS();
183 InvalidExprs.insert(E->IgnoreParenImpCasts());
184 return true;
185 }
186
187 } // End anonymous namespace
188
189 class ExprDetectorTempVarVisitor :
190 public RecursiveASTVisitor<ExprDetectorTempVarVisitor> {
191 public:
192
193 explicit ExprDetectorTempVarVisitor(ExpressionDetector *Instance)
194 : ConsumerInstance(Instance)
195 { }
196
197 bool VisitDeclStmt(DeclStmt *DS);
198
199 private:
200
201 ExpressionDetector *ConsumerInstance;
202 };
203
204 bool ExprDetectorTempVarVisitor::VisitDeclStmt(DeclStmt *DS)
205 {
206 for (auto I : DS->decls()) {
207 ConsumerInstance->addOneTempVar(dyn_cast<VarDecl>(I));
208 }
209 return true;
210 }
211
212 class ExprDetectorCollectionVisitor :
213 public RecursiveASTVisitor<ExprDetectorCollectionVisitor> {
214 public:
215
216 explicit ExprDetectorCollectionVisitor(ExpressionDetector *Instance)
217 : ConsumerInstance(Instance)
218 { }
219
220 bool VisitFunctionDecl(FunctionDecl *FD);
221
222 private:
223
224 ExpressionDetector *ConsumerInstance;
225 };
226
227 class ExprDetectorStmtVisitor :
228 public CommonStatementVisitor<ExprDetectorStmtVisitor> {
229 public:
230
231 explicit ExprDetectorStmtVisitor(ExpressionDetector *Instance)
232 : ConsumerInstance(Instance)
233 { }
234
235 bool VisitExpr(Expr *E);
236
237 private:
238 ExpressionDetector *ConsumerInstance;
239 };
240
241 bool ExprDetectorCollectionVisitor::VisitFunctionDecl(FunctionDecl *FD)
242 {
243 if (!ConsumerInstance->HFInfo.HasFunction &&
244 FD->getNameAsString() == ConsumerInstance->HFInfo.FunctionName) {
245 ConsumerInstance->HFInfo.HasFunction = true;
246 ConsumerInstance->HFInfo.FunctionLoc = FD->getSourceRange().getBegin();
247 }
248
249 if (ConsumerInstance->isInIncludedFile(FD) ||
250 !FD->isThisDeclarationADefinition())
251 return true;
252
253 ExprDetectorTempVarVisitor VarVisitor(ConsumerInstance);
254 VarVisitor.TraverseDecl(FD);
255
256 ExprDetectorStmtVisitor StmtVisitor(ConsumerInstance);
257 StmtVisitor.setCurrentFunctionDecl(FD);
258 StmtVisitor.TraverseDecl(FD);
259 StmtVisitor.setCurrentFunctionDecl(NULL);
260 ConsumerInstance->UniqueExprs.clear();
261 ConsumerInstance->ProcessedExprs.clear();
262 return true;
263 }
264
265 bool ExprDetectorStmtVisitor::VisitExpr(Expr *E)
266 {
267 if (ConsumerInstance->isInIncludedFile(E))
268 return true;
269
270 switch(E->getStmtClass()) {
271 default: return true;
272
273 case Expr::ArraySubscriptExprClass:
274 case Expr::BinaryOperatorClass:
275 case Expr::CallExprClass:
276 case Expr::DeclRefExprClass:
277 case Expr::MemberExprClass:
278 case Expr::UnaryOperatorClass: // Fall-through
279 break;
280 }
281
282 const Type *Ty = E->getType().getTypePtr();
283 // Currently, integer and floating point only.
284 if (!Ty->isIntegerType() && !Ty->isFloatingType())
285 return true;
286
287 if (!ConsumerInstance->isValidExpr(CurrentStmt, E))
288 return true;
289
290 ConsumerInstance->ValidInstanceNum++;
291 if (ConsumerInstance->ValidInstanceNum ==
292 ConsumerInstance->TransformationCounter) {
293 ConsumerInstance->TheFunc = CurrentFuncDecl;
294 ConsumerInstance->TheStmt = CurrentStmt;
295 ConsumerInstance->TheExpr = E;
296 }
297 return true;
298 }
299
300 void ExpressionDetector::Initialize(ASTContext &context)
301 {
302 Transformation::Initialize(context);
303 CollectionVisitor = new ExprDetectorCollectionVisitor(this);
304 if (CheckReference) {
305 ControlVarNamePrefix = CheckedVarNamePrefix;
306 HFInfo.HeaderName = "stdlib.h";
307 HFInfo.FunctionName = "abort";
308 HFInfo.FunctionDeclStr = "void abort(void)";
309 }
310 else {
311 ControlVarNamePrefix = PrintedVarNamePrefix;
312 HFInfo.HeaderName = "stdio.h";
313 HFInfo.FunctionName = "printf";
314 HFInfo.FunctionDeclStr = "int printf(const char *format, ...)";
315 }
316
317 ControlVarNameQueryWrap =
318 new TransNameQueryWrap(ControlVarNamePrefix);
319 TmpVarNameQueryWrap =
320 new TransNameQueryWrap(TmpVarNamePrefix);
321 Preprocessor &PP = TransformationManager::getPreprocessor();
322 IncludesPPCallbacks *C =
323 new IncludesPPCallbacks(PP.getSourceManager(),
324 HFInfo.HeaderName,
325 HFInfo.HasHeader,
326 HFInfo.HeaderLoc);
327 PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(C));
328 }
329
330 bool ExpressionDetector::HandleTopLevelDecl(DeclGroupRef D)
331 {
332 // Skip C++ programs for now.
333 if (TransformationManager::isCXXLangOpt()) {
334 ValidInstanceNum = 0;
335 return true;
336 }
337
338 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
339 CollectionVisitor->TraverseDecl(*I);
340 }
341 return true;
342 }
343
344 void ExpressionDetector::HandleTranslationUnit(ASTContext &Ctx)
345 {
346 if (QueryInstanceOnly)
347 return;
348
349 if (TransformationCounter > ValidInstanceNum) {
350 TransError = TransMaxInstanceError;
351 return;
352 }
353
354 Ctx.getDiagnostics().setSuppressAllDiagnostics(false);
355
356 TransAssert(TheFunc && "NULL TheFunc!");
357 TransAssert(TheStmt && "NULL TheStmt!");
358 TransAssert(TheExpr && "NULL TheExpr");
359
360 if (DoReplacement) {
361 RewriteHelper->replaceExpr(TheExpr, Replacement);
362 }
363 else {
364 ControlVarNameQueryWrap->TraverseDecl(TheFunc);
365 TmpVarNameQueryWrap->TraverseDecl(TheFunc);
366 doRewrite();
367 }
368
369 if (Ctx.getDiagnostics().hasErrorOccurred() ||
370 Ctx.getDiagnostics().hasFatalErrorOccurred())
371 TransError = TransInternalError;
372 }
373
374 // Return true if
375 // (1) we don't have the function declaration or the decl appears after
376 // the recorded FunctionLoc; and
377 // (2) header file is not included in the main file or header file
378 // appears after the Loc.
379 bool ExpressionDetector::shouldAddFunctionDecl(SourceLocation Loc)
380 {
381 return (!HFInfo.HasFunction ||
382 SrcManager->isBeforeInSLocAddrSpace(Loc, HFInfo.FunctionLoc)) &&
383 (!HFInfo.HasHeader ||
384 SrcManager->isBeforeInSLocAddrSpace(Loc, HFInfo.HeaderLoc));
385 }
386
387 void ExpressionDetector::addOneTempVar(const VarDecl *VD)
388 {
389 if (!VD)
390 return;
•391 #if LLVM_VERSION_MAJOR < 18
392 if (!VD->getName().startswith(TmpVarNamePrefix))
•393 #else
394 if (!VD->getName().starts_with(TmpVarNamePrefix))
395 #endif
396 return;
397 if (const Expr *E = VD->getInit())
398 ProcessedExprs[VD] = E->IgnoreParenImpCasts();
399 }
400
401 bool ExpressionDetector::refToTmpVar(const NamedDecl *ND)
402 {
403 StringRef Name = ND->getName();
404 // We don't want to repeatly replace temporary variables
405 // __creduce_expr_tmp_xxx, __creduce_printed_yy and __creduce_checked_zzz.
•406 #if LLVM_VERSION_MAJOR < 18
407 return Name.startswith(TmpVarNamePrefix) ||
408 Name.startswith(PrintedVarNamePrefix) ||
409 Name.startswith(CheckedVarNamePrefix);
•410 #else
411 return Name.starts_with(TmpVarNamePrefix) ||
412 Name.starts_with(PrintedVarNamePrefix) ||
413 Name.starts_with(CheckedVarNamePrefix);
414 #endif
415 }
416
417 // Reference: IdenticalExprChecker.cpp from Clang
418 bool ExpressionDetector::isIdenticalExpr(const Expr *E1, const Expr *E2)
419 {
420 if (!E1 || !E2)
421 return !E1 && !E2;
422
423 E1 = E1->IgnoreParenImpCasts();
424 E2 = E2->IgnoreParenImpCasts();
425 Stmt::StmtClass SC1 = E1->getStmtClass();
426 Stmt::StmtClass SC2 = E2->getStmtClass();
427 if (SC1 != SC2)
428 return false;
429
430 // If either of E1 or E2 has side-effects, treat them as non-identical
431 // expressions.
432 if (E1->HasSideEffects(*Context) || E2->HasSideEffects(*Context))
433 return false;
434
435 Expr::const_child_iterator I1 = E1->child_begin(), I2 = E2->child_begin();
436 while (I1 != E1->child_end() && I2 != E2->child_end()) {
437 if (!isIdenticalExpr(dyn_cast<Expr>(*I1), dyn_cast<Expr>(*I2)))
438 return false;
439 ++I1;
440 ++I2;
441 }
442 if (I1 != E1->child_end() || I2 != E2->child_end())
443 return false;
444
445 switch (SC1) {
446 default:
447 return false;
448 case Stmt::ArraySubscriptExprClass:
449 case Stmt::CallExprClass: // Fall-through
450 return true;
451
452 case Stmt::CStyleCastExprClass: {
453 const CStyleCastExpr *Cast1 = cast<CStyleCastExpr>(E1);
454 const CStyleCastExpr *Cast2 = cast<CStyleCastExpr>(E2);
455 return Cast1->getTypeAsWritten() == Cast2->getTypeAsWritten();
456 }
457
458 case Stmt::MemberExprClass: {
459 const MemberExpr *ME1 = cast<MemberExpr>(E1);
460 const MemberExpr *ME2 = cast<MemberExpr>(E2);
461 return ME1->getMemberDecl() == ME2->getMemberDecl();
462 }
463
464 case Stmt::DeclRefExprClass: {
465 const DeclRefExpr *DRE1 = cast<DeclRefExpr>(E1);
466 const DeclRefExpr *DRE2 = cast<DeclRefExpr>(E2);
467 return DRE1->getDecl() == DRE2->getDecl();
468 }
469
470 case Stmt::CompoundAssignOperatorClass:
471 case Stmt::BinaryOperatorClass: // Fall-through
472 {
473 const BinaryOperator *BO1 = cast<BinaryOperator>(E1);
474 const BinaryOperator *BO2 = cast<BinaryOperator>(E2);
475 return BO1->getOpcode() == BO2->getOpcode();
476 }
477
478 case Stmt::UnaryOperatorClass:
479 {
480 const UnaryOperator *UO1 = cast<UnaryOperator>(E1);
481 const UnaryOperator *UO2 = cast<UnaryOperator>(E2);
482 return UO1->getOpcode() == UO2->getOpcode();
483 }
484
485 case Stmt::CharacterLiteralClass: {
486 const CharacterLiteral *Lit1 = cast<CharacterLiteral>(E1);
487 const CharacterLiteral *Lit2 = cast<CharacterLiteral>(E2);
488 return Lit1->getValue() == Lit2->getValue();
489 }
490
491 case Stmt::StringLiteralClass: {
492 const clang::StringLiteral *Lit1 = cast<clang::StringLiteral>(E1);
493 const clang::StringLiteral *Lit2 = cast<clang::StringLiteral>(E2);
494 return Lit1->getBytes() == Lit2->getBytes();
495 }
496
497 case Stmt::IntegerLiteralClass: {
498 const IntegerLiteral *Lit1 = cast<IntegerLiteral>(E1);
499 const IntegerLiteral *Lit2 = cast<IntegerLiteral>(E2);
500 llvm::APInt I1 = Lit1->getValue();
501 llvm::APInt I2 = Lit2->getValue();
502 return I1.getBitWidth() == I2.getBitWidth() && I1 == I2;
503 }
504
505 case Stmt::FloatingLiteralClass: {
506 const FloatingLiteral *Lit1 = cast<FloatingLiteral>(E1);
507 const FloatingLiteral *Lit2 = cast<FloatingLiteral>(E2);
508 return Lit1->getValue().bitwiseIsEqual(Lit2->getValue());
509 }
510
511 }
512
513 return true;
514 }
515
516 bool ExpressionDetector::hasIdenticalExpr(
517 const SmallVector<const VarDecl *, 4> &TmpVars, const Expr *E)
518 {
519 for (auto V : TmpVars) {
520 auto I = ProcessedExprs.find(V);
521 if (I != ProcessedExprs.end() && isIdenticalExpr(I->second, E))
522 return true;
523 }
524 return false;
525 }
526
527 bool ExpressionDetector::isValidExpr(Stmt *S, const Expr *E)
528 {
529 Stmt::StmtClass SC = S->getStmtClass();
530 // Don't mess up with init/condition/inc exprs of loops.
531 if (SC == Stmt::ForStmtClass ||
532 SC == Stmt::DoStmtClass ||
533 SC == Stmt::WhileStmtClass) {
534 return false;
535 }
536
537 if (const Expr *SE = dyn_cast<Expr>(S)) {
538 // Don't do self-replacement. Note that E can't be of paren
539 // or cast expr (See ExprDetectorStmtVisitor::VisitExpr).
540 if (SE->IgnoreParenCasts() == E)
541 return false;
542 }
543
544 if (const DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
545 if (DS->isSingleDecl()) {
546 const NamedDecl *ND = dyn_cast<NamedDecl>(DS->getSingleDecl());
547 if (ND == NULL || refToTmpVar(ND))
548 return false;
549 }
550 else {
551 // Skip group decls for now.
552 return false;
553 }
554 }
555
556 // don't handle !__creduce_printed and !__creduce_checked
557 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
558 if (UO->getOpcode() == UO_LNot) {
559 if (const DeclRefExpr *SubE =
560 dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParenCasts())) {
561 StringRef SubEName = SubE->getDecl()->getName();
•562 #if LLVM_VERSION_MAJOR < 18
563 if (SubEName.startswith(PrintedVarNamePrefix) ||
564 SubEName.startswith(CheckedVarNamePrefix))
•565 #else
566 if (SubEName.starts_with(PrintedVarNamePrefix) ||
567 SubEName.starts_with(CheckedVarNamePrefix))
568 #endif
569 return false;
570 }
571 }
572 }
573
574 // skip if (__creduce_expr_tmp != xxx)
575 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
576 if (BO->getOpcode() == BO_NE) {
577 const Expr *Lhs = BO->getLHS()->IgnoreParenCasts();
578 const Expr *Rhs = BO->getRHS()->IgnoreParenCasts();
579 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Lhs);
580 Stmt::StmtClass SC = Rhs->getStmtClass();
581 bool IsLit = SC == Stmt::IntegerLiteralClass ||
582 SC == Stmt::FloatingLiteralClass;
583 if (IsLit && DRE &&
•584 #if LLVM_VERSION_MAJOR < 18
585 DRE->getDecl()->getName().startswith(TmpVarNamePrefix) &&
•586 #else
587 DRE->getDecl()->getName().starts_with(TmpVarNamePrefix) &&
588 #endif
589 S->getStmtClass() == Stmt::IfStmtClass) {
590 return false;
591 }
592 }
593 }
594
595 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
596 // Don't repeatly process temp vars.
597 if (refToTmpVar(DRE->getDecl()))
598 return false;
599 // Skip cases such as printf("%d", a);
600 if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
601 const FunctionDecl *FD = CE->getDirectCallee();
602 if (FD && FD->getNameAsString() == "printf")
603 return false;
604 }
605 }
606
607 // If the Expr is the LHS of a binary operator, we don't
608 // need to process it, e.g., given
609 // a = x + y;
610 // we don't need to replace "a" with "__creduce_expr_tmp_xxx"
611 //
612 // We also skip x++, --x and &x, because we don't want to make
613 // the following transformation:
614 // x++;
615 // ==>
616 // __creduce_expr_tmp_xxx = x;
617 // ++__creduce_expr_tmp_xxx;
618 // In the original code, we pre-increment x, but after the "transformation",
619 // we would end up doing that for __creduce_expr_tmp_xxx.
620 // Note that we cache the result, because we don't want to re-visit the same
621 // statement many times. Gain a log of performance improvement.
622 auto EI = InvalidExprsInUOBO.find(S);
623 if (EI == InvalidExprsInUOBO.end()) {
624 llvm::SmallPtrSet<const Expr *, 10> InvalidExprs;
625 LocalUOBOVisitor UOBOVisitor(InvalidExprs);
626 UOBOVisitor.TraverseStmt(S);
627 InvalidExprsInUOBO[S] = InvalidExprs;
628 if (InvalidExprs.count(E))
629 return false;
630 }
631 else if (EI->second.count(E)) {
632 return false;
633 }
634
635 // Skip identical expression. For example, for
636 // the given statement below:
637 // x = y[1] + y[1] + y[1];
638 // we only need to print one y[1] before the assignment statement.
639 // This optimization is able to avoid a lots of dups.
640 auto &Vec = UniqueExprs[S];
641 for (auto I : Vec) {
642 if (isIdenticalExpr(I, E))
643 return false;
644 }
645 // update UniqueExprs
646 Vec.push_back(E);
647
648 // The optimization above only works for single iteration. The code
649 // below handles the following patterns:
650 // int __creduce_expr_tmp_1 = y[1];
651 // ...printf("%d\n", __creduce_expr_tmp_1);
652 // x = __creduce_expr_tmp_1 + y[1] + y[1]
653 // We don't need to generate another tmp var for y[1] in this case.
654 auto VI = TmpVarsInStmt.find(S);
655 if (VI == TmpVarsInStmt.end()) {
656 SmallVector<const VarDecl *, 4> TmpVars;
657 LocalTmpVarCollector TmpCollector(TmpVars, TmpVarNamePrefix);
658 TmpCollector.TraverseStmt(S);
659 TmpVarsInStmt[S] = TmpVars;
660 if (hasIdenticalExpr(TmpVars, E))
661 return false;
662 }
663 else if (hasIdenticalExpr(VI->second, E)) {
664 return false;
665 }
666
667 return true;
668 }
669
670 static std::string getFormatString(const BuiltinType *BT)
671 {
672 switch(BT->getKind()) {
673 default:
674 TransAssert(0 && "Bad BuiltinType!");
675 return "";
676
677 case BuiltinType::Bool:
678 case BuiltinType::Char_U:
679 case BuiltinType::WChar_U:
680 case BuiltinType::UChar:
681 case BuiltinType::UShort:
682 case BuiltinType::UInt:
683 return "u";
684
685 case BuiltinType::Char_S:
686 case BuiltinType::SChar:
687 case BuiltinType::WChar_S:
688 case BuiltinType::Short:
689 case BuiltinType::Int:
690 case BuiltinType::Char16:
691 case BuiltinType::Char32:
692 return "d";
693
694 case BuiltinType::ULong:
695 return "lu";
696
697 case BuiltinType::Long:
698 return "ld";
699
700 case BuiltinType::ULongLong:
701 return "llu";
702
703 case BuiltinType::LongLong:
704 return "lld";
705
706 case BuiltinType::Float:
707 case BuiltinType::Double:
708 return "f";
709
710 case BuiltinType::LongDouble:
711 return "Lf";
712 }
713
714 return "";
715 }
716
717 void ExpressionDetector::doRewrite()
718 {
719 SourceLocation LocStart = TheStmt->getBeginLoc();
720 if (shouldAddFunctionDecl(LocStart)) {
721 SourceLocation Loc =
722 SrcManager->getLocForStartOfFile(SrcManager->getMainFileID());
723 TheRewriter.InsertText(Loc, HFInfo.FunctionDeclStr+";\n");
724 }
725
726 std::string Str, ExprStr, TmpVarName;
727 RewriteHelper->getExprString(TheExpr, ExprStr);
728
729 std::string TyStr;
730 TheExpr->getType().getAsStringInternal(TyStr, Context->getPrintingPolicy());
731 TmpVarName = TmpVarNamePrefix +
732 std::to_string(TmpVarNameQueryWrap->getMaxNamePostfix()+1);
733 Str += TyStr + " " + TmpVarName + " = " + ExprStr + ";\n";
734
735 std::string ControlVarName = ControlVarNamePrefix +
736 std::to_string(ControlVarNameQueryWrap->getMaxNamePostfix()+1);
737 Str += "static int " + ControlVarName + " = 0;\n";
738 Str += "if (" + ControlVarName + " == __CREDUCE_INSTANCE_NUMBER) {\n";
739 if (CheckReference) {
740 Str += " if (" + TmpVarName + " != " + ReferenceValue + ") ";
741 Str += HFInfo.FunctionName + "();\n";
742 }
743 else {
744 const Type *Ty =
745 TheExpr->getType().getTypePtr()->getUnqualifiedDesugaredType();
746 std::string FormatStr = getFormatString(dyn_cast<BuiltinType>(Ty));
747 Str += " " + HFInfo.FunctionName;
748 Str += "(\"creduce_value(%" + FormatStr + ")\\n\", ";
749 Str += TmpVarName + ");\n";
750 }
751 Str += "}\n";
752 Str += "++" + ControlVarName + ";";
753
754 bool NeedParen = TheStmt->getStmtClass() != Stmt::DeclStmtClass;
755 RewriteHelper->addStringBeforeStmtAndReplaceExpr(TheStmt, Str,
756 TheExpr, TmpVarName,
757 NeedParen);
758 }
759
760 ExpressionDetector::~ExpressionDetector(void)
761 {
762 delete CollectionVisitor;
763 delete ControlVarNameQueryWrap;
764 delete TmpVarNameQueryWrap;
765 }