klee
ExprSMTLIBPrinter.cpp
Go to the documentation of this file.
1//===-- ExprSMTLIBPrinter.cpp -----------------------------------*- C++ -*-===//
2//
3// The KLEE Symbolic Virtual Machine
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
12
13#include "llvm/Support/CommandLine.h"
14#include "llvm/Support/ErrorHandling.h"
15
16#include <stack>
17
19// Command line options
20llvm::cl::opt<klee::ExprSMTLIBPrinter::ConstantDisplayMode>
22 "smtlib-display-constants",
23 llvm::cl::desc("Sets how bitvector constants are written in generated "
24 "SMT-LIBv2 files (default=dec)"),
25 llvm::cl::values(clEnumValN(klee::ExprSMTLIBPrinter::BINARY, "bin",
26 "Use binary form (e.g. #b00101101)"),
27 clEnumValN(klee::ExprSMTLIBPrinter::HEX, "hex",
28 "Use Hexadecimal form (e.g. #x2D)"),
29 clEnumValN(klee::ExprSMTLIBPrinter::DECIMAL, "dec",
30 "Use decimal form (e.g. (_ bv45 8) )")),
32 llvm::cl::cat(klee::ExprCat));
33
34llvm::cl::opt<bool>
35 humanReadableSMTLIB("smtlib-human-readable",
36 llvm::cl::desc("Enables generated SMT-LIBv2 files to "
37 "be human readable (default=false)"),
38 llvm::cl::init(false), llvm::cl::cat(klee::ExprCat));
39
40llvm::cl::opt<klee::ExprSMTLIBPrinter::AbbreviationMode> abbreviationMode(
41 "smtlib-abbreviation-mode",
42 llvm::cl::desc(
43 "Choose abbreviation mode to use in SMT-LIBv2 files (default=let)"),
44 llvm::cl::values(clEnumValN(klee::ExprSMTLIBPrinter::ABBR_NONE, "none",
45 "Do not abbreviate"),
46 clEnumValN(klee::ExprSMTLIBPrinter::ABBR_LET, "let",
47 "Abbreviate with let"),
48 clEnumValN(klee::ExprSMTLIBPrinter::ABBR_NAMED, "named",
49 "Abbreviate with :named annotations")),
51 llvm::cl::cat(klee::ExprCat));
52} // namespace ExprSMTLIBOptions
53
54namespace klee {
55
57 : usedArrays(), o(NULL), query(NULL), p(NULL), haveConstantArray(false),
58 logicToUse(QF_AUFBV),
60 smtlibBoolOptions(), arraysToCallGetValueOn(NULL) {
63}
64
66 delete p;
67}
68
69void ExprSMTLIBPrinter::setOutput(llvm::raw_ostream &output) {
70 o = &output;
71 delete p;
72
73 p = new PrintContext(output);
74}
75
77 query = &q;
78 reset(); // clear the data structures
79 scanAll();
80}
81
83 bindings.clear();
84 orderedBindings.clear();
85 seenExprs.clear();
86 usedArrays.clear();
87 haveConstantArray = false;
88
89 /* Clear the PRODUCE_MODELS option if it was automatically set.
90 * We need to do this because the next query might not need the
91 * (get-value) SMT-LIBv2 command.
92 */
93 if (arraysToCallGetValueOn != NULL)
95
97}
98
100
102 if (cdm > DECIMAL)
103 return false;
104
105 this->cdm = cdm;
106 return true;
107}
108
110 /* Handle simple boolean constants */
111
112 if (e->isTrue()) {
113 *p << "true";
114 return;
115 }
116
117 if (e->isFalse()) {
118 *p << "false";
119 return;
120 }
121
122 /* Handle bitvector constants */
123
124 std::string value;
125
126 /* SMTLIBv2 deduces the bit-width (should be 8-bits in our case)
127 * from the length of the string (e.g. zero is #b00000000). LLVM
128 * doesn't know about this so we need to pad the printed output
129 * with the appropriate number of zeros (zeroPad)
130 */
131 unsigned int zeroPad = 0;
132
133 switch (cdm) {
134 case BINARY:
135 e->toString(value, 2);
136 *p << "#b";
137
138 zeroPad = e->getWidth() - value.length();
139
140 for (unsigned int count = 0; count < zeroPad; count++)
141 *p << "0";
142
143 *p << value;
144 break;
145
146 case HEX:
147 e->toString(value, 16);
148 *p << "#x";
149
150 zeroPad = (e->getWidth() / 4) - value.length();
151 for (unsigned int count = 0; count < zeroPad; count++)
152 *p << "0";
153
154 *p << value;
155 break;
156
157 case DECIMAL:
158 e->toString(value, 10);
159 *p << "(_ bv" << value << " " << e->getWidth() << ")";
160 break;
161
162 default:
163 llvm_unreachable("Unexpected constant display mode");
164 }
165}
166
168 const ref<Expr> &e, ExprSMTLIBPrinter::SMTLIB_SORT expectedSort) {
169 // check if casting might be necessary
170 if (getSort(e) != expectedSort) {
171 printCastToSort(e, expectedSort);
172 return;
173 }
174
175 switch (abbrMode) {
176 case ABBR_NONE:
177 break;
178
179 case ABBR_LET: {
180 BindingMap::iterator i = bindings.find(e);
181 if (i != bindings.end()) {
182 *p << "?B" << i->second;
183 return;
184 }
185 break;
186 }
187
188 case ABBR_NAMED: {
189 BindingMap::iterator i = bindings.find(e);
190 if (i != bindings.end()) {
191 if (i->second > 0) {
192 *p << "(! ";
193 printFullExpression(e, expectedSort);
194 *p << " :named ?B" << i->second << ")";
195 i->second = -i->second;
196 } else {
197 *p << "?B" << -i->second;
198 }
199 return;
200 }
201 break;
202 }
203 }
204
205 printFullExpression(e, expectedSort);
206}
207
209 const ref<Expr> &e, ExprSMTLIBPrinter::SMTLIB_SORT expectedSort) {
210 switch (e->getKind()) {
211 case Expr::Constant:
212 printConstant(cast<ConstantExpr>(e));
213 return; // base case
214
216 // skip to child
217 printExpression(e->getKid(0), expectedSort);
218 return;
219
220 case Expr::Read:
221 printReadExpr(cast<ReadExpr>(e));
222 return;
223
224 case Expr::Extract:
225 printExtractExpr(cast<ExtractExpr>(e));
226 return;
227
228 case Expr::SExt:
229 case Expr::ZExt:
230 printCastExpr(cast<CastExpr>(e));
231 return;
232
233 case Expr::Select:
234 // the if-then-else expression.
235 printSelectExpr(cast<SelectExpr>(e), expectedSort);
236 return;
237
238 case Expr::Eq:
239 case Expr::Ne:
240 /* The "=" and distinct operators are special in that it can take any sort
241 * but we must enforce that both arguments are the same sort. We do this in
242 * a lazy way by enforcing the second argument is of the same type as the
243 * first.
244 */
246 return;
247
248 case Expr::And:
249 case Expr::Or:
250 case Expr::Xor:
251 case Expr::Not:
252 /* These operators have a bitvector version and a bool version.
253 * For these operators only (e.g. wouldn't apply to bvult) if the expected
254 * sort of the expression is T then that implies the arguments are also of
255 * type T.
256 */
257 printLogicalOrBitVectorExpr(e, expectedSort);
258 return;
259
260 case Expr::AShr:
261 printAShrExpr(cast<AShrExpr>(e));
262 return;
263
264 default:
265 /* The remaining operators (Add,Sub...,Ult,Ule,..)
266 * Expect SORT_BITVECTOR arguments
267 */
269 return;
270 }
271}
272
274 *p << "(" << getSMTLIBKeyword(e) << " ";
275 p->pushIndent();
276
278
279 // print array with updates recursively
280 printUpdatesAndArray(e->updates.head.get(), e->updates.root);
281
282 // print index
285
286 p->popIndent();
288 *p << ")";
289}
290
292 unsigned int lowIndex = e->offset;
293 unsigned int highIndex = lowIndex + e->width - 1;
294
295 *p << "((_ " << getSMTLIBKeyword(e) << " " << highIndex << " " << lowIndex
296 << ") ";
297
298 p->pushIndent(); // add indent for recursive call
300
301 // recurse
302 printExpression(e->getKid(0), SORT_BITVECTOR);
303
304 p->popIndent(); // pop indent added for the recursive call
306 *p << ")";
307}
308
310 /* sign_extend and zero_extend behave slightly unusually in SMTLIBv2,
311 * instead of specifying of what bit-width we would like to extend to
312 * we specify how many bits to add to the child expression
313 *
314 * e.g
315 * ((_ sign_extend 64) (_ bv5 32))
316 *
317 * gives a (_ BitVec 96) instead of (_ BitVec 64)
318 *
319 * So we must work out how many bits we need to add.
320 *
321 * (e->width) is the desired number of bits
322 * (e->src->getWidth()) is the number of bits in the child
323 */
324 unsigned int numExtraBits = (e->width) - (e->src->getWidth());
325
326 *p << "((_ " << getSMTLIBKeyword(e) << " " << numExtraBits << ") ";
327
328 p->pushIndent(); // add indent for recursive call
330
331 // recurse
333
334 p->popIndent(); // pop indent added for recursive call
336
337 *p << ")";
338}
339
341 // There is a difference between AShr and SMT-LIBv2's
342 // bvashr function when the shift amount is >= the bit width
343 // so we need to treat it specially here.
344 //
345 // Technically this is undefined behaviour for LLVM's ashr operator
346 // but currently llvm::APInt:ashr(...) will emit 0 if the shift amount
347 // is >= the bit width but this does not match how SMT-LIBv2's bvashr
348 // behaves as demonstrates by the following query
349 //
350 // (declare-fun x () (_ BitVec 32))
351 // (declare-fun y () (_ BitVec 32))
352 // (declare-fun result () (_ BitVec 32))
353 // (assert (bvuge y (_ bv32 32)))
354 // (assert (= result (bvashr x y)))
355 // (assert (distinct (_ bv0 32) result))
356 // (check-sat)
357 // sat
358 //
359 // Our solution is to instead emit
360 //
361 // (ite (bvuge shift_amount bit_width)
362 // (_ bv0 bitwidth)
363 // (bvashr value_to_shift shift_amount)
364 // )
365 //
366
367 Expr::Width bitWidth = e->getKid(0)->getWidth();
368 assert(bitWidth > 0 && "Invalid bit width");
369 ref<Expr> bitWidthExpr = ConstantExpr::create(bitWidth, bitWidth);
370 ref<Expr> zeroExpr = ConstantExpr::create(0, bitWidth);
371
372 // FIXME: we print e->getKid(1) twice and it might not get
373 // abbreviated
374 *p << "(ite";
375 p->pushIndent();
377
378 *p << "(bvuge";
379 p->pushIndent();
381 printExpression(e->getKid(1), SORT_BITVECTOR);
383 printExpression(bitWidthExpr, SORT_BITVECTOR);
384 p->popIndent();
386 *p << ")";
387
391
392 *p << "(bvashr";
393 p->pushIndent();
395 printExpression(e->getKid(0), SORT_BITVECTOR);
397 printExpression(e->getKid(1), SORT_BITVECTOR);
398 p->popIndent();
400 *p << ")";
401
402 p->popIndent();
404 *p << ")";
405}
406
408
409 switch (e->getKind()) {
410 case Expr::Read:
411 return "select";
412 case Expr::Select:
413 return "ite";
414 case Expr::Concat:
415 return "concat";
416 case Expr::Extract:
417 return "extract";
418 case Expr::ZExt:
419 return "zero_extend";
420 case Expr::SExt:
421 return "sign_extend";
422
423 case Expr::Add:
424 return "bvadd";
425 case Expr::Sub:
426 return "bvsub";
427 case Expr::Mul:
428 return "bvmul";
429 case Expr::UDiv:
430 return "bvudiv";
431 case Expr::SDiv:
432 return "bvsdiv";
433 case Expr::URem:
434 return "bvurem";
435 case Expr::SRem:
436 return "bvsrem";
437
438 /* And, Xor, Not and Or are not handled here because there different versions
439 * for different sorts. See printLogicalOrBitVectorExpr()
440 */
441
442 case Expr::Shl:
443 return "bvshl";
444 case Expr::LShr:
445 return "bvlshr";
446 // AShr is not supported here. See printAShrExpr()
447
448 case Expr::Eq:
449 return "=";
450 case Expr::Ne:
451 return "distinct";
452
453 case Expr::Ult:
454 return "bvult";
455 case Expr::Ule:
456 return "bvule";
457 case Expr::Ugt:
458 return "bvugt";
459 case Expr::Uge:
460 return "bvuge";
461
462 case Expr::Slt:
463 return "bvslt";
464 case Expr::Sle:
465 return "bvsle";
466 case Expr::Sgt:
467 return "bvsgt";
468 case Expr::Sge:
469 return "bvsge";
470
471 default:
472 llvm_unreachable("Conversion from Expr to SMTLIB keyword failed");
473 }
474}
475
477 const Array *root) {
478 if (un != NULL) {
479 *p << "(store ";
480 p->pushIndent();
482
483 // recurse to get the array or update that this store operations applies to
484 printUpdatesAndArray(un->next.get(), root);
485
487
488 // print index
491
492 // print value that is assigned to this index of the array
494
495 p->popIndent();
497 *p << ")";
498 } else {
499 // The base case of the recursion
500 *p << root->name;
501 }
502}
503
505 // perform scan of all expressions
506 for (const auto &constraint : query->constraints)
507 scan(constraint);
508
509 // Scan the query too
510 scan(query->expr);
511
512 // Scan bindings for expression intra-dependencies
513 if (abbrMode == ABBR_LET)
515}
516
518 if (p == NULL || query == NULL || o == NULL) {
519 llvm::errs() << "ExprSMTLIBPrinter::generateOutput() Can't print SMTLIBv2. "
520 "Output or query bad!\n";
521 return;
522 }
523
524 if (humanReadable)
525 printNotice();
526 printOptions();
529
530 if (humanReadable)
532 else
534
535 printAction();
536 printExit();
537}
538
540 *o << "(set-logic ";
541 switch (logicToUse) {
542 case QF_ABV:
543 *o << "QF_ABV";
544 break;
545 case QF_AUFBV:
546 *o << "QF_AUFBV";
547 break;
548 }
549 *o << " )\n";
550}
551
552namespace {
553
554struct ArrayPtrsByName {
555 bool operator()(const Array *a1, const Array *a2) const {
556 return a1->name < a2->name;
557 }
558};
559
560}
561
563 // Assume scan() has been called
564 if (humanReadable)
565 *o << "; Array declarations\n";
566
567 // Declare arrays in a deterministic order.
568 std::vector<const Array *> sortedArrays(usedArrays.begin(), usedArrays.end());
569 std::sort(sortedArrays.begin(), sortedArrays.end(), ArrayPtrsByName());
570 for (std::vector<const Array *>::iterator it = sortedArrays.begin();
571 it != sortedArrays.end(); it++) {
572 *o << "(declare-fun " << (*it)->name << " () "
573 "(Array (_ BitVec "
574 << (*it)->getDomain() << ") "
575 "(_ BitVec " << (*it)->getRange() << ") ) )"
576 << "\n";
577 }
578
579 // Set array values for constant values
580 if (haveConstantArray) {
581 if (humanReadable)
582 *o << "; Constant Array Definitions\n";
583
584 const Array *array;
585
586 // loop over found arrays
587 for (std::vector<const Array *>::iterator it = sortedArrays.begin();
588 it != sortedArrays.end(); it++) {
589 array = *it;
590 int byteIndex = 0;
591 if (array->isConstantArray()) {
592 /*loop over elements in the array and generate an assert statement
593 for each one
594 */
595 for (std::vector<ref<ConstantExpr> >::const_iterator
596 ce = array->constantValues.begin();
597 ce != array->constantValues.end(); ce++, byteIndex++) {
598 *p << "(assert (";
599 p->pushIndent();
600 *p << "= ";
601 p->pushIndent();
603
604 *p << "(select " << array->name << " (_ bv" << byteIndex << " "
605 << array->getDomain() << ") )";
607 printConstant((*ce));
608
609 p->popIndent();
611 *p << ")";
612 p->popIndent();
614 *p << ")";
615
616 p->breakLineI();
617 }
618 }
619 }
620 }
621}
622
624 assert(humanReadable && "method must be called in humanReadable mode");
625 *o << "; Constraints\n";
626
627 if (abbrMode != ABBR_LET) {
628 // Generate assert statements for each constraint
629 for (const auto &constraint : query->constraints)
630 printAssert(constraint);
631
632 *o << "; QueryExpr\n";
633
634 // We negate the Query Expr because in KLEE queries are solved
635 // in terms of validity, but SMT-LIB works in terms of satisfiability
638 } else {
639 // let bindings are only scoped within a single (assert ...) so
640 // the entire query must be printed within a single assert
641 *o << "; Constraints and QueryExpr\n";
643 }
644}
646 assert(!humanReadable && "method should not be called in humanReadable mode");
648}
649
650
652 // We negate the Query Expr because in KLEE queries are solved
653 // in terms of validity, but SMT-LIB works in terms of satisfiability
655
656 // Print constraints inside the main query to reuse the Expr bindings
657 for (std::vector<ref<Expr> >::const_iterator i = query->constraints.begin(),
658 e = query->constraints.end();
659 i != e; ++i) {
660 queryAssert = AndExpr::create(queryAssert, *i);
661 }
662
663 // print just a single (assert ...) containing entire query
665}
666
668 // Ask solver to check for satisfiability
669 *o << "(check-sat)\n";
670
671 /* If we have arrays to find the values of then we'll
672 * ask the solver for the value of each bitvector in each array
673 */
674 if (arraysToCallGetValueOn != NULL && !arraysToCallGetValueOn->empty()) {
675
676 const Array *theArray = 0;
677
678 // loop over the array names
679 for (std::vector<const Array *>::const_iterator it =
680 arraysToCallGetValueOn->begin();
681 it != arraysToCallGetValueOn->end(); it++) {
682 theArray = *it;
683 // Loop over the array indices
684 for (unsigned int index = 0; index < theArray->size; ++index) {
685 *o << "(get-value ( (select " << (**it).name << " (_ bv" << index << " "
686 << theArray->getDomain() << ") ) ) )\n";
687 }
688 }
689 }
690}
691
693 assert(e && "found NULL expression");
694
695 if (isa<ConstantExpr>(e))
696 return; // we don't need to scan simple constants
697
698 if (seenExprs.insert(e).second) {
699 // We've not seen this expression before
700
701 if (const ReadExpr *re = dyn_cast<ReadExpr>(e)) {
702
703 if (usedArrays.insert(re->updates.root).second) {
704 // Array was not recorded before
705
706 // check if the array is constant
707 if (re->updates.root->isConstantArray())
708 haveConstantArray = true;
709
710 // scan the update list
711 scanUpdates(re->updates.head.get());
712 }
713 }
714
715 // recurse into the children
716 Expr *ep = e.get();
717 for (unsigned int i = 0; i < ep->getNumKids(); i++)
718 scan(ep->getKid(i));
719 } else {
720 // Add the expression to the binding map. The semantics of std::map::insert
721 // are such that it will not be inserted twice.
722 bindings.insert(std::make_pair(e, bindings.size()+1));
723 }
724}
725
727 if (!bindings.size())
728 return;
729
730 // Mutual dependency storage
731 typedef std::map<const ref<Expr>, std::set<ref<Expr> > > ExprDepMap;
732
733 // A map from binding Expr (need abbreviating) "e" to the set of binding Expr
734 // that are sub expressions of "e" (i.e. "e" uses these sub expressions).
735 // usesSubExprMap[a].count(b) == 1 means that binding Expr "a" uses
736 // sub Expr "b" (also a binding Expr).
737 // One can think of this map representing the "depends on" edges
738 // in a "dependency graph" where nodes are binding Expr roots
739 ExprDepMap usesSubExprMap;
740
741 // A map from Binding Expr "e" to the set of binding Expr that use "e"
742 // subExprOfMap[a].count(b) == 1 means that binding Expr "a" is a sub Expr
743 // of binding Expr "b".
744 // One can think of this map as representing the edges in the previously
745 // mentioned "dependency graph" except the direction of the edges
746 // have been reversed
747 ExprDepMap subExprOfMap;
748
749 // Working queue holding expressions with no dependencies
750 std::vector<ref<Expr> > nonDepBindings;
751
752 // Iterate over bindings and collect dependencies
753 for (BindingMap::const_iterator it = bindings.begin();
754 it != bindings.end(); ++it) {
755 std::stack<ref<Expr> > childQueue;
756 childQueue.push(it->first);
757 // Non-recursive expression parsing
758 while (childQueue.size()) {
759 Expr *ep = childQueue.top().get();
760 childQueue.pop();
761 for (unsigned i = 0; i < ep->getNumKids(); ++i) {
762 ref<Expr> e = ep->getKid(i);
763 if (isa<ConstantExpr>(e))
764 continue;
765 // Are there any dependencies in the bindings?
766 if (bindings.count(e)) {
767 usesSubExprMap[it->first].insert(e);
768 subExprOfMap[e].insert(it->first);
769 } else {
770 childQueue.push(e);
771 }
772 }
773 }
774 // Store expressions with zero deps
775 if (!usesSubExprMap.count(it->first))
776 nonDepBindings.push_back(it->first);
777 }
778 assert(nonDepBindings.size() && "there must be expr bindings with no deps");
779
780 // Unroll the dependency tree starting with zero-dep expressions
781 // and redefine bindings
782 unsigned counter = 1;
783 // nonDepBindings always holds expressions with no dependencies
784 while (nonDepBindings.size()) {
785 BindingMap levelExprs;
786 std::vector<ref<Expr> > tmp(nonDepBindings);
787 nonDepBindings.clear();
788 for (std::vector<ref<Expr> >::const_iterator nonDepExprIt = tmp.begin();
789 nonDepExprIt != tmp.end(); ++nonDepExprIt) {
790 // Save to the level expression bindings
791 levelExprs.insert(std::make_pair(*nonDepExprIt, counter++));
792 // Who is dependent on me?
793 ExprDepMap::iterator depsIt = subExprOfMap.find(*nonDepExprIt);
794 if (depsIt != subExprOfMap.end()) {
795 for (std::set<ref<Expr> >::iterator exprIt = depsIt->second.begin();
796 exprIt != depsIt->second.end(); ) {
797 // Erase dependency
798 ExprDepMap::iterator subExprIt = usesSubExprMap.find(*exprIt);
799 assert(subExprIt != usesSubExprMap.end());
800 assert(subExprIt->second.count(*nonDepExprIt));
801 subExprIt->second.erase(*nonDepExprIt);
802 // If the expression *exprIt does not have any
803 // dependencies anymore, add it to the queue
804 if (!subExprIt->second.size()) {
805 nonDepBindings.push_back(*exprIt);
806 depsIt->second.erase(exprIt++);
807 } else {
808 ++exprIt;
809 }
810 }
811 }
812 }
813 // Store level bindings
814 orderedBindings.push_back(levelExprs);
815 }
816}
817
819 while (un != NULL) {
820 scan(un->index);
821 scan(un->value);
822 un = un->next.get();
823 }
824}
825
826void ExprSMTLIBPrinter::printExit() { *o << "(exit)\n"; }
827
829 if (l > QF_AUFBV)
830 return false;
831
832 logicToUse = l;
833 return true;
834}
835
837 if (humanReadable)
838 p->breakLineI();
839 else
840 p->write(" ");
841}
842
844 *o << "; This file conforms to SMTLIBv2 and was generated by KLEE\n";
845}
846
848
850 // Print out SMTLIBv2 boolean options
851 for (std::map<SMTLIBboolOptions, bool>::const_iterator i =
852 smtlibBoolOptions.begin();
853 i != smtlibBoolOptions.end(); i++) {
854 *o << "(set-option :" << getSMTLIBOptionString(i->first) << " "
855 << ((i->second) ? "true" : "false") << ")\n";
856 }
857}
858
860 p->pushIndent();
861 *p << "(assert";
862 p->pushIndent();
864
865 if (abbrMode == ABBR_LET && orderedBindings.size() != 0) {
866 // Only print let expression if we have bindings to use.
867 *p << "(let";
868 p->pushIndent();
870 *p << "(";
871 p->pushIndent();
872
873 // Clear original bindings, we'll be using orderedBindings
874 // to print nested let expressions
875 bindings.clear();
876
877 // Print each binding on its level
878 for (unsigned i = 0; i < orderedBindings.size(); ++i) {
879 BindingMap levelBindings = orderedBindings[i];
880 for (BindingMap::const_iterator j = levelBindings.begin();
881 j != levelBindings.end(); ++j) {
883 *p << "(?B" << j->second;
884 p->pushIndent();
886
887 // We can abbreviate SORT_BOOL or SORT_BITVECTOR in let expressions
888 printExpression(j->first, getSort(j->first));
889
890 p->popIndent();
892 *p << ")";
893 }
894 p->popIndent();
896 *p << ")";
898
899 // Add nested let expressions (if any)
900 if (i < orderedBindings.size()-1) {
901 *p << "(let";
902 p->pushIndent();
904 *p << "(";
905 p->pushIndent();
906 }
907 // Insert current level bindings so that they can be used
908 // in the next level during expression printing
909 bindings.insert(levelBindings.begin(), levelBindings.end());
910 }
911
913
914 for (unsigned i = 0; i < orderedBindings.size(); ++i) {
915 p->popIndent();
917 *p << ")";
918 }
919 } else {
921 }
922
923 p->popIndent();
925 *p << ")";
926 p->popIndent();
927 p->breakLineI();
928}
929
931 switch (e->getKind()) {
933 return getSort(e->getKid(0));
934
935 // The relational operators are bools.
936 case Expr::Eq:
937 case Expr::Ne:
938 case Expr::Slt:
939 case Expr::Sle:
940 case Expr::Sgt:
941 case Expr::Sge:
942 case Expr::Ult:
943 case Expr::Ule:
944 case Expr::Ugt:
945 case Expr::Uge:
946 return SORT_BOOL;
947
948 // These may be bitvectors or bools depending on their width (see
949 // printConstant and printLogicalOrBitVectorExpr).
950 case Expr::Constant:
951 case Expr::And:
952 case Expr::Not:
953 case Expr::Or:
954 case Expr::Xor:
955 return e->getWidth() == Expr::Bool ? SORT_BOOL : SORT_BITVECTOR;
956
957 // Everything else is a bitvector.
958 default:
959 return SORT_BITVECTOR;
960 }
961}
962
965 switch (sort) {
966 case SORT_BITVECTOR:
967 if (humanReadable) {
968 p->breakLineI();
969 *p << ";Performing implicit bool to bitvector cast";
970 p->breakLine();
971 }
972 // We assume the e is a bool that we need to cast to a bitvector sort.
973 *p << "(ite";
974 p->pushIndent();
978 *p << "(_ bv1 1)";
979 printSeperator(); // printing the "true" bitvector
980 *p << "(_ bv0 1)";
981 p->popIndent();
982 printSeperator(); // printing the "false" bitvector
983 *p << ")";
984 break;
985 case SORT_BOOL: {
986 /* We make the assumption (might be wrong) that any bitvector whose unsigned
987 * decimal value is is zero is interpreted as "false", otherwise it is
988 * true.
989 *
990 * This may not be the interpretation we actually want!
991 */
992 Expr::Width bitWidth = e->getWidth();
993 if (humanReadable) {
994 p->breakLineI();
995 *p << ";Performing implicit bitvector to bool cast";
996 p->breakLine();
997 }
998 *p << "(bvugt";
999 p->pushIndent();
1001 // We assume is e is a bitvector
1004 *p << "(_ bv0 " << bitWidth << ")";
1005 p->popIndent();
1006 printSeperator(); // Zero bitvector of required width
1007 *p << ")";
1008
1009 if (bitWidth != Expr::Bool)
1010 llvm::errs()
1011 << "ExprSMTLIBPrinter : Warning. Casting a bitvector (length "
1012 << bitWidth << ") to bool!\n";
1013
1014 } break;
1015 default:
1016 llvm_unreachable("Unsupported cast");
1017 }
1018}
1019
1022 // This is the if-then-else expression
1023
1024 *p << "(" << getSMTLIBKeyword(e) << " ";
1025 p->pushIndent(); // add indent for recursive call
1026
1027 // The condition
1029 printExpression(e->getKid(0), SORT_BOOL);
1030
1031 /* This operator is special in that the remaining children
1032 * can be of any sort.
1033 */
1034
1035 // if true
1037 printExpression(e->getKid(1), s);
1038
1039 // if false
1041 printExpression(e->getKid(2), s);
1042
1043 p->popIndent(); // pop indent added for recursive call
1045 *p << ")";
1046}
1047
1050 *p << "(" << getSMTLIBKeyword(e) << " ";
1051 p->pushIndent(); // add indent for recursive call
1052
1053 // loop over children and recurse into each expecting they are of sort "s"
1054 for (unsigned int i = 0; i < e->getNumKids(); i++) {
1056 printExpression(e->getKid(i), s);
1057 }
1058
1059 p->popIndent(); // pop indent added for recursive call
1061 *p << ")";
1062}
1063
1066 /* For these operators it is the case that the expected sort is the same as
1067 * the sorts
1068 * of the arguments.
1069 */
1070
1071 *p << "(";
1072 switch (e->getKind()) {
1073 case Expr::And:
1074 *p << ((s == SORT_BITVECTOR) ? "bvand" : "and");
1075 break;
1076 case Expr::Not:
1077 *p << ((s == SORT_BITVECTOR) ? "bvnot" : "not");
1078 break;
1079 case Expr::Or:
1080 *p << ((s == SORT_BITVECTOR) ? "bvor" : "or");
1081 break;
1082
1083 case Expr::Xor:
1084 *p << ((s == SORT_BITVECTOR) ? "bvxor" : "xor");
1085 break;
1086 default:
1087 llvm_unreachable("Conversion from Expr to SMTLIB keyword failed");
1088 }
1089 *p << " ";
1090
1091 p->pushIndent(); // add indent for recursive call
1092
1093 // loop over children and recurse into each expecting they are of sort "s"
1094 for (unsigned int i = 0; i < e->getNumKids(); i++) {
1096 printExpression(e->getKid(i), s);
1097 }
1098
1099 p->popIndent(); // pop indent added for recursive call
1101 *p << ")";
1102}
1103
1105 SMTLIBboolValues value) {
1106 std::pair<std::map<SMTLIBboolOptions, bool>::iterator, bool> thePair;
1107 bool theValue = (value == OPTION_TRUE) ? true : false;
1108
1109 switch (option) {
1110 case PRINT_SUCCESS:
1111 case PRODUCE_MODELS:
1112 case INTERACTIVE_MODE:
1113 thePair = smtlibBoolOptions.insert(
1114 std::pair<SMTLIBboolOptions, bool>(option, theValue));
1115
1116 if (value == OPTION_DEFAULT) {
1117 // we should unset (by removing from map) this option so the solver uses
1118 // its default
1119 smtlibBoolOptions.erase(thePair.first);
1120 return true;
1121 }
1122
1123 if (!thePair.second) {
1124 // option was already present so modify instead.
1125 thePair.first->second = value;
1126 }
1127 return true;
1128 default:
1129 return false;
1130 }
1131}
1132
1133void
1134ExprSMTLIBPrinter::setArrayValuesToGet(const std::vector<const Array *> &a) {
1136
1137 // This option must be set in order to use the SMTLIBv2 command (get-value ()
1138 // )
1139 if (!a.empty())
1141
1142 /* There is a risk that users will ask about array values that aren't
1143 * even in the query. We should add them to the usedArrays list and hope
1144 * that the solver knows what to do when we ask for the values of arrays
1145 * that don't feature in our query!
1146 */
1147 for (std::vector<const Array *>::const_iterator i = a.begin(); i != a.end();
1148 ++i) {
1149 usedArrays.insert(*i);
1150 }
1151}
1152
1155 switch (option) {
1156 case PRINT_SUCCESS:
1157 return "print-success";
1158 case PRODUCE_MODELS:
1159 return "produce-models";
1160 case INTERACTIVE_MODE:
1161 return "interactive-mode";
1162 default:
1163 return "unknown-option";
1164 }
1165}
1166}
PrintContext & popIndent()
Definition: PrintContext.h:77
PrintContext & breakLineI()
Definition: PrintContext.h:61
void breakLine(unsigned indent=0)
Definition: PrintContext.h:52
PrintContext & pushIndent()
Definition: PrintContext.h:69
void write(const std::string &s)
Definition: PrintContext.h:85
bool isConstantArray() const
Definition: Expr.h:525
const unsigned size
Definition: Expr.h:489
const std::vector< ref< ConstantExpr > > constantValues
Definition: Expr.h:498
const std::string name
Definition: Expr.h:486
Expr::Width getDomain() const
Definition: Expr.h:529
static ref< ConstantExpr > create(uint64_t v, Width w)
Definition: Expr.h:1079
constraint_iterator end() const
constraint_iterator begin() const
@ PRODUCE_MODELS
produce-models SMTLIBv2 option
@ PRINT_SUCCESS
print-success SMTLIBv2 option
@ INTERACTIVE_MODE
interactive-mode SMTLIBv2 option
const char * getSMTLIBOptionString(ExprSMTLIBPrinter::SMTLIBboolOptions option)
std::map< SMTLIBboolOptions, bool > smtlibBoolOptions
@ ABBR_LET
Abbreviate with let.
@ ABBR_NAMED
Abbreviate with :named annotations.
@ ABBR_NONE
Do not abbreviate.
void printExit()
Print the SMTLIBv2 command to exit.
llvm::raw_ostream * o
Output stream to write to.
void printReadExpr(const ref< ReadExpr > &e)
void setQuery(const Query &q)
void setOutput(llvm::raw_ostream &output)
const char * getSMTLIBKeyword(const ref< Expr > &e)
void scan(const ref< Expr > &e)
SMTLIB_SORT getSort(const ref< Expr > &e)
Determine the SMTLIBv2 sort of the expression.
void printAShrExpr(const ref< AShrExpr > &e)
bool setLogic(SMTLIBv2Logic l)
bool setConstantDisplayMode(ConstantDisplayMode cdm)
void printFullExpression(const ref< Expr > &e, SMTLIB_SORT expectedSort)
Print expression without top-level abbreviations.
void printConstant(const ref< ConstantExpr > &e)
void setAbbreviationMode(AbbreviationMode am)
void printCastExpr(const ref< CastExpr > &e)
@ QF_ABV
Logic using Theory of Arrays and Theory of Bitvectors.
const std::vector< const Array * > * arraysToCallGetValueOn
std::map< const ref< Expr >, int > BindingMap
void printCastToSort(const ref< Expr > &e, ExprSMTLIBPrinter::SMTLIB_SORT sort)
Print an expression but cast it to a particular SMTLIBv2 sort first.
bool haveConstantArray
Indicates if there were any constant arrays founds during a scan()
const Query * query
The query to print.
SMTLIB_SORT
Different supported SMTLIBv2 sorts (a.k.a type) in QF_AUFBV.
PrintContext * p
Helper printer class.
std::set< const Array * > usedArrays
Contains the arrays found during scans.
void setArrayValuesToGet(const std::vector< const Array * > &a)
void printExpression(const ref< Expr > &e, SMTLIB_SORT expectedSort)
void printSelectExpr(const ref< SelectExpr > &e, ExprSMTLIBPrinter::SMTLIB_SORT s)
void scanUpdates(const UpdateNode *un)
Helper function for scan() that scans the expressions of an update node.
@ OPTION_TRUE
Set option to true.
void printUpdatesAndArray(const UpdateNode *un, const Array *root)
Recursively prints updatesNodes.
void printSortArgsExpr(const ref< Expr > &e, ExprSMTLIBPrinter::SMTLIB_SORT s)
@ HEX
Display bit vector constants in Hexidecimal e.g.#x2D.
@ BINARY
Display bit vector constants in binary e.g. #b00101101.
@ DECIMAL
Display bit vector constants in Decimal e.g. (_ bv45 8)
std::set< ref< Expr > > seenExprs
Set of expressions seen during scan.
void printAssert(const ref< Expr > &e)
Print an assert statement for the given expr.
ExprSMTLIBPrinter()
Create a new printer that will print a query in the SMTLIBv2 language.
std::vector< BindingMap > orderedBindings
void printExtractExpr(const ref< ExtractExpr > &e)
bool setSMTLIBboolOption(SMTLIBboolOptions option, SMTLIBboolValues value)
ConstantDisplayMode cdm
void printLogicalOrBitVectorExpr(const ref< Expr > &e, ExprSMTLIBPrinter::SMTLIB_SORT s)
Class representing symbolic expressions.
Definition: Expr.h:91
virtual Kind getKind() const =0
static ref< Expr > createIsZero(ref< Expr > e)
Definition: Expr.cpp:322
virtual Width getWidth() const =0
virtual unsigned getNumKids() const =0
@ Xor
Definition: Expr.h:149
@ Not
Definition: Expr.h:133
@ Ule
Definition: Expr.h:158
@ LShr
Definition: Expr.h:151
@ Sge
Not used in canonical form.
Definition: Expr.h:164
@ Add
Definition: Expr.h:138
@ Select
Definition: Expr.h:124
@ Ne
Not used in canonical form.
Definition: Expr.h:156
@ And
Definition: Expr.h:147
@ ZExt
Definition: Expr.h:129
@ URem
Definition: Expr.h:143
@ SDiv
Definition: Expr.h:142
@ NotOptimized
Definition: Expr.h:120
@ Mul
Definition: Expr.h:140
@ AShr
Definition: Expr.h:152
@ Extract
Definition: Expr.h:126
@ Read
Definition: Expr.h:123
@ Constant
Definition: Expr.h:113
@ Ugt
Not used in canonical form.
Definition: Expr.h:159
@ Sub
Definition: Expr.h:139
@ Ult
Definition: Expr.h:157
@ Shl
Definition: Expr.h:150
@ SRem
Definition: Expr.h:144
@ Concat
Definition: Expr.h:125
@ Or
Definition: Expr.h:148
@ Sle
Definition: Expr.h:162
@ Sgt
Not used in canonical form.
Definition: Expr.h:163
@ Slt
Definition: Expr.h:161
@ Uge
Not used in canonical form.
Definition: Expr.h:160
@ SExt
Definition: Expr.h:130
@ UDiv
Definition: Expr.h:141
@ Eq
Definition: Expr.h:155
unsigned Width
The type of an expression is simply its width, in bits.
Definition: Expr.h:97
static const Width Bool
Definition: Expr.h:100
virtual ref< Expr > getKid(unsigned i) const =0
Class representing a one byte read from an array.
Definition: Expr.h:565
Class representing a byte update of an array.
Definition: Expr.h:451
ref< Expr > index
Definition: Expr.h:459
const ref< UpdateNode > next
Definition: Expr.h:458
ref< Expr > value
Definition: Expr.h:459
Definition: Ref.h:82
T * get() const
Definition: Ref.h:129
llvm::cl::opt< klee::ExprSMTLIBPrinter::ConstantDisplayMode > argConstantDisplayMode("smtlib-display-constants", llvm::cl::desc("Sets how bitvector constants are written in generated " "SMT-LIBv2 files (default=dec)"), llvm::cl::values(clEnumValN(klee::ExprSMTLIBPrinter::BINARY, "bin", "Use binary form (e.g. #b00101101)"), clEnumValN(klee::ExprSMTLIBPrinter::HEX, "hex", "Use Hexadecimal form (e.g. #x2D)"), clEnumValN(klee::ExprSMTLIBPrinter::DECIMAL, "dec", "Use decimal form (e.g. (_ bv45 8) )")), llvm::cl::init(klee::ExprSMTLIBPrinter::DECIMAL), llvm::cl::cat(klee::ExprCat))
llvm::cl::opt< bool > humanReadableSMTLIB("smtlib-human-readable", llvm::cl::desc("Enables generated SMT-LIBv2 files to " "be human readable (default=false)"), llvm::cl::init(false), llvm::cl::cat(klee::ExprCat))
llvm::cl::opt< klee::ExprSMTLIBPrinter::AbbreviationMode > abbreviationMode("smtlib-abbreviation-mode", llvm::cl::desc("Choose abbreviation mode to use in SMT-LIBv2 files (default=let)"), llvm::cl::values(clEnumValN(klee::ExprSMTLIBPrinter::ABBR_NONE, "none", "Do not abbreviate"), clEnumValN(klee::ExprSMTLIBPrinter::ABBR_LET, "let", "Abbreviate with let"), clEnumValN(klee::ExprSMTLIBPrinter::ABBR_NAMED, "named", "Abbreviate with :named annotations")), llvm::cl::init(klee::ExprSMTLIBPrinter::ABBR_LET), llvm::cl::cat(klee::ExprCat))
Definition: main.cpp:291
llvm::cl::OptionCategory ExprCat
ref< Expr > expr
Definition: Solver.h:35
const ConstraintSet & constraints
Definition: Solver.h:34