├── .gitignore ├── INSTALL.md ├── LICENSE.txt ├── README.md ├── REQUIREMENTS.md ├── STATUS.md ├── legacy ├── Makefile ├── python │ ├── README.md │ ├── backend.py │ ├── frontend.py │ ├── passes-16.txt │ ├── runthrough.sh │ └── wrapper.sh └── slot.cpp ├── results ├── analysis.py ├── bv.csv ├── bvfp.csv └── fp.csv ├── runthrough.sh ├── samples └── multiplyOverflow.smt2 ├── slot.dockerfile ├── src ├── LLVMFunction.cpp ├── LLVMNode.cpp ├── LLVMNode.h ├── Makefile ├── SLOTExceptions.h ├── SMTFormula.cpp ├── SMTFormula.h ├── SMTNode.cpp ├── SMTNode.h └── main.cpp └── wrapper.sh /.gitignore: -------------------------------------------------------------------------------- 1 | #Compiled binaries and object files 2 | *.o 3 | slot/main 4 | legacy/slot 5 | -------------------------------------------------------------------------------- /INSTALL.md: -------------------------------------------------------------------------------- 1 | # SLOT Installation 2 | 3 | ## Installation option 1: Docker (recommended) 4 | 5 | For ease of use, we have made available a Docker image containing SLOT at https://hub.docker.com/repository/docker/mikekben/slot (~80 GB). This docker image was generated using the provided [dockerfile](./slot.dockerfile). Building SLOT requires a build of LLVM, which may be time consuming. Therefore, we recommend using the pre-built image as follows. Note that the docker run command should automatically pull the image from Dockerhub, but you may also pull it using `docker pull mikekben/slot` 6 | 7 | 8 | To test SLOT's functionality, run the docker image in interactive mode: 9 | ``` 10 | docker run -it mikekben/slot 11 | ``` 12 | and then run SLOT inside the container: 13 | 14 | ``` 15 | ./slot -pall -m -s samples/multiplyOverflow.smt2 -lu samples/multiplyOverflow.ll -lo samples/multiplyOverflow-opt.ll -o samples/multiplyOverflow-opt.smt2 16 | 17 | #Expected output: samples/multiplyOverflow.smt2,true,1,1,1,1,1,1,1,1,0.0188988,0.0019054,0.00338006,1,0,1,0,1,0,0,0 18 | ``` 19 | 20 | The output above indicates the SLOT has run successfully and shows some statistics about runtime and which optimization passes affected the constraint. The above commands replicate the Motivating Example in the accepted paper, and SLOT's functionality can be verified by inspecting the output in ``samples/multiplyOverflow-opt.smt2``: 21 | 22 | ``` 23 | cat samples/multiplyOverflow-opt.smt2 24 | 25 | #Expected output: 26 | (set-info :status unknown) 27 | (assert 28 | false) 29 | (check-sat) 30 | ``` 31 | 32 | You can also now run both the original constraint and the optimized constraint with a solver to observe the solving time difference: 33 | 34 | ``` 35 | z3/build/z3 samples/multiplyOverflow-opt.smt2 36 | 37 | #Expected output (almost instant): 38 | unsat 39 | 40 | z3/build/z3 samples/multiplyOverflow.smt2 41 | 42 | #Expected output (takes several minutes): 43 | unsat 44 | ``` 45 | 46 | 47 | 48 | Alternatively, you can build the docker image yourself as follows (note that this re-builds LLVM from scratch and may take more than 30 minutes): 49 | 50 | ``` 51 | docker build -t slot:latest -f slot.dockerfile . 52 | ``` 53 | 54 | 55 | ## Installation option 2: Manual 56 | 57 | To build SLOT locally, follow the following steps: 58 | 59 | Download and build LLVM, according to the guide found at https://llvm.org/docs/GettingStarted.html#getting-the-source-code-and-building-llvm. 60 | 61 | Building LLVM yourself allows explicit version choice, but you can also install LLVM using your package manager of choice. 62 | 63 | Download and build Z3 according to the directions found at https://github.com/Z3Prover/z3. Again, you can also install Z3 using your package manager. 64 | 65 | Clone the SLOT repository and navigate the src directory 66 | ``` 67 | git clone https://github.com/mikekben/SLOT 68 | cd SLOT/src 69 | ``` 70 | You may have to adjust the paths to LLVM and Z3 in SLOT's Makefile to point to the correct location on your system; this is done by changing the `CPPFLAGS` and `LDLIBS` variables. 71 | 72 | Build SLOT: 73 | ``` 74 | make 75 | cp slot ../ 76 | cd .. 77 | ``` 78 | From this point onwards, simple replications can follow the instructions provided under the docker installation. -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SLOT Readme 2 | 3 | ## About 4 | SLOT (SMT-LLVM Optimizing Translation) is a software tool that speeds up SMT solving in a solver-agnostic way by simplifying constraints. It converts SMT constraints to LLVM, applies the existing LLVM optimizer, and translates back. 5 | 6 | SLOT is made publicly available on Github at https://github.com/mikekben/SLOT. 7 | 8 | Detailed installation and simple example instructions can be found in [INSTALL.md](INSTALL.md). The recommended option is replicated below for simplicity. 9 | 10 | ## Recommended installation method with Docker 11 | 12 | For ease of use, we have made available a Docker image containing SLOT at https://hub.docker.com/repository/docker/mikekben/slot (~80 GB). This docker image was generated using the provided [dockerfile](./slot.dockerfile). Building SLOT requires a build of LLVM, which may be time consuming. Therefore, we recommend using the pre-built image as follows. Note that the docker run command should automatically pull the image from Dockerhub, but you may also pull it using `docker pull mikekben/slot` 13 | 14 | 15 | To test SLOT's functionality, run the docker image in interactive mode: 16 | ``` 17 | docker run -it mikekben/slot 18 | ``` 19 | and then run SLOT inside the container: 20 | 21 | ``` 22 | ./slot -pall -m -s samples/multiplyOverflow.smt2 -lu samples/multiplyOverflow.ll -lo samples/multiplyOverflow-opt.ll -o samples/multiplyOverflow-opt.smt2 23 | 24 | #Expected output: samples/multiplyOverflow.smt2,true,1,1,1,1,1,1,1,1,0.0188988,0.0019054,0.00338006,1,0,1,0,1,0,0,0 25 | ``` 26 | 27 | The output above indicates the SLOT has run successfully and shows some statistics about runtime and which optimization passes affected the constraint. The above commands replicate the Motivating Example in the accepted paper, and SLOT's functionality can be verified by inspecting the output in ``samples/multiplyOverflow-opt.smt2``: 28 | 29 | ``` 30 | cat samples/multiplyOverflow-opt.smt2 31 | 32 | #Expected output: 33 | (set-info :status unknown) 34 | (assert 35 | false) 36 | (check-sat) 37 | ``` 38 | 39 | You can also now run both the original constraint and the optimized constraint with a solver to observe the solving time difference: 40 | 41 | ``` 42 | z3/build/z3 samples/multiplyOverflow-opt.smt2 43 | 44 | #Expected output (almost instant): 45 | unsat 46 | 47 | z3/build/z3 samples/multiplyOverflow.smt2 48 | 49 | #Expected output (takes several minutes): 50 | unsat 51 | ``` 52 | 53 | 54 | ## Further details 55 | 56 | The above described method verifies that SLOT has been installed and is working correctly. We also encourage you to apply SLOT to other SMT constraints if you are interested! 57 | 58 | The SLOT executable takes the following terminal flags and arguments (which can also be viewed by running `slot -h`). 59 | ``` 60 | -h : See help menu 61 | -s : The input SMTLIB2 format file (required) 62 | -o : The output file. If not provided, output is sent to stdout 63 | -lu : Output intermediate LLVM IR before optimization (optional) 64 | -lo : Output intermediate LLVM IR after optimization (optional) 65 | -m : Convert constant shifts to multiplication 66 | -t : Output statistics file. If not provided, output is sent to stdout 67 | 68 | #Optimization pass flags. By default, no passes are run 69 | 70 | -pall : Run all relevant passes (roughly equivalent to -O3 in LLVM) 71 | -instcombine : Run instcombine pass 72 | -ainstcombine : Run aggressive instcombine pass 73 | -reassociate : Run reassociate pass 74 | -sccp : Run sparse conditional constant propagation (SCCP) pass 75 | -dce : Run dead code elimination (DCE) pass 76 | -adce : Run aggressive dead code elimination (ADCE) pass 77 | -instsimplify : Run instsimplify pass 78 | -gvn : Run global value numbering (GVN) pass 79 | ``` 80 | The `-lo` and `-lu` optional flags allow users to see the LLVM IR produced by SLOT before and after optimization. By default, both statistics and the output simplified constraint are sent to stdout, but these can be redirected to files with the `-o` and `-t` flags. Flags are also provided for each of the relevant optimization passes (see the accepted paper for further details), in addition to the `-pall` flag which runs all passes. 81 | 82 | SLOT's output statistics take the following form: 83 | ``` 84 | samples/multiplyOverflow.smt2,true,1,1,1,1,1,1,1,1,0.0188988,0.0019054,0.00338006,1,0,1,0,1,0,0,0 85 | ``` 86 | This output is, in order, the filename; true or false representing whether the `-m` flag was passed; 8 binary digits representing which of the 8 possible passes was *requested by the user*; three time values (in seconds) corresponding to the amount of time spent on frontend, optimization, and backend; and 8 more binary digits representing which of the 8 possible passes *affected the input constraint*. 87 | 88 | 89 | 90 | For replicability, we also provide the scripts used to run the large scale testing reported in our results section, the raw data collected during those experiments, and a simple Python script used in data analysis. Rerunning the entire benchmark set has substantial hardware requirements and may take more than one week to finish, depending on the available resources. 91 | 92 | ### Re-running large scale experiments 93 | 94 | To test SLOT on the entire SMTLIB benchmark set, follow the following steps: 95 | 96 | Clone the three benchmark sets from SMTLIB (about 50GB total, mostly from QF_BV). **Note that some constraints require Git LFS**. 97 | ``` 98 | git clone https://clc-gitlab.cs.uiowa.edu:2443/SMT-LIB-benchmarks/QF_BV 99 | git clone https://clc-gitlab.cs.uiowa.edu:2443/SMT-LIB-benchmarks/QF_FP 100 | git clone https://clc-gitlab.cs.uiowa.edu:2443/SMT-LIB-benchmarks/QF_BVFP 101 | ``` 102 | 103 | For each of the three benchmark sets, run 104 | 105 | ``` 106 | find ./QF_BV -name '*.smt2' -type f | parallel -j 80 ./wrapper.sh 107 | ``` 108 | Within `wrapper.sh`, you may adjust the arguments to test with only those solvers you are interested in. If you wish to test with CVC5 or Boolector, you must install those solvers as well. If a solver is not in your path, you may need to adjust the solver variables at the start of `runthrough.sh`. Note that Boolector does not support floating-point constraints. 109 | 110 | Replace 80 with the number of threads available on your machine. SMT solving has substantial memory requirements. During our experiments running with 80 threads on a server, memory usage never exceeded ~400 GB. During our experiments, running all three benchmark sets took approximately one week. QF_BV is by far the longest. In addition, the speed of solvers on a particular constraint depends on hardware and other limitations. We therefore focus largely on proportional speedups in our analysis, rather than absolute speedups. 111 | 112 | ## Experimental data and analysis 113 | 114 | The experimental data collected during our large scale run is provided in `/data`, with one file for each of the three benchmark sets. We also provide a Python script, `analysis.py` which analyzes this data and replicates the tables and statistics found in the accepted paper. To run the analysis, do the following, replacing fp.csv with your benchmark set of choice. 115 | 116 | ``` 117 | cd results 118 | python3 analysis.py -f fp.csv 119 | ``` -------------------------------------------------------------------------------- /REQUIREMENTS.md: -------------------------------------------------------------------------------- 1 | # SLOT Requirements 2 | 3 | ## For installation with pre-built Docker image: 4 | At lest 100GB of free storage 5 | At least 8GB of memory 6 | 7 | + Ubuntu (tested with version 20.04) 8 | + A recent version of Docker 9 | 10 | ## For building Docker image: 11 | At least 100GB of free storage 12 | At least 64GB of memory. 13 | 14 | Note that the memory requirement can be reduced by changing the number of threads in the Ninja build of LLVM on line 12 of the dockerfile--there is a tradeoff between memory consumption and speed of build. The substantial memory requirements are associated with building LLVM, not SLOT perse. If you have a pre-existing build of LLVM, you can also copy this build into the docker container to save time. 15 | 16 | + Ubuntu (tested with version 20.04) 17 | + A recent version of Docker 18 | 19 | 20 | ## For manual builds: 21 | At least 100GB of free storage 22 | At least 8GB of memory. 23 | 24 | + Ubuntu (tested with version 20.04) 25 | + git 26 | + gcc 27 | + g++ 28 | + cmake (for building LLVM) 29 | + ninja-build (for building LLVM) 30 | + python3 (for building Z3) 31 | + zlib1g-dev 32 | + libtinfo-dev 33 | + libxml2-dev -------------------------------------------------------------------------------- /STATUS.md: -------------------------------------------------------------------------------- 1 | # Artifact Evaluation Status 2 | 3 | We respectfully request review for the following badges: **Available**, **Evaluated - Functional**, and ****Evaluated - Reusable**. 4 | 5 | # Available 6 | 7 | Our artifact, SLOT, is made publicly available on Github at https://github.com/mikekben/SLOT. We have created a tag "FSE2023" marking the record version of our artifact for review. We distribute SLOT under the open source GNU General Public License v3.0. The implementation of SLOT and the data collected are therefore publicly accessible. 8 | 9 | # Evaluated-Functional 10 | 11 | We provide in three forms substantial documentation of SLOT. First, we provide both the README and INSTALL files included in this repository, which describe in detail how to (1) run a minimal example to show SLOT can be built and functions, (2) re-run large scale experiments on benchmark sets using SLOT, and (3) re-analyze the raw data we collected during our experiments. Second, we provide extensive in-code comments in SLOT's source code to aid future researchers who wish to examine the artifact. Third, we document SLOT in our accepted paper, giving details on design decisions and experimental runs. SLOT's implementation is consistent with each of these descriptions. It is a single complete software artifact which can be re-run. Evidence for this is provided by the implementation, installation packages, and raw data provided in this repository. 12 | 13 | # Evaluated-Reusable 14 | 15 | In addition to the functionality described above, SLOT is carefully-documented and logically structured. In particular, C++ conventions are adhered-to to make the production of derivative software easier, and SLOT's source code provides copious comments explaining non-obvious functionality. SLOT takes as input constraints in the standard, widely-used, and well-documented SMT-LIB format, and produces output in the same format. Moreover, it's intermediate products (the unoptimized and optimized LLVM IR) are made available to facilitate further scrutiny, and they are in the widely-known language LLVM IR. 16 | -------------------------------------------------------------------------------- /legacy/Makefile: -------------------------------------------------------------------------------- 1 | all: 2 | g++ -g -fsanitize=address -O1 slot.cpp -I /nethome/bmikek3/z3/src/api -I /nethome/bmikek3/z3/src/api/c++ -I /nethome/bmikek3/z3/build /nethome/bmikek3/z3/build/libz3.so `/nethome/qzhang414/trunk/root-clang/bin/llvm-config --cxxflags --ldflags --system-libs --libs core passes` -fexceptions -o slot -------------------------------------------------------------------------------- /legacy/python/README.md: -------------------------------------------------------------------------------- 1 | ## Outline 2 | Python code for SLOT frontend is located in ``frontend.py.`` SLOT backend is ``backend.py``. ``runthrough.sh`` is a shell script run SLOT on an input SMT constraint. ``wrapper.sh`` is a convenient way to run large numbers of benchmarks. ``bv-600-raw.csv`` and ``fp-600-raw.csv`` contain the benchmark results used to generate statistics in the submitted paper. The several ``multiplyOverflow`` files are the motivating example described in the paper. 3 | 4 | ## Existing results 5 | Results of the bitvector benchmarks used in the evaluation are given in ``bv-600-raw.csv``. ``fp-600-raw.csv`` contains the data for floating point constraints. The first column is the name of the benchmark. Columns 2-5 give the sizes (bytes) of the original constraint, the frontend translation, the optimized LLVM, and backend translation, respectively. Columns 6-8 are the time taken for frontend translation, optimization, and backend translation, in seconds. The remaining columns give the pre-optimization result, pre-optimization time, post-SLOT result, and post-SLOT time. Solvers are in the order Z3, CVC5, and Boolector (for bitvector benchmarks). Any rows for which times are empty indicate that SLOT failed to produce a translation within the 600 second timeout. For evaluation, we count all of these entries as 600 seconds. 6 | 7 | ## Requirements 8 | Running SLOT requires Python 3, with the following packages installed: 9 | + Numba LLVMLite: https://github.com/numba/llvmlite (tested with version 0.39.0) 10 | + Z3 Python bindings: https://pypi.org/project/z3-solver/ (tested with version 0.2.0) 11 | 12 | In addition, LLVM opt must be installed. LLVM can be installed with your package manager, or built from source (https://github.com/llvm/llvm-project). If opt is in PATH, then ``runthrough.sh`` should find it. Otherwise, set the ``OPT_CMD`` variable to your optimizer location. ``passes-16.txt`` contains a list of all LLVM 16 passes for ``-O3``, with only those which produce vector instructions removed. To test different optimization passes, you can change the contents of this file. Note that the normal O3 optimization pipeline includes many instcombine passes, most of which are to cleanup the results of irrelevant optimizations. 13 | 14 | SLOT supports the following solvers: 15 | + Z3 can be installed from https://github.com/Z3Prover/z3. 16 | + CVC5 can be installed from https://github.com/cvc5/cvc5. 17 | + Boolector can be installed from https://github.com/Boolector/boolector. 18 | 19 | SLOT can be run with any (or none) of these solvers. If a solver is in your path, then ``runthrough.sh`` should recognize it. Otherwise, modify the corresponding variable (``Z3``, ``CVC5``, or ``BOOLECTOR``) with the appropriate location. 20 | 21 | 22 | ## Running SLOT 23 | To run SLOT on a particular SMT constraint, use the command, 24 | ``./runthrough.sh -z -c -b -t 200 -f multiplyOverflow.smt2`` 25 | 26 | ``runthrough.sh`` takes several flags: 27 | + ``-r`` (optional) to remove all intermediate files 28 | + ``-z`` (optional) calls the Z3 SMT solver 29 | + ``-c`` (optional) calls the CVC5 SMT solver 30 | + ``-b`` (optional) calls the Boolector solver. Boolector does not support floating point constraints 31 | + ``-t`` (required) timeout (seconds) 32 | + ``-f`` (required) the input SMT constraint 33 | 34 | ## Translation step-by-step 35 | 36 | To perform a frontend translation (if -o is omitted, output is written to stdout), 37 | ``python3 frontend.py -s multiplyOverflow.smt2 -o multiplyOverflow.ll`` 38 | 39 | To invoke the optimizer, 40 | ``opt multiplyOverflow.ll -O3 -S -o multiplyOverflow-opt.ll`` 41 | 42 | To perform a backend translation, 43 | ``python3 backend.py -l multiplyOverflow-opt.ll -o multiplyOverflow-opt.smt2`` 44 | 45 | NOTE: LLVMLite does not support recent changes to LLVM debug information, so invoking the above command after optimizing with LLVM 11 or later will produce a backend error. To avoid this error, remove any lines beginning with ``attributes #0`` from the input LLVM file. This is performed automatically by SLOT in the ``runthrough.sh`` script. Using this script instead of manually translating is highly recommended. 46 | 47 | 48 | ## Large-scale testing 49 | 50 | To replicate the large-scale testing, first clone the SMTLIB repositories for [QF_BV](https://clc-gitlab.cs.uiowa.edu:2443/SMT-LIB-benchmarks/QF_BV) (>70 GB, requires Git LFS) and [QF_BVFP](https://clc-gitlab.cs.uiowa.edu:2443/SMT-LIB-benchmarks/QF_BVFP) (500 MB). Then invoke SLOT on each benchmark with the desired command line arguments -- ``wrapper.sh`` may be helpful for this purpose. One option for testing is to use GNU parallel with a command like this: 51 | ``find QF_BV -name '*.smt2' -type f | parallel ./wrapper.sh >> results.csv`` 52 | 53 | All experiments were performed on a server with two AMD EPYC 7402 CPUs (96 cores total) and 512GB RAM, running Ubuntu 20.04. In our testing, running on all benchmarks with all solvers took on the order of 48 hours. -------------------------------------------------------------------------------- /legacy/python/backend.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | from functools import * 3 | from llvmlite import ir 4 | import llvmlite.binding as llvm 5 | from z3 import * 6 | import struct 7 | 8 | ROUNDING_MODE = RoundNearestTiesToEven() 9 | 10 | 11 | def parse_args(): 12 | parser = argparse.ArgumentParser() 13 | parser.add_argument('-l', '--llvm', 14 | help='Input .ll file', 15 | required=True) 16 | parser.add_argument('-o', '--output', 17 | help='Output .smt2 file', 18 | required=True) 19 | parser.add_argument('-s','--shiftToMultiply',nargs='?', const=True, default=False, 20 | help='Include this flag to convert shift instructions with constant right argument to multiplication', 21 | required=False) 22 | 23 | args = parser.parse_args() 24 | return args 25 | 26 | #Instruction.get_name() function from llvmlite contains a bug on inputs like %0 and %1 27 | def get_name(v): 28 | if ('=' in str(v)): 29 | return 'b'+str(v).strip().split(' ')[0].split('%')[1] 30 | elif v.name =="": 31 | if '%' in str(v): 32 | return 'b'+str(v).split('%')[1] 33 | else: 34 | return '' 35 | else: 36 | return 'b'+v.name 37 | 38 | 39 | def get_operand(op, force_bv, smt_vars): 40 | if get_name(op) == '': 41 | stn = str(op).split(' ')[1] 42 | if str(op.type) == 'i1': 43 | return stn =='true' 44 | elif str(op.type).startswith('i'): 45 | val = int(stn) 46 | return BitVecVal(val,int(str(op.type)[1:])) if force_bv else val 47 | elif str(op.type) in ['half', 'float', 'double']: 48 | new_type = to_smt_type(op.type) 49 | hfd = [16,32,64,128].index(new_type.ebits()+new_type.sbits()) 50 | if ('e+' in stn) or ('e-' in stn): 51 | #Interpret the exponential fp with Python's parser, convert the bits to an integer, and return a bitvector with that value 52 | 53 | val = struct.unpack(['H','I','Q'][hfd], struct.pack(['e','f','d'][hfd], float(stn)))[0] 54 | else: 55 | 56 | #Read the LLVM hex float constant as a python integer (always 64 bits based on LLVM) 57 | val = int(stn,16) 58 | #Bitcast to a python 64-bit floating point 59 | py_64fp = struct.unpack('d',struct.pack('Q',val))[0] 60 | #Convert 64-bit python floating point to appropriate size 61 | inter2 = struct.unpack(['e','f','d'][hfd],struct.pack(['e','f','d'][hfd],py_64fp))[0] 62 | #Bitcast correct size floating point back to integer of corresponding size 63 | val = struct.unpack(['H','I','Q'][hfd],struct.pack(['e','f','d'][hfd],inter2))[0] 64 | 65 | return fpBVToFP(BitVecVal(val,new_type.ebits()+new_type.sbits()),new_type) 66 | else: 67 | raise Exception("Unsupported operand type: "+str(op)) 68 | else: 69 | return smt_vars[get_name(op)] 70 | 71 | def to_smt_type(t): 72 | if str(t) == 'i1': 73 | return Bool() 74 | elif str(t).startswith("i"): 75 | return BitVecSort(int(str(t)[1:])) 76 | elif str(t) == 'half': 77 | return Float16() 78 | elif str(t) == 'float': 79 | return Float32() 80 | elif str(t) == 'double': 81 | return Float64() 82 | else: 83 | raise Exception("Unsupported LLVM type: " + str(v.type)) 84 | 85 | def to_smt_var(v): 86 | if str(v.type) == 'i1': 87 | return Bool(get_name(v)) 88 | elif str(v.type).startswith("i"): 89 | return BitVec(get_name(v),int(str(v.type)[1:])) 90 | elif str(v.type) == 'half': 91 | return FP(get_name(v),Float16()) 92 | elif str(v.type) == 'float': 93 | return FP(get_name(v),Float32()) 94 | elif str(v.type) == 'double': 95 | return FP(get_name(v),Float64()) 96 | else: 97 | raise Exception("Unsupported LLVM type: " + str(v.type)) 98 | 99 | def class_bits_to_fun(b): 100 | bits_dict = { 101 | 3: fpIsNaN, 102 | 516: fpIsInf, 103 | 96: fpIsZero, 104 | 264: fpIsNormal, 105 | 144: fpIsSubnormal, 106 | 60: fpIsNegative, 107 | 960: fpIsPositive 108 | } 109 | return bits_dict[b] 110 | 111 | def interpret_fcmp(inst_str, val, left, right): 112 | name = inst_str.split('fcmp ')[1].split(' ')[0] 113 | if name == "false": 114 | sol.add(val == False) 115 | elif name == "oeq": 116 | sol.add(val == fpEQ(left,right)) 117 | elif name == "ogt": 118 | sol.add(val == fpGT(left,right)) 119 | elif name == "oge": 120 | sol.add(val == fpGEQ(left,right)) 121 | elif name == "olt": 122 | sol.add(val == fpLT(left,right)) 123 | elif name == "ole": 124 | sol.add(val == fpLEQ(left,right)) 125 | elif name == "one": 126 | sol.add(val == And(Not(fpIsNaN(left)),Not(fpIsNaN(right),Not(fpEQ(left,right))))) 127 | elif name == "ord": 128 | sol.add(val == And(Not(fpIsNaN(left)),Not(fpIsNaN(right)))) 129 | elif name == "ueq": 130 | sol.add(val == Or(fpIsNaN(left),fpIsNaN(right),fpEQ(left,right))) 131 | elif name == "ugt": 132 | sol.add(val == Or(fpIsNaN(left),fpIsNaN(right),fpGT(left,right))) 133 | elif name == "uge": 134 | sol.add(val == Or(fpIsNaN(left),fpIsNaN(right),fpGEQ(left,right))) 135 | elif name == "ult": 136 | sol.add(val == Or(fpIsNaN(left),fpIsNaN(right),fpLT(left,right))) 137 | elif name == "ule": 138 | sol.add(val == Or(fpIsNaN(left),fpIsNaN(right),fpLEQ(left,right))) 139 | elif name == "une": 140 | sol.add(val == Or(fpIsNaN(left),fpIsNaN(right),Not(fpEQ(left,right)))) 141 | elif name == "uno": 142 | sol.add(val == Or(fpIsNaN(left),fpIsNaN(right))) 143 | elif name == "true": 144 | sol.add(val == True) 145 | else: 146 | raise Exception("Badly formed FCMP instruction (only ordered comparisons supported): " + inst_str) 147 | 148 | 149 | def interpret_bv_icmp(inst_str, val, left, right, altl=None): 150 | #Optional argument altl is for the case where both left and right are constants 151 | name = inst_str.split('icmp ')[1].split(' ')[0] 152 | if name == "eq": 153 | sol.add(val == (left == right)) 154 | elif name == "ne": 155 | sol.add(val == (left != right)) 156 | elif name == "ugt": 157 | sol.add(val == UGT(altl if altl else left,right)) 158 | elif name == "uge": 159 | sol.add(val == UGE(altl if altl else left,right)) 160 | elif name == "ult": 161 | sol.add(val == ULT(altl if altl else left,right)) 162 | elif name == "ule": 163 | sol.add(val == ULE(altl if altl else left,right)) 164 | elif name == "sgt": 165 | sol.add(val == (left > right)) 166 | elif name == "sge": 167 | sol.add(val == (left >= right)) 168 | elif name == "slt": 169 | sol.add(val == (left < right)) 170 | elif name == "sle": 171 | sol.add(val == (left <= right)) 172 | else: 173 | raise Exception("Badly formed ICMP instruction for bitvectors: " + inst_str) 174 | 175 | def interpret_bool_icmp(inst_str, val, left, right): 176 | name = inst_str.split('icmp ')[1].split(' ')[0] 177 | if name == "eq": 178 | sol.add(val == (left == right)) 179 | elif name == "ne": 180 | sol.add(val == (left != right)) 181 | else: 182 | raise Exception("Badly formed ICMP instruction for booleans: " + inst_str) 183 | 184 | 185 | 186 | args = parse_args() 187 | 188 | sol = Solver() 189 | 190 | with open(args.llvm) as f: 191 | llvm_ir = f.read() 192 | 193 | 194 | 195 | 196 | mod = llvm.parse_assembly(llvm_ir) 197 | mod.verify() 198 | 199 | fun = mod.get_function("smt") 200 | llvm_vars = fun.arguments 201 | smt_vars = {} 202 | blocks = list(fun.blocks) 203 | 204 | for var in llvm_vars: 205 | smt_vars[get_name(var)] = to_smt_var(var) 206 | 207 | 208 | for block in blocks: 209 | insts = list(block.instructions) 210 | i = 0 211 | #Must use a concrete loop counter because some instructions skip over the next 212 | while i < len(insts): 213 | inst = insts[i] 214 | #Handle the return instruction 215 | if (inst.opcode == "ret"): 216 | sol.add(get_operand(list(inst.operands)[0],False, smt_vars)) 217 | 218 | else: 219 | #umul.with.overflow is a special instruction which produces a vector 220 | #In SMT translation, we only ever deal with the second element of that vector, so we don't make it a variable 221 | if (not "umul.with.overflow" in str(inst)): 222 | if (not get_name(inst) in smt_vars.keys()): 223 | smt_vars[get_name(inst)] = to_smt_var(inst) 224 | new_var = smt_vars[get_name(inst)] 225 | 226 | #Handle llvm intrinsics 227 | if (inst.opcode == "call"): 228 | intrinsic = list(inst.operands)[-1].name[5:] 229 | #Floating point intrinsics 230 | if intrinsic.startswith("fabs"): 231 | arg = get_operand(list(inst.operands)[0],False, smt_vars) 232 | sol.add(new_var == fpAbs(arg)) 233 | elif intrinsic.startswith("fma"): 234 | a = get_operand(list(inst.operands)[0], False, smt_vars) 235 | b = get_operand(list(inst.operands)[1], False, smt_vars) 236 | c = get_operand(list(inst.operands)[2], False, smt_vars) 237 | sol.add(new_var == fpFMA(ROUNDING_MODE,a,b,c)) 238 | elif intrinsic.startswith("sqrt"): 239 | arg = get_operand(list(inst.operands)[0], False, smt_vars) 240 | sol.add(new_var == fpSqrt(ROUNDING_MODE,arg)) 241 | elif intrinsic.startswith("minnum"): 242 | left = get_operand(list(inst.operands)[0], False, smt_vars) 243 | right = get_operand(list(inst.operands)[1], False, smt_vars) 244 | sol.add(new_var == fpMin(left,right)) 245 | elif intrinsic.startswith("maxnum"): 246 | left = get_operand(list(inst.operands)[0], False, smt_vars) 247 | right = get_operand(list(inst.operands)[1], False, smt_vars) 248 | sol.add(new_var == fpMax(left,right)) 249 | elif intrinsic.startswith("is.fpclass"): 250 | arg = get_operand(list(inst.operands)[0], False, smt_vars) 251 | bitmask = int(str(list(inst.operands)[1]).split(' ')[1]) 252 | fun = class_bits_to_fun(bitmask) 253 | sol.add(new_var == fun(arg)) 254 | #Bitvector intrinsics 255 | elif intrinsic.startswith("bswap"): 256 | arg = get_operand(list(inst.operands)[0],True,smt_vars) 257 | width = int(str(inst.type)[1:]) 258 | bytes = [ Extract(width-(8*i)-1, width-(8*(i+1)), arg) for i in range((width//8)-1,-1,-1) ] 259 | sol.add(new_var == Concat(bytes)) 260 | elif intrinsic.startswith("ctpop"): 261 | arg = get_operand(list(inst.operands)[0],True,smt_vars) 262 | width = int(str(inst.type)[1:]) 263 | bits = [ ZeroExt(width-1,Extract(i, i, arg)) for i in range(0,width) ] 264 | sol.add(new_var == reduce(lambda a, b: a + b, bits)) 265 | elif intrinsic.startswith("bitreverse"): 266 | arg = get_operand(list(inst.operands)[0],True,smt_vars) 267 | width = int(str(inst.type)[1:]) 268 | bits = [ Extract(i, i, arg) for i in range(width-1,-1,-1) ] 269 | sol.add(new_var == Concat(bits)) 270 | elif intrinsic.startswith("abs"): 271 | arg = get_operand(list(inst.operands)[0],False,smt_vars) 272 | width = int(str(inst.type)[1:]) 273 | sol.add(new_var == If(arg < 0,-arg,arg)) 274 | elif intrinsic.startswith("fshl"): 275 | left = get_operand(list(inst.operands)[0],False,smt_vars) 276 | right = get_operand(list(inst.operands)[1],False,smt_vars) 277 | shamt = get_operand(list(inst.operands)[2],False,smt_vars) 278 | width = int(str(inst.type)[1:]) 279 | sol.add(new_var == Extract((width*2)-1,width,Concat(left,right) << shamt)) 280 | elif intrinsic.startswith("fshr"): 281 | left = get_operand(list(inst.operands)[0],False,smt_vars) 282 | right = get_operand(list(inst.operands)[1],False,smt_vars) 283 | shamt = get_operand(list(inst.operands)[2],False,smt_vars) 284 | width = int(str(inst.type)[1:]) 285 | sol.add(new_var == Extract(width-1,0,Concat(left,right) >> shamt)) 286 | elif intrinsic.startswith("usub.sat"): 287 | left = get_operand(list(inst.operands)[0],False,smt_vars) 288 | right = get_operand(list(inst.operands)[1],False,smt_vars) 289 | width = int(str(inst.type)[1:]) 290 | sol.add(new_var == If(ULE(left,right),0,left-right)) 291 | elif intrinsic.startswith("umin"): 292 | left = get_operand(list(inst.operands)[0],False,smt_vars) 293 | right = get_operand(list(inst.operands)[1],False,smt_vars) 294 | sol.add(new_var == If(ULE(left,right),left,right)) 295 | elif intrinsic.startswith("umax"): 296 | left = get_operand(list(inst.operands)[0],False,smt_vars) 297 | right = get_operand(list(inst.operands)[1],False,smt_vars) 298 | sol.add(new_var == If(ULE(left,right),right,left)) 299 | elif intrinsic.startswith("smin"): 300 | left = get_operand(list(inst.operands)[0],False,smt_vars) 301 | right = get_operand(list(inst.operands)[1],False,smt_vars) 302 | sol.add(new_var == If(left <= right,left,right)) 303 | elif intrinsic.startswith("smax"): 304 | left = get_operand(list(inst.operands)[0],False,smt_vars) 305 | right = get_operand(list(inst.operands)[1],False,smt_vars) 306 | sol.add(new_var == If(left <= right,right,left)) 307 | elif intrinsic.startswith("umul.with.overflow"): 308 | if (insts[i+1].opcode=="extractvalue") and (str(insts[i+1])[-1]=='1'): 309 | left = get_operand(list(inst.operands)[0],False,smt_vars) 310 | right = get_operand(list(inst.operands)[1],False,smt_vars) 311 | smt_vars[get_name(insts[i+1])] = to_smt_var(insts[i+1]) 312 | sol.add(smt_vars[get_name(insts[i+1])] == If(Or(left==0,right==0),False,Not(((left*right)/left)==right))) 313 | i+=1 314 | else: 315 | raise Exception("Unsupported LLVM intrinsic: "+str(inst)) 316 | 317 | elif len(list(inst.operands)) == 1: 318 | arg = get_operand(list(inst.operands)[0],True,smt_vars) 319 | #Only one unary floating point instruction 320 | if (inst.opcode == "fneg"): 321 | sol.add(new_var == fpNeg(arg)) 322 | elif (inst.opcode == 'fptoui'): 323 | sol.add(new_var == fpToUBV(ROUNDING_MODE,arg,BitVecSort(arg.ebits()+arg.sbits()))) 324 | elif (inst.opcode == 'fptosi'): 325 | sol.add(new_var == fpToSBV(ROUNDING_MODE,arg,BitVecSort(arg.ebits()+arg.sbits()))) 326 | elif (inst.opcode == 'fpext') or (inst.opcode == 'fptrunc'): 327 | sol.add(new_var == fpFPToFP(ROUNDING_MODE,arg,to_smt_type(inst.type))) 328 | else: 329 | #Unary bitvector operations 330 | if not (inst.opcode in ['sitofp','uitofp','bitcast']): 331 | #Not an integer return type for these two conversion instructions 332 | width = int(str(inst.type)[1:]) 333 | if (inst.opcode == "trunc"): 334 | sol.add(new_var == Extract(width-1,0,arg)) 335 | elif (inst.opcode == "zext"): 336 | if (is_bool(arg)): 337 | #Special case: the optimizer introduces a zext i1 ..., which needs to be an integer in SMT 338 | sol.add(new_var == ZeroExt(width-int(str(list(inst.operands)[0].type)[1:]),If(arg,BitVecVal(1,1),BitVecVal(0,1)))) 339 | else: 340 | sol.add(new_var == ZeroExt(width-int(str(list(inst.operands)[0].type)[1:]),arg)) 341 | elif (inst.opcode == "sext"): 342 | if (is_bool(arg)): 343 | #Special case: the optimizer introduces a sext i1 ..., which needs to be an integer in SMT 344 | sol.add(new_var == SignExt(width-int(str(list(inst.operands)[0].type)[1:]),If(arg,BitVecVal(1,1),BitVecVal(0,1)))) 345 | else: 346 | sol.add(new_var == SignExt(width-int(str(list(inst.operands)[0].type)[1:]),arg)) 347 | elif (inst.opcode == "freeze"): 348 | #Frontend always introduces a check for divisions by 0, so all freeze instructions are guaranteed to return their argument 349 | sol.add(new_var == arg) 350 | elif (inst.opcode == "bitcast"): 351 | if str(inst.type) in ['half', 'float', 'double']: 352 | sol.add(new_var == fpBVToFP(arg,to_smt_type(inst.type))) 353 | else: 354 | #There is no FP -> BV bitcast equivalent in SMT since NaN has multiple representations 355 | #So convert the new variable into a floating and constrain them to be equal 356 | new_type = [Float16(),Float32(),Float64()][[16,32,64].index(int(str(inst.type)[1:]))] 357 | sol.add(fpBVToFP(new_var,new_type) == arg) 358 | 359 | elif (inst.opcode == "sitofp"): 360 | sol.add(new_var == fpSignedToFP(ROUNDING_MODE,arg,to_smt_type(inst.type))) 361 | elif (inst.opcode == "uitofp"): 362 | sol.add(new_var == fpToFPUnsigned(ROUNDING_MODE,arg,to_smt_type(inst.type))) 363 | else: 364 | raise Exception("Unsupported LLVM instruction on one argument: "+str(inst)) 365 | elif len(list(inst.operands)) == 2: 366 | left = get_operand(list(inst.operands)[0], False, smt_vars) 367 | right = get_operand(list(inst.operands)[1], False, smt_vars) 368 | 369 | #Boolean case 370 | if (is_bool(left) or isinstance(left,bool)) and (is_bool(right) or isinstance(right,bool)): 371 | if (inst.opcode == "and"): 372 | sol.add(new_var == And(left,right)) 373 | elif (inst.opcode == "or"): 374 | sol.add(new_var == Or(left,right)) 375 | elif (inst.opcode == "xor"): 376 | sol.add(new_var == Xor(left,right)) 377 | elif (inst.opcode == "icmp"): 378 | interpret_bool_icmp(str(inst),new_var,left,right) 379 | else: 380 | raise Exception("Unsupported LLVM instruction on booleans: "+str(inst)) 381 | #FloatingPoint case 382 | elif is_fp(left) and is_fp(right): 383 | if (inst.opcode == "fadd"): 384 | sol.add(new_var == fpAdd(ROUNDING_MODE,left,right)) 385 | elif (inst.opcode == "fsub"): 386 | sol.add(new_var == fpSub(ROUNDING_MODE,left,right)) 387 | elif (inst.opcode == "fmul"): 388 | sol.add(new_var == fpMul(ROUNDING_MODE,left,right)) 389 | elif (inst.opcode == "fdiv"): 390 | sol.add(new_var == fpDiv(ROUNDING_MODE,left,right)) 391 | elif (inst.opcode == "frem"): 392 | sol.add(new_var == fpRem(ROUNDING_MODE,left,right)) 393 | elif (inst.opcode == "fcmp"): 394 | interpret_fcmp(str(inst),new_var,left,right) 395 | else: 396 | raise Exception("Unsupported LLVM floating point instruction: "+str(inst)) 397 | #Bitvector case 398 | else: 399 | if (inst.opcode == "shl"): 400 | if (args.shiftToMultiply and isinstance(right,int)): 401 | #Convert shift by a constant to a multiplication 402 | sol.add(new_var == left * (2**right)) 403 | else: 404 | sol.add(new_var == (left << right)) 405 | elif (inst.opcode == "lshr"): 406 | #The left operand must be forced to be a bitvector 407 | sol.add(new_var == LShR(get_operand(list(inst.operands)[0], True, smt_vars),right)) 408 | elif (inst.opcode == "ashr"): 409 | #Shift right is not equivalent to division 410 | sol.add(new_var == left >> right) 411 | elif (inst.opcode == "and"): 412 | sol.add(new_var == (left & right)) 413 | elif (inst.opcode == "or"): 414 | sol.add(new_var == (left | right)) 415 | elif (inst.opcode == "sub"): 416 | sol.add(new_var == (left - right)) 417 | elif (inst.opcode == "add"): 418 | sol.add(new_var == (left + right)) 419 | elif (inst.opcode == "mul"): 420 | sol.add(new_var == (left * right)) 421 | elif (inst.opcode == "sdiv"): 422 | sol.add(new_var == (left / right)) 423 | elif (inst.opcode == "udiv"): 424 | sol.add(new_var == UDiv(left, right)) 425 | elif (inst.opcode == "urem"): 426 | sol.add(new_var == URem(left,right)) 427 | elif (inst.opcode == "srem"): 428 | sol.add(new_var == SRem(left,right)) 429 | elif (inst.opcode == "xor"): 430 | sol.add(new_var == (left ^ right)) 431 | elif (inst.opcode == "icmp"): 432 | if isinstance(left,int) and isinstance(right,int): 433 | interpret_bv_icmp(str(inst), new_var, left, right, get_operand(list(inst.operands)[0], True, smt_vars)) 434 | else: 435 | interpret_bv_icmp(str(inst), new_var, left, right) 436 | else: 437 | raise Exception("Unsupported LLVM bitvector instruction: "+str(inst)) 438 | 439 | elif len(list(inst.operands)) == 3: 440 | if (inst.opcode == "select"): 441 | #Handles select on boolean, bitvectors, and fp 442 | cond = get_operand(list(inst.operands)[0], False, smt_vars) 443 | left = get_operand(list(inst.operands)[1], False, smt_vars) 444 | right = get_operand(list(inst.operands)[2], False, smt_vars) 445 | if isinstance(left,int) and isinstance(right,int): 446 | left = get_operand(list(inst.operands)[1], True, smt_vars) 447 | sol.add(new_var==If(cond,left,right)) 448 | else: 449 | raise Exception("Unsupported LLVM instruction on 3 arguments: "+str(inst)) 450 | else: 451 | raise Exception("Unexpected number of arguments: "+str(inst)) 452 | i+=1 453 | 454 | 455 | 456 | filename = args.output 457 | with open(filename, mode='w') as f: 458 | f.write(sol.to_smt2()) -------------------------------------------------------------------------------- /legacy/python/frontend.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | from llvmlite import ir 3 | from z3 import * 4 | import sys 5 | import re 6 | 7 | 8 | #### Translation #### 9 | 10 | module = None 11 | sys.setrecursionlimit(100000) 12 | 13 | 14 | def bits_to_floating(bits): 15 | correspondence = {16: (5,11), 32: (8,24), 64: (11,53), 128: (15,113)} 16 | if isinstance(bits,int) or len(bits)==1: 17 | if bits in correspondence: 18 | bits = correspondence[bits] 19 | if bits == (5,11) or bits == [5,11]: 20 | return ir.HalfType() 21 | elif bits == (8,24) or bits == [8,24]: 22 | return ir.FloatType() 23 | elif bits == (11,53) or bits == [11,53]: 24 | return ir.DoubleType() 25 | elif bits == (15,113) or bits == [15,113]: 26 | raise Exception("Unsupported type FP128") 27 | else: 28 | raise Exception("Unsupported floating point type (only IEEE 16, 32 and 64 are supported)") 29 | 30 | def floating_to_bits(type): 31 | return [(5,11),(8,24),(11,53),(15,113)][[ir.HalfType(),ir.FloatType(),ir.DoubleType()].index(type)] 32 | 33 | def to_ll_type(smt_type): 34 | if is_fp_sort(smt_type): 35 | return bits_to_floating((smt_type.ebits(),smt_type.sbits())) 36 | elif smt_type==BoolSort(): 37 | return ir.IntType(1) 38 | else: 39 | raise Exception("Unsupported type (only floating point and booleans supported)") 40 | 41 | def ll_is_class(val, name, builder): 42 | return builder.call(get_intrinsic('class',val.type), [val,ir.Constant(ir.IntType(32),class_to_bits(name))]) 43 | 44 | def ll_is_zero(val, builder): 45 | return builder.icmp_unsigned("==",val,ir.Constant(val.type,0)) 46 | 47 | def ll_is_neg(val, builder): 48 | return builder.icmp_signed("<",val,ir.Constant(val.type,0)) 49 | 50 | def ll_is_posz(val,builder): 51 | return builder.icmp_signed(">=",val,ir.Constant(val.type,0)) 52 | 53 | def ll_urem(left,right, builder): 54 | return builder.select(ll_is_zero(right,builder),left,builder.urem(left,right)) 55 | 56 | def ll_smod(s,t, builder): 57 | zero = ir.Constant(s.type,0) 58 | #Check for t = 0 case 59 | u = ll_urem(builder.select(ll_is_neg(s,builder),builder.sub(zero,s),s),builder.select(ll_is_neg(t,builder),builder.sub(zero,t),t),builder) 60 | return builder.select( ll_is_zero(u,builder), \ 61 | u, \ 62 | builder.select( builder.and_(ll_is_posz(s,builder),ll_is_posz(t,builder)), \ 63 | u, \ 64 | builder.select( builder.and_(ll_is_neg(s,builder),ll_is_posz(t,builder)), \ 65 | builder.add(builder.sub(zero,u),t), \ 66 | builder.select( builder.and_(ll_is_posz(s,builder),ll_is_neg(t,builder)), \ 67 | builder.add(u,t), \ 68 | builder.sub(zero,u))))) 69 | 70 | def ll_repeat(val, times, builder): 71 | width = val.type.width 72 | newType = ir.IntType(times*width) 73 | if times == 1: 74 | return val 75 | else: 76 | current = builder.zext(val,ir.IntType(width*times)) 77 | for i in range(1,times): 78 | current = builder.or_(current,builder.shl(builder.zext(val,newType),ir.Constant(newType,i*width))) 79 | return current 80 | 81 | def to_bv_const(node): 82 | return ir.Constant(ir.IntType(node.size()),node.as_long()) 83 | 84 | def transform_name(name): 85 | return name.replace('=','_').replace('|','') 86 | 87 | def get_fun_name(node): 88 | op_names = { 89 | 258: '=', 90 | 259: 'distinct', 91 | 260: 'ite', 92 | 261: 'and', 93 | 262: 'or', 94 | 264: 'xor', 95 | 265: 'not', 96 | 266: '=>', 97 | 98 | 1024: 'bv', 99 | 1027: 'bvneg', 100 | 1028: 'bvadd', 101 | 1029: 'bvsub', 102 | 1030: 'bvmul', 103 | 1031: 'bvsdiv', 104 | 1032: 'bvudiv', 105 | 1033: 'bvsrem', 106 | 1034: 'bvurem', 107 | 1035: 'bvsmod', 108 | 1041: 'bvule', 109 | 1042: 'bvsle', 110 | 1043: 'bvuge', 111 | 1044: 'bvsge', 112 | 1045: 'bvult', 113 | 1046: 'bvslt', 114 | 1047: 'bvugt', 115 | 1048: 'bvsgt', 116 | 1049: 'bvand', 117 | 1050: 'bvor', 118 | 1051: 'bvnot', 119 | 1052: 'bvxor', 120 | 1053: 'bvnand', 121 | 1054: 'bvnor', 122 | 1055: 'bvxnor', 123 | 1056: 'concat', 124 | 1057: 'sign_extend', 125 | 1058: 'zero_extend', 126 | 1059: 'extract', 127 | 1060: 'repeat', 128 | 1063: 'bvcomp', 129 | 1064: 'bvshl', 130 | 1065: 'bvlshr', 131 | 1066: 'bvashr', 132 | 1067: 'rotate_left', 133 | 1068: 'rotate_right', 134 | 135 | 136 | 45062: '+oo', 137 | 45063: '-oo', 138 | 45064: 'NaN', 139 | 45065: '+zero', 140 | 45066: '-zero', 141 | 45069: 'fneg', 142 | 45067: 'fadd', 143 | 45068: 'fsub', 144 | 45070: 'fmul', 145 | 45071: 'fdiv', 146 | 45072: 'frem', 147 | 45073: 'fabs', 148 | 45074: 'fmin', 149 | 45075: 'fmax', 150 | 45076: 'fma', 151 | 45077: 'sqrt', 152 | 45079: 'feq', 153 | 45080: 'flt', 154 | 45081: 'fgt', 155 | 45082: 'fleq', 156 | 45083: 'fgeq', 157 | 45084: 'nan', 158 | 45085: 'infinite', 159 | 45086: 'zero', 160 | 45087: 'normal', 161 | 45088: 'subnormal', 162 | 45089: 'negative', 163 | 45090: 'positive', 164 | 45091: 'fp', 165 | 45092: 'to_fp', 166 | 45093: 'to_fp_unsigned', 167 | 45094: 'fp.to_ubv', 168 | 45095: 'fp.to_sbv', 169 | 170 | 45101: '!var' 171 | } 172 | return op_names[node.decl().kind()] 173 | 174 | 175 | def ifun(node, name): 176 | try: 177 | return get_fun_name(node)==name 178 | except: 179 | return False 180 | 181 | def class_to_bits(name): 182 | bits_dict = { 183 | 'nan': 3, #0000000011 = signaling nan, quiet nan 184 | 'infinite': 516, #1000000100 = signaling nan, quiet nan 185 | 'zero': 96, #0001100000 = negative zero, positive zero 186 | 'normal': 264, #0100001000 = negative normal, positive normal 187 | 'subnormal': 144, #0010010000 = negative subnormal, positive subnormal 188 | 'negative': 60, #0000111100 = neg infinity, neg normal, neg subnormal, neg zero 189 | 'positive': 960 #1111000000 = pos infinity, pos normal, pos subnormal, pos zero 190 | } 191 | try: 192 | return bits_dict[name] 193 | except: 194 | raise Exception("Unsupported floating point class check: "+name) 195 | 196 | def comp_to_str(name): 197 | op_dict = { 198 | 'feq': '==', 199 | 'flt': '<', 200 | 'fgt': '>', 201 | 'fleq': '<=', 202 | 'fgeq': '>=', 203 | 'bvsle': '<=', 204 | 'bvsge': '>=', 205 | 'bvslt': '<', 206 | 'bvsgt': '>', 207 | 'bvule': '<=', 208 | 'bvuge': '>=', 209 | 'bvult': '<', 210 | 'bvugt': '>' 211 | } 212 | try: 213 | return op_dict[name] 214 | except: 215 | raise Exception("Unsupported comparison: "+name) 216 | 217 | #Does not include == 218 | def is_bv_signed_comparison(node): 219 | return get_fun_name(node) in ['bvsle', 'bvsge', 'bvslt', 'bvsgt'] 220 | 221 | #Does not include == 222 | def is_bv_unsigned_comparison(node): 223 | return get_fun_name(node) in ['bvule', 'bvuge', 'bvult', 'bvugt'] 224 | 225 | def is_bv_comparison(node): 226 | return node.children() and ((is_bv_sort(node.children()[0].sort()) and (ifun(node,'=') or ifun(node,'distinct'))) or is_bv_signed_comparison(node) or is_bv_unsigned_comparison(node)) 227 | 228 | def is_fp_comparison(node): 229 | return node.children() and (((node.children()[0].sort() in [Float16(),Float32(),Float64(),Float128()]) and (ifun(node,'=') or ifun(node,'distinct'))) or (get_fun_name(node) in ['feq', 'flt', 'fgt', 'fleq', 'fgeq'])) 230 | 231 | def is_class_check(node): 232 | return node.children() and (get_fun_name(node) in ['nan', 'infinite', 'zero', 'normal', 'subnormal', 'negative', 'positive']) 233 | 234 | 235 | def build_formula(contents, builder, fun_args): 236 | #print("building formula "+str(contents)) 237 | results = list(map(lambda a: build_constraint(a,builder,fun_args),contents)) 238 | 239 | if len(results)==0: 240 | #An empty constraint 241 | return ir.Constant(ir.IntType(1),1) 242 | elif len(results)==1: 243 | return results[0] 244 | elif len(results)==2: 245 | return builder.and_(results[0],results[1]) 246 | else: 247 | temp = results[0] 248 | for i in range(1,len(results)): 249 | temp = builder.and_(temp,results[i]) 250 | return temp 251 | 252 | 253 | def build_constraint(node, builder, fun_args): 254 | #print("building constraint "+str(node)) 255 | 256 | if is_fp_comparison(node) or is_class_check(node): 257 | return build_fp_comparison(node,builder,fun_args) 258 | elif is_bv_comparison(node): 259 | return build_bv_comparison(node,builder,fun_args) 260 | elif not node.children(): 261 | #Boolean leaf 262 | if is_const(node) and is_bool(node): 263 | if str(node)=='True': 264 | return ir.Constant(ir.IntType(1),1) 265 | elif str(node)=='False': 266 | return ir.Constant(ir.IntType(1),0) 267 | else: 268 | return fun_args[transform_name(str(node))] 269 | else: 270 | raise Exception("Unexpected type for boolean leaf: "+str(node)) 271 | else: 272 | results = list(map(lambda a: build_constraint(a,builder,fun_args),node.children())) 273 | 274 | if ifun(node,'and'): 275 | temp = results[0] 276 | for i in range(1,len(results)): 277 | temp = builder.and_(temp,results[i]) 278 | return temp 279 | elif ifun(node,'or'): 280 | temp = results[0] 281 | for i in range(1,len(results)): 282 | temp = builder.or_(temp,results[i]) 283 | return temp 284 | elif ifun(node,'xor'): 285 | temp = results[0] 286 | for i in range(1,len(results)): 287 | temp = builder.xor(temp,results[i]) 288 | return temp 289 | elif ifun(node,'='): 290 | if len(results) == 2: 291 | return builder.icmp_unsigned("==",results[0],results[1]) 292 | else: 293 | raise Exception("Unexpected number of arguments for boolean = (iff): "+str(node)) 294 | elif ifun(node,'distinct'): 295 | if len(results) == 2: 296 | return builder.icmp_unsigned("!=",results[0],results[1]) 297 | else: 298 | raise Exception("Unexpected number of arguments for boolean distinct: "+str(node)) 299 | elif ifun(node,'=>'): 300 | if len(results)==2: 301 | temp = builder.not_(results[0]) 302 | return builder.or_(temp,results[1]) 303 | else: 304 | raise Exception("Unexpected number of arguments for implies: "+str(node)) 305 | elif ifun(node,'not'): 306 | if len(results) == 1: 307 | return builder.not_(results[0]) 308 | else: 309 | raise Exception("Unexpected number of arguments for boolean not: "+str(node)) 310 | elif ifun(node,'ite'): 311 | if len(results) == 3: 312 | return builder.select(results[0],results[1],results[2]) 313 | else: 314 | raise Exception("Unexpected number of arguments for boolean ite: "+str(node)) 315 | else: 316 | raise Exception("Unexpected constraint operation: "+str(node)) 317 | 318 | def build_fp_comparison(node, builder, fun_args): 319 | #print("building fp comparison "+str(node)) 320 | left = build_fp_value(node.children()[0],builder,fun_args) 321 | if len(node.children())==2: 322 | right = build_fp_value(node.children()[1], builder, fun_args) 323 | 324 | #All comparisons are ordered (SMT-LIB says comparison is false if either argument is NaN) 325 | if ifun(node,'='): 326 | #Bitwise equality, except that all NaNs are equal 327 | iType = ir.IntType({ir.HalfType():16, ir.FloatType():32, ir.DoubleType():64}[left.type]) 328 | lb = builder.bitcast(left,iType) 329 | rb = builder.bitcast(right,iType) 330 | return builder.or_(builder.and_(ll_is_class(left,'nan',builder),ll_is_class(right,'nan',builder)),builder.icmp_unsigned('==',lb,rb)) 331 | elif ifun(node,'distinct'): 332 | #Bitwise inequality (not both NaNs, or bits are different) 333 | iType = ir.IntType({ir.HalfType():16, ir.FloatType():32, ir.DoubleType():64}[left.type]) 334 | lb = builder.bitcast(left,iType) 335 | rb = builder.bitcast(right,iType) 336 | return builder.or_(builder.not_(builder.and_(ll_is_class(left,'nan',builder),ll_is_class(right,'nan',builder))),builder.icmp_unsigned('!=',lb,rb)) 337 | elif is_fp_comparison(node): 338 | return builder.fcmp_ordered(comp_to_str(get_fun_name(node)),left,right) 339 | elif is_class_check(node): 340 | return ll_is_class(left, get_fun_name(node),builder) 341 | else: 342 | raise Exception("Unexpected floating point comparison operation: "+str(node)) 343 | 344 | def build_bv_comparison(node, builder, fun_args): 345 | #print("building bv comparison "+str(node)) 346 | left = build_bv_value(node.children()[0],builder,fun_args) 347 | right = build_bv_value(node.children()[1], builder, fun_args) 348 | 349 | if ifun(node,'='): 350 | return builder.icmp_unsigned('==',left,right) 351 | elif ifun(node,'distinct'): 352 | return builder.icmp_unsigned('!=',left,right) 353 | elif is_bv_signed_comparison(node): 354 | return builder.icmp_signed(comp_to_str(get_fun_name(node)),left,right) 355 | elif is_bv_unsigned_comparison(node): 356 | return builder.icmp_unsigned(comp_to_str(get_fun_name(node)),left,right) 357 | else: 358 | raise Exception("Unexpected bitvector comparison operation: "+str(node)) 359 | 360 | 361 | def build_fp_value(node, builder, fun_args): 362 | #print("building fp value "+str(node)) 363 | 364 | #Check that the rounding mode is supported (only round to nearest in LLVM) 365 | if is_fprm(node): 366 | if node == RoundNearestTiesToEven(): 367 | return None 368 | else: 369 | raise Exception("Unsupported fp rounding mode: "+str(node)) 370 | 371 | #Floating point variables 372 | elif ifun(node,'!var'): 373 | return fun_args[transform_name(str(node))] 374 | #There are no floating point constants in SMT--all come from bitvectors 375 | 376 | #Tree case 377 | else: 378 | 379 | #Fixed floating point constants 380 | if ifun(node,'NaN'): 381 | return ir.Constant(to_ll_type(node.sort()),float("nan")) 382 | elif ifun(node,'-oo'): 383 | return ir.Constant(to_ll_type(node.sort()),float('-inf')) 384 | elif ifun(node,'+oo'): 385 | return ir.Constant(to_ll_type(node.sort()),float('-inf')) 386 | elif ifun(node,'-zero'): 387 | return ir.Constant(to_ll_type(node.sort()),-0.0) 388 | elif ifun(node,'+zero'): 389 | return ir.Constant(to_ll_type(node.sort()),0.0) 390 | elif ifun(node,'fp'): 391 | #Construct a floating point from 3 bitvectors (sign, exponent, significand) 392 | #Significand INCLUDES the hidden bit 393 | width = node.sort().sbits()+node.sort().ebits() 394 | 395 | parts = list(map(lambda a: builder.zext(build_bv_value(a,builder,fun_args),ir.IntType(width)),node.children())) 396 | 397 | sign = builder.shl(parts[0],ir.Constant(ir.IntType(width),width-1)) 398 | exp = builder.shl(parts[1],ir.Constant(ir.IntType(width),node.sbits()-1)) 399 | val = parts[2] 400 | 401 | return builder.bitcast(builder.or_(sign,builder.or_(exp,val)),bits_to_floating(width)) 402 | 403 | elif ifun(node,'to_fp'): 404 | if len(node.children())==1: 405 | #bitcast conversion bv to fp 406 | res = build_bv_value(node.children()[0],builder,fun_args) 407 | return builder.bitcast(res,bits_to_floating(res.type.width)) 408 | elif len(node.children())==2: 409 | if is_fp_sort(node.children()[1].sort()): 410 | #Conversion from one fp type to another 411 | newType = bits_to_floating(node.decl().params()) 412 | res = build_fp_value(node.children()[1],builder,fun_args) 413 | if newType == res.type: 414 | return res 415 | elif sum(floating_to_bits(newType)) > sum(floating_to_bits(res.type)): 416 | return builder.fpext(res,newType) 417 | else: 418 | return builder.fptrunc(res,newType) 419 | else: 420 | #Signed numeric conversion bv to fp 421 | res = build_bv_value(node.children()[1],builder,fun_args) 422 | return builder.sitofp(res,bits_to_floating(node.decl().params())) 423 | else: 424 | raise Exception("Unexpected number of arguments to to_fp conversion: "+str(node)) 425 | elif ifun(node,'to_fp_unsigned'): 426 | res = build_bv_value(node.children()[1],builder,fun_args) 427 | return builder.uitofp(res,bits_to_floating(node.decl().params())) 428 | if ifun(node,'ite'): 429 | return builder.select(build_constraint(node.children()[0],builder,fun_args),build_fp_value(node.children()[1],builder,fun_args),build_fp_value(node.children()[2],builder,fun_args)) 430 | 431 | 432 | 433 | results = list(map(lambda a: build_fp_value(a,builder,fun_args),node.children())) 434 | 435 | if ifun(node,'fabs'): 436 | return builder.call(get_intrinsic('fabs',results[0].type), [results[0]]) 437 | elif ifun(node,'fneg'): 438 | return builder.fneg(results[0]) 439 | elif ifun(node,'fadd'): 440 | #results[0] is the rounding mode 441 | return builder.fadd(results[1],results[2]) 442 | elif ifun(node,'fsub'): 443 | return builder.fsub(results[1],results[2]) 444 | elif ifun(node,'fmul'): 445 | return builder.fmul(results[1],results[2]) 446 | elif ifun(node,'fdiv'): 447 | return builder.fdiv(results[1],results[2]) 448 | elif ifun(node,'fma'): 449 | return builder.call(get_intrinsic('fma',results[1].type), [results[1],results[2],results[3]]) 450 | elif ifun(node,'sqrt'): 451 | return builder.call(get_intrinsic('sqrt',results[1].type), [results[1]]) 452 | elif ifun(node,'frem'): 453 | return builder.frem(results[0],results[1]) 454 | elif ifun(node,'fmin'): 455 | return builder.call(get_intrinsic('min',results[0].type), [results[0],results[1]]) 456 | elif ifun(node,'fmax'): 457 | return builder.call(get_intrinsic('max',results[0].type), [results[0],results[1]]) 458 | else: 459 | raise Exception("Unexpected floating point value operation: "+str(node)) 460 | 461 | def build_bv_value(node, builder, fun_args): 462 | #print("building bv value "+str(node)) 463 | 464 | #Bitvector constant 465 | if ifun(node,'bv'): 466 | return to_bv_const(node) 467 | 468 | #Symbol (variable) 469 | elif ifun(node,'!var'): 470 | return fun_args[transform_name(str(node))] 471 | 472 | #Tree case 473 | else: 474 | if ifun(node,'ite'): 475 | return builder.select(build_constraint(node.children()[0],builder,fun_args),build_bv_value(node.children()[1],builder,fun_args),build_bv_value(node.children()[2],builder,fun_args)) 476 | elif ifun(node,'fp.to_ubv'): 477 | build_fp_value(node.children()[0]) #Need to check the rounding mode, even though the result is unused 478 | res = build_fp_value(node.children()[1], builder, fun_args) 479 | return builder.fptoui(res,ir.IntType(sum(floating_to_bits(node.size())))) 480 | elif ifun(node,'fp.to_sbv'): 481 | build_fp_value(node.children()[0], builder, fun_args) #Need to check the rounding mode, even though the result is unused 482 | res = build_fp_value(node.children()[1]) 483 | return builder.fptosi(res,ir.IntType(sum(floating_to_bits(node.size())))) 484 | 485 | 486 | results = list(map(lambda a: build_bv_value(a,builder,fun_args),node.children())) 487 | 488 | if ifun(node,'bvneg'): 489 | return builder.sub(ir.Constant(results[0].type,0),results[0]) 490 | elif ifun(node,'bvadd'): 491 | return builder.add(results[0],results[1]) 492 | elif ifun(node,'bvsub'): 493 | return builder.sub(results[0],results[1]) 494 | elif ifun(node,'bvmul'): 495 | return builder.mul(results[0],results[1]) 496 | elif ifun(node,'bvsdiv'): 497 | return builder.select(ll_is_zero(results[1],builder),builder.select(ll_is_neg(results[0],builder),ir.Constant(results[0].type,1),ir.Constant(results[0].type,-1)),builder.sdiv(results[0],results[1])) 498 | elif ifun(node,'bvudiv'): 499 | return builder.select(ll_is_zero(results[1],builder),ir.Constant(results[0].type,-1),builder.udiv(results[0],results[1])) 500 | elif ifun(node,'bvsrem'): 501 | return builder.select(ll_is_zero(results[1],builder),results[0],builder.srem(results[0],results[1])) 502 | elif ifun(node,'bvurem'): 503 | return ll_urem(results[0],results[1],builder) 504 | elif ifun(node,'bvsmod'): 505 | return ll_smod(results[0],results[1],builder) 506 | elif ifun(node,'bvand'): 507 | return builder.and_(results[0],results[1]) 508 | elif ifun(node,'bvor'): 509 | return builder.or_(results[0],results[1]) 510 | elif ifun(node,'bvnot'): 511 | return builder.not_(results[0]) 512 | elif ifun(node,'bvxor'): 513 | #bvxor is left associative (any number of arguments) 514 | temp = results[0] 515 | for i in range(1,len(results)): 516 | temp = builder.xor(temp,results[i]) 517 | return temp 518 | elif ifun(node,'bvnand'): 519 | return builder.not_(builder.and_(results[0],results[1])) 520 | elif ifun(node,'bvnor'): 521 | return builder.not_(builder.or_(results[0],results[1])) 522 | elif ifun(node,'bvxnor'): 523 | return builder.not_(builder.xor(results[0],results[1])) 524 | elif ifun(node,'concat'): 525 | final_width = node.size() 526 | left = builder.zext(results[0],ir.IntType(final_width)) 527 | right = builder.zext(results[1],ir.IntType(final_width)) 528 | shifted = builder.shl(left,ir.Constant(ir.IntType(final_width),results[1].type.width)) 529 | return builder.or_(right,shifted) 530 | elif ifun(node,'sign_extend'): 531 | return builder.sext(results[0],ir.IntType(node.size())) 532 | elif ifun(node,'zero_extend'): 533 | return builder.zext(results[0],ir.IntType(node.size())) 534 | elif ifun(node,'extract'): 535 | return builder.trunc(builder.lshr(results[0],ir.Constant(results[0].type,node.decl().params()[1])),ir.IntType(node.decl().params()[0]-node.decl().params()[1]+1)) 536 | elif ifun(node,'repeat'): 537 | return ll_repeat(results[0],node.decl().params()[0],builder) 538 | elif ifun(node,'bvcomp'): 539 | return builder.icmp_unsigned("==",results[0],results[1]) 540 | elif ifun(node,'bvshl'): 541 | #Check that the shift does not exceed the bit width to avoid LLVM undefined behavior 542 | return builder.select(builder.icmp_unsigned(">=",results[1],ir.Constant(results[0].type,node.size())),ir.Constant(results[0].type,0),builder.shl(results[0],results[1])) 543 | elif ifun(node,'bvlshr'): 544 | #Check for shift exceeding the bit width 545 | return builder.select(builder.icmp_unsigned(">=",results[1],ir.Constant(results[0].type,node.size())),ir.Constant(results[0].type,0),builder.lshr(results[0],results[1])) 546 | elif ifun(node,'bvashr'): 547 | #Check for shift exceeding the bit width 548 | return builder.select(builder.icmp_unsigned(">=",results[1],ir.Constant(results[0].type,node.size())),builder.select(ll_is_neg(results[0],builder),ir.Constant(results[0].type,-1),ir.Constant(results[0].type,0)),builder.ashr(results[0],results[1])) 549 | elif ifun(node,'rotate_left'): 550 | return builder.call(get_intrinsic('fshl',results[0].type), [results[0],results[0],ir.Constant(results[0].type,node.decl().params()[0]%node.size())]) 551 | elif ifun(node,'rotate_right'): 552 | return builder.call(get_intrinsic('fshr',results[0].type), [results[0],results[0],ir.Constant(results[0].type,node.decl().params()[0]%node.size())]) 553 | 554 | else: 555 | print(node.decl().kind()) 556 | raise Exception("Unexpected bitvector value operation: "+str(node)) 557 | 558 | 559 | def parse_args(): 560 | parser = argparse.ArgumentParser() 561 | parser.add_argument('-s', '--smt', 562 | help='Input .smt2 constraints', 563 | required=True) 564 | parser.add_argument('-o', '--output', 565 | help='Output .ll file', 566 | required=False) 567 | 568 | args = parser.parse_args() 569 | return args 570 | 571 | args = parse_args() 572 | filename = args.smt 573 | 574 | 575 | module = ir.Module(name=__file__) 576 | 577 | fp_intrinsics = { 578 | 'fabs': list(map(lambda t: module.declare_intrinsic('llvm.fabs', [t]),[ir.HalfType(),ir.FloatType(),ir.DoubleType()])), 579 | 'fma': list(map(lambda t: module.declare_intrinsic('llvm.fma', [t,t,t]),[ir.HalfType(),ir.FloatType(),ir.DoubleType()])), 580 | 'sqrt': list(map(lambda t: module.declare_intrinsic('llvm.sqrt', [t]),[ir.HalfType(),ir.FloatType(),ir.DoubleType()])), 581 | 'class': list(map(lambda x: ir.Function(module,ir.FunctionType(ir.IntType(1),[x[0],ir.IntType(32)]), 'llvm.is.fpclass.f'+str(x[1])),[(ir.HalfType(),16),(ir.FloatType(),32),(ir.DoubleType(),64)])), 582 | 'min': list(map(lambda x: ir.Function(module,ir.FunctionType(x[0],[x[0],x[0]]), 'llvm.minnum.f'+str(x[1])),[(ir.HalfType(),16),(ir.FloatType(),32),(ir.DoubleType(),64)])), 583 | 'max': list(map(lambda x: ir.Function(module,ir.FunctionType(x[0],[x[0],x[0]]), 'llvm.maxnum.f'+str(x[1])),[(ir.HalfType(),16),(ir.FloatType(),32),(ir.DoubleType(),64)])) 584 | } 585 | 586 | bv_rols = dict() 587 | bv_rors = dict() 588 | 589 | def get_intrinsic(name,type): 590 | if str(type).startswith('i'): 591 | #Integer intrinsics 592 | width = int(str(type)[1:]) 593 | if name=='fshl': 594 | if not (width in bv_rols): 595 | bv_rols[width] = ir.Function(module,ir.FunctionType(type,[type,type,type]),'llvm.fshl.i'+str(width)) 596 | return bv_rols[width] 597 | elif name == 'fshr': 598 | if not (width in bv_rors): 599 | bv_rors[width] = ir.Function(module,ir.FunctionType(type,[type,type,type]),'llvm.fshr.i'+str(width)) 600 | return bv_rors[width] 601 | else: 602 | #Floating point intrinsics 603 | pos = [ir.HalfType(),ir.FloatType(),ir.DoubleType()].index(type) 604 | return fp_intrinsics[name][pos] 605 | 606 | 607 | ctx = z3.Context() 608 | s = z3.Solver(ctx=ctx) 609 | contents = z3.parse_smt2_file(filename) 610 | 611 | 612 | 613 | #Parse variable declarations (Z3 parser doesn't do this transparently) 614 | declared=[] 615 | 616 | with open(filename, 'r') as file: 617 | declaration = re.compile(r'\(declare-fun\s(\|.*\||[\~\!\@\$\%\^\&\*\_\-\+\=\<\>\.\?\/A-Za-z0-9]+)\s*\(\s*\)\s*(\(\s*_\s*FloatingPoint\s*(\d+)\s*(\d+)\s*\)|Bool|\(\s*_\s*BitVec\s*(\d+)\s*\))\s*|declare-const\s(\|.*\||[\~\!\@\$\%\^\&\*\_\-\+\=\<\>\.\?\/A-Za-z0-9]+)\s*(\(\s*_\s*FloatingPoint\s*(\d+)\s*(\d+)\s*\)|Bool|\(\s*_\s*BitVec\s*(\d+)\s*\))\s*\)') 618 | sc = file.read() 619 | #SMTLIB type synonyms 620 | c = sc.replace('Float16','(_ FloatingPoint 5 11)') 621 | c = c.replace('Float32','(_ FloatingPoint 8 24)') 622 | c = c.replace('Float64','(_ FloatingPoint 11 53)') 623 | c = c.replace('Float128','(_ FloatingPoint 15 113)') 624 | matches = declaration.findall(c) 625 | for match in matches: 626 | if not match[0]: 627 | match = match[5:] 628 | else: 629 | match = match[:5] 630 | 631 | name = transform_name(match[0]) 632 | if match[2]: 633 | #Floating point case 634 | declared.append((name,bits_to_floating((int(match[2]),int(match[3]))))) 635 | elif match[4]: 636 | #Bitvector case 637 | declared.append((name,ir.IntType(int(match[4])))) 638 | else: 639 | #Boolean case 640 | declared.append((name,ir.IntType(1))) 641 | 642 | # Declared symbols -> function arguments 643 | argt = (x[1] for x in declared) 644 | fnty = ir.FunctionType(ir.IntType(1),argt) 645 | func = ir.Function(module,fnty,"smt") 646 | for i in range(0,len(declared)): 647 | func.args[i].name = transform_name(declared[i][0]) 648 | fun_args = dict([(arg.name,arg) for arg in func.args]) 649 | 650 | 651 | 652 | block = func.append_basic_block() 653 | builder = ir.IRBuilder(block) 654 | 655 | result = build_formula(contents, builder, fun_args) 656 | 657 | builder.ret(result) 658 | 659 | if args.output: 660 | with open(args.output,'w') as file: 661 | file.write(str(module)) 662 | else: 663 | print(module) 664 | -------------------------------------------------------------------------------- /legacy/python/passes-16.txt: -------------------------------------------------------------------------------- 1 | -targetlibinfo -tbaa -scoped-noalias-aa -annotation2metadata -forceattrs -inferattrs -domtree -callsite-splitting -ipsccp -called-value-propagation -globalopt -domtree -mem2reg -deadargelim -domtree -basic-aa -aa -loops -instcombine -simplifycfg -globals-aa -inline -openmp-opt-cgscc -function-attrs -domtree -sroa -basic-aa -aa -memoryssa -early-cse-memssa -speculative-execution -aa -lazy-value-info -jump-threading -correlated-propagation -simplifycfg -domtree -aggressive-instcombine -basic-aa -aa -loops -instcombine -libcalls-shrinkwrap -basic-aa -aa -loops -tailcallelim -simplifycfg -reassociate -domtree -basic-aa -aa -memoryssa -loops -loop-simplify -lcssa -scalar-evolution -loop-instsimplify -loop-simplifycfg -licm -loop-rotate -licm -simple-loop-unswitch -simplifycfg -domtree -basic-aa -aa -loops -instcombine -loop-simplify -lcssa -scalar-evolution -loop-idiom -indvars -loop-deletion -loop-unroll -sroa -aa -mldst-motion -phi-values -aa -memdep -gvn -sccp -demanded-bits -bdce -basic-aa -aa -loops -instcombine -lazy-value-info -jump-threading -correlated-propagation -postdomtree -adce -basic-aa -aa -memoryssa -memcpyopt -loops -dse -loop-simplify -lcssa -aa -scalar-evolution -licm -simplifycfg -domtree -basic-aa -aa -loops -instcombine -elim-avail-extern -rpo-function-attrs -globalopt -globaldce -globals-aa -domtree -float2int -lower-constant-intrinsics -loops -loop-simplify -lcssa -basic-aa -aa -scalar-evolution -loop-rotate -loop-distribute -postdomtree -branch-prob -block-freq -scalar-evolution -basic-aa -aa -demanded-bits -inject-tli-mappings -loop-simplify -scalar-evolution -aa -loop-load-elim -basic-aa -aa -instcombine -simplifycfg -domtree -loops -scalar-evolution -basic-aa -aa -demanded-bits -inject-tli-mappings -instcombine -loop-simplify -lcssa -scalar-evolution -loop-unroll -instcombine -memoryssa -loop-simplify -lcssa -scalar-evolution -licm -transform-warning -alignment-from-assumptions -strip-dead-prototypes -globaldce -constmerge -domtree -loops -postdomtree -branch-prob -block-freq -loop-simplify -lcssa -basic-aa -aa -scalar-evolution -memoryssa -block-freq -loop-sink -instsimplify -div-rem-pairs -simplifycfg -annotation-remarks -verify -------------------------------------------------------------------------------- /legacy/python/runthrough.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | CLANG_FLAGS=$(cat passes-16.txt) 3 | OPT_CMD=opt 4 | Z3=z3 5 | BOOLECTOR=boolector 6 | CVC5=cvc5 7 | 8 | usage() { 9 | echo "Usage: $0 [-r] [-z] [-c] [-b] [-f ]" 1>&2 10 | echo " -r : Remove all produced files" 11 | echo " -z : Use Z3 solver" 12 | echo " -c : Use CVC5 solver" 13 | echo " -b : Use Boolector solver" 14 | echo " -t : Timeout (seconds)" 15 | echo " -f : .smt2 file to process" 16 | exit 17 | } 18 | 19 | FILE="" 20 | CLEANUP=false 21 | USE_Z3=false 22 | USE_CV=false 23 | USE_BL=false 24 | 25 | while getopts "hrzcbt:f:" arg; do 26 | case $arg in 27 | h) 28 | usage 29 | ;; 30 | r) 31 | CLEANUP=true 32 | ;; 33 | z) 34 | USE_Z3=true 35 | ;; 36 | c) 37 | USE_CV=true 38 | ;; 39 | b) 40 | USE_BL=true 41 | ;; 42 | t) 43 | SMT_TIMEOUT=${OPTARG} 44 | PYTHON_TIMEOUT=${OPTARG} 45 | ;; 46 | f) 47 | FILE=${OPTARG} 48 | ;; 49 | esac 50 | done 51 | 52 | #SMT_TIMEOUT=300 53 | #PYTHON_TIMEOUT=300 54 | 55 | #echo "$FILE" 56 | NAME="${FILE%.*}" 57 | 58 | FT_GOOD=true 59 | OPT_GOOD=true 60 | BK_GOOD=true 61 | 62 | S1_SIZE=$(($(wc -c < "$FILE"))) 63 | #echo "Running frontend ..." 64 | FRONTEND_OUT=$( { /usr/bin/time -f "tmr%e" timeout $PYTHON_TIMEOUT python3 frontend.py -s $FILE -o $NAME.ll; } 2>&1 > /dev/null ) 65 | if [[ $? == 124 ]] 66 | then 67 | FT_GOOD=false 68 | FT_TIME=$PYTHON_TIMEOUT 69 | else 70 | FT_TIME=$(echo "$FRONTEND_OUT" | grep -Po 'tmr*.*' | tr -dc '.0-9') 71 | fi 72 | #Check for unsupported floating point files 73 | if [[ "$FRONTEND_OUT" == *"Unsupported floating point type"* ]] 74 | then 75 | echo "$FILE,UnsupportedFP" 76 | exit 77 | fi 78 | 79 | if $FT_GOOD 80 | then 81 | L1_SIZE=$(($(wc -c < "$NAME.ll"))) 82 | #echo "Running optimizer ..." 83 | OPT_OUT=$( { /usr/bin/time -f "tmr%e" timeout $PYTHON_TIMEOUT $OPT_CMD $NAME.ll $CLANG_FLAGS -S -o $NAME-opt.ll; } 2>&1 > /dev/null ) 84 | if [[ $? == 124 ]] 85 | then 86 | OPT_GOOD=false 87 | OPT_TIME=$PYTHON_TIMEOUT 88 | else 89 | OPT_TIME=$(echo "$OPT_OUT" | grep -Po 'tmr*.*' | tr -dc '.0-9') 90 | #Remove attributes since the LLVM parser doesn't support the newer ones 91 | sed -i '/attributes/d' $NAME-opt.ll 92 | L2_SIZE=$(($(wc -c < "$NAME-opt.ll"))) 93 | 94 | #echo "Running backend ..." 95 | BACKEND_OUT=$( { /usr/bin/time -f "tmr%e" timeout $PYTHON_TIMEOUT python3 backend.py -s -l $NAME-opt.ll -o $NAME-opt.smt2; } 2>&1 > /dev/null) 96 | if [[ $? == 124 ]] 97 | then 98 | BK_GOOD=false 99 | BK_TIME=$PYTHON_TIMEOUT 100 | else 101 | BK_TIME=$(echo "$BACKEND_OUT" | grep -Po 'tmr*.*' | tr -dc '.0-9') 102 | S2_SIZE=$(($(wc -c < "$NAME-opt.smt2"))) 103 | fi 104 | fi 105 | fi 106 | 107 | 108 | 109 | #Z3---------------- 110 | if $USE_Z3 111 | then 112 | PRE_SOL_OUT=$($Z3 -smt2 $FILE -st -T:$SMT_TIMEOUT) 113 | PRE_SOL_OUT=$( { /usr/bin/time -f "tmr%e" $Z3 $FILE -T:$SMT_TIMEOUT; } 2>&1 ) 114 | if [[ "$PRE_SOL_OUT" == "timeout" ]] 115 | then 116 | Z3_PRE_TIME=$SMT_TIMEOUT 117 | Z3_PRE_RESULT="timeout" 118 | else 119 | Z3_PRE_TIME=$(echo "$PRE_SOL_OUT" | grep -Po 'tmr*.*' | tr -dc '.0-9') 120 | Z3_PRE_RESULT=$(echo $PRE_SOL_OUT | awk '{print $1;}') 121 | fi 122 | 123 | if $FT_GOOD && $OPT_GOOD && $BK_GOOD 124 | then 125 | POST_SOL_OUT=$( { /usr/bin/time -f "tmr%e" $Z3 $NAME-opt.smt2 -T:$SMT_TIMEOUT; } 2>&1 ) 126 | if [[ "$POST_SOL_OUT" == "timeout" ]] 127 | then 128 | Z3_POST_TIME=$SMT_TIMEOUT 129 | Z3_POST_RESULT="timeout" 130 | else 131 | Z3_POST_TIME=$(echo "$POST_SOL_OUT" | grep -Po 'tmr*.*' | tr -dc '.0-9') 132 | Z3_POST_RESULT=$(echo $POST_SOL_OUT | awk '{print $1;}') 133 | fi 134 | fi 135 | fi 136 | 137 | 138 | #------------------ 139 | 140 | 141 | #CVC5---------------- 142 | if $USE_CV 143 | then 144 | PRE_SOL_OUT=$( { /usr/bin/time -f "tmr%e" $CVC5 $FILE -q --tlimit=$(( 1000 * SMT_TIMEOUT )); } 2>&1 ) 145 | if [[ "$PRE_SOL_OUT" == *"timeout"* ]] 146 | then 147 | CV_PRE_TIME=$SMT_TIMEOUT 148 | CV_PRE_RESULT="timeout" 149 | else 150 | CV_PRE_TIME=$(echo "$PRE_SOL_OUT" | grep -Po 'tmr*.*' | tr -dc '.0-9') 151 | CV_PRE_RESULT=$(echo $PRE_SOL_OUT | awk '{print $1;}') 152 | fi 153 | 154 | if $FT_GOOD && $OPT_GOOD && $BK_GOOD 155 | then 156 | POST_SOL_OUT=$( { /usr/bin/time -f "tmr%e" $CVC5 $NAME-opt.smt2 -q --tlimit=$(( 1000 * SMT_TIMEOUT )); } 2>&1 ) 157 | if [[ "$POST_SOL_OUT" == *"timeout"* ]] 158 | then 159 | CV_POST_TIME=$SMT_TIMEOUT 160 | CV_POST_RESULT="timeout" 161 | else 162 | CV_POST_TIME=$(echo "$POST_SOL_OUT" | grep -Po 'tmr*.*' | tr -dc '.0-9') 163 | CV_POST_RESULT=$(echo $POST_SOL_OUT | awk '{print $1;}') 164 | fi 165 | fi 166 | fi 167 | #------------------ 168 | 169 | 170 | #BOOLECTOR---------------- 171 | if $USE_BL 172 | then 173 | PRE_SOL_OUT=$( { /usr/bin/time -f "tmr%e" $BOOLECTOR $FILE -t $SMT_TIMEOUT; } 2>&1 ) 174 | if [[ "$PRE_SOL_OUT" == *"unknown"* ]] 175 | then 176 | BL_PRE_TIME=$SMT_TIMEOUT 177 | BL_PRE_RESULT="timeout" 178 | else 179 | BL_PRE_TIME=$(echo "$PRE_SOL_OUT" | grep -Po 'tmr*.*' | tr -dc '.0-9') 180 | BL_PRE_RESULT=$(echo $PRE_SOL_OUT | awk '{print $1;}') 181 | fi 182 | 183 | if $FT_GOOD && $OPT_GOOD && $BK_GOOD 184 | then 185 | POST_SOL_OUT=$( { /usr/bin/time -f "tmr%e" $BOOLECTOR $NAME-opt.smt2 -t $SMT_TIMEOUT; } 2>&1 ) 186 | if [[ "$POST_SOL_OUT" == *"unknown"* ]] 187 | then 188 | BL_POST_TIME=$SMT_TIMEOUT 189 | BL_POST_RESULT="timeout" 190 | else 191 | BL_POST_TIME=$(echo "$POST_SOL_OUT" | grep -Po 'tmr*.*' | tr -dc '.0-9') 192 | BL_POST_RESULT=$(echo $POST_SOL_OUT | awk '{print $1;}') 193 | fi 194 | fi 195 | fi 196 | #------------------ 197 | 198 | echo "$FILE,$S1_SIZE,$L1_SIZE,$L2_SIZE,$S2_SIZE,$FT_TIME,$OPT_TIME,$BK_TIME,$Z3_PRE_RESULT,$Z3_PRE_TIME,$Z3_POST_RESULT,$Z3_POST_TIME,$CV_PRE_RESULT,$CV_PRE_TIME,$CV_POST_RESULT,$CV_POST_TIME,$BL_PRE_RESULT,$BL_PRE_TIME,$BL_POST_RESULT,$BL_POST_TIME" 199 | 200 | if $CLEANUP 201 | then 202 | rm $NAME.ll 203 | rm $NAME-opt.ll 204 | rm $NAME-opt.smt2 205 | fi 206 | 207 | 208 | 209 | -------------------------------------------------------------------------------- /legacy/python/wrapper.sh: -------------------------------------------------------------------------------- 1 | ./runthrough.sh -z -c -b -t 600 -f $1 -------------------------------------------------------------------------------- /results/analysis.py: -------------------------------------------------------------------------------- 1 | import csv 2 | import argparse 3 | import statistics 4 | from prettytable import PrettyTable 5 | 6 | def parse_args(): 7 | parser = argparse.ArgumentParser() 8 | parser.add_argument('-f', '--file', 9 | help='Input statistics file', 10 | required=True) 11 | args = parser.parse_args() 12 | return args 13 | 14 | 15 | class Entry: 16 | def __init__(self, arr): 17 | self.arr = arr 18 | 19 | def name(self): 20 | return self.arr[0] 21 | 22 | def result(self, solver, isPre): 23 | n = 0 if isPre else 2 24 | if solver == 'z': 25 | return self.arr[1+n] 26 | elif solver == 'c': 27 | return self.arr[5+n] 28 | elif solver == 'b': 29 | return self.arr[9+n] 30 | 31 | def solTime(self, solver, isPre): 32 | n = 0 if isPre else 2 33 | if solver == 'z': 34 | if (not isPre) and (self.arr[2+n] ==''): 35 | return 600 #SLOT timeout 36 | else: 37 | return max(float(self.arr[2+n]), 0.005) 38 | elif solver == 'c': 39 | if (not isPre) and (self.arr[6+n] ==''): 40 | return 600 #SLOT timeout 41 | else: 42 | return max(float(self.arr[6+n]), 0.005) 43 | elif solver == 'b': 44 | if (not isPre) and (self.arr[10+n] ==''): 45 | return 600 #SLOT timeout 46 | else: 47 | return max(float(self.arr[10+n]), 0.005) 48 | 49 | def isSlotTimeout(self): 50 | return len(self.arr) < 16 51 | 52 | def frontTime(self): 53 | #print(self.arr) 54 | return 0 if self.isSlotTimeout() else float(self.arr[23]) 55 | def optTime(self): 56 | return 0 if self.isSlotTimeout() else float(self.arr[24]) 57 | def backTime(self): 58 | return 0 if self.isSlotTimeout() else float(self.arr[25]) 59 | 60 | def slotTime(self): 61 | return 600 if self.isSlotTimeout() else self.frontTime()+self.optTime()+self.backTime() 62 | 63 | def usedPass(self, n): 64 | return (not self.isSlotTimeout()) and (self.arr[26+n] == '1') 65 | 66 | def finalTime(self, solver): 67 | return self.solTime(solver, False)+self.frontTime()+self.optTime()+self.backTime() 68 | 69 | def ratio(self, solver): 70 | return self.solTime(solver, True)/self.finalTime(solver) 71 | 72 | def portfolioRatio(self, solver): 73 | return max(self.ratio(solver), 1) 74 | 75 | def inRange(self, solver, range): 76 | if (type(range) == int or type(range) == float): 77 | return self.solTime(solver, True) >= range 78 | else: 79 | return (self.solTime(solver, True) >= range[0]) and (self.solTime(solver, True) < range[1]) 80 | 81 | def isImp(self, solver, time): 82 | if (type(solver) == list): 83 | return all([self.solTime(s, True) >= time for s in solver]) and any([self.finalTime(s) < time for s in solver]) 84 | else: 85 | return (self.solTime(solver, True) >= time) and (self.finalTime(solver) < time) 86 | 87 | def isTimeout(self, solver, time): 88 | if (type(solver) == list): 89 | return all([self.solTime(s, True) >= time for s in solver]) 90 | else: 91 | return (self.solTime(solver, True) >= time) 92 | 93 | 94 | 95 | data=[] 96 | args = parse_args() 97 | 98 | with open(args.file, newline='') as file: 99 | 100 | reader = csv.reader(file, delimiter=',') 101 | 102 | for row in reader: 103 | data.append(Entry(row)) 104 | 105 | def flatten(l): 106 | return [item for sublist in l for item in sublist] 107 | 108 | def count(solver, range): 109 | return len(list(filter(lambda x: x.inRange(solver, range), data))) 110 | 111 | def countImp(solver, time): 112 | return len(list(filter(lambda x: x.isImp(solver, time), data))) 113 | 114 | def countTimeout(solver, time): 115 | return len(list(filter(lambda x: x.isTimeout(solver, time), data))) 116 | 117 | def geomeanSpeedup(solver, range, isPortfolio): 118 | lst = list(map(lambda x: x.portfolioRatio(solver) if isPortfolio else x.ratio(solver), filter(lambda x: x.inRange(solver, range), data))) 119 | if (len(lst) > 0): 120 | return statistics.geometric_mean(lst) 121 | else: 122 | return None 123 | 124 | def averageSpeedup(solver, range, isPortfolio): 125 | lst = list(map(lambda x: x.portfolioRatio(solver) if isPortfolio else x.ratio(solver), filter(lambda x: x.inRange(solver, range), data))) 126 | if (len(lst) > 0): 127 | return statistics.mean(lst) 128 | else: 129 | return None 130 | 131 | def usedCount(passid, solver, tm): 132 | if solver and tm: 133 | return len(list(filter(lambda x: x.usedPass(passid) and x.inRange(solver, tm), data))) 134 | else: 135 | return len(list(filter(lambda x: x.usedPass(passid), data))) 136 | 137 | def geomeanPassSpeedup(solver, passid, tm, isPortfolio): 138 | lst = list(map(lambda x: x.portfolioRatio(solver) if isPortfolio else x.ratio(solver), filter(lambda x: x.usedPass(passid) and x.inRange(solver, tm), data))) 139 | if (len(lst) == 0): 140 | return None 141 | else: 142 | return statistics.geometric_mean(lst) 143 | 144 | def geomeanWithoutPassSpeedup(solver, passid, tm, isPortfolio): 145 | lst = list(map(lambda x: x.portfolioRatio(solver) if isPortfolio else x.ratio(solver), filter(lambda x: (not x.usedPass(passid)) and x.inRange(solver, tm), data))) 146 | if (len(lst) == 0): 147 | return None 148 | else: 149 | return statistics.geometric_mean(lst) 150 | 151 | 152 | 153 | def averagePassSpeedup(solver, passid, tm, isPortfolio): 154 | lst = list(map(lambda x: x.portfolioRatio(solver) if isPortfolio else x.ratio(solver), filter(lambda x: x.usedPass(passid) and x.inRange(solver, tm), data))) 155 | if (len(lst) == 0): 156 | return None 157 | else: 158 | return statistics.mean(lst) 159 | 160 | def slotpost(solver, range): 161 | return statistics.geometric_mean(list(map(lambda x: x.slotTime()/x.finalTime(solver), filter(lambda x: x.inRange(solver, range), data)))) 162 | 163 | def frontaverage(): 164 | return statistics.geometric_mean(list(map(lambda x: x.frontTime()/x.slotTime(), filter(lambda x: (not x.isSlotTimeout()), data)))) 165 | 166 | def optaverage(): 167 | return statistics.geometric_mean(list(map(lambda x: x.optTime()/x.slotTime(), filter(lambda x: (not x.isSlotTimeout()), data)))) 168 | 169 | def backaverage(): 170 | return statistics.geometric_mean(list(map(lambda x: x.backTime()/x.slotTime(), filter(lambda x: (not x.isSlotTimeout()), data)))) 171 | 172 | 173 | 174 | # Specify the Column Names while initializing the Table 175 | 176 | 177 | if ("bv" in args.file) and (not "bvfp" in args.file): 178 | allSolvers = ['z', 'c', 'b'] 179 | else: 180 | allSolvers = ['z', 'c'] 181 | 182 | for s in allSolvers: 183 | print(s) 184 | myTable = PrettyTable(["Interval", "Count", "SLOT-only geomean", "Portfolio geomean"]) 185 | 186 | for r in [(0,30), (30,60), (60,120), (120,300), 300]: 187 | myTable.add_row([str(r), str(count(s, r)), str(round(geomeanSpeedup(s, r, False), 2)), str(round(geomeanSpeedup(s, r, True), 2))]) 188 | 189 | print(myTable) 190 | 191 | 192 | tos = [30, 60, 120, 300, 600] 193 | myTable = PrettyTable([" "] + list(map(lambda x: "sol " + x, allSolvers)) + ["all"]) 194 | for r in [30, 60, 120, 300, 600]: 195 | myTable.add_row([str(r)+" total"] + [str(countTimeout(s, r)) for s in allSolvers] + [str(countTimeout(allSolvers, r))]) 196 | myTable.add_row([str(r)+" imp"] + [str(countImp(s, r)) for s in allSolvers] + [str(countImp(allSolvers, r))]) 197 | myTable.add_row([str(r)+" %"] + [str(round(100*countImp(s, r)/countTimeout(s, r), 2)) for s in allSolvers] + [str(round(100*countImp(allSolvers, r)/countTimeout(allSolvers, r), 2))]) 198 | 199 | print(myTable) 200 | 201 | print("Total: " + str(len(data))) 202 | passes = ["instcombine", "ainstcombine", "reassociate", "sccp", "dce", "adce", "instsimplify", "gvn"] 203 | 204 | 205 | for tm in [0, 30, 300, 600]: 206 | myTable = PrettyTable(["Pass", "Used Count", "%", "speedup with", "speedup without"]) 207 | print(f"In range ({tm}): " + str(count('z', tm))) 208 | n = 0 209 | 210 | 211 | 212 | 213 | for i in range(len(passes)): 214 | myTable.add_row([passes[i], str(usedCount(i, 'z', tm)), str(round(100*usedCount(i, 'z', tm)/count('z', tm), 2)), \ 215 | #str(round(geomeanPassSpeedup('z', i, 0, True), 2) if geomeanPassSpeedup('z', i, 0, True) else '-'), \ 216 | #str(round(geomeanWithoutPassSpeedup('z', i, 0, True), 2) if geomeanWithoutPassSpeedup('z', i, 0, True) else '-'), \ 217 | str(round(geomeanPassSpeedup('z', i, tm, True), 2) if geomeanPassSpeedup('z', i, tm, True) else '-'), \ 218 | str(round(geomeanWithoutPassSpeedup('z', i, tm, True), 2) if geomeanWithoutPassSpeedup('z', i, tm, True) else '-')]) 219 | 220 | print(myTable) 221 | 222 | 223 | for r in [(0,30), (30,60), (60,120), (120,300), 300]: 224 | print(f"{r} : {round(100*slotpost('z', r),2)}") 225 | 226 | 227 | print(frontaverage()) 228 | print(optaverage()) 229 | print(backaverage()) 230 | #print(s + " " + str(r) + " " + str(countTimeout(s, r)) + " " + str(countImp(s, r))) 231 | 232 | #for r in [30, 60, 120, 300, 600]: 233 | # print("all" + " " + str(r) + " " + str(countTimeout(allSolvers, r)) + " " + str(countImp(allSolvers, r))) 234 | 235 | 236 | #bv 237 | #0.5951222387386229 238 | #0.10710224347359946 239 | #0.053089776125046076 240 | 241 | #bvfp 242 | #0.30546484370053445 243 | #0.0704644619075241 244 | #0.5986981787552723 245 | 246 | #fp 247 | #0.34238276547630403 248 | #0.07923041627326863 249 | #0.5732070251353116 250 | 251 | 252 | 253 | 254 | #print(statistics.geometric_mean(list(map(lambda x: x.ratio('z'), filter(lambda x: x.inRange('z', 300), data))))) 255 | 256 | #print(list(filter(lambda x: x.inRange('z', 300), data))) -------------------------------------------------------------------------------- /runthrough.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | Z3=z3 #4.12.1 3 | BOOLECTOR=boolector #3.2.2 4 | CVC5=cvc5 #1.0.5 5 | 6 | usage() { 7 | echo "Usage: $0 [-r] [-z] [-c] [-b] [-f ]" 1>&2 8 | echo " -r : Remove all produced files" 9 | echo " -z : Use Z3 solver" 10 | echo " -c : Use CVC5 solver" 11 | echo " -b : Use Boolector solver" 12 | echo " -t : Timeout (seconds)" 13 | echo " -f : .smt2 file to process" 14 | exit 15 | } 16 | 17 | FILE="" 18 | STATS="slot-stats.csv" 19 | CLEANUP=false 20 | USE_Z3=false 21 | USE_CV=false 22 | USE_BL=false 23 | 24 | while getopts "hrzcbt:f:" arg; do 25 | case $arg in 26 | h) 27 | usage 28 | ;; 29 | r) 30 | CLEANUP=true 31 | ;; 32 | z) 33 | USE_Z3=true 34 | ;; 35 | c) 36 | USE_CV=true 37 | ;; 38 | b) 39 | USE_BL=true 40 | ;; 41 | t) 42 | SMT_TIMEOUT=${OPTARG} 43 | SLOT_TIMEOUT=${OPTARG} 44 | ;; 45 | f) 46 | FILE=${OPTARG} 47 | ;; 48 | esac 49 | done 50 | 51 | #echo "$FILE" 52 | NAME="${FILE%.*}" 53 | 54 | SLOT_GOOD=true 55 | 56 | #Check for timeout of SLOT 57 | SLOT_OUT=$( { /usr/bin/time -f "tmr%e" timeout $SLOT_TIMEOUT ./main -m -pall -s $FILE -o $NAME-opt.smt2 -t $STATS; } 2>&1 > /dev/null ) 58 | if [[ $? == 124 ]] 59 | then 60 | SLOT_GOOD=false 61 | echo "$FILE,Timeout" >> $STATS 62 | fi 63 | 64 | 65 | #Check for unsupported floating point files 66 | 67 | 68 | #Encountered unsupported SMT type (Floating point type 69 | #Encountered unsupported SMT operation (floating point rounding mode) 70 | 71 | 72 | if [[ "$SLOT_OUT" == *"Encountered unsupported SMT type (floating point type"* ]] 73 | then 74 | echo "$FILE,UnsupportedFPType" 75 | exit 76 | fi 77 | 78 | if [[ "$SLOT_OUT" == *"Encountered unsupported SMT operation (floating point rounding mode)"* ]] 79 | then 80 | echo "$FILE,UnsupportedRoundingMode" 81 | exit 82 | fi 83 | 84 | 85 | 86 | #Z3---------------- 87 | if $USE_Z3 88 | then 89 | PRE_SOL_OUT=$( { /usr/bin/time -f "tmr%e" $Z3 $FILE -T:$SMT_TIMEOUT; } 2>&1 ) 90 | if [[ "$PRE_SOL_OUT" == "timeout" ]] 91 | then 92 | Z3_PRE_TIME=$SMT_TIMEOUT 93 | Z3_PRE_RESULT="timeout" 94 | else 95 | Z3_PRE_TIME=$(echo "$PRE_SOL_OUT" | grep -Po 'tmr*.*' | tr -dc '.0-9') 96 | Z3_PRE_RESULT=$(echo $PRE_SOL_OUT | awk '{print $1;}') 97 | fi 98 | 99 | if $SLOT_GOOD 100 | then 101 | POST_SOL_OUT=$( { /usr/bin/time -f "tmr%e" $Z3 $NAME-opt.smt2 -T:$SMT_TIMEOUT; } 2>&1 ) 102 | if [[ "$POST_SOL_OUT" == "timeout" ]] 103 | then 104 | Z3_POST_TIME=$SMT_TIMEOUT 105 | Z3_POST_RESULT="timeout" 106 | else 107 | Z3_POST_TIME=$(echo "$POST_SOL_OUT" | grep -Po 'tmr*.*' | tr -dc '.0-9') 108 | Z3_POST_RESULT=$(echo $POST_SOL_OUT | awk '{print $1;}') 109 | fi 110 | fi 111 | fi 112 | 113 | 114 | #------------------ 115 | 116 | 117 | #CVC5---------------- 118 | if $USE_CV 119 | then 120 | PRE_SOL_OUT=$( { /usr/bin/time -f "tmr%e" $CVC5 $FILE -q --tlimit=$(( 1000 * SMT_TIMEOUT )); } 2>&1 ) 121 | if [[ "$PRE_SOL_OUT" == *"timeout"* ]] 122 | then 123 | CV_PRE_TIME=$SMT_TIMEOUT 124 | CV_PRE_RESULT="timeout" 125 | else 126 | CV_PRE_TIME=$(echo "$PRE_SOL_OUT" | grep -Po 'tmr*.*' | tr -dc '.0-9') 127 | CV_PRE_RESULT=$(echo $PRE_SOL_OUT | awk '{print $1;}') 128 | fi 129 | 130 | if $SLOT_GOOD 131 | then 132 | POST_SOL_OUT=$( { /usr/bin/time -f "tmr%e" $CVC5 $NAME-opt.smt2 -q --tlimit=$(( 1000 * SMT_TIMEOUT )); } 2>&1 ) 133 | if [[ "$POST_SOL_OUT" == *"timeout"* ]] 134 | then 135 | CV_POST_TIME=$SMT_TIMEOUT 136 | CV_POST_RESULT="timeout" 137 | else 138 | CV_POST_TIME=$(echo "$POST_SOL_OUT" | grep -Po 'tmr*.*' | tr -dc '.0-9') 139 | CV_POST_RESULT=$(echo $POST_SOL_OUT | awk '{print $1;}') 140 | fi 141 | fi 142 | fi 143 | #------------------ 144 | 145 | 146 | #BOOLECTOR---------------- 147 | if $USE_BL 148 | then 149 | PRE_SOL_OUT=$( { /usr/bin/time -f "tmr%e" $BOOLECTOR $FILE -t $SMT_TIMEOUT; } 2>&1 ) 150 | if [[ "$PRE_SOL_OUT" == *"unknown"* ]] 151 | then 152 | BL_PRE_TIME=$SMT_TIMEOUT 153 | BL_PRE_RESULT="timeout" 154 | else 155 | BL_PRE_TIME=$(echo "$PRE_SOL_OUT" | grep -Po 'tmr*.*' | tr -dc '.0-9') 156 | BL_PRE_RESULT=$(echo $PRE_SOL_OUT | awk '{print $1;}') 157 | fi 158 | 159 | if $SLOT_GOOD 160 | then 161 | POST_SOL_OUT=$( { /usr/bin/time -f "tmr%e" $BOOLECTOR $NAME-opt.smt2 -t $SMT_TIMEOUT; } 2>&1 ) 162 | if [[ "$POST_SOL_OUT" == *"unknown"* ]] 163 | then 164 | BL_POST_TIME=$SMT_TIMEOUT 165 | BL_POST_RESULT="timeout" 166 | else 167 | BL_POST_TIME=$(echo "$POST_SOL_OUT" | grep -Po 'tmr*.*' | tr -dc '.0-9') 168 | BL_POST_RESULT=$(echo $POST_SOL_OUT | awk '{print $1;}') 169 | fi 170 | fi 171 | fi 172 | #------------------ 173 | 174 | echo "$FILE,$Z3_PRE_RESULT,$Z3_PRE_TIME,$Z3_POST_RESULT,$Z3_POST_TIME,$CV_PRE_RESULT,$CV_PRE_TIME,$CV_POST_RESULT,$CV_POST_TIME,$BL_PRE_RESULT,$BL_PRE_TIME,$BL_POST_RESULT,$BL_POST_TIME" 175 | 176 | if $CLEANUP 177 | then 178 | rm $NAME-opt.smt2 179 | fi 180 | 181 | 182 | 183 | -------------------------------------------------------------------------------- /samples/multiplyOverflow.smt2: -------------------------------------------------------------------------------- 1 | (set-info :smt-lib-version 2.6) 2 | ;; This can arise from program analysis of programs checking for 3 | ;; integer overflow with constructs like: 4 | ;; void *calloc(size_t a, size_t b) 5 | ;; { 6 | ;; if( ((size_t)-1) / a < b ){ errno = ENOMEM; return NULL; } 7 | ;; return memset(malloc(a*b), 0, a*b); 8 | ;; } 9 | 10 | ;; The answer is unsat. 11 | 12 | (set-logic QF_BV) 13 | (set-info :source |GrammaTech|) 14 | (set-info :category "industrial") 15 | (set-info :status unsat) 16 | (declare-fun a () (_ BitVec 32)) 17 | (declare-fun b () (_ BitVec 32)) 18 | (assert (not (= 19 | ((_ extract 63 32) 20 | (bvmul ((_ zero_extend 32) a) 21 | ((_ zero_extend 32) b))) 22 | #x00000000))) 23 | (assert (bvuge (bvudiv #xffffffff a) b)) 24 | (check-sat) 25 | (exit) 26 | 27 | -------------------------------------------------------------------------------- /slot.dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:20.04 2 | ENV DEBIAN_FRONTEND noninteractive 3 | 4 | RUN apt update 5 | RUN apt install -y git gcc g++ cmake ninja-build python3 zlib1g-dev libtinfo-dev libxml2-dev vim 6 | 7 | WORKDIR /root 8 | RUN git clone https://github.com/llvm/llvm-project 9 | WORKDIR /root/llvm-project 10 | RUN git checkout llvmorg-16.0.0 11 | RUN cmake -S llvm -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug 12 | RUN ninja -j 4 -C build 13 | #Because of docker limitations, Ninja build of LLVM may be memory constrained 14 | #Number of threads can be increased if there is excess memory 15 | 16 | WORKDIR /root 17 | RUN git clone https://github.com/Z3Prover/z3 18 | WORKDIR /root/z3 19 | RUN git checkout z3-4.12.1 20 | RUN python3 scripts/mk_make.py 21 | WORKDIR /root/z3/build 22 | RUN make 23 | RUN make install 24 | 25 | WORKDIR /root 26 | COPY src ./src 27 | WORKDIR /root/src 28 | RUN make 29 | RUN cp slot ../slot 30 | WORKDIR /root 31 | 32 | COPY samples ./samples 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /src/LLVMFunction.cpp: -------------------------------------------------------------------------------- 1 | #include "LLVMNode.h" 2 | #include "SLOTExceptions.h" 3 | #include 4 | 5 | #ifndef LLMAPPING 6 | #define LLMAPPING std::map 7 | #endif 8 | 9 | namespace SLOT 10 | { 11 | 12 | LLVMFunction::LLVMFunction(bool t_shiftToMultiply, context& t_scx, Function* t_contents) : shiftToMultiply(t_shiftToMultiply), scx(t_scx), contents(t_contents), extraVariables(t_scx) 13 | { 14 | scx.set_rounding_mode(RNE); 15 | for (Argument* arg = contents->arg_begin(); arg < contents->arg_end(); arg++) 16 | { 17 | if (arg->getType()->isIntegerTy()) 18 | { 19 | //1-wide integer --> boolean 20 | if (arg->getType()->getIntegerBitWidth() == 1) 21 | { 22 | variables.insert(make_pair(arg->getName().str(), scx.bool_const(arg->getName().str().c_str()))); 23 | } 24 | else 25 | { 26 | //Regular bitvector case 27 | variables.insert(make_pair(arg->getName().str(), scx.bv_const(arg->getName().str().c_str(),arg->getType()->getIntegerBitWidth()))); 28 | } 29 | } 30 | else if (arg->getType()->isHalfTy()) 31 | { 32 | variables.insert(make_pair(arg->getName().str(), scx.fpa_const(arg->getName().str().c_str(), 5, 11))); 33 | } 34 | else if (arg->getType()->isFloatTy()) 35 | { 36 | variables.insert(make_pair(arg->getName().str(), scx.fpa_const(arg->getName().str().c_str(), 8, 24))); 37 | } 38 | else if (arg->getType()->isDoubleTy()) 39 | { 40 | variables.insert(make_pair(arg->getName().str(), scx.fpa_const(arg->getName().str().c_str(), 11, 53))); 41 | } 42 | else if (arg->getType()->isFP128Ty()) 43 | { 44 | variables.insert(make_pair(arg->getName().str(), scx.fpa_const(arg->getName().str().c_str(), 15, 113))); 45 | } 46 | else 47 | { 48 | std::string type_str; 49 | llvm::raw_string_ostream rso(type_str); 50 | arg->print(rso); 51 | throw UnsupportedTypeException("unsupported LLVM variable type", rso.str()); 52 | } 53 | } 54 | } 55 | 56 | //For fp to bv bitcast, create a new variable and constraint it equal at the top level 57 | expr LLVMFunction::AddBCVariable(std::unique_ptr contents) 58 | { 59 | std::string name = "_slot_smtbc_" + std::to_string(LLVMFunction::varCounter) + "_"; 60 | expr var = scx.bv_const(name.c_str(), contents->Width()); 61 | variables.insert(make_pair(name, var)); 62 | expr added = (var.mk_from_ieee_bv(contents->SMTSort()) == contents->ToSMT()); 63 | extraVariables = (LLVMFunction::varCounter == 0) ? added : (extraVariables && added); 64 | LLVMFunction::varCounter++; 65 | return var; 66 | } 67 | 68 | expr LLVMFunction::ToSMT() 69 | { 70 | expr fromChildren = LLVMNode::MakeLLVMNode(shiftToMultiply, scx, *this, ((ReturnInst *)contents->getEntryBlock().getTerminator())->getOperand(0))->ToSMT(); 71 | return (LLVMFunction::varCounter == 0) ? fromChildren : (extraVariables && fromChildren); 72 | } 73 | } -------------------------------------------------------------------------------- /src/LLVMNode.cpp: -------------------------------------------------------------------------------- 1 | #include "LLVMNode.h" 2 | #include "SLOTExceptions.h" 3 | 4 | // Does not support any constants whose string expression 5 | // (base 10) is more than CONSTANT_STRING_MAX_WIDTH 6 | #define CONSTANT_STRING_MAX_WIDTH 2048 7 | 8 | #ifndef SMTMAPPING 9 | #define SMTMAPPING std::map 10 | #endif 11 | 12 | #ifndef LLVM_FUNCTION_NAME 13 | #define LLVM_FUNCTION_NAME "SMT" 14 | #endif 15 | 16 | 17 | namespace SLOT 18 | { 19 | LLVMNode::LLVMNode(bool t_shiftToMultiply, context& t_scx, LLVMFunction& t_function, Value* t_contents) : shiftToMultiply(t_shiftToMultiply), scx(t_scx), function(t_function), contents(t_contents) 20 | { 21 | 22 | } 23 | 24 | 25 | std::unique_ptr LLVMNode::MakeLLVMNode(bool shiftToMultiply, context& scx, LLVMFunction& function, Value *contents) 26 | { 27 | if (isa(contents)) 28 | { 29 | return std::make_unique(shiftToMultiply, scx, function, contents); 30 | } 31 | else if (isa(contents)) 32 | { 33 | return std::make_unique(shiftToMultiply, scx, function, contents); 34 | } 35 | else if (isa(contents)) 36 | { 37 | Instruction* uv = ((Instruction*)contents); 38 | if (uv->getOpcode()==Instruction::Call) 39 | { 40 | return std::make_unique(shiftToMultiply, scx, function, contents); 41 | } 42 | else if (uv->getOpcode()==Instruction::ICmp) 43 | { 44 | return std::make_unique(shiftToMultiply, scx, function, contents); 45 | } 46 | else if (uv->getOpcode()==Instruction::FCmp) 47 | { 48 | return std::make_unique(shiftToMultiply, scx, function, contents); 49 | } 50 | else 51 | { 52 | return std::make_unique(shiftToMultiply, scx, function, contents); 53 | } 54 | } 55 | else 56 | { 57 | throw UnsupportedLLVMOpException("node construction on non-instruction, argument, or constant", contents); 58 | } 59 | } 60 | 61 | z3::sort LLVMNode::SMTSort() 62 | { 63 | if (contents->getType()->isHalfTy()) 64 | { 65 | return scx.fpa_sort(5,11); 66 | } 67 | else if (contents->getType()->isFloatTy()) 68 | { 69 | return scx.fpa_sort(8,24); 70 | } 71 | else if (contents->getType()->isDoubleTy()) 72 | { 73 | return scx.fpa_sort(11,53); 74 | } 75 | else if (contents->getType()->isFP128Ty()) 76 | { 77 | return scx.fpa_sort(15,113); 78 | } 79 | else if (contents->getType()->isIntegerTy()) 80 | { 81 | //1-bit integers are booleans 82 | if (contents->getType()->getIntegerBitWidth()==1) 83 | { 84 | return scx.bool_sort(); 85 | } 86 | else 87 | { 88 | return scx.bv_sort(contents->getType()->getIntegerBitWidth()); 89 | } 90 | } 91 | else 92 | { 93 | std::string type_str; 94 | llvm::raw_string_ostream rso(type_str); 95 | contents->print(rso); 96 | throw UnsupportedTypeException("unsupported LLVM type", rso.str()); 97 | } 98 | } 99 | 100 | unsigned LLVMNode::Width() 101 | { 102 | if (SMTSort().is_bool()) 103 | { 104 | return 1; 105 | } 106 | else if (SMTSort().is_bv()) 107 | { 108 | return SMTSort().bv_size(); 109 | } 110 | else //FPA case 111 | { 112 | return SMTSort().fpa_sbits() + SMTSort().fpa_ebits(); 113 | } 114 | } 115 | 116 | 117 | //============================LLVMArgument================================== 118 | 119 | 120 | LLVMArgument::LLVMArgument(bool t_shiftToMultiply, context& t_scx, LLVMFunction& t_function, Value* t_contents) : LLVMNode(t_shiftToMultiply, t_scx, t_function, t_contents) 121 | { 122 | assert(isa(contents)); 123 | } 124 | 125 | expr LLVMArgument::ToSMT() 126 | { 127 | return function.variables.at(contents->getName().str()); 128 | } 129 | 130 | 131 | //============================LLVMConstant================================== 132 | 133 | 134 | LLVMConstant::LLVMConstant(bool t_shiftToMultiply, context& t_scx, LLVMFunction& t_function, Value* t_contents) : LLVMNode(t_shiftToMultiply, t_scx, t_function, t_contents) 135 | { 136 | assert(isa(contents)); 137 | } 138 | 139 | expr LLVMConstant::ToSMT() 140 | { 141 | if (SMTSort().is_bool()) 142 | { 143 | return scx.bool_val(((Constant*)contents)->isOneValue()); 144 | } 145 | else if (SMTSort().is_bv()) 146 | { 147 | SmallString str; 148 | ((Constant*)contents)->getUniqueInteger().toString(str,10,false); 149 | return scx.bv_val(str.c_str(), Width()); 150 | } 151 | else //FPA case 152 | { 153 | //bitcastToAPInt 154 | SmallString str; 155 | ((ConstantFP *)contents)->getValue().bitcastToAPInt().toString(str, 10, false); 156 | return scx.bv_val(str.c_str(), Width()).mk_from_ieee_bv(SMTSort()); 157 | } 158 | } 159 | 160 | //============================LLVMIntrinsicCall================================== 161 | LLVMIntrinsicCall::LLVMIntrinsicCall(bool t_shiftToMultiply, context& t_scx, LLVMFunction& t_function, Value* t_contents) : LLVMExpression(t_shiftToMultiply, t_scx, t_function, t_contents) 162 | { 163 | assert(Opcode() == Instruction::Call); 164 | } 165 | 166 | expr LLVMIntrinsicCall::FPClassCheck(context& scx, expr val, int64_t bits) 167 | { 168 | switch(bits) 169 | { 170 | case 3: 171 | return val.mk_is_nan(); 172 | case 516: 173 | return val.mk_is_inf(); 174 | case 96: 175 | return val.mk_is_zero(); 176 | case 264: 177 | return val.mk_is_normal(); 178 | case 144: 179 | return val.mk_is_subnormal(); 180 | case 60: 181 | return expr(scx,Z3_mk_fpa_is_negative(scx, val)); 182 | case 960: 183 | return expr(scx,Z3_mk_fpa_is_positive(scx, val)); 184 | case 504: 185 | return (!val.mk_is_nan()) && (!val.mk_is_inf()); 186 | case 507: 187 | return !val.mk_is_inf(); 188 | case 759: 189 | return !val.mk_is_normal(); 190 | case 519: 191 | return val.mk_is_nan() || val.mk_is_inf(); 192 | case 256: 193 | return val.mk_is_normal() && expr(scx,Z3_mk_fpa_is_positive(scx, val)); 194 | case 448: 195 | return expr(scx,Z3_mk_fpa_is_positive(scx, val)) && (!val.mk_is_inf()); 196 | case 879: 197 | return !val.mk_is_subnormal(); 198 | case 360: 199 | return val.mk_is_zero() || val.mk_is_normal(); 200 | default: 201 | throw UnsupportedSMTOpException("unsupported floating point class check flag bitmask " + std::to_string(bits), val); 202 | } 203 | } 204 | 205 | expr LLVMIntrinsicCall::AsRoundingMode(unsigned n) 206 | { 207 | std::string mst; 208 | llvm::raw_string_ostream rso(mst); 209 | AsInstruction()->getOperand(n)->print(rso); 210 | if (rso.str()=="!\"round.tonearest\"") 211 | { 212 | return expr(scx, Z3_mk_fpa_rne(scx)); 213 | } 214 | else if (rso.str()=="!\"round.downward\"") 215 | { 216 | return expr(scx, Z3_mk_fpa_rtn(scx)); 217 | } 218 | else if (rso.str()=="!\"round.upward\"") 219 | { 220 | return expr(scx, Z3_mk_fpa_rtp(scx)); 221 | } 222 | else if (rso.str()=="!\"round.towardzero\"") 223 | { 224 | return expr(scx, Z3_mk_fpa_rtz(scx)); 225 | } 226 | else if (rso.str()=="!\"round.tonearestaway\"") 227 | { 228 | return expr(scx, Z3_mk_fpa_rna(scx)); 229 | } 230 | else 231 | { 232 | throw UnsupportedLLVMOpException("unsupported constrained rounding mode", contents); 233 | } 234 | } 235 | 236 | expr LLVMIntrinsicCall::ToSMT() 237 | { 238 | Intrinsic::ID id = ((CallInst*)contents)->getCalledFunction()->getIntrinsicID(); 239 | //Intrinsics which are reasonable in the integer context 240 | expr arg(scx); 241 | expr left(scx); 242 | expr right(scx); 243 | expr temp(scx); 244 | expr_vector v(scx); 245 | int bits; 246 | switch (id) 247 | { 248 | case Intrinsic::is_fpclass: 249 | bits = ((ConstantInt*)(AsInstruction()->getOperand(1)))->getSExtValue(); 250 | return LLVMIntrinsicCall::FPClassCheck(scx, Child(0)->ToSMT(), bits); 251 | /*case Intrinsic::round: 252 | return z3::round_fpa_to_closest_integer(Child(0)->ToSMT());*/ 253 | case Intrinsic::abs: 254 | arg = Child(0)->ToSMT(); 255 | return ite(arg < Zero(), -arg, arg); 256 | case Intrinsic::smin: 257 | left = Child(0)->ToSMT(); 258 | right = Child(1)->ToSMT(); 259 | return ite(left <= right,left,right); 260 | case Intrinsic::smax: 261 | left = Child(0)->ToSMT(); 262 | right = Child(1)->ToSMT(); 263 | return ite(left <= right,right,left); 264 | case Intrinsic::fabs: 265 | return z3::abs(Child(0)->ToSMT()); 266 | case Intrinsic::fma: 267 | return z3::fma(Child(0)->ToSMT(),Child(1)->ToSMT(),Child(2)->ToSMT(), scx.fpa_rounding_mode()); 268 | case Intrinsic::sqrt: 269 | return z3::sqrt(Child(0)->ToSMT(), scx.fpa_rounding_mode()); 270 | case Intrinsic::minnum: 271 | return min(Child(0)->ToSMT(),Child(1)->ToSMT()); 272 | case Intrinsic::maxnum: 273 | return max(Child(0)->ToSMT(),Child(1)->ToSMT()); 274 | case Intrinsic::bswap: 275 | //Reverse the order of bytes 276 | arg = Child(0)->ToSMT(); 277 | v = expr_vector(scx); 278 | for (int i = (Width()/8)-1; i>=0; i--) 279 | { 280 | v.push_back(arg.extract(Width()-(8*i)-1, Width()-(8*(i+1)))); 281 | } 282 | return concat(v); 283 | case Intrinsic::ctpop: 284 | //Count the number of 1 bits 285 | arg = Child(0)->ToSMT(); 286 | temp = zext(arg.extract(0,0), Width()-1); 287 | for (int i = 1; iToSMT(); 295 | v = expr_vector(scx); 296 | for (int i = Width()-1; i>=0; i++) 297 | { 298 | v.push_back(arg.extract(i,i)); 299 | } 300 | return concat(v); 301 | case Intrinsic::fshl: 302 | //Funnel shift 303 | return shl(concat(Child(0)->ToSMT(), Child(1)->ToSMT()), zext(Child(2)->ToSMT(), Width())).extract((Width() * 2) - 1, Width()); 304 | case Intrinsic::fshr: 305 | //Funnel shift 306 | return lshr(concat(Child(0)->ToSMT(),Child(1)->ToSMT()),Child(2)->ToSMT()).extract(Width()-1,0); 307 | case Intrinsic::usub_sat: 308 | //Subtraction without underflow (clamped to 0) 309 | left = Child(0)->ToSMT(); 310 | right = Child(1)->ToSMT(); 311 | return ite(ule(left, right), Zero(), left - right); 312 | case Intrinsic::uadd_sat: 313 | //Addition without overflow (clamped to max, i.e. -1) 314 | left = Child(0)->ToSMT(); 315 | right = Child(1)->ToSMT(); 316 | return ite(ule(left + right, left), scx.bv_val(-1, Width()), left + right); 317 | case Intrinsic::umin: 318 | left = Child(0)->ToSMT(); 319 | right = Child(1)->ToSMT(); 320 | return ite(ule(left, right), left, right); 321 | case Intrinsic::umax: 322 | left = Child(0)->ToSMT(); 323 | right = Child(1)->ToSMT(); 324 | return ite(ule(left,right),right,left); 325 | case Intrinsic::roundeven: 326 | return expr(scx, Z3_mk_fpa_round_to_integral(scx, expr(scx, Z3_mk_fpa_rne(scx)), Child(0)->ToSMT())); 327 | case Intrinsic::lround: 328 | return expr(scx, Z3_mk_fpa_round_to_integral(scx, expr(scx, Z3_mk_fpa_rna(scx)), Child(0)->ToSMT())); 329 | case Intrinsic::ceil: 330 | return expr(scx, Z3_mk_fpa_round_to_integral(scx, expr(scx, Z3_mk_fpa_rtp(scx)), Child(0)->ToSMT())); 331 | case Intrinsic::floor: 332 | return expr(scx, Z3_mk_fpa_round_to_integral(scx, expr(scx, Z3_mk_fpa_rtn(scx)), Child(0)->ToSMT())); 333 | case Intrinsic::trunc: 334 | return expr(scx, Z3_mk_fpa_round_to_integral(scx, expr(scx, Z3_mk_fpa_rtz(scx)), Child(0)->ToSMT())); 335 | case Intrinsic::experimental_constrained_uitofp: 336 | return expr(scx, Z3_mk_fpa_to_fp_unsigned(scx, AsRoundingMode(1), Child(0)->ToSMT(), SMTSort())); 337 | case Intrinsic::experimental_constrained_sitofp: 338 | return expr(scx, Z3_mk_fpa_to_fp_signed(scx, AsRoundingMode(1), Child(0)->ToSMT(), SMTSort())); 339 | case Intrinsic::experimental_constrained_fpext: 340 | case Intrinsic::experimental_constrained_fptrunc: 341 | return expr(scx, Z3_mk_fpa_to_fp_float(scx, AsRoundingMode(1), Child(0)->ToSMT(), SMTSort())); 342 | case Intrinsic::experimental_constrained_fadd: 343 | return expr(scx,Z3_mk_fpa_add(scx, AsRoundingMode(2), Child(0)->ToSMT(), Child(1)->ToSMT())); 344 | case Intrinsic::experimental_constrained_fsub: 345 | return expr(scx,Z3_mk_fpa_sub(scx, AsRoundingMode(2), Child(0)->ToSMT(), Child(1)->ToSMT())); 346 | case Intrinsic::experimental_constrained_fmul: 347 | return expr(scx,Z3_mk_fpa_mul(scx, AsRoundingMode(2), Child(0)->ToSMT(), Child(1)->ToSMT())); 348 | case Intrinsic::experimental_constrained_fdiv: 349 | return expr(scx,Z3_mk_fpa_div(scx, AsRoundingMode(2), Child(0)->ToSMT(), Child(1)->ToSMT())); 350 | case Intrinsic::experimental_constrained_fma: 351 | return expr(scx,Z3_mk_fpa_fma(scx, AsRoundingMode(3), Child(0)->ToSMT(), Child(1)->ToSMT(), Child(2)->ToSMT())); 352 | case Intrinsic::experimental_constrained_sqrt: 353 | return expr(scx, Z3_mk_fpa_sqrt(scx, AsRoundingMode(1), Child(0)->ToSMT())); 354 | default: 355 | throw UnsupportedLLVMOpException("unsupported intrinsic function", contents); 356 | } 357 | } 358 | 359 | 360 | //============================LLVMIcmp================================== 361 | LLVMIcmp::LLVMIcmp(bool t_shiftToMultiply, context& t_scx, LLVMFunction& t_function, Value* t_contents) : LLVMExpression(t_shiftToMultiply, t_scx, t_function, t_contents) 362 | { 363 | assert(Opcode() == Instruction::ICmp); 364 | } 365 | 366 | expr LLVMIcmp::ToSMT() 367 | { 368 | ICmpInst* vi = ((ICmpInst*)contents); 369 | 370 | //Operator overloads for EQ and NE work for both booleans and integers 371 | if (Predicate()==CmpInst::ICMP_EQ) 372 | { 373 | //This arose from a floating point = comparison. Important since there is no floating point to bitvector bitcast in SMT 374 | if (isa(vi->getOperand(0)) && isa(vi->getOperand(1))) 375 | { 376 | return std::unique_ptr{static_cast(Child(0).release())}->Child(0)->ToSMT() == std::unique_ptr{static_cast(Child(1).release())}->Child(0)->ToSMT(); 377 | } 378 | else if (isa(vi->getOperand(0))) 379 | { 380 | expr left = std::unique_ptr{static_cast(Child(0).release())}->Child(0)->ToSMT(); 381 | expr right = Child(1)->ToSMT().mk_from_ieee_bv(left.get_sort()); 382 | return left == right; 383 | } 384 | else if (isa(vi->getOperand(1))) 385 | { 386 | //Reverse order so we can do right.get_sort() 387 | expr right = std::unique_ptr{static_cast(Child(1).release())}->Child(0)->ToSMT(); 388 | expr left = Child(0)->ToSMT().mk_from_ieee_bv(right.get_sort()); 389 | return left == right; 390 | } 391 | else 392 | { 393 | //Regular case 394 | return Child(0)->ToSMT() == Child(1)->ToSMT(); 395 | } 396 | } 397 | else if (vi->getPredicate()==CmpInst::ICMP_NE) 398 | { 399 | //This arose from a floating point distinct comparison. Important since there is no floating point to bitvector bitcast in SMT 400 | if (isa(vi->getOperand(0)) && isa(vi->getOperand(1))) 401 | { 402 | return std::unique_ptr{static_cast(Child(0).release())}->Child(0)->ToSMT() != std::unique_ptr{static_cast(Child(1).release())}->Child(0)->ToSMT(); 403 | } 404 | else if (isa(vi->getOperand(0))) 405 | { 406 | expr left = std::unique_ptr{static_cast(Child(0).release())}->Child(0)->ToSMT(); 407 | expr right = Child(1)->ToSMT().mk_from_ieee_bv(left.get_sort()); 408 | return left != right; 409 | } 410 | else if (isa(vi->getOperand(1))) 411 | { 412 | //Reverse order so we can do right.get_sort() 413 | expr right = std::unique_ptr{static_cast(Child(1).release())}->Child(0)->ToSMT(); 414 | expr left = Child(0)->ToSMT().mk_from_ieee_bv(right.get_sort()); 415 | return left != right; 416 | } 417 | else 418 | { 419 | //Regular case 420 | return Child(0)->ToSMT() != Child(1)->ToSMT(); 421 | } 422 | } 423 | else 424 | { 425 | //Can evaluate the children regularly 426 | expr left = Child(0)->ToSMT(); 427 | expr right = Child(1)->ToSMT(); 428 | //std::cout << left.to_string(); 429 | //std::cout << right.to_string(); 430 | switch (Predicate()) 431 | { 432 | case CmpInst::ICMP_SGT: 433 | return left > right; 434 | case CmpInst::ICMP_SGE: 435 | return left >= right; 436 | case CmpInst::ICMP_SLT: 437 | return left < right; 438 | case CmpInst::ICMP_SLE: 439 | return left <= right; 440 | case CmpInst::ICMP_UGT: 441 | return ugt(left,right); 442 | case CmpInst::ICMP_UGE: 443 | return uge(left,right); 444 | case CmpInst::ICMP_ULT: 445 | return ult(left,right); 446 | case CmpInst::ICMP_ULE: 447 | return ule(left,right); 448 | default: 449 | throw UnsupportedLLVMOpException("unsupported ICMP predicate", contents); 450 | } 451 | } 452 | } 453 | 454 | 455 | 456 | //============================LLVMFcmp================================== 457 | LLVMFcmp::LLVMFcmp(bool t_shiftToMultiply, context& t_scx, LLVMFunction& t_function, Value* t_contents) : LLVMExpression(t_shiftToMultiply, t_scx, t_function, t_contents) 458 | { 459 | assert(Opcode() == Instruction::FCmp); 460 | } 461 | 462 | expr LLVMFcmp::ToSMT() 463 | { 464 | expr left = Child(0)->ToSMT(); 465 | expr right = Child(1)->ToSMT(); 466 | switch (Predicate()) 467 | { 468 | case CmpInst::FCMP_FALSE: 469 | return scx.bool_val(false); 470 | //Ordered (not both NaN, matches SMT semantics) 471 | case CmpInst::FCMP_OEQ: 472 | return fp_eq(left, right); 473 | case CmpInst::FCMP_OGT: 474 | return left > right; 475 | case CmpInst::FCMP_OGE: 476 | return left >= right; 477 | case CmpInst::FCMP_OLT: 478 | return left < right; 479 | case CmpInst::FCMP_OLE: 480 | return left <= right; 481 | case CmpInst::FCMP_ONE: 482 | return (!left.mk_is_nan()) && (!right.mk_is_nan()) && (!fp_eq(left,right)); 483 | case CmpInst::FCMP_ORD: 484 | return (!left.mk_is_nan()) && (!right.mk_is_nan()); 485 | //Unordered (either is NaN or the comparison) 486 | case CmpInst::FCMP_UEQ: 487 | return left.mk_is_nan() || right.mk_is_nan() || fp_eq(left,right); 488 | case CmpInst::FCMP_UGT: 489 | return left.mk_is_nan() || right.mk_is_nan() || (left > right); 490 | case CmpInst::FCMP_UGE: 491 | return left.mk_is_nan() || right.mk_is_nan() || (left >= right); 492 | case CmpInst::FCMP_ULT: 493 | return left.mk_is_nan() || right.mk_is_nan() || (left < right); 494 | case CmpInst::FCMP_ULE: 495 | return left.mk_is_nan() || right.mk_is_nan() || (left <= right); 496 | case CmpInst::FCMP_UNE: 497 | return left.mk_is_nan() || right.mk_is_nan() || (!fp_eq(left, right)); 498 | case CmpInst::FCMP_UNO: 499 | return left.mk_is_nan() || right.mk_is_nan(); 500 | case CmpInst::FCMP_TRUE: 501 | return scx.bool_val(true); 502 | default: 503 | throw UnsupportedLLVMOpException("unsupported FCMP predicate", contents); 504 | } 505 | } 506 | 507 | 508 | 509 | //============================LLVMExpression================================== 510 | 511 | LLVMExpression::LLVMExpression(bool t_shiftToMultiply, context& t_scx, LLVMFunction& t_function, Value* t_contents) : LLVMNode(t_shiftToMultiply, t_scx, t_function, t_contents) 512 | { 513 | assert(isa(contents)); 514 | } 515 | 516 | expr LLVMExpression::ToSMT() 517 | { 518 | //uv = AsInstruction() 519 | Value* child; 520 | expr arg(scx); 521 | expr left(scx); 522 | expr right(scx); 523 | int rr; 524 | switch (Opcode()) // Instructions 525 | { 526 | //Special case: umul.with.overflow followed by extract value 527 | case Instruction::ExtractValue: 528 | child = ((Instruction *)contents)->getOperand(0); 529 | if (isa(child) && ((CallInst*)child)->getCalledFunction()->getIntrinsicID()==Intrinsic::umul_with_overflow) 530 | { 531 | expr left = std::unique_ptr{static_cast(Child(0).release())}->Child(0)->ToSMT(); 532 | expr right = std::unique_ptr{static_cast(Child(0).release())}->Child(1)->ToSMT(); 533 | expr zero = scx.bv_val(0,left.get_sort().bv_size()); //Not the same as Zero() 534 | return ite(((left == zero) || (right == zero)),scx.bool_val(false),!(udiv((left*right),left)==right)); 535 | } 536 | else 537 | { 538 | throw UnsupportedLLVMOpException("extract value without umul.with.overflow", contents); 539 | } 540 | case Instruction::FNeg: 541 | //Z3 api redefines operators 542 | return -Child(0)->ToSMT(); 543 | case Instruction::FPToUI: 544 | child = ((Instruction *)contents)->getOperand(0); 545 | //Convert sequences of round, fptoui into to_ubv with correct rounding mode 546 | if (isa(child)) 547 | { 548 | switch(((CallInst*)child)->getCalledFunction()->getIntrinsicID()) 549 | { 550 | case Intrinsic::roundeven: 551 | return expr(scx,Z3_mk_fpa_to_ubv(scx, expr(scx, Z3_mk_fpa_rne(scx)), Child(0)->ToSMT(), Width())); 552 | case Intrinsic::lround: 553 | return expr(scx,Z3_mk_fpa_to_ubv(scx, expr(scx, Z3_mk_fpa_rna(scx)), Child(0)->ToSMT(), Width())); 554 | case Intrinsic::ceil: 555 | return expr(scx,Z3_mk_fpa_to_ubv(scx, expr(scx, Z3_mk_fpa_rtp(scx)), Child(0)->ToSMT(), Width())); 556 | case Intrinsic::floor: 557 | return expr(scx,Z3_mk_fpa_to_ubv(scx, expr(scx, Z3_mk_fpa_rtn(scx)), Child(0)->ToSMT(), Width())); 558 | default: 559 | break; 560 | } 561 | } 562 | //default behavior of fptoui is round towards zero 563 | return expr(scx,Z3_mk_fpa_to_ubv(scx, expr(scx, Z3_mk_fpa_rtz(scx)), Child(0)->ToSMT(), Width())); 564 | case Instruction::FPToSI: 565 | child = ((Instruction *)contents)->getOperand(0); 566 | //Convert sequences of round, fptoui into to_ubv with correct rounding mode 567 | if (isa(child)) 568 | { 569 | switch(((CallInst*)child)->getCalledFunction()->getIntrinsicID()) 570 | { 571 | case Intrinsic::roundeven: 572 | return expr(scx,Z3_mk_fpa_to_sbv(scx, expr(scx, Z3_mk_fpa_rne(scx)), Child(0)->ToSMT(), Width())); 573 | case Intrinsic::lround: 574 | return expr(scx,Z3_mk_fpa_to_sbv(scx, expr(scx, Z3_mk_fpa_rna(scx)), Child(0)->ToSMT(), Width())); 575 | case Intrinsic::ceil: 576 | return expr(scx,Z3_mk_fpa_to_sbv(scx, expr(scx, Z3_mk_fpa_rtp(scx)), Child(0)->ToSMT(), Width())); 577 | case Intrinsic::floor: 578 | return expr(scx,Z3_mk_fpa_to_sbv(scx, expr(scx, Z3_mk_fpa_rtn(scx)), Child(0)->ToSMT(), Width())); 579 | default: 580 | break; 581 | } 582 | } 583 | //default behavior of fptosi is round towards zero 584 | return expr(scx,Z3_mk_fpa_to_sbv(scx, expr(scx, Z3_mk_fpa_rtz(scx)), Child(0)->ToSMT(), Width())); 585 | case Instruction::FPExt: 586 | case Instruction::FPTrunc: 587 | return fpa_to_fpa(Child(0)->ToSMT(), SMTSort()); 588 | case Instruction::SIToFP: 589 | return sbv_to_fpa(Child(0)->ToSMT(), SMTSort()); 590 | case Instruction::UIToFP: 591 | return ubv_to_fpa(Child(0)->ToSMT(), SMTSort()); 592 | //Unary bitvector instructions 593 | case Instruction::BitCast: 594 | //Bitcast from bitvector to floating point 595 | if(SMTSort().is_fpa()) 596 | { 597 | return Child(0)->ToSMT().mk_from_ieee_bv(SMTSort()); 598 | } 599 | else 600 | { 601 | // There is no floating to bitvector bitcast equivalent in SMT since NaN has multiple representations 602 | // Add a new variable and constrain it equal 603 | return function.AddBCVariable(Child(0)); 604 | } 605 | case Instruction::Trunc: 606 | return Child(0)->ToSMT().extract(Width()-1, 0); 607 | case Instruction::ZExt: 608 | arg = Child(0)->ToSMT(); 609 | if (arg.is_bool()) //optimizer created zext i1 610 | { 611 | return zext(ite(arg, scx.bv_val(1,1), scx.bv_val(0,1)), Width()-1); 612 | } 613 | else 614 | { 615 | return zext(arg, Width()-std::unique_ptr{static_cast(Child(0).release())}->Width()); 616 | } 617 | case Instruction::SExt: 618 | arg = Child(0)->ToSMT(); 619 | if (arg.is_bool()) //optimizer created sext i1 620 | { 621 | //The optimizer may introduce sext i1 ... 622 | return sext(ite(arg, scx.bv_val(1,1), scx.bv_val(0,1)), Width()-1); 623 | } 624 | else 625 | { 626 | return sext(arg, Width()-std::unique_ptr{static_cast(Child(0).release())}->Width()); 627 | } 628 | case Instruction::Freeze: 629 | //Frontend guarantees no undefined behavior, so freeze always returns its argument 630 | return Child(0)->ToSMT(); 631 | //Binary instructions (boolean or bitvector) 632 | case Instruction::And: 633 | left = Child(0)->ToSMT(); 634 | right = Child(1)->ToSMT(); 635 | return left.is_bool() ? (left && right) : (left & right); 636 | case Instruction::Or: 637 | left = Child(0)->ToSMT(); 638 | right = Child(1)->ToSMT(); 639 | return left.is_bool() ? (left || right) : (left | right); 640 | case Instruction::Xor: 641 | //The type check is built into the z3 ^ operator overload 642 | return Child(0)->ToSMT() ^ Child(1)->ToSMT(); 643 | //Binary bitvector instructions 644 | case Instruction::Shl: 645 | left = Child(0)->ToSMT(); 646 | right = Child(1)->ToSMT(); 647 | // Check for shift left by a constant; this can be replaced with multiplication 648 | if (shiftToMultiply && right.is_const() && ((rr = std::atoi(right.to_string().c_str())) > 0)) 649 | { 650 | int i = 1; 651 | while (rr > 0) { i*=2; rr--;} 652 | return left * scx.bv_val(i,Width()); 653 | } 654 | else 655 | { 656 | return shl(left,right); 657 | } 658 | case Instruction::LShr: 659 | return lshr(Child(0)->ToSMT(),Child(1)->ToSMT()); 660 | case Instruction::AShr: 661 | return ashr(Child(0)->ToSMT(),Child(1)->ToSMT()); 662 | case Instruction::UDiv: 663 | return udiv(Child(0)->ToSMT(),Child(1)->ToSMT()); 664 | case Instruction::URem: 665 | return urem(Child(0)->ToSMT(),Child(1)->ToSMT()); 666 | case Instruction::SRem: 667 | return srem(Child(0)->ToSMT(),Child(1)->ToSMT()); 668 | //Bitvector and floating instructions (double operator overload meaning) 669 | case Instruction::Add: 670 | case Instruction::FAdd: 671 | return Child(0)->ToSMT() + Child(1)->ToSMT(); 672 | case Instruction::Sub: 673 | case Instruction::FSub: 674 | return Child(0)->ToSMT() - Child(1)->ToSMT(); 675 | case Instruction::Mul: 676 | case Instruction::FMul: 677 | return Child(0)->ToSMT() * Child(1)->ToSMT(); 678 | case Instruction::SDiv: 679 | case Instruction::FDiv: 680 | return Child(0)->ToSMT() / Child(1)->ToSMT(); 681 | //Binary floating instructions 682 | case Instruction::FRem: 683 | return rem(Child(0)->ToSMT(), Child(1)->ToSMT()); 684 | //Select instruction 685 | case Instruction::Select: 686 | return ite(Child(0)->ToSMT(),Child(1)->ToSMT(),Child(2)->ToSMT()); 687 | default: 688 | throw UnsupportedLLVMOpException("unsupported LLVM instruction", contents); 689 | 690 | } 691 | } 692 | } -------------------------------------------------------------------------------- /src/LLVMNode.h: -------------------------------------------------------------------------------- 1 | #include "llvm/ADT/APFloat.h" 2 | #include "llvm/ADT/STLExtras.h" 3 | #include "llvm/ADT/SmallString.h" 4 | #include "llvm/IR/BasicBlock.h" 5 | #include "llvm/IR/Constants.h" 6 | #include "llvm/IR/DerivedTypes.h" 7 | #include "llvm/IR/Function.h" 8 | #include "llvm/IR/IRBuilder.h" 9 | #include "llvm/IR/LLVMContext.h" 10 | #include "llvm/IR/Module.h" 11 | #include "llvm/IR/Type.h" 12 | #include "llvm/IR/Verifier.h" 13 | #include "llvm/IR/InstrTypes.h" 14 | #include "llvm/IR/PassManager.h" 15 | #include "llvm/Analysis/LoopAnalysisManager.h" 16 | #include "llvm/Analysis/CGSCCPassManager.h" 17 | #include "llvm/Analysis/LazyValueInfo.h" 18 | #include "llvm/Passes/PassBuilder.h" 19 | #include "llvm/Pass.h" 20 | #include "llvm/Support/raw_ostream.h" 21 | 22 | #include 23 | #include 24 | 25 | #include"z3++.h" 26 | 27 | #ifndef SMTMAPPING 28 | #define SMTMAPPING std::map 29 | #endif 30 | 31 | using namespace llvm; 32 | using namespace z3; 33 | 34 | namespace SLOT 35 | { 36 | class LLVMNode; 37 | class LLVMFunction; 38 | 39 | class LLVMFunction 40 | { 41 | public: 42 | static int varCounter; 43 | 44 | context &scx; 45 | SMTMAPPING variables; 46 | Function *contents; 47 | bool shiftToMultiply; 48 | expr extraVariables; // Hold results of bitcast to bitvector 49 | 50 | expr AddBCVariable(std::unique_ptr contents); 51 | 52 | LLVMFunction(bool t_shiftToMultiply, context &t_scx, Function *t_contents); 53 | expr ToSMT(); 54 | 55 | // bool CheckAssignment(model m); 56 | }; 57 | 58 | class LLVMNode 59 | { 60 | public: 61 | context& scx; 62 | //const SMTMAPPING& variables; 63 | Value *contents; 64 | bool shiftToMultiply; 65 | LLVMFunction& function; 66 | 67 | z3::sort SMTSort(); 68 | unsigned Width(); 69 | 70 | static std::unique_ptr MakeLLVMNode(bool shiftToMultiply, context& scx, LLVMFunction& function, Value *contents); 71 | 72 | LLVMNode(bool t_shiftToMultiply, context& t_scx, LLVMFunction& t_function, Value* t_contents); 73 | virtual ~LLVMNode() {} 74 | virtual expr ToSMT() = 0; 75 | }; 76 | 77 | class LLVMArgument : public LLVMNode 78 | { 79 | public: 80 | expr ToSMT() override; 81 | LLVMArgument(bool t_shiftToMultiply, context& t_scx, LLVMFunction& function, Value* t_contents); 82 | }; 83 | 84 | class LLVMConstant : public LLVMNode 85 | { 86 | public: 87 | expr ToSMT() override; 88 | LLVMConstant(bool t_shiftToMultiply, context& t_scx, LLVMFunction& function, Value* t_contents); 89 | }; 90 | 91 | 92 | 93 | class LLVMExpression : public LLVMNode 94 | { 95 | public: 96 | inline Instruction* AsInstruction() { return (Instruction *)contents; } 97 | inline std::unique_ptr Child(unsigned n) { return LLVMNode::MakeLLVMNode(shiftToMultiply, scx, function, AsInstruction()->getOperand(n)); } 98 | inline unsigned Opcode() { return AsInstruction()->getOpcode(); } 99 | inline expr Zero() { return scx.bv_val(0,Width()); } 100 | 101 | expr ToSMT() override; 102 | LLVMExpression(bool t_shiftToMultiply, context& t_scx, LLVMFunction& function, Value* t_contents); 103 | }; 104 | 105 | class LLVMIcmp : public LLVMExpression 106 | { 107 | public: 108 | 109 | inline CmpInst::Predicate Predicate() { return ((ICmpInst*)contents)->getPredicate(); } 110 | 111 | expr ToSMT() override; 112 | LLVMIcmp(bool t_shiftToMultiply, context& t_scx, LLVMFunction& function, Value* t_contents); 113 | }; 114 | 115 | class LLVMFcmp : public LLVMExpression 116 | { 117 | public: 118 | 119 | inline CmpInst::Predicate Predicate() { return ((FCmpInst*)contents)->getPredicate(); } 120 | 121 | expr ToSMT() override; 122 | LLVMFcmp(bool t_shiftToMultiply, context& t_scx, LLVMFunction& function, Value* t_contents); 123 | }; 124 | 125 | class LLVMIntrinsicCall : public LLVMExpression 126 | { 127 | public: 128 | static expr FPClassCheck(context& scx, expr val, int64_t bits); 129 | 130 | expr AsRoundingMode(unsigned n); 131 | 132 | expr ToSMT() override; 133 | LLVMIntrinsicCall(bool t_shiftToMultiply, context& t_scx, LLVMFunction& function, Value* t_contents); 134 | }; 135 | 136 | 137 | 138 | } 139 | -------------------------------------------------------------------------------- /src/Makefile: -------------------------------------------------------------------------------- 1 | CC= g++ 2 | CPPFLAGS= -I/root/z3/usr/include -I/z3/src -I/root/llvm-project/build/include -std=c++17 -fno-rtti -D_GNU_SOURCE -D_DEBUG -D_GLIBCXX_ASSERTIONS -D_LIBCPP_ENABLE_ASSERTIONS -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -g -O3 -fexceptions 3 | 4 | # Add z3 library flags 5 | Z3_LDFLAGS=-L/root/z3/usr/lib -lz3 6 | 7 | # Use llvm-config to get the necessary flags and libraries 8 | LLVM_LDFLAGS=$(shell llvm-config --ldflags) 9 | LLVM_LIBS=$(shell llvm-config --system-libs --libs core passes) 10 | 11 | LDLIBS=$(Z3_LDFLAGS) $(LLVM_LDFLAGS) $(LLVM_LIBS) -lrt -ldl -lpthread -lm -lz -ltinfo -lxml2 12 | 13 | main: main.o SMTFormula.o SMTNode.o LLVMFunction.o LLVMNode.o 14 | $(CC) $(CPPFLAGS) -o slot main.o SMTFormula.o SMTNode.o LLVMFunction.o LLVMNode.o $(LDLIBS) 15 | 16 | main.o: main.cpp SMTFormula.h SMTNode.h LLVMNode.h SLOTExceptions.h #LLVMFunction.h 17 | $(CC) $(CPPFLAGS) -c main.cpp 18 | 19 | SMTNode.o: SMTNode.h SLOTExceptions.h 20 | $(CC) $(CPPFLAGS) -c SMTNode.cpp 21 | 22 | LLVMNode.o: LLVMNode.h SLOTExceptions.h 23 | $(CC) $(CPPFLAGS) -c LLVMNode.cpp 24 | 25 | SMTFormula.o: SMTFormula.h SLOTExceptions.h 26 | $(CC) $(CPPFLAGS) -c SMTFormula.cpp 27 | 28 | LLVMFunction.o: LLVMNode.h SLOTExceptions.h 29 | $(CC) $(CPPFLAGS) -c LLVMFunction.cpp 30 | 31 | clean: 32 | rm *.o -------------------------------------------------------------------------------- /src/SLOTExceptions.h: -------------------------------------------------------------------------------- 1 | namespace SLOT 2 | { 3 | class UnsupportedSMTOpException : public std::exception { 4 | std::string description; 5 | std::string expression; 6 | std::string string; 7 | 8 | public: 9 | UnsupportedSMTOpException(std::string t_description, expr t_expression) : description(t_description), expression(t_expression.to_string()) 10 | { 11 | string = "Encountered unsupported SMT operation (" + description + ") in expression " + expression; 12 | } 13 | const char * what () const throw () 14 | { 15 | return string.c_str(); 16 | } 17 | }; 18 | 19 | 20 | class UnsupportedLLVMOpException : public std::exception { 21 | Value* expression; 22 | std::string description; 23 | std::string string; 24 | 25 | public: 26 | UnsupportedLLVMOpException(std::string t_description, Value* t_expression) : description(t_description), expression(t_expression) 27 | { 28 | std::string mst; 29 | llvm::raw_string_ostream rso(mst); 30 | expression->print(rso); 31 | //throw UnsupportedTypeException("unsupported LLVM type", rso.str()); 32 | string = "Encountered unsupported LLVM operation (" + description + ")" + rso.str(); 33 | } 34 | const char * what () const throw () 35 | { 36 | return string.c_str(); 37 | } 38 | }; 39 | 40 | 41 | class UnsupportedTypeException : public std::exception { 42 | std::string description; 43 | std::string expression; 44 | std::string string; 45 | 46 | public: 47 | UnsupportedTypeException(std::string t_description, expr t_expression) : UnsupportedTypeException(t_description,t_expression.to_string()) {} 48 | UnsupportedTypeException(std::string t_description, std::string t_expression) : description(t_description), expression(t_expression) 49 | { 50 | string = "Encountered unsupported SMT type (" + description + ") in expression " + expression; 51 | } 52 | const char * what () const throw () 53 | { 54 | return string.c_str(); 55 | } 56 | }; 57 | 58 | class NotImplementedException : public std::logic_error 59 | { 60 | public: 61 | NotImplementedException() : std::logic_error("Function not yet implemented") { }; 62 | }; 63 | 64 | 65 | } -------------------------------------------------------------------------------- /src/SMTFormula.cpp: -------------------------------------------------------------------------------- 1 | #include "SMTFormula.h" 2 | #include "SLOTExceptions.h" 3 | #include 4 | 5 | #ifndef LLMAPPING 6 | #define LLMAPPING std::map 7 | #endif 8 | 9 | namespace SLOT 10 | { 11 | static context c; 12 | 13 | SMTFormula::SMTFormula(LLVMContext& t_lcx, Module* t_lmodule, IRBuilder<>& t_builder, std::string t_string, std::string t_func_name) : lcx(t_lcx), lmodule(t_lmodule), builder(t_builder), string(t_string), contents(c), func_name(t_func_name) 14 | { 15 | //context c; 16 | //Regular expression matching to get variables 17 | std::string s = string; 18 | std::smatch m; 19 | std::regex e (R"(\((declare-fun\s(\|.*\||[\~\!\@\$\%\^\&\*_\-\+\=\<\>\.\?\/A-Za-z0-9]+)\s*\(\s*\)\s*(\(\s*_\s*FloatingPoint\s*(\d+)\s*(\d+)\s*\)|Float16|Float32|Float64|Float128|FPN|Bool|\(\s*_\s*BitVec\s*(\d+)\s*\))\s*|declare-const\s(\|.*\||[\~\!\@\$\%\^\&\*_\-\+\=\<\>\.\?\/A-Za-z0-9]+)\s*(\(\s*_\s*FloatingPoint\s*(\d+)\s*(\d+)\s*\)|Float16|Float32|Float64|Float128|FPN|Bool|\(\s*_\s*BitVec\s*(\d+)\s*\))\s*)\))"); 20 | 21 | std::vector types; 22 | std::vector names; 23 | std::string temp = ""; 24 | while (std::regex_search(s, m, e)) 25 | { 26 | if (m[2]!="") 27 | { 28 | temp = m[2]; 29 | } 30 | else 31 | { 32 | temp = m[7]; 33 | } 34 | 35 | if (temp[0] == '|') 36 | { 37 | names.push_back(temp.substr(1, temp.length() - 2)); 38 | } 39 | else 40 | { 41 | names.push_back(temp); 42 | } 43 | 44 | if (m[3]=="Bool" || m[8] == "Bool") //Boolean 45 | { 46 | types.push_back(Type::getInt1Ty(lcx)); 47 | } 48 | else if (m[6] != "") //Bitvector 49 | { 50 | types.push_back(Type::getIntNTy(lcx,stoi(m[6].str()))); 51 | } 52 | else if (m[11] != "") 53 | { 54 | types.push_back(Type::getIntNTy(lcx,stoi(m[11].str()))); 55 | } 56 | else if (m[4] != "" && m[5] != "") //General floating point 57 | { 58 | types.push_back(FloatingNode::ToFloatingType(lcx,names.back(),stoi(m[4])+stoi(m[5]))); 59 | } 60 | else if (m[9] != "" && m[10] != "") 61 | { 62 | types.push_back(FloatingNode::ToFloatingType(lcx,names.back(),stoi(m[9])+stoi(m[10]))); 63 | } 64 | else if (m[3]=="Float16" || m[3]=="Float32" || m[3]=="Float64" || m[3]=="Float128") //Named floating points 65 | { 66 | types.push_back(FloatingNode::ToFloatingType(lcx,names.back(),stoi(m[3].str().substr(5)))); 67 | } 68 | else if (m[8]=="Float16" || m[8]=="Float32" || m[8]=="Float64" || m[8]=="Float128") //Named floating points 69 | { 70 | types.push_back(FloatingNode::ToFloatingType(lcx,names.back(),stoi(m[8].str().substr(5)))); 71 | } 72 | else if (m[3]=="FPN" || m[8]=="FPN") //Special case for the convention (define-sort FPN () (_ FloatingPoint 11 53)) in QF_FP 73 | { 74 | types.push_back(FloatingNode::ToFloatingType(lcx,names.back(),64)); 75 | } 76 | else 77 | { 78 | throw UnsupportedTypeException("unsupported SMT variable type", names.back()); 79 | } 80 | s = m.suffix().str(); 81 | } 82 | 83 | 84 | //Create function 85 | FunctionType* fnty = FunctionType::get(Type::getInt1Ty(lcx),types,false); 86 | function = Function::Create(fnty, Function::ExternalLinkage, func_name, lmodule); 87 | //Assign variable types 88 | int i = 0; 89 | for (auto &arg : function->args()) 90 | { 91 | arg.setName(names[i]); 92 | variables[names[i]] = &arg; 93 | i++; 94 | } 95 | 96 | contents = c.parse_string(t_string.c_str()); 97 | 98 | for (expr e : contents) 99 | { 100 | assertions.push_back(BooleanNode(lcx, lmodule, builder, variables, e)); 101 | } 102 | 103 | //assert(assertions.size() >= 1); 104 | } 105 | 106 | void SMTFormula::ToLLVM() 107 | { 108 | BasicBlock* bb = BasicBlock::Create(lcx, "b", function); 109 | builder.SetInsertPoint(bb); 110 | 111 | if (assertions.size() == 0) 112 | { 113 | //Empty constraint is sat 114 | builder.CreateRet(ConstantInt::getBool(lcx, true)); 115 | } 116 | else 117 | { 118 | Value* temp = assertions[0].ToLLVM(); 119 | //Conjunction of all assertions 120 | if (assertions.size() > 1) 121 | { 122 | for (int i = 1; i < assertions.size(); i++) 123 | { 124 | temp = builder.CreateAnd(temp,assertions[i].ToLLVM()); 125 | } 126 | } 127 | 128 | builder.CreateRet(temp); 129 | } 130 | } 131 | } -------------------------------------------------------------------------------- /src/SMTFormula.h: -------------------------------------------------------------------------------- 1 | #include "SMTNode.h" 2 | 3 | #ifndef LLMAPPING 4 | #define LLMAPPING std::map 5 | #endif 6 | 7 | namespace SLOT 8 | { 9 | class SMTFormula 10 | { 11 | public: 12 | LLVMContext& lcx; 13 | Module* lmodule; 14 | IRBuilder<>& builder; 15 | 16 | Function* function; 17 | 18 | std::string string; 19 | std::string func_name; 20 | expr_vector contents; 21 | std::vector assertions; 22 | LLMAPPING variables; 23 | 24 | SMTFormula(LLVMContext& t_lcx, Module* t_lmodule, IRBuilder<>& t_builder, std::string t_string, std::string t_func_name); 25 | void ToLLVM(); 26 | 27 | //bool CheckAssignment(model m); 28 | }; 29 | } -------------------------------------------------------------------------------- /src/SMTNode.h: -------------------------------------------------------------------------------- 1 | #include "llvm/ADT/APFloat.h" 2 | #include "llvm/ADT/STLExtras.h" 3 | #include "llvm/IR/BasicBlock.h" 4 | #include "llvm/IR/Constants.h" 5 | #include "llvm/IR/DerivedTypes.h" 6 | #include "llvm/IR/Function.h" 7 | #include "llvm/IR/IRBuilder.h" 8 | #include "llvm/IR/LLVMContext.h" 9 | #include "llvm/IR/Module.h" 10 | #include "llvm/IR/Type.h" 11 | #include "llvm/IR/Verifier.h" 12 | #include "llvm/IR/InstrTypes.h" 13 | #include "llvm/IR/PassManager.h" 14 | #include "llvm/Analysis/LoopAnalysisManager.h" 15 | #include "llvm/Analysis/CGSCCPassManager.h" 16 | #include "llvm/Analysis/LazyValueInfo.h" 17 | #include "llvm/Passes/PassBuilder.h" 18 | #include "llvm/Pass.h" 19 | #include "llvm/Support/raw_ostream.h" 20 | 21 | #include 22 | #include 23 | 24 | #include"z3++.h" 25 | 26 | #ifndef LLMAPPING 27 | #define LLMAPPING std::map 28 | #endif 29 | 30 | using namespace llvm; 31 | using namespace z3; 32 | 33 | namespace SLOT 34 | { 35 | class IntegerNode; 36 | class FloatingNode; 37 | class BitvectorNode; 38 | class BooleanNode; 39 | class RealNode; 40 | 41 | class SMTNode 42 | { 43 | public: 44 | LLVMContext& lcx; 45 | Module* lmodule; 46 | IRBuilder<>& builder; 47 | unsigned integer_width; 48 | const LLMAPPING& variables; 49 | expr contents; 50 | bool noOverflow = true; 51 | 52 | //Z3 ''constants'' can be either variables or constants 53 | inline std::string StrippedName() { return ((contents.to_string()[0] == '|') ? contents.to_string().substr(1, contents.to_string().length() - 2) : contents.to_string()); } 54 | inline bool IsVariable() { return contents.is_const() && variables.count(StrippedName()); } 55 | inline bool IsConstant() { return contents.is_const() && !variables.count(StrippedName()); } 56 | inline Z3_decl_kind Op() { return contents.decl().decl_kind(); } 57 | 58 | inline Z3_decl_kind RoundingMode() { return ((contents.arg(0).get_sort().sort_kind() == Z3_ROUNDING_MODE_SORT) ? contents.arg(0).decl().decl_kind() : Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN); } 59 | inline bool IsRNE() { return RoundingMode() == Z3_OP_FPA_RM_NEAREST_TIES_TO_EVEN; } 60 | 61 | MetadataAsValue* LLVMRoundingMode(); 62 | MetadataAsValue* LLVMException(); 63 | 64 | //Syntax sugar for extracting children 65 | inline FloatingNode FloatingChild(expr cont); 66 | inline FloatingNode FloatingChild(int index); 67 | inline BitvectorNode BitvectorChild(expr cont); 68 | inline BitvectorNode BitvectorChild(int index); 69 | inline BooleanNode BooleanChild(expr cont); 70 | inline BooleanNode BooleanChild(int index); 71 | 72 | SMTNode(LLVMContext& t_lcx, Module* t_lmodule, IRBuilder<>& t_builder, const LLMAPPING& t_variables, expr t_contents); 73 | virtual ~SMTNode() {} 74 | virtual Value* ToLLVM() = 0; 75 | }; 76 | 77 | //-------------------------------------------------------------------------------- 78 | 79 | class FloatingNode : public SMTNode 80 | { 81 | public: 82 | 83 | static const std::map class_flags; 84 | 85 | inline unsigned SBits() { return contents.get_sort().fpa_sbits(); } 86 | inline unsigned Width() { return contents.get_sort().fpa_sbits() + contents.get_sort().fpa_ebits(); } 87 | 88 | static Type* ToFloatingType(LLVMContext& lcx, std::string name, unsigned width); 89 | inline Type* FloatingType() { return FloatingNode::ToFloatingType(lcx, contents.to_string(), Width()); } 90 | 91 | Value * LLVMClassCheck(Z3_decl_kind op); 92 | Value * LLVMEq(FloatingNode other); 93 | Value * LLVMNE(FloatingNode other); 94 | 95 | 96 | Value* ToLLVM() override; 97 | FloatingNode(LLVMContext& t_lcx, Module* t_lmodule, IRBuilder<>& t_builder, const LLMAPPING& t_variables, expr t_contents); 98 | }; 99 | 100 | //-------------------------------------------------------------------------------- 101 | 102 | class BitvectorNode : public SMTNode 103 | { 104 | public: 105 | inline unsigned Width() { return contents.get_sort().bv_size(); } 106 | inline Value* Zero() { return ConstantInt::get(IntegerType::get(lcx, Width()), 0);} 107 | 108 | inline Value* IsZero() { return builder.CreateICmpEQ(ToLLVM(),Zero()); } 109 | inline Value* IsNegative() { return builder.CreateICmpSLT(ToLLVM(),Zero()); } 110 | inline Value* IsPositive() { return builder.CreateICmpSGE(ToLLVM(),Zero()); } 111 | 112 | 113 | 114 | static Value* LlURem(IRBuilder<>& builder, Value * left, Value * right); 115 | 116 | Value* ToLLVM() override; 117 | BitvectorNode(LLVMContext& t_lcx, Module* t_lmodule, IRBuilder<>& t_builder, const LLMAPPING& t_variables, expr t_contents); 118 | }; 119 | 120 | //-------------------------------------------------------------------------------- 121 | 122 | class BooleanNode : public SMTNode 123 | { 124 | public: 125 | 126 | Value* ToLLVM() override; 127 | 128 | BooleanNode(LLVMContext& t_lcx, Module* t_lmodule, IRBuilder<>& t_builder, const LLMAPPING& t_variables, expr t_contents); 129 | }; 130 | } 131 | -------------------------------------------------------------------------------- /src/main.cpp: -------------------------------------------------------------------------------- 1 | #include "SMTFormula.h" 2 | #include "LLVMNode.h" 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include "llvm/Transforms/InstCombine/InstCombine.h" 9 | #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h" 10 | #include "llvm/Transforms/Scalar/Reassociate.h" 11 | #include "llvm/Transforms/Scalar/SCCP.h" 12 | #include "llvm/Transforms/Scalar/DCE.h" 13 | #include "llvm/Transforms/Scalar/ADCE.h" 14 | #include "llvm/Transforms/Scalar/InstSimplifyPass.h" 15 | #include "llvm/Transforms/Scalar/GVN.h" 16 | #include "llvm/Transforms/Scalar/EarlyCSE.h" 17 | 18 | #ifndef LLMAPPING 19 | #define LLMAPPING std::map& 20 | #endif 21 | 22 | #ifndef LLVM_FUNCTION_NAME 23 | #define LLVM_FUNCTION_NAME "SMT" 24 | #endif 25 | 26 | using namespace SLOT; 27 | using namespace std::chrono; 28 | 29 | 30 | void Help() 31 | { 32 | std::cout << "SLOT arguments:\n"; 33 | std::cout << " -h : See help menu\n"; 34 | std::cout << " -s : The input SMTLIB2 format file (required)\n"; 35 | std::cout << " -o : The output file. If not provided, output is sent to stdout\n"; 36 | std::cout << " -lu : Output intermediate LLVM IR before optimization (optional)\n"; 37 | std::cout << " -lo : Output intermediate LLVM IR after optimization (optional)\n"; 38 | std::cout << " -m : Convert constant shifts to multiplication\n"; 39 | std::cout << " -t : Output statistics file. If not provided, output is sent to stdout\n"; 40 | std::cout << " -pall : Run all relevant passes (roughly equivalent to -O3 in LLVM). By default, no passes are run\n"; 41 | std::cout << " -instcombine : Run instcombine pass\n"; 42 | std::cout << " -ainstcombine : Run aggressive instcombine pass\n"; 43 | std::cout << " -reassociate : Run reassociate pass\n"; 44 | std::cout << " -sccp : Run sparse conditional constant propagation (SCCP) pass\n"; 45 | std::cout << " -dce : Run dead code elimination (DCE) pass\n"; 46 | std::cout << " -adce : Run aggressive dead code elimination (ADCE) pass\n"; 47 | std::cout << " -instsimplify : Run instsimplify pass\n"; 48 | std::cout << " -gvn : Run global value numbering (GVN) pass\n"; 49 | } 50 | 51 | //Not safe: assumes HasFlag returned true and that there is an argument after the flag of interest 52 | char* GetFlag(int argc, char* argv[], const std::string &flag) 53 | { 54 | for (int i = 1; i < argc-1; i++) 55 | { 56 | if (flag.compare(argv[i]) == 0) 57 | { 58 | return argv[i+1]; 59 | } 60 | } 61 | return 0; 62 | } 63 | 64 | bool HasFlag(int argc, char* argv[], const std::string& flag) 65 | { 66 | for (int i = 1; i < argc; i++) 67 | { 68 | if (flag.compare(argv[i]) == 0) 69 | { 70 | return true; 71 | } 72 | } 73 | return false; 74 | } 75 | 76 | #define INST_COMBINE 1 77 | #define AG_INST_COMBINE 2 78 | #define REASSOCIATE 4 79 | #define SCCP 8 80 | #define DCE 16 81 | #define ADCE 32 82 | #define INST_SIMPLIFY 64 83 | #define GVN 128 84 | 85 | unsigned short ParsePasses(int argc, char* argv[]) 86 | { 87 | if (HasFlag(argc, argv, "-pall")) 88 | { 89 | return ~0; 90 | } 91 | else 92 | { 93 | unsigned short toReturn = 0; 94 | if (HasFlag(argc, argv, "-instcombine")) { toReturn |= INST_COMBINE; } 95 | if (HasFlag(argc, argv, "-ainstcombine")) { toReturn |= AG_INST_COMBINE; } 96 | if (HasFlag(argc, argv, "-reassociate")) { toReturn |= REASSOCIATE; } 97 | if (HasFlag(argc, argv, "-sccp")) { toReturn |= SCCP; } 98 | if (HasFlag(argc, argv, "-dce")) { toReturn |= DCE; } 99 | if (HasFlag(argc, argv, "-adce")) { toReturn |= ADCE; } 100 | if (HasFlag(argc, argv, "-instsimplify")) { toReturn |= INST_SIMPLIFY; } 101 | if (HasFlag(argc, argv, "-gvn")) { toReturn |= GVN; } 102 | return toReturn; 103 | } 104 | } 105 | 106 | std::string PrintPasses(unsigned short flags) 107 | { 108 | return ((flags & INST_COMBINE) ? "1" : "0") + ((std::string)",") + 109 | ((flags & AG_INST_COMBINE) ? "1" : "0") + "," + 110 | ((flags & REASSOCIATE) ? "1" : "0") + "," + 111 | ((flags & SCCP) ? "1" : "0") + "," + 112 | ((flags & DCE) ? "1" : "0") + "," + 113 | ((flags & ADCE) ? "1" : "0") + "," + 114 | ((flags & INST_SIMPLIFY) ? "1" : "0") + "," + 115 | ((flags & GVN) ? "1" : "0"); 116 | } 117 | 118 | unsigned short RunPasses(unsigned short flags, Function& fun) 119 | { 120 | //instcombine and aggressive instcombine are run twice, according to the -O3 optimization pass sequence 121 | LoopAnalysisManager LAM; 122 | FunctionAnalysisManager FAM; 123 | CGSCCAnalysisManager CGAM; 124 | ModuleAnalysisManager MAM; 125 | 126 | PassBuilder PB; 127 | 128 | PB.registerModuleAnalyses(MAM); 129 | PB.registerCGSCCAnalyses(CGAM); 130 | PB.registerFunctionAnalyses(FAM); 131 | PB.registerLoopAnalyses(LAM); 132 | PB.crossRegisterProxies(LAM, FAM, CGAM, MAM); 133 | 134 | int count = fun.getEntryBlock().sizeWithoutDebug(); 135 | unsigned short used = 0; 136 | 137 | if (flags & INST_COMBINE) 138 | { 139 | InstCombinePass().run(fun, FAM); 140 | if (fun.getEntryBlock().sizeWithoutDebug() != count) 141 | { 142 | count = fun.getEntryBlock().sizeWithoutDebug(); 143 | used |= INST_COMBINE; 144 | } 145 | } 146 | 147 | if (flags & AG_INST_COMBINE) 148 | { 149 | AggressiveInstCombinePass().run(fun, FAM); 150 | if (fun.getEntryBlock().sizeWithoutDebug() != count) 151 | { 152 | count = fun.getEntryBlock().sizeWithoutDebug(); 153 | used |= AG_INST_COMBINE; 154 | } 155 | } 156 | 157 | EarlyCSEPass().run(fun, FAM); 158 | 159 | if (flags & REASSOCIATE) 160 | { 161 | ReassociatePass().run(fun, FAM); 162 | if (fun.getEntryBlock().sizeWithoutDebug() != count) 163 | { 164 | count = fun.getEntryBlock().sizeWithoutDebug(); 165 | used |= REASSOCIATE; 166 | } 167 | } 168 | 169 | if (flags & SCCP) 170 | { 171 | SCCPPass().run(fun, FAM); 172 | if (fun.getEntryBlock().sizeWithoutDebug() != count) 173 | { 174 | count = fun.getEntryBlock().sizeWithoutDebug(); 175 | used |= SCCP; 176 | } 177 | } 178 | 179 | if (flags & DCE) 180 | { 181 | DCEPass().run(fun, FAM); 182 | if (fun.getEntryBlock().sizeWithoutDebug() != count) 183 | { 184 | count = fun.getEntryBlock().sizeWithoutDebug(); 185 | used |= DCE; 186 | } 187 | } 188 | 189 | if (flags & ADCE) 190 | { 191 | ADCEPass().run(fun, FAM); 192 | if (fun.getEntryBlock().sizeWithoutDebug() != count) 193 | { 194 | count = fun.getEntryBlock().sizeWithoutDebug(); 195 | used |= ADCE; 196 | } 197 | } 198 | 199 | if (flags & INST_SIMPLIFY) 200 | { 201 | InstSimplifyPass().run(fun, FAM); 202 | if (fun.getEntryBlock().sizeWithoutDebug() != count) 203 | { 204 | count = fun.getEntryBlock().sizeWithoutDebug(); 205 | used |= INST_SIMPLIFY; 206 | } 207 | } 208 | 209 | if (flags & GVN) 210 | { 211 | GVNPass().run(fun, FAM); 212 | if (fun.getEntryBlock().sizeWithoutDebug() != count) 213 | { 214 | count = fun.getEntryBlock().sizeWithoutDebug(); 215 | used |= GVN; 216 | } 217 | } 218 | 219 | if (flags & INST_COMBINE) 220 | { 221 | InstCombinePass().run(fun, FAM); 222 | if (fun.getEntryBlock().sizeWithoutDebug() != count) 223 | { 224 | count = fun.getEntryBlock().sizeWithoutDebug(); 225 | used |= INST_COMBINE; 226 | } 227 | } 228 | 229 | if (flags & AG_INST_COMBINE) 230 | { 231 | AggressiveInstCombinePass().run(fun, FAM); 232 | if (fun.getEntryBlock().sizeWithoutDebug() != count) 233 | { 234 | count = fun.getEntryBlock().sizeWithoutDebug(); 235 | used |= AG_INST_COMBINE; 236 | } 237 | } 238 | 239 | return used; 240 | } 241 | 242 | 243 | int LLVMFunction::varCounter = 0; 244 | 245 | 246 | 247 | int main(int argc, char* argv[]) 248 | { 249 | bool shiftToMultiply = false; 250 | //UI parsing 251 | if(HasFlag(argc, argv, "-h")) 252 | { 253 | Help(); 254 | exit(0); 255 | } 256 | if (HasFlag(argc, argv, "-m")) 257 | { 258 | shiftToMultiply = true; 259 | } 260 | 261 | if(!HasFlag(argc, argv, "-s")) 262 | { 263 | std::cout << "Must specify input file with -s.\n"; 264 | return 1; 265 | } 266 | char * inputFilename = GetFlag(argc, argv, "-s"); 267 | if (!inputFilename) 268 | { 269 | std::cout << "Invalid input file name.\n"; 270 | return 1; 271 | } 272 | 273 | //LLVM and Z3 setup 274 | LLVMContext lcx; 275 | Module lmodule = Module(inputFilename, lcx); 276 | IRBuilder builder = IRBuilder(lcx); 277 | 278 | std::ifstream t(inputFilename); 279 | std::stringstream buffer; 280 | buffer << t.rdbuf(); 281 | std::string smt_str = buffer.str(); 282 | 283 | 284 | //Frontend translation 285 | auto frontStart = high_resolution_clock::now(); 286 | SMTFormula a = SMTFormula(lcx, &lmodule, builder, smt_str, LLVM_FUNCTION_NAME); 287 | a.ToLLVM(); 288 | auto frontEnd = high_resolution_clock::now(); 289 | duration frontTime = frontEnd - frontStart; 290 | //Frontend translation 291 | 292 | 293 | 294 | Function *fun = lmodule.getFunction(LLVM_FUNCTION_NAME); 295 | unsigned short parsedPasses = ParsePasses(argc, argv); 296 | 297 | 298 | char * luFilename; 299 | if(HasFlag(argc, argv, "-lu") && (luFilename = GetFlag(argc, argv, "-lu"))) 300 | { 301 | raw_fd_ostream file(luFilename, *(new std::error_code())); 302 | lmodule.print(file, nullptr); 303 | } 304 | 305 | 306 | //Optimization 307 | auto optStart = high_resolution_clock::now(); 308 | unsigned short usedPasses = RunPasses(parsedPasses, *fun); 309 | auto optEnd = high_resolution_clock::now(); 310 | duration optTime = optEnd - optStart; 311 | //Optimization 312 | 313 | 314 | char * loFilename; 315 | if(HasFlag(argc, argv, "-lo") && (loFilename = GetFlag(argc, argv, "-lo"))) 316 | { 317 | raw_fd_ostream file(loFilename, *(new std::error_code())); 318 | lmodule.print(file, nullptr); 319 | } 320 | 321 | 322 | context c; 323 | solver s(c); 324 | 325 | 326 | //Backend translation 327 | auto backStart = high_resolution_clock::now(); 328 | LLVMFunction f = LLVMFunction(shiftToMultiply, c, fun); 329 | s.add(f.ToSMT()); 330 | auto backEnd = high_resolution_clock::now(); 331 | duration backTime = backEnd - backStart; 332 | //Backend translation 333 | 334 | 335 | 336 | //Print output constraint 337 | char * outputFilename; 338 | if(HasFlag(argc, argv, "-o") && (outputFilename = GetFlag(argc, argv, "-o"))) 339 | { 340 | std::ofstream out(outputFilename); 341 | out << s.to_smt2(); 342 | } 343 | else 344 | { 345 | std::cout << s.to_smt2(); 346 | } 347 | 348 | //Print statistics 349 | char * statsFilename; 350 | if(HasFlag(argc, argv, "-t") && (statsFilename = GetFlag(argc, argv, "-t"))) 351 | { 352 | std::ofstream out; 353 | out.open(statsFilename, std::ios_base::app); 354 | out << inputFilename << "," << (shiftToMultiply ? "true" : "false") << "," << PrintPasses(parsedPasses) << "," << frontTime.count() << "," << optTime.count() << "," << backTime.count() << "," << PrintPasses(usedPasses) << "\n"; 355 | } 356 | else 357 | { 358 | std::cout << inputFilename << "," << (shiftToMultiply ? "true" : "false") << "," << PrintPasses(parsedPasses) << "," << frontTime.count() << "," << optTime.count() << "," << backTime.count() << "," << PrintPasses(usedPasses) << "\n"; 359 | } 360 | 361 | } -------------------------------------------------------------------------------- /wrapper.sh: -------------------------------------------------------------------------------- 1 | ./runthrough.sh -z -c -b -t 600 -f $1 >> solver-stats.csv --------------------------------------------------------------------------------