├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── bin ├── Cargo.toml └── src │ └── main.rs ├── default.nix ├── examples └── brainfuck.rs ├── lib ├── Cargo.toml └── src │ ├── compile.rs │ ├── context.rs │ ├── lib.rs │ └── lir.rs ├── plugin ├── Cargo.toml └── src │ ├── lib.rs │ └── trans.rs ├── release.nix ├── rust-toolchain ├── rustc.sh └── shell.nix /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "holyjit_pkg" 3 | version = "0.0.0" 4 | authors = [ "Nicolas B. Pierron " ] 5 | 6 | [workspace] 7 | members = [ 8 | "lib", 9 | "plugin", 10 | "bin" 11 | ] 12 | 13 | [dependencies] 14 | holyjit_lib = { path = "./lib" } 15 | holyjit_plugin = { path = "./plugin" } 16 | holyjit = { path = "./bin" } 17 | 18 | # Before running any tests or examples, make sure to set the RUSTC_WRAPPER as 19 | # follow: 20 | # 21 | # export RUSTC_WRAPPER=$PWD/rustc.sh 22 | # 23 | # This wrapper will choose whether to start holyjit as a compiler instead of 24 | # starting the default rustc compiler. 25 | [[example]] 26 | name = "brainfuck" 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Making a Just-In-Time compiler is complex, a large source of security 2 | issues, and is a price which is frequently paid to have better performance 3 | results. 4 | 5 | HolyJit is made to remove this trade-off! Simplicity and security should no 6 | longer be sacrificed for performance reasons. 7 | 8 | # HolyJit 9 | 10 | HolyJit is a high-level Just-In-Time compiler. It extends the Rust compiler 11 | to convert the code of an interpreter written in Rust to tune a JIT compiler 12 | to handle the same interpreted language. 13 | 14 | HolyJit aims at being: 15 | * Easy. 16 | * Safe. 17 | * Fast. 18 | 19 | ### Easy 20 | 21 | HolyJit extends the Rust compiler to copy its internal representation of 22 | functions and convert it into a representation which can be consumed by the 23 | JIT compiler provided by HolyJit library. 24 | 25 | As a user, this implies that to inline a function in JIT compiled code, one 26 | just need to annotate it with the `jit!` macro: 27 | 28 | ```rust 29 | jit!{ 30 | fn eval(script: &Script, args: &[Value]) -> Result 31 | = eval_impl 32 | in script.as_ref() 33 | } 34 | 35 | fn eval_impl(script: &Script, args: &[Value]) -> Result { 36 | // ... 37 | // ... A few hundred lines of ordinary Rust code later ... 38 | // ... 39 | } 40 | 41 | fn main() { 42 | let script = ...; 43 | let args = ...; 44 | // Call it as any ordinary function. 45 | let res = eval(&script, &args); 46 | println!("Result: {}", res); 47 | } 48 | ``` 49 | 50 | Thus, you basically have to write an interpreter, and annotate it properly 51 | to teach the JIT compiler what can be optimized by the compiler. 52 | 53 | No assembly knowledge is required to start instrumenting your code to make 54 | it available to the JIT compiler's set of known functions. 55 | 56 | ### Safe 57 | 58 | Security issues from JIT compilers arise from: 59 | * Duplication of the runtime into a set of MacroAssembler functions. 60 | * Correctness of the compiler optimizations. 61 | 62 | As HolyJit extends the Rust compiler to extract the effective knowledge of 63 | the compiler, there is no more risk of having correctness issues caused by 64 | the duplication of code. 65 | 66 | Moreover, the code which is given to the JIT compiler is as safe as the code 67 | users wrote in the Rust language. 68 | 69 | As HolyJit aims at being a JIT library which can easily be embedded into 70 | other projects, correctness of the compiler optimizations should be caught 71 | by the community of users and fuzzers, thus leaving less bugs for you to 72 | find. 73 | 74 | ### Fast 75 | 76 | Fast is a tricky question when dealing with a JIT compiler, as the cost of 77 | the compilation is part of the equation. 78 | 79 | HolyJit aims at reducing the start-up time, based on annotations made out of 80 | macros, to guide the early tiers of the compilers for unrolling loops and 81 | generating inline caches. 82 | 83 | For final compilation tiers, it uses special types/traits to wrap the data 84 | in order to instrument and monitor the values which are being used, such 85 | that guards can later be converted into constraints. 86 | 87 | ## Using HolyJit 88 | 89 | HolyJit is a rustc driver, which means that it has to be used in-place of rustc 90 | or as a rustc wrapper, i.e. by settings either the `RUSTC` or `RUSTC_WRAPPER` 91 | environment variable. 92 | 93 | When `holyjit` is used, the binary is instrumented the generated code with 94 | enough information to resume with the JIT compilation at runtime. 95 | 96 | When `rustc` is used, a binary is still produced but the JIT is disabled as no 97 | data are stored in the binary to be consumed by the JIT compiler at runtime. 98 | 99 | To run tests, you can either run the test of the library with `cargo test`, 100 | or run the examples of HolyJit with: 101 | 102 | ```sh 103 | $ RUSTC_WRAPPER=$(pwd)/rustc.sh cargo run --example brainfuck --verbose 104 | ``` 105 | 106 | At the moment, HolyJit is far from being yet ready for production! This is 107 | currently at a prototype stage, and most of the code & dependencies present 108 | today were made only as a proof of concept and not as a definitive 109 | implementation design. 110 | 111 | ## HolyJit Roadmap for 0.0.0 112 | 113 | The current goal is to make a proof of concept which highlights the main 114 | feature, i.e. being trivial to integrate into an existing code base and to 115 | have a running JIT compiler. 116 | 117 | As of today, HolyJit contains a draft of what the interface might look like, 118 | and is able to generate code for the example present in the repository. 119 | 120 | - [x] Create Rust library 121 | - [x] Allocate pages and map them as executable. 122 | - [x] Add a way to call either a dynamically compiled function or a 123 | statically compiled function. 124 | - [x] Add a `jit!` macro, to make calls transparent from the usage point of 125 | view. 126 | - [x] Create a JitContext class, and use it to request JIT compiled code. 127 | - [x] Create a graph representation. 128 | - [x] Consume the graph to generate code. 129 | 130 | - [x] Create a MIR plugin 131 | - [x] Detect locations which have to be patched. 132 | - [x] Find functions which have to be converted. 133 | - [x] Inject a generated vector in the binary content. 134 | - [x] Inject static variables as a tuple. 135 | - [x] Collect static variable references. 136 | - [x] Convert the MIR (from the Rust compiler) to the library graph 137 | representation. 138 | -------------------------------------------------------------------------------- /bin/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "holyjit" 3 | version = "0.0.0" 4 | authors = ["Nicolas B. Pierron "] 5 | 6 | [dependencies] 7 | holyjit_plugin = { path = "../plugin" } 8 | -------------------------------------------------------------------------------- /bin/src/main.rs: -------------------------------------------------------------------------------- 1 | // error-pattern:yummy 2 | #![feature(box_syntax)] 3 | #![feature(rustc_private)] 4 | #![feature(decl_macro)] 5 | 6 | //extern crate holyjit_plugin; 7 | extern crate getopts; 8 | extern crate rustc; 9 | extern crate rustc_driver; 10 | extern crate rustc_errors; 11 | extern crate rustc_plugin; 12 | extern crate rustc_trans_utils; 13 | extern crate rustc_mir; 14 | extern crate syntax; 15 | 16 | extern crate holyjit_plugin; 17 | 18 | use rustc::hir::def_id::DefId; 19 | use rustc::mir::Mir; 20 | use rustc::ty::TyCtxt; 21 | use rustc::ty::maps::Providers; 22 | use rustc_driver::{driver, Compilation, CompilerCalls, RustcDefaultCalls}; 23 | use rustc_trans_utils::trans_crate::TransCrate; 24 | use rustc::session::{config, Session}; 25 | use rustc::session::config::{ErrorOutputType, Input}; 26 | use std::path::PathBuf; 27 | use syntax::ast; 28 | use std::env; 29 | use std::process::Command; 30 | use rustc_mir::transform::run_passes; 31 | 32 | struct HolyJitCompilerCalls { 33 | default: RustcDefaultCalls, 34 | 35 | // Whether we should instrument or not the code with HolyJIT. 36 | add_jit: bool, 37 | } 38 | 39 | impl HolyJitCompilerCalls { 40 | fn new(add_jit: bool) -> Self { 41 | Self { 42 | default: RustcDefaultCalls, 43 | add_jit, 44 | } 45 | } 46 | } 47 | 48 | impl<'a> CompilerCalls<'a> for HolyJitCompilerCalls { 49 | fn early_callback( 50 | &mut self, 51 | matches: &getopts::Matches, 52 | sopts: &config::Options, 53 | cfg: &ast::CrateConfig, 54 | descriptions: &rustc_errors::registry::Registry, 55 | output: ErrorOutputType, 56 | ) -> Compilation { 57 | self.default 58 | .early_callback(matches, sopts, cfg, descriptions, output) 59 | } 60 | 61 | fn no_input( 62 | &mut self, 63 | matches: &getopts::Matches, 64 | sopts: &config::Options, 65 | cfg: &ast::CrateConfig, 66 | odir: &Option, 67 | ofile: &Option, 68 | descriptions: &rustc_errors::registry::Registry, 69 | ) -> Option<(Input, Option)> { 70 | self.default 71 | .no_input(matches, sopts, cfg, odir, ofile, descriptions) 72 | } 73 | 74 | fn late_callback( 75 | &mut self, 76 | trans_crate: &TransCrate, 77 | matches: &getopts::Matches, 78 | sess: &Session, 79 | crate_stores: &rustc::middle::cstore::CrateStore, 80 | input: &Input, 81 | odir: &Option, 82 | ofile: &Option, 83 | ) -> Compilation { 84 | self.default 85 | .late_callback(trans_crate, matches, sess, crate_stores, input, odir, ofile) 86 | } 87 | 88 | fn build_controller(&mut self, sess: &Session, matches: &getopts::Matches) -> driver::CompileController<'a> { 89 | let mut controller = self.default.build_controller(sess, matches); 90 | 91 | // Extend rustc default driver, with the extra pass provided by the 92 | // holyjit driver. This extra pass is registered at the end of the 93 | // optimization made on the Mir, such that we have a desugared version 94 | // of Rust before it goes into the trans phase. 95 | if self.add_jit { 96 | // nbp-note: controller.provide_extern = ? 97 | // https://github.com/rust-lang/rust/blob/1670a532dd769763f1d6ad9e5d624ec31361a098/src/librustc_driver/driver.rs#L1003 98 | 99 | // https://github.com/rust-lang/rust/blob/1670a532dd769763f1d6ad9e5d624ec31361a098/src/librustc_driver/driver.rs#L328 100 | // 101 | // controller.provide = box |providers| providers.optimized_mir = |tcx, def_id| { let mut mir = transform::optimized_mir(tcx, def_id).clone(); /* mutate mir */ tcx.alloc_mir(mir) }; 102 | 103 | 104 | // instead of transform::optimized_mir... 105 | // let mut p = ty::maps::Providers::default(); driver::default_provide(&mut p); (p.optimized_mir)(tcx, def_id) 106 | let old_provide = std::mem::replace(&mut controller.provide, box |_| {}); 107 | controller.provide = box (move |providers| { 108 | old_provide(providers); 109 | // Note: this erases the default one, but we re-create the 110 | // default Provider within optimized_mir function in order to 111 | // execute all other optimization passes. 112 | *providers = Providers { 113 | optimized_mir, 114 | ..*providers 115 | }; 116 | }); 117 | } 118 | 119 | controller 120 | } 121 | } 122 | 123 | fn optimized_mir<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx Mir<'tcx> { 124 | let mut p = Providers::default(); 125 | driver::default_provide(&mut p); 126 | let optmir = p.optimized_mir; 127 | let mut mir = optmir(tcx, def_id).clone(); 128 | // TODO 129 | run_passes![tcx, mir, def_id, 3; 130 | holyjit_plugin::AttachFnGraphOnCst, 131 | ]; 132 | tcx.alloc_mir(mir) 133 | } 134 | 135 | fn extract_sysroot() -> String { 136 | // If we attempt to compile without a sysroot, then the core library would 137 | // not be found which would prevent the compilation of some crates. This 138 | // code is a work-around which either relies on the environment variables, 139 | // or on the original rustc compiler to extra the sysroot path. 140 | option_env!("SYSROOT") 141 | .map(String::from) 142 | .or_else(|| env::var("SYSROOT").ok()) 143 | .or_else(|| { 144 | let home = option_env!("RUSTUP_HOME").or(option_env!("MULTIRUST_HOME")); 145 | let toolchain = option_env!("RUSTUP_TOOLCHAIN").or(option_env!("MULTIRUST_TOOLCHAIN")); 146 | home.and_then(|home| toolchain.map(|toolchain| format!("{}/toolchains/{}", home, toolchain))) 147 | }) 148 | .or_else(|| { 149 | Command::new("rustc") 150 | .arg("--print") 151 | .arg("sysroot") 152 | .output() 153 | .ok() 154 | .and_then(|out| String::from_utf8(out.stdout).ok()) 155 | .map(|s| s.trim().to_owned()) 156 | }) 157 | .expect("need to specify SYSROOT env var during holyjit compilation, or use rustup or multirust") 158 | } 159 | 160 | pub fn main() { 161 | let mut args: Vec = env::args().collect(); 162 | 163 | 164 | // Setting RUSTC_WRAPPER causes Cargo to pass 'rustc' as the first argument. 165 | // We're invoking the compiler programmatically, so we ignore this. 166 | if args.len() <= 1 { 167 | std::process::exit(1); 168 | } 169 | if args[1] == "rustc" { 170 | // we still want to be able to invoke it normally though 171 | args.remove(1); 172 | } 173 | 174 | let args = if args.iter().any(|s| s == "--sysroot") { 175 | // User provides the --sysroot on the command line. 176 | args 177 | } else { 178 | // HolyJit provide the --sysroot from the environment or extracted from 179 | // rustc. 180 | args.into_iter() 181 | .chain(Some("--sysroot".to_owned())) 182 | .chain(Some(extract_sysroot())) 183 | .collect() 184 | }; 185 | 186 | let holyjit_enabled = true; 187 | let mut holyjit_cc = HolyJitCompilerCalls::new(holyjit_enabled); 188 | rustc_driver::run(move || { 189 | rustc_driver::run_compiler(&args, &mut holyjit_cc, None, None) 190 | }); 191 | } 192 | -------------------------------------------------------------------------------- /default.nix: -------------------------------------------------------------------------------- 1 | { stdenv, rust }: 2 | 3 | stdenv.mkDerivation rec { 4 | version = "0.0.0"; 5 | name = "holyjit-${version}"; 6 | buildInputs = [ rust ]; 7 | shellHook = " 8 | export RUSTC_WRAPPER=$PWD/rustc.sh 9 | export RUST_BACKTRACE=1 10 | "; 11 | } -------------------------------------------------------------------------------- /examples/brainfuck.rs: -------------------------------------------------------------------------------- 1 | #![feature(custom_attribute)] 2 | #![feature(unboxed_closures)] 3 | #[macro_use] extern crate holyjit_lib as hj; 4 | 5 | jit!{ fn eval(jc: hj::JitContext, program: String) -> Result<(), ()> = eval_impl in jc; } 6 | fn eval_impl(_jc: hj::JitContext, program: String) -> Result<(), ()> { 7 | let prog = program.as_bytes(); 8 | let mut pc : usize = 0; 9 | let mut ptr : usize = 0; 10 | let mut mem : Vec = Vec::with_capacity(256); 11 | mem.resize(256, 0); 12 | loop { 13 | if pc >= prog.len() { 14 | return Ok(()); 15 | } 16 | match prog[pc] { 17 | b'>' => { 18 | ptr += 1; 19 | if ptr >= mem.len() { 20 | mem.push(0); 21 | } 22 | } 23 | b'<' => { ptr = ptr.saturating_sub(1); } 24 | b'-' => { mem[ptr] = mem[ptr].wrapping_sub(1); } 25 | b'+' => { mem[ptr] = mem[ptr].wrapping_add(1); } 26 | b'.' => { panic!("putchar: NYI"); } 27 | b',' => { panic!("getchar: NYI"); } 28 | b'[' => { 29 | if mem[ptr] == 0 { 30 | let mut iter = (pc + 1, 0); 31 | loop { 32 | iter = match (iter, prog[iter.0]) { 33 | ((p, 0), b']') => { 34 | pc = p + 1; 35 | break; 36 | }, 37 | ((p, d), b'[') => (p + 1, d + 1), 38 | ((p, d), b']') => (p + 1, d - 1), 39 | ((p, d), _) => (p + 1, d) 40 | } 41 | } 42 | continue; // skip pc increment 43 | } 44 | } 45 | b']' => { 46 | let mut iter = (pc - 1, 0); 47 | loop { 48 | iter = match (iter, prog[iter.0]) { 49 | ((p, 0), b'[') => { 50 | pc = p; 51 | break; 52 | }, 53 | ((p, d), b'[') => (p - 1, d + 1), 54 | ((p, d), b']') => (p - 1, d - 1), 55 | ((p, d), _) => (p - 1, d) 56 | } 57 | } 58 | continue; // skip pc increment 59 | } 60 | _ => { panic!("Unknown Symbol"); } 61 | } 62 | pc += 1; 63 | } 64 | } 65 | 66 | fn main() { 67 | let prog = "++"; 68 | // Run without the Jit. 69 | let jc : hj::JitContext = Default::default(); 70 | eval_impl(jc, prog.into()).unwrap(); 71 | // Run with the Jit. 72 | let jc : hj::JitContext = Default::default(); 73 | eval(jc, prog.into()).unwrap(); 74 | } 75 | -------------------------------------------------------------------------------- /lib/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "holyjit_lib" 3 | version = "0.0.0" 4 | authors = [ "Nicolas B. Pierron " ] 5 | 6 | # Lock dynasm and serde_derive in order to build against old versions of 7 | # rustc. 8 | [dependencies] 9 | dynasm = "=0.1.3" 10 | dynasmrt = "=0.1.3" 11 | serde = "1.0" 12 | serde_derive = "=1.0.12" 13 | bincode = "0.8" 14 | 15 | [lib] 16 | name = "holyjit_lib" 17 | path = "src/lib.rs" 18 | 19 | -------------------------------------------------------------------------------- /lib/src/context.rs: -------------------------------------------------------------------------------- 1 | /// A context contains a way to map a vector to its jit-compiled counter 2 | /// part. It provides an interface for tuning the JIT compiler parameters 3 | /// as well as the heuristics for enterring the JIT. 4 | 5 | use compile::JitCode; 6 | use std::rc::Rc; 7 | 8 | /// Opaque structure which is used to store the function mapping, and tune 9 | /// the JIT parameters. 10 | pub struct JitContext { 11 | code: Option> 12 | } 13 | 14 | impl JitContext { 15 | pub fn lookup(&self, bytes: &[u8], defs: *const ()) -> Option> { 16 | match &self.code { 17 | &Some(ref jit) => { 18 | println!("Found JIT Code in the context"); 19 | Some(jit.clone()) 20 | } 21 | &None => { 22 | println!("Did not found JIT Code in the context.\nStart compiling ..."); 23 | match JitCode::compile(bytes, defs) { 24 | Ok(jit) => { 25 | let jit = Rc::new(jit); 26 | // TODO: Store the Jit code on the context. 27 | // self.code = Some(jit); 28 | Some(jit) 29 | } 30 | Err(e) => { 31 | println!("JIT Compiler Error: {:?}", e); 32 | None 33 | } 34 | } 35 | } 36 | } 37 | } 38 | } 39 | 40 | impl Default for JitContext { 41 | fn default() -> JitContext { 42 | JitContext{ code: None } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /lib/src/lib.rs: -------------------------------------------------------------------------------- 1 | // TODO: Use #![feature(fn_traits)] once this accepted in the compiler, as 2 | // this would allow to move the call in an Fn trait for the 3 | // ExecutableMemory, making it callable. 4 | 5 | #![feature(associated_type_defaults)] // Used for adding a type Output to HolyJitFn 6 | #![feature(unboxed_closures)] 7 | #![feature(fn_traits)] 8 | 9 | // For dynasm plugin. 10 | #![feature(plugin)] 11 | #![plugin(dynasm)] 12 | 13 | pub use std::marker::PhantomData; 14 | use std::rc::Rc; 15 | 16 | // dynasm is "currently" used by the compiler as a way to generate code 17 | // without the burden of implementing yet another macro-assembler. 18 | #[macro_use] 19 | extern crate dynasmrt; 20 | 21 | // Serde is used for serializing and deserializing the LIR which is stored 22 | // by the plugin in a constant, and deserialized by the JIT compiler in 23 | // order to be manipulated. 24 | #[macro_use] 25 | extern crate serde_derive; 26 | extern crate serde; 27 | extern crate bincode; 28 | 29 | pub mod lir; 30 | mod context; 31 | mod compile; 32 | 33 | pub use context::JitContext; 34 | pub use compile::JitCode; 35 | 36 | /// This trait should be implemented by every function that we want to be able to Jit. This trait 37 | /// implements the Fn trait to make this function callable, and to make it a potential entry point 38 | /// for the Jit. When functions from this class are called, HolyJit will decided whether it should 39 | /// be called or inlined. When a caller of such function is Jitted, the Jit compiler would be able 40 | /// to decide whether it might be interesting to call or inline this function in the Jitted code. 41 | /// 42 | /// The structure which are implementing the hj_call function, with the macro named [TODO] would be 43 | /// used as a place-holder space for being populated by the HolyJit plugin. If the plugin is not 44 | /// used, then the program should still work as-is but the Jit would be disabled. 45 | 46 | /// CurryN types are made to wrap the native function pointer and provide 47 | /// a FnOnce, FnMut, and Fn traits implementation. 48 | pub enum Curry0 { 49 | Native(fn() -> Output), 50 | // Use an Rc in order to ensure that the JitCode is kept alive as long 51 | // as the function is running on the stack. 52 | Jit(Rc) 53 | } 54 | impl FnOnce<()> for Curry0 { 55 | type Output = Output; 56 | extern "rust-call" fn call_once(self, _: ()) -> Output { 57 | match self { 58 | Curry0::Native(fun) => fun(), 59 | Curry0::Jit(jit) => { 60 | let fun : fn() -> Output = unsafe { 61 | std::mem::transmute(jit.get_fn()) 62 | }; 63 | fun() 64 | } 65 | } 66 | } 67 | } 68 | impl FnMut<()> for Curry0 { 69 | extern "rust-call" fn call_mut(&mut self, _: ()) -> Output { 70 | match self { 71 | &mut Curry0::Native(ref mut fun) => fun(), 72 | &mut Curry0::Jit(ref mut jit) => { 73 | let fun : fn() -> Output = unsafe { 74 | std::mem::transmute(jit.get_fn()) 75 | }; 76 | fun() 77 | } 78 | } 79 | } 80 | } 81 | impl Fn<()> for Curry0 { 82 | extern "rust-call" fn call(&self, _: ()) -> Output { 83 | match self { 84 | &Curry0::Native(ref fun) => fun(), 85 | &Curry0::Jit(ref jit) => { 86 | let fun : fn() -> Output = unsafe { 87 | std::mem::transmute(jit.get_fn()) 88 | }; 89 | fun() 90 | } 91 | } 92 | } 93 | } 94 | 95 | macro_rules! curry_call { 96 | ($fun:expr => $arg:ident : ($a0:ty)) => { $fun($arg.0) }; 97 | ($fun:expr => $arg:ident : ($a0:ty,$a1:ty)) => { $fun($arg.0,$arg.1) }; 98 | ($fun:expr => $arg:ident : ($a0:ty,$a1:ty,$a2:ty)) => { $fun($arg.0,$arg.1,$arg.2) }; 99 | ($fun:expr => $arg:ident : ($a0:ty,$a1:ty,$a2:ty,$a3:ty)) => { $fun($arg.0,$arg.1,$arg.2,$arg.3) }; 100 | } 101 | 102 | #[macro_export] 103 | macro_rules! fn_ty { 104 | () => { () }; 105 | ($a0:ty) => { ($a0,) }; 106 | ($a0:ty,$($as:ty),*) => { ($a0,$($as),*) }; 107 | } 108 | 109 | macro_rules! curry_decl { 110 | ($name:ident<($($arg:ident),*) -> $ret:ident>) => { 111 | pub enum $name<$($arg,)* $ret> { 112 | Native(fn($($arg),*) -> $ret), 113 | Jit(Rc) 114 | } 115 | impl<$($arg,)* $ret> FnOnce for $name<$($arg,)* $ret> { 116 | type Output = $ret; 117 | extern "rust-call" fn call_once(self, args: fn_ty!{$($arg),*}) -> $ret { 118 | match self { 119 | $name::Native(fun) => curry_call!{ fun => args: ($($arg),*) }, 120 | $name::Jit(jit) => { 121 | let fun : fn($($arg),*) -> $ret = unsafe { 122 | std::mem::transmute(jit.get_fn()) 123 | }; 124 | curry_call!{ fun => args: ($($arg),*) } 125 | } 126 | } 127 | } 128 | } 129 | impl<$($arg,)* $ret> FnMut for $name<$($arg,)* $ret> { 130 | extern "rust-call" fn call_mut(&mut self, args: fn_ty!{$($arg),*}) -> $ret { 131 | match self { 132 | &mut $name::Native(ref mut fun) => curry_call!{ fun => args: ($($arg),*) }, 133 | &mut $name::Jit(ref mut jit) => { 134 | let fun : fn($($arg),*) -> $ret = unsafe { 135 | std::mem::transmute(jit.get_fn()) 136 | }; 137 | curry_call!{ fun => args: ($($arg),*) } 138 | } 139 | } 140 | } 141 | } 142 | impl<$($arg,)* $ret> Fn for $name<$($arg,)* $ret> { 143 | extern "rust-call" fn call(&self, args: fn_ty!{$($arg),*}) -> $ret { 144 | match self { 145 | &$name::Native(ref fun) => curry_call!{ fun => args: ($($arg),*) }, 146 | &$name::Jit(ref jit) => { 147 | let fun : fn($($arg),*) -> $ret = unsafe { 148 | std::mem::transmute(jit.get_fn()) 149 | }; 150 | curry_call!{ fun => args: ($($arg),*) } 151 | } 152 | } 153 | } 154 | } 155 | } 156 | } 157 | 158 | curry_decl!{ Curry1<(A0) -> Output> } 159 | curry_decl!{ Curry2<(A0,A1) -> Output> } 160 | curry_decl!{ Curry3<(A0,A1,A2) -> Output> } 161 | curry_decl!{ Curry4<(A0,A1,A2,A3) -> Output> } 162 | 163 | /// This trait defines get_fn function which is used to select which 164 | /// function is going to be executed. Based on various criteria, such as 165 | /// the number of hit-counts, this function will select either the function 166 | /// statically compiled by rustc, or the result of the compilation performed 167 | /// by HolyJit. 168 | pub trait HolyJitFn { 169 | type Curry; 170 | type Output; 171 | fn get_fn(&self) -> Self::Curry; 172 | fn from_code(jit: Rc) -> Self::Curry where Self : Sized; 173 | fn get_jc<'a>(&self, args: &'a Args) -> &'a JitContext; 174 | } 175 | 176 | /// Structure made for wrapping both the function pointer and the serialized 177 | /// bytes of the LIR graph. The first parameter defines the tuple of 178 | /// arguments type, and the second parameter defines Output of the function. 179 | /// The last parameter T corresponds to the structure which is wrapping the 180 | /// function pointer. This structure should implement the HolyJitFn trait. 181 | pub struct HolyJitFnWrapper 182 | where T : HolyJitFn 183 | { 184 | /// Reference to the statically compiled function. 185 | pub fun: T, 186 | 187 | /// Serialized LIR graph, of the statically compiled function. 188 | pub bytes: &'static [u8], 189 | 190 | /// Statically compiled function might contain references to other 191 | /// symbols. At the time of the plugin compilation, we do not know what 192 | /// these symbols addresses would be, as they would be decided by LLVM 193 | /// assembler, and the dynamic-linker. 194 | /// 195 | /// To carry this information, we use a tuple, as not all symbols have 196 | /// the same type. Moreover, there is no single cast target possible for 197 | /// all. The previous vector of bytes, thus know how to interpret the 198 | /// content of this pointer. 199 | pub defs: *const (), 200 | 201 | // Keep track of the types. 202 | pub _proto: PhantomData> 203 | } 204 | 205 | impl HolyJitFnWrapper 206 | where T : HolyJitFn 207 | { 208 | /// Given a list of argument, extract a JitContext from it, and look for 209 | /// existing compiled code. Otherwise, either return the static 210 | /// function, or the newly JIT compiled function. 211 | fn select_fn<'ctx>(&'ctx self, args: &Args) -> Curry { 212 | let jc = self.fun.get_jc(args); 213 | match jc.lookup(self.bytes, self.defs) { 214 | Some(code) => T::from_code(code), 215 | None => self.fun.get_fn() 216 | } 217 | } 218 | } 219 | 220 | impl FnOnce 221 | for HolyJitFnWrapper 222 | where T : HolyJitFn, 223 | Curry : FnOnce 224 | { 225 | type Output = Output; 226 | extern "rust-call" fn call_once(self, args: Args) -> Self::Output { 227 | let f = { 228 | let ra = &args; 229 | self.select_fn(ra) 230 | }; 231 | f.call_once(args) 232 | } 233 | } 234 | impl> FnMut 235 | for HolyJitFnWrapper 236 | where T : HolyJitFn, 237 | Curry : FnMut 238 | { 239 | extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output { 240 | let mut f = { 241 | let ra = &args; 242 | self.select_fn(ra) 243 | }; 244 | f.call_mut(args) 245 | } 246 | } 247 | impl> Fn 248 | for HolyJitFnWrapper 249 | where T : HolyJitFn, 250 | Curry : Fn 251 | { 252 | extern "rust-call" fn call(&self, args: Args) -> Self::Output { 253 | let f = { 254 | let ra = &args; 255 | self.select_fn(ra) 256 | }; 257 | f.call(args) 258 | } 259 | } 260 | 261 | #[macro_export] 262 | macro_rules! curry { 263 | (() -> $ret_type:ty) => { $crate::Curry0<$ret_type> }; 264 | (($a0:ty) -> $ret_type:ty) => { $crate::Curry1<$a0,$ret_type> }; 265 | (($a0:ty,$a1:ty) -> $ret_type:ty) => { $crate::Curry2<$a0,$a1,$ret_type> }; 266 | (($a0:ty,$a1:ty,$a2:ty) -> $ret_type:ty) => { $crate::Curry3<$a0,$a1,$a2,$ret_type> }; 267 | (($a0:ty,$a1:ty,$a2:ty,$a3:ty) -> $ret_type:ty) => { $crate::Curry4<$a0,$a1,$a2,$a3,$ret_type> }; 268 | 269 | (() -> $ret_type:ty = $e:ident ) => { $crate::Curry0::Native( $e ) }; 270 | (($a0:ty) -> $ret_type:ty = $e:ident ) => { $crate::Curry1::Native( $e ) }; 271 | (($a0:ty,$a1:ty) -> $ret_type:ty = $e:ident ) => { $crate::Curry2::Native( $e ) }; 272 | (($a0:ty,$a1:ty,$a2:ty) -> $ret_type:ty = $e:ident ) => { $crate::Curry3::Native( $e ) }; 273 | (($a0:ty,$a1:ty,$a2:ty,$a3:ty) -> $ret_type:ty = $e:ident ) => { $crate::Curry4::Native( $e ) }; 274 | 275 | (() -> $ret_type:ty = < $e:ident > ) => { $crate::Curry0::Jit( $e ) }; 276 | (($a0:ty) -> $ret_type:ty = < $e:ident > ) => { $crate::Curry1::Jit( $e ) }; 277 | (($a0:ty,$a1:ty) -> $ret_type:ty = < $e:ident > ) => { $crate::Curry2::Jit( $e ) }; 278 | (($a0:ty,$a1:ty,$a2:ty) -> $ret_type:ty = < $e:ident > ) => { $crate::Curry3::Jit( $e ) }; 279 | (($a0:ty,$a1:ty,$a2:ty,$a3:ty) -> $ret_type:ty = < $e:ident > ) => { $crate::Curry4::Jit( $e ) }; 280 | } 281 | 282 | #[macro_export] 283 | macro_rules! match_ref_args { 284 | () => { () }; 285 | ($a0:ident) => { (ref $a0,) }; 286 | ($a0:ident,$($as:ident),*) => { (ref $a0,$(ref $as),*) }; 287 | } 288 | 289 | // TODO: Add support arguments, and their types: $($arg_name:ident: $arg_type:ty),* ? 290 | 291 | /// The jit! macro is used to define function which is compiled statically 292 | /// and which can be compiled dynamically too. This function definitions 293 | /// aliases an existing function definition which has an identical 294 | /// signature. 295 | #[macro_export] 296 | macro_rules! jit { 297 | (fn $fun:ident ($($arg:ident: $typ:ty),*) -> $ret_type:ty = $delegate:ident 298 | in $jc:expr ; 299 | ) => { 300 | // WARNING: The $fun identifier is used both for the struct name, 301 | // which holds the graph representation of the $delegate function, 302 | // and for the constant of type HolyJitFnWrapper. As there is no 303 | // proper way to generate new identifier, we use this aliasing 304 | // technique to avoid conflicting hard-coded names. 305 | #[allow(non_upper_case_globals)] 306 | const $fun : $crate::HolyJitFnWrapper $ret_type }, $fun> = $crate::HolyJitFnWrapper{ 307 | fun : $fun{ curry: curry!{ ($($typ),*) -> $ret_type = $delegate } }, 308 | bytes : &[ 0 /* placeholder for holyjit plugin */ ], 309 | defs : &(1u8, 2u8) as *const _ as *const (), 310 | _proto: $crate::PhantomData, 311 | }; 312 | #[allow(non_camel_case_types)] 313 | struct $fun { curry: curry!{ ($($typ),*) -> $ret_type } } 314 | impl $crate::HolyJitFn for $fun { 315 | type Curry = curry!{ ($($typ),*) -> $ret_type }; 316 | type Output = $ret_type; 317 | fn get_fn(&self) -> Self::Curry { 318 | // Return the statically compiled function. 319 | if let curry!{ ($($typ),*) -> $ret_type = fun } = self.curry { 320 | curry!{ ($($typ),*) -> $ret_type = fun } 321 | } else { 322 | panic!("The impossible happened!") 323 | } 324 | } 325 | fn from_code(jit: std::rc::Rc<$crate::JitCode>) -> Self::Curry { 326 | // Return the dynamically compiled function. 327 | curry!{($($typ),*) -> $ret_type = < jit > } 328 | } 329 | fn get_jc<'a>(&self, args: &'a fn_ty!{$($typ),*}) -> &'a $crate::JitContext { 330 | // Use a match statement to fake the arguments bindings of 331 | // the function. 332 | #[allow(unused_variables)] 333 | match args { 334 | &match_ref_args!{$($arg),*} => $jc 335 | } 336 | } 337 | } 338 | } 339 | } 340 | 341 | #[cfg(test)] 342 | mod tests { 343 | use super::*; 344 | 345 | // Add wrappers for the test functions, and check that we can call them 346 | // without any syntax overhead. Check that we can use a function to get 347 | // the JitContext from a global. 348 | jit!{ fn test0() -> i32 = test0_impl in global_jc(); } 349 | fn test0_impl() -> i32 { 42 } 350 | 351 | jit!{ fn test1(x: i32) -> i32 = test1_impl in global_jc(); } 352 | fn test1_impl(x: i32) -> i32 { x } 353 | 354 | jit!{ fn test2(x: i32, y: i32) -> i32 = test2_impl in global_jc(); } 355 | fn test2_impl(x: i32, y: i32) -> i32 { x + y } 356 | 357 | // Check that we can use one of the argument to extract a JitContext. 358 | jit!{ fn test3(jc: JitContext, x: i32, y: i32) -> i32 = test3_impl in jc; } 359 | fn test3_impl(_jc: JitContext, x: i32, y: i32) -> i32 { 360 | x + y 361 | } 362 | 363 | static mut JC: Option<*const JitContext> = None; 364 | fn global_jc() -> &'static JitContext { 365 | // Good enough for a test case? 366 | unsafe { 367 | if JC == None { 368 | let jc : Box = Box::new(Default::default()); 369 | JC = Some(std::mem::transmute(jc)); 370 | }; 371 | std::mem::transmute(JC.unwrap()) 372 | } 373 | } 374 | 375 | #[test] 376 | fn check_transparent_wrappers() { 377 | assert_eq!(test0(), 42); 378 | assert_eq!(test1(51), 51); 379 | assert_eq!(test2(21, 21), 42); 380 | let jc : JitContext = Default::default(); 381 | assert_eq!(test3(jc, 21, 21), 42); 382 | } 383 | } 384 | -------------------------------------------------------------------------------- /lib/src/lir.rs: -------------------------------------------------------------------------------- 1 | //! Defines the LIR structures and how to represent a graph and its 2 | //! instructions. 3 | use std::fmt; 4 | 5 | /// Prototype of the Mir graph of a single function. This representation is 6 | /// not optimized for graph optimizations, but optimized only for the ease 7 | /// of convertion from the MIR and the ease of naive compilation. 8 | #[derive(Serialize, Deserialize, Debug)] 9 | pub struct CompilationUnit { 10 | /// Size of all local variable of the Mir. 11 | pub stack_size: usize, 12 | 13 | /// Ordered list of arguments, with their associated registers. 14 | pub args_defs: Vec, 15 | 16 | /// List of basic blocks of a given function. 17 | pub blocks: Vec, 18 | } 19 | 20 | /// (Prototype) Set of instruction within a block. 21 | pub type BasicBlock = usize; 22 | 23 | /// Basic block which contains a list of instructions. 24 | #[derive(Serialize, Deserialize, Debug)] 25 | pub struct BasicBlockData { 26 | /// Ordered list of registers available in this basic block. 27 | // 28 | // Note: We should probably look at encoding these lists of registers as 29 | // spagheti stacks, such that we do not over-consume memory, by storing 30 | // this information. 31 | pub input_regs: Vec, 32 | /// Ordered list of registers available after this basic block. 33 | pub output_regs: Vec, 34 | /// Ordered list of instructions. 35 | pub insts: Vec, 36 | /// How the basic block ends. 37 | pub end: Terminator, 38 | } 39 | 40 | /// Basic block terminator instruction, which resume the execution in 41 | /// another basic block. 42 | #[derive(Serialize, Deserialize, Debug)] 43 | pub enum Terminator { 44 | /// Exit successfully the current function. 45 | Return { 46 | value: Option, 47 | }, 48 | 49 | /// Unwind the current function. 50 | Unwind, 51 | 52 | /// Trap. 53 | Unreachable, 54 | 55 | /// Jump unconditionally to the next basic block. 56 | Goto { 57 | target: BasicBlock, 58 | }, 59 | 60 | /// Conditional branches, implemented as a switch case to handle all 61 | /// forms of conditionals. 62 | SwitchInt { 63 | value: Reg, 64 | range: RangeInclusive, 65 | targets: Vec<(Imm, BasicBlock)>, 66 | otherwise: Option, 67 | }, 68 | 69 | /// Call a function. (any function, or an assertion, or a drop function) 70 | Call { 71 | /// Pointer to a given function. 72 | function: Reg, 73 | 74 | // TODO: Add a reference of the ABI we are compiling this call with. 75 | 76 | /// Set of argument to be used for calling the function. 77 | args: Vec, 78 | 79 | /// If the function returns, then the following register would be 80 | /// defined in the block, and listed in the output_regs of the 81 | /// current block, and the inputs-regs of the listed block. 82 | return_target: Option<(Option, BasicBlock)>, 83 | 84 | /// If the function unwinds then the unwinding resumes in the 85 | /// following block., 86 | unwind_target: Option 87 | } 88 | } 89 | 90 | pub type Sz = usize; 91 | pub type Reg = usize; 92 | pub type Imm = isize; 93 | pub type ByValue = bool; 94 | pub type ArgDef = (Imm, Sz, ByValue); 95 | pub type RegDef = (Reg, Sz); 96 | pub type RangeInclusive = (Imm, Imm); 97 | 98 | /// (Prototype) Minimal set of instructions to support the MIR graph of 99 | /// Rust for the examples directory. 100 | #[derive(Serialize, Deserialize, Debug)] 101 | pub enum Inst { 102 | // Initialize the frame pointer. 103 | SetFramePtr(Reg, Sz, Sz), 104 | 105 | // Copy the address of a static value in a register. 106 | Static(Reg, Imm, Sz), 107 | 108 | // Copy a constant into a register. 109 | CopyImm(Reg, Imm, Sz), 110 | 111 | // Cast operator for dummies. 112 | Resize(Reg, Reg, Sz), 113 | 114 | // Logical & Math operations. 115 | Add(Reg, Reg, Reg), 116 | Sub(Reg, Reg, Reg), 117 | Mul(Reg, Reg, Reg), 118 | Div(Reg, Reg, Reg), 119 | Rem(Reg, Reg, Reg), 120 | BitXor(Reg, Reg, Reg), 121 | BitAnd(Reg, Reg, Reg), 122 | BitOr(Reg, Reg, Reg), 123 | Shl(Reg, Reg, Reg), 124 | Shr(Reg, Reg, Reg), 125 | Eq(Reg, Reg, Reg), 126 | Lt(Reg, Reg, Reg), 127 | Le(Reg, Reg, Reg), 128 | Ne(Reg, Reg, Reg), 129 | Gt(Reg, Reg, Reg), 130 | Ge(Reg, Reg, Reg), 131 | 132 | // Convert an operation result into a checked operation result, i-e add 133 | // a boolean size value to the register size. 134 | Chk(Reg, Reg), 135 | 136 | // Store at the address, the register value. 137 | Store(Reg, Reg, Sz), 138 | 139 | // Load into the register, from the address. 140 | Load(Reg, Reg, Sz), 141 | 142 | // Note: These 2 instructions are based on the infinite size registers, 143 | // and are made to represent structures which are held in 144 | // registers. This is a useful trick for generating code from Rust's 145 | // Mir, but also a useful trick to represent owned memory. 146 | 147 | // Initialize the content of a register with the the content of a 148 | // smaller one at an offset of the first. 149 | StoreInto(Reg, Reg, /* offset */ Sz, /* size */ Sz), 150 | 151 | // Load from a register at a given offset, and a given size within the 152 | // register the value to be output in the first register. 153 | LoadFrom(Reg, Reg, /* offset */ Sz, /* size */ Sz), 154 | 155 | // Reserve, or kill a register allocation. 156 | // Note: Live is useless in case of SSA forms. 157 | Live(Reg), Dead(Reg), 158 | } 159 | 160 | /// Display a Compilation unit with some hard-coded indentation level. 161 | impl fmt::Display for CompilationUnit { 162 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 163 | write!(f, "CompilationUnit {{\n")?; 164 | write!(f, " stack_size: {:?},\n", self.stack_size)?; 165 | write!(f, " args_defs: {:?},\n", self.args_defs)?; 166 | write!(f, " blocks: [\n")?; 167 | for (x, b) in self.blocks.iter().enumerate() { 168 | write!(f, " [{}] = {},\n", x, b)?; 169 | } 170 | write!(f, " ],\n")?; 171 | write!(f, "}}") 172 | } 173 | } 174 | 175 | /// Display a BasicBlockData unit with some hard-coded indentation level. 176 | impl fmt::Display for BasicBlockData { 177 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 178 | write!(f, "BasicBlockData {{\n")?; 179 | write!(f, " input_regs: {:?},\n", self.input_regs)?; 180 | write!(f, " insts: [\n")?; 181 | for ins in &self.insts { 182 | write!(f, " {:?},\n", ins)?; 183 | } 184 | write!(f, " ],\n")?; 185 | write!(f, " end: {:?},\n", self.end)?; 186 | write!(f, " output_regs: {:?},\n", self.output_regs)?; 187 | write!(f, " }}") 188 | } 189 | } 190 | -------------------------------------------------------------------------------- /plugin/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "holyjit_plugin" 3 | version = "0.0.0" 4 | authors = [ "Nicolas B. Pierron " ] 5 | 6 | [dependencies] 7 | holyjit_lib = { path = "../lib" } 8 | serde = "1.0" 9 | bincode = "0.8" 10 | 11 | [lib] 12 | name = "holyjit_plugin" 13 | path = "src/lib.rs" 14 | plugin = true 15 | -------------------------------------------------------------------------------- /plugin/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![crate_type="dylib"] 2 | #![feature(plugin_registrar, rustc_private)] 3 | 4 | // extern crate syntax; 5 | extern crate rustc; 6 | extern crate rustc_mir; 7 | // extern crate rustc_typeck; 8 | extern crate rustc_data_structures; 9 | extern crate rustc_const_math; 10 | extern crate syntax_pos; 11 | 12 | use rustc_mir::transform::{MirPass, MirSource}; 13 | use rustc::mir::{Mir, self}; 14 | // use rustc::mir::visit::MutVisitor; 15 | use rustc::ty::{self, TyCtxt}; 16 | use rustc::middle::const_val::ConstVal; 17 | use rustc_const_math::ConstInt; 18 | use rustc::hir::def_id::DefId; 19 | use rustc::hir; 20 | 21 | // Used to express the Mir into the Lir used for the Jit compilation. 22 | extern crate holyjit_lib; 23 | 24 | // Used to serialize the lir provided in holyjit_lib. 25 | extern crate serde; 26 | extern crate bincode; 27 | 28 | mod trans; 29 | 30 | // This plugin works in 3 steps: 31 | // - Collect classes which are implementing a specific holyjit library trait, added by one of the 32 | // Macro of the holyjit library. From these pieces of code, find the location of the function 33 | // which have to be implemented. 34 | // - For all the previous functions, found in the previous phase, copy the MIR graph content, and 35 | // convert into a format readable by the holyjit library. 36 | // - For each converted MIR graph generated in the previous phase, add the cloned MIR graph in the 37 | // trait implementation which implement the given function. 38 | 39 | #[derive(Debug)] 40 | enum Error { 41 | /// The HolyJitFnWrapper constant defined by the jit! macro should use a 42 | /// CurryN structure to wrap a function pointer. This error is returned 43 | /// if we cannot find any local with this function pointer. 44 | NoLocalWithFnType, 45 | /// We found a local with the fn type, but we cannot find any assignment 46 | /// to it. 47 | NoLocalAssignment, 48 | /// We found the assignment to the local but not the expected cast 49 | /// operator. 50 | NoFnCast, 51 | /// We found a cast operator, but it does not contain a constant. 52 | NoCastConstOperand, 53 | /// We found a cast operator, but it does not contain a constant. 54 | NoLiteralOperand, 55 | /// We found a cast operator, but it does not contain a constant. 56 | NoFnConstLiteral, 57 | /// We found a cast operator, but it does not contain a constant. 58 | FunctionIsNotAvailable, 59 | 60 | /// We fail while converting the Mir into the Lir. 61 | UnableToConvert, 62 | 63 | /// While replacing the array types, we found an array with a bad 64 | /// length, which does not match what is introduced by the jit! macro. 65 | UnexpectedArrayLen, 66 | /// While replacing the array/tuple types, we expected to find a single 67 | /// local with the array type, instead of a reference to it. 68 | MultipleArrayDefinitions, 69 | MultipleTupleDefinitions, 70 | /// While replacing the array/tuple content, we did not found any local with 71 | /// the matching type. 72 | NoArrayDefinition, 73 | NoTupleDefinition, 74 | } 75 | 76 | impl From for Error { 77 | fn from(err: trans::Error) -> Error { 78 | println!("error: {:?}", err); 79 | // All errors are converted into this one. 80 | Error::UnableToConvert 81 | } 82 | } 83 | 84 | struct AttachJitGraph<'a, 'tcx: 'a> { 85 | tcx: TyCtxt<'a, 'tcx, 'tcx>, 86 | source: MirSource, 87 | } 88 | 89 | impl<'a, 'tcx> AttachJitGraph<'a, 'tcx> { 90 | /// Check if the Mir graph is a place where we expect to be storing a 91 | /// copy of the Mir graph to be used for the Jit. At the moment, 92 | /// placeholder are defined as constant instances of the 93 | /// HolyJitFnWrapper. 94 | fn is_placeholder(&self, mir: &mut Mir<'tcx>) -> bool { 95 | // Filter out any mir which does not define a constant. 96 | let id = self.tcx.hir.as_local_node_id(self.source.def_id).unwrap(); 97 | match self.tcx.hir.body_owner_kind(id) { 98 | hir::BodyOwnerKind ::Const => (), 99 | _ => return false 100 | }; 101 | 102 | // Check that the constant type is defined as being an 103 | // HolyJitFnWrapper, which is only supposed to be created by the 104 | // jit! macro. 105 | // 106 | // mir.return_ty == "holyjit::HolyJitFnWrapper<...>" 107 | match mir.return_ty().ty_adt_def() { 108 | Some(adt) => { 109 | let wrpr = self.tcx.def_key(adt.did).disambiguated_data.data; 110 | let wrpr = wrpr.get_opt_name().unwrap(); 111 | // println!("CollectFunctionsIndex: {}", wrpr); 112 | "HolyJitFnWrapper" == wrpr 113 | }, 114 | None => false 115 | } 116 | } 117 | 118 | /// Returns the definition identifier of the function which graph should 119 | /// be saved for Jit compilations. The placeholder should be wrap a 120 | /// reference to this function. 121 | /// 122 | /// If for some reasons we cannot find the definition identifer, then 123 | /// None is returned. 124 | fn wrapped_fn(&self, mir: &mut Mir<'tcx>) -> Result<(DefId, mir::SourceInfo), Error> { 125 | // Locate which local variable which has a "fn() -> " type. 126 | let mut fn_local : Option = None; 127 | for temp in mir.temps_iter() { 128 | if mir.local_decls[temp].ty.is_fn() { 129 | fn_local = Some(temp); 130 | break; 131 | } 132 | } 133 | let fn_local = match fn_local { 134 | Some(l) => l, 135 | None => return Err(Error::NoLocalWithFnType) 136 | }; 137 | // println!("local_decls: {:?};", fn_local); 138 | 139 | // Look for one assignment to the local which has the fn type. 140 | let mut fn_ref : Option<&mir::Rvalue> = None; 141 | let mut src_info : Option = None; 142 | 'search: for block in mir.basic_blocks().indices() { 143 | let data = &mir[block]; 144 | for statement in &data.statements { 145 | match *statement { 146 | mir::Statement { kind: mir::StatementKind::Assign( 147 | mir::Place::Local(assign_local), 148 | ref rvalue 149 | ), ref source_info} 150 | if assign_local == fn_local => { 151 | fn_ref = Some(rvalue); 152 | src_info = Some(source_info.clone()); 153 | break 'search; 154 | }, 155 | _ => {}, 156 | } 157 | } 158 | } 159 | 160 | // Deconstruct the rvalue and the expected cast operator 161 | let fn_ref = match fn_ref { 162 | Some(&mir::Rvalue::Cast(_, mir::Operand::Constant(ref op), _)) => op, 163 | Some(&mir::Rvalue::Cast(_, _, _)) => return Err(Error::NoCastConstOperand), 164 | Some(&_) => return Err(Error::NoFnCast), 165 | None => return Err(Error::NoLocalAssignment), 166 | }; 167 | 168 | // Deconstruct the operand of the cast operator to find the DefId of 169 | // the function. 170 | let fn_id = match fn_ref.literal { 171 | mir::Literal::Value { 172 | value: &ty::Const { val: ConstVal::Function(did, _), .. } 173 | } => did, 174 | mir::Literal::Value { .. } => return Err(Error::NoFnConstLiteral), 175 | _ => return Err(Error::NoLiteralOperand), 176 | }; 177 | 178 | if !self.tcx.is_mir_available(fn_id) { 179 | return Err(Error::FunctionIsNotAvailable) 180 | } 181 | 182 | Ok((fn_id, src_info.unwrap())) 183 | } 184 | 185 | /// This function convert the Mir of the wrapped function into a vector 186 | /// of serialized graph, which would be deserialized by the Jit library. 187 | fn serialize_mir(&self, fn_id: DefId, src_info: mir::SourceInfo, nb_promoted: usize) -> Result<(Vec, Vec>, Vec>), Error> { 188 | 189 | let fn_mir = ty::queries::optimized_mir::try_get(self.tcx, src_info.span, fn_id); 190 | let fn_mir = match fn_mir { 191 | Ok(ref callee_mir) => { 192 | // We are not supposed to have generics at the moment, thus 193 | // no need to carry a substitution list and substitute them 194 | // in the Mir of the function. 195 | // callee_mir.subst(self.tcx, callsite.substs) 196 | callee_mir 197 | } 198 | _ => return Err(Error::FunctionIsNotAvailable), 199 | }; 200 | 201 | let trans = trans::Transpiler::new(self.tcx, fn_id, nb_promoted); 202 | Ok(trans.convert(fn_mir)?) 203 | } 204 | 205 | /// The placeholder should have a constant array of u8, which is 206 | /// supposed to be binary serialization of the converted Mir graph. This 207 | /// function replaces the type of the locals to match the type of size 208 | /// of the vector, and copy the content of the vector on the Mir graph. 209 | fn replace_bytes(&self, mir: &mut Mir<'tcx>, bytes: Vec) -> Result<(), Error> { 210 | 211 | // This Loop ierates over all local types, and replace the [u8; 1] 212 | // and &[u8; 1] by [u8; x] and &[u8; x] where x corresponds to the 213 | // size of the encoded graph contains in bytes vector. 214 | // 215 | // This loop also collects the only local index with the array type 216 | // [u8; 1], in order to replace the its content with the content of 217 | // the bytes vector. 218 | let mut arr_local : Option = None; 219 | let locals : Vec<_> = mir.temps_iter().collect(); 220 | for idx in locals { 221 | let arr_ty = match mir.local_decls[idx].ty.sty { 222 | ty::TypeVariants::TyRef(ref region, ref tam) => { 223 | match tam.ty.sty { 224 | ty::TypeVariants::TyArray(t, l) if t == self.tcx.types.u8 => { 225 | if l.val.to_const_int().unwrap().to_u64().unwrap() != 1 { 226 | return Err(Error::UnexpectedArrayLen) 227 | } 228 | // TyArray(t, ..) 229 | let arr_ty = self.tcx.mk_array(t, bytes.len() as u64); 230 | let ref_ty = self.tcx.mk_ref(*region, ty::TypeAndMut{ 231 | ty: arr_ty, 232 | ..*tam 233 | }); 234 | Some(ref_ty) 235 | } 236 | _ => None, 237 | } 238 | }, 239 | ty::TypeVariants::TyArray(t, l) if t == self.tcx.types.u8 => { 240 | if l.val.to_const_int().unwrap().to_u64().unwrap() != 1 { 241 | return Err(Error::UnexpectedArrayLen) 242 | } 243 | if arr_local != None { 244 | return Err(Error::MultipleArrayDefinitions) 245 | } 246 | arr_local = Some(idx); 247 | let arr_ty = self.tcx.mk_array(t, bytes.len() as u64); 248 | Some(arr_ty) 249 | }, 250 | _ => None, 251 | }; 252 | 253 | if let Some(arr_ty) = arr_ty { 254 | mir.local_decls[idx].ty = arr_ty; 255 | } 256 | } 257 | 258 | let arr_local = match arr_local { 259 | Some(l) => l, 260 | None => return Err(Error::NoArrayDefinition) 261 | }; 262 | 263 | // Create operands for each element of the vector. 264 | let mk_literal = |i| mir::Literal::Value{ 265 | value: self.tcx.mk_const(ty::Const { 266 | val: ConstVal::Integral(ConstInt::U8(i)), 267 | ty: self.tcx.types.u8 268 | }) 269 | }; 270 | let mk_operand = |cst: &mir::Constant<'tcx>, i| mir::Operand::Constant(Box::new( 271 | mir::Constant{ literal: mk_literal(i), ..cst.clone() })); 272 | 273 | // Find the statement which contains the assignment to arr_local, 274 | // and change its rvalue to be a vector which contains the content 275 | // of the bytes vector. 276 | 'search: for block in mir.basic_blocks().indices() { 277 | let data = &mut mir[block]; 278 | for statement in &mut data.statements { 279 | let cst = { 280 | let op = match *statement { 281 | mir::Statement { kind: mir::StatementKind::Assign( 282 | mir::Place::Local(assign_local), 283 | mir::Rvalue::Aggregate(_, ref op) 284 | ), ..} 285 | if assign_local == arr_local && op.len() == 1 => { 286 | &op[0] 287 | }, 288 | _ => continue, 289 | }; 290 | 291 | match *op { 292 | mir::Operand::Constant(ref c) => c.clone(), 293 | _ => continue, 294 | } 295 | }; 296 | 297 | statement.kind = mir::StatementKind::Assign( 298 | mir::Place::Local(arr_local), 299 | mir::Rvalue::Aggregate(Box::new(mir::AggregateKind::Array(self.tcx.types.u8)), 300 | bytes.into_iter().map(|i| mk_operand(&cst, i)).collect()) 301 | ); 302 | break 'search; 303 | } 304 | } 305 | 306 | Ok(()) 307 | } 308 | 309 | /// Symbols referenced by the functions need to be patched by the static 310 | /// compiler, but we do not know yet with which value. 311 | /// 312 | /// The placeholder has a "defs" field which is a tuple coerced into a 313 | /// "*const()", which contains all the values that have to be known by 314 | /// the compiler. When decoding the bytes, the compiler will recover an 315 | /// offset of this pointer, and reinterpret these data in the generated 316 | /// code. 317 | /// 318 | /// This function replace the placeholder tuple by the actual tuple 319 | /// which contains all the references to other functions, slices, and 320 | /// constants. It also updates the type to be consistent with the type 321 | /// of the referenced content. 322 | /// 323 | /// All rvalues are supposed to be static: 324 | /// Rvalue::Ref(region, mut, Place::Static(box Static{ def_id, ty })) 325 | fn replace_defs(&self, mir: &mut Mir<'tcx>, statics: Vec>, promoted: Vec>) -> Result<(), Error> { 326 | // Addcopied promoted Mir, copied from the function body, and references 327 | // by the rvalue defs. 328 | for m in promoted.into_iter() { 329 | mir.promoted.push(m); 330 | } 331 | 332 | // Create references to the extracted static definitions' types. 333 | let tys : Vec<_> = 334 | statics.iter() 335 | // TODO: We need to create a reference to the statics types. 336 | .map(|rv| match rv { 337 | &mir::Rvalue::Ref(ref region, _, mir::Place::Static(ref st)) => 338 | // region == tcx.types.re_erased 339 | self.tcx.mk_imm_ref(region.clone(), st.ty), 340 | &mir::Rvalue::Use(mir::Operand::Constant(ref constant)) => 341 | constant.ty, 342 | &mir::Rvalue::Cast(_, _, ty) => ty, 343 | _ => unreachable!("Unexpected Rvalue: {:?}", rv) 344 | }) 345 | .collect(); 346 | 347 | // Create a tuple type with the types of all the operands. 348 | let tup_ty = self.tcx.intern_tup(&tys, false); 349 | 350 | // Create a list of locals definitions to be added into the graph. 351 | let local_decls : Vec<_> = 352 | tys.iter() 353 | .map(|ty| mir::LocalDecl::new_temp(ty, Default::default())) 354 | .collect(); 355 | 356 | // Replace the following type patterns, with the equivalent tuple 357 | // with the types of the operands: 358 | // (u8, u8) 359 | // &(u8, u8) 360 | // *const (u8, u8) 361 | // 362 | // This loop also record the local index with the type (u8; u8), in 363 | // order to replace the its value, by a tuple build with the 364 | // previous list of operands. 365 | let mut tup_local : Option = None; 366 | let mut coerce_locals : Vec = Vec::default(); 367 | let mut coerce_ty : Option<_> = None; 368 | let locals : Vec<_> = mir.temps_iter().collect(); 369 | for idx in locals { 370 | let ty = match mir.local_decls[idx].ty.sty { 371 | ty::TypeVariants::TyRef(ref region, ref tam) => { 372 | match tam.ty.sty { 373 | ty::TypeVariants::TyTuple(ref slice, _) 374 | if slice.len() == 2 375 | && slice[0] == self.tcx.types.u8 376 | && slice[1] == self.tcx.types.u8 => 377 | { 378 | let ref_ty = ty::TypeVariants::TyRef(*region, ty::TypeAndMut{ 379 | ty: tup_ty, ..*tam 380 | }); 381 | Some(self.tcx.mk_ty(ref_ty)) 382 | } 383 | _ => None, 384 | } 385 | }, 386 | ty::TypeVariants::TyRawPtr(ref tam) => { 387 | match tam.ty.sty { 388 | ty::TypeVariants::TyTuple(ref slice, _) 389 | if slice.len() == 2 390 | && slice[0] == self.tcx.types.u8 391 | && slice[1] == self.tcx.types.u8 => 392 | { 393 | // One of the local is a cast, we should be 394 | // consistent and convert the cast operand too. 395 | coerce_locals.push(idx); 396 | if coerce_ty == None { 397 | let ptr_ty = ty::TypeVariants::TyRawPtr(ty::TypeAndMut{ 398 | ty: tup_ty, ..*tam 399 | }); 400 | coerce_ty = Some(self.tcx.mk_ty(ptr_ty)); 401 | } 402 | coerce_ty 403 | } 404 | _ => None, 405 | } 406 | }, 407 | ty::TypeVariants::TyTuple(ref slice, _) 408 | if slice.len() == 2 409 | && slice[0] == self.tcx.types.u8 410 | && slice[1] == self.tcx.types.u8 => 411 | { 412 | if tup_local != None { 413 | return Err(Error::MultipleTupleDefinitions) 414 | } 415 | tup_local = Some(idx); 416 | Some(tup_ty) 417 | }, 418 | _ => None, 419 | }; 420 | 421 | if let Some(ty) = ty { 422 | mir.local_decls[idx].ty = ty; 423 | } 424 | } 425 | 426 | let tup_local = match tup_local { 427 | Some(l) => l, 428 | None => return Err(Error::NoTupleDefinition) 429 | }; 430 | 431 | // Find the statement which contains the assignment to tup_local, 432 | // and the statement which cast a value into a typed tuple pointer. 433 | let mut insert_block = None; 434 | let mut tuple_idx = None; 435 | let mut cast_idx = None; 436 | let mut cast_rep = None; 437 | 'find: for block in mir.basic_blocks().indices() { 438 | let data = &mir[block]; 439 | for (st_idx, statement) in data.statements.iter().enumerate() { 440 | match *statement { 441 | // replace the constant tuple. 442 | mir::Statement { kind: mir::StatementKind::Assign( 443 | mir::Place::Local(assign_local), 444 | mir::Rvalue::Aggregate(_, _) 445 | ), ..} 446 | if assign_local == tup_local => { 447 | tuple_idx = Some(st_idx); 448 | }, 449 | // Replace the cast type. 450 | mir::Statement { kind: mir::StatementKind::Assign( 451 | mir::Place::Local(assign_local), 452 | mir::Rvalue::Cast(ref ck, ref op, _) 453 | ), ..} 454 | if coerce_locals.contains(&assign_local) => { 455 | cast_idx = Some(st_idx); 456 | cast_rep = Some(mir::StatementKind::Assign( 457 | mir::Place::Local(assign_local), 458 | mir::Rvalue::Cast(ck.clone(), op.clone(), coerce_ty.unwrap()) 459 | )); 460 | }, 461 | 462 | _ => continue, 463 | }; 464 | 465 | match (tuple_idx, cast_idx) { 466 | (Some(_), Some(_)) => { 467 | insert_block = Some(block); 468 | break 'find 469 | }, 470 | _ => continue 471 | } 472 | } 473 | } 474 | 475 | // Add temporary locals in the list of locals of the Mir. 476 | let local_ids : Vec<_> = 477 | local_decls.into_iter() 478 | .map(|l| mir.local_decls.push(l)) 479 | .collect(); 480 | 481 | // Create a list of local operands of the tuple. 482 | // We move the operands computed from the locals into the array. 483 | let local_ops : Vec<_> = 484 | local_ids.iter() 485 | .map(|idx| mir::Operand::Move(mir::Place::Local(idx.clone()))) 486 | .collect(); 487 | 488 | // Create locals and initialize them. 489 | let mut stmt_before : Vec<_> = 490 | local_ids.iter().zip(statics.iter()) 491 | .fold(vec![],|mut stmts, (idx, rv)| { 492 | stmts.push(mir::Statement { 493 | kind: mir::StatementKind::StorageLive(idx.clone()), 494 | source_info: mir::SourceInfo { 495 | span: Default::default(), 496 | scope: mir::ARGUMENT_VISIBILITY_SCOPE, 497 | } 498 | }); 499 | stmts.push(mir::Statement { 500 | kind: mir::StatementKind::Assign( 501 | mir::Place::Local(idx.clone()), 502 | rv.clone() 503 | ), 504 | source_info: mir::SourceInfo { 505 | span: Default::default(), 506 | scope: mir::ARGUMENT_VISIBILITY_SCOPE, 507 | } 508 | }); 509 | stmts 510 | }); 511 | 512 | // Remove the storage associate to each local. 513 | let mut stmt_after : Vec<_> = 514 | local_ids.iter().fold(vec![], |mut stmts, idx| { 515 | stmts.push(mir::Statement { 516 | kind: mir::StatementKind::StorageDead(idx.clone()), 517 | source_info: mir::SourceInfo { 518 | span: Default::default(), 519 | scope: mir::ARGUMENT_VISIBILITY_SCOPE, 520 | } 521 | }); 522 | stmts 523 | }); 524 | 525 | let insert_block = insert_block.unwrap(); 526 | let tuple_idx = tuple_idx.unwrap(); 527 | let cast_idx = cast_idx.unwrap(); 528 | let cast_rep = cast_rep.unwrap(); 529 | 530 | // Cut the list of statements in order to insert statements to 531 | // declare each of the elements, and statements to mark the 532 | // temporary locals as dead. 533 | let data = &mut mir[insert_block]; 534 | data.statements[tuple_idx].kind = 535 | mir::StatementKind::Assign( 536 | mir::Place::Local(tup_local), 537 | mir::Rvalue::Aggregate(Box::new(mir::AggregateKind::Tuple), 538 | local_ops) 539 | ); 540 | data.statements[cast_idx].kind = cast_rep; 541 | let mut head = data.statements.split_off(tuple_idx); 542 | let mut tail = head.split_off(1); 543 | data.statements.append(&mut stmt_before); 544 | data.statements.append(&mut head); 545 | data.statements.append(&mut stmt_after); 546 | data.statements.append(&mut tail); 547 | 548 | Ok(()) 549 | } 550 | 551 | /// 552 | fn run_pass(&self, mir: &mut Mir<'tcx>) { 553 | // Step 1: Filter all references to holyjit data structures. 554 | if !self.is_placeholder(mir) { 555 | return 556 | } 557 | 558 | // Step 2: Find the function reference wrapped in the holyjit data 559 | // structure. 560 | let (fn_id, src_info) = self.wrapped_fn(mir).unwrap_or_else(|e| 561 | panic!("Fail to find wrapped function: {:?}", e), 562 | ); 563 | 564 | // Print the NodeId corresponding the DefId of the function. 565 | //let fn_node = self.tcx.hir.as_local_node_id(fn_id).unwrap(); 566 | //println!("wrapped function NodeId: {:?};", fn_node); 567 | 568 | // Step 3: Convert the Mir of function into HolyJit representation 569 | // and serialize it. 570 | let nb_promoted = mir.promoted.len(); 571 | let (bytes, defs, promoted) = self.serialize_mir(fn_id, src_info, nb_promoted).unwrap_or_else(|e| 572 | panic!("Fail to convert the wrapped function: {:?}", e), 573 | ); 574 | 575 | // Step 4: Replace the constant array of the HolyJit data structure 576 | // by one which contains the serialized graph. 577 | self.replace_bytes(mir, bytes).unwrap_or_else(|e| 578 | panic!("Fail to attach the serialized function: {:?}", e), 579 | ); 580 | self.replace_defs(mir, defs, promoted).unwrap_or_else(|e| 581 | panic!("Fail to attach static references: {:?}", e), 582 | ); 583 | } 584 | } 585 | 586 | /// This structure is registered as a MirPass and is used to deletage to 587 | /// AttachJitGraph implementation. 588 | pub struct AttachFnGraphOnCst; 589 | impl MirPass for AttachFnGraphOnCst { 590 | fn run_pass<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, 591 | src: MirSource, mir: &mut Mir<'tcx>) 592 | { 593 | let attach_jit = AttachJitGraph { 594 | tcx: tcx, 595 | source: src, 596 | }; 597 | 598 | attach_jit.run_pass(mir); 599 | } 600 | } 601 | -------------------------------------------------------------------------------- /plugin/src/trans.rs: -------------------------------------------------------------------------------- 1 | /// This module converts the rustc::mir into a holyjit::lir. 2 | 3 | use std::collections::HashMap; 4 | use std::boxed::Box; 5 | use std::mem; 6 | 7 | use rustc::ty::{self, TyCtxt}; 8 | use rustc::ty::subst::Subst; 9 | use rustc::mir; 10 | use rustc::hir::def_id::DefId; 11 | use rustc::middle::const_val::{ConstVal, ConstInt}; 12 | use rustc::middle::lang_items::DropInPlaceFnLangItem; 13 | use rustc_const_math::ConstUsize; 14 | use rustc_data_structures::indexed_vec::Idx; 15 | 16 | use syntax_pos::DUMMY_SP; 17 | 18 | use holyjit_lib::lir; 19 | 20 | use bincode; 21 | 22 | /// Contains all the logic for converting a Rust Mir graph into an HolyJit 23 | /// Lir graph. 24 | pub struct Transpiler<'a, 'tcx: 'a> { 25 | tcx: TyCtxt<'a, 'tcx, 'tcx>, 26 | 27 | // Needed to get the layout from a given type. 28 | param_env: ty::ParamEnv<'tcx>, 29 | 30 | /// Map indexes from the Mir to indexes of the Lir. 31 | blocks_map: HashMap, 32 | // last_block: lir::BasicBlock, 33 | blocks: Vec, 34 | 35 | // Map a local id, to its offsets from the beginning of the stack. If 36 | // the stack grows down, this value should be removed from the stack 37 | // pointer to obtain the desired location. 38 | locals_map: HashMap>, 39 | fp: lir::Reg, 40 | ret_local: Option, 41 | 42 | // Collect the list of static operands which are not yet bound to any 43 | // addresses. These would be attached to the HolyJitFnWrapper constant, 44 | // in order to collect their values.m/ 45 | statics: Vec>, 46 | statics_size: usize, 47 | 48 | // The lir is an infinite register language. Each register being 49 | // represented by a number. This number is used for allocating new 50 | // registers in the MIR. 51 | last_reg: lir::Reg, 52 | 53 | /// Map indexes of the function promoted MIR, to indexes of the of the 54 | /// contant promoted MIR. 55 | promoted_map: HashMap, 56 | // Number of promoted blocks which are already listed in the constant MIR 57 | // before attaching any new promoted MIR ot it. 58 | promoted_idx: usize, 59 | } 60 | 61 | #[derive(Debug)] 62 | struct Local<'tcx> { 63 | _idx: mir::Local, 64 | ty: ty::Ty<'tcx>, 65 | off: usize, 66 | size: usize, 67 | reg: Option, 68 | } 69 | 70 | /// Determine if the address or the value should be returned to the caller. 71 | #[derive(Debug, Copy, Clone)] 72 | enum PlaceCtx { 73 | Value, 74 | Address, 75 | RefSlice, 76 | } 77 | 78 | #[derive(Debug)] 79 | pub enum Error { 80 | UnknownType, 81 | TooLargeType, 82 | 83 | // Validate statement is used by Miri to ensure that the content of a given 84 | // place contains data which correspond to the type assumption. Maybe we 85 | // could later generate proper assertions as well. 86 | ValidateStmt, 87 | 88 | /// Inline Assembly code is not supported for the moment, and probably 89 | /// would not be in the future versions of HolyJit. 90 | InlineAssembly, 91 | 92 | /// Serialization error while converting the Lir into a vector of bytes. 93 | Serialize, 94 | 95 | /// PlaceCtx::RefSlice is used to indicate that a Deref projection is 96 | /// not supposed to do anything because it would depend on the consumer. 97 | UnexpectedRefSliceCtx, 98 | 99 | /// Not Yet Implemented. 100 | NYI, 101 | } 102 | 103 | macro_rules! report_nyi { 104 | ($($msg:expr),*) => { 105 | |e| match e { 106 | Error::UnexpectedRefSliceCtx | 107 | Error::NYI => panic!($($msg),*), 108 | e => Err(e) 109 | } 110 | } 111 | } 112 | 113 | impl<'tcx> From> for Error { 114 | fn from(err: ty::layout::LayoutError<'tcx>) -> Error { 115 | println!("ty::layout::LayoutError = {}", err); 116 | match err { 117 | ty::layout::LayoutError::Unknown(_) => Error::UnknownType, 118 | ty::layout::LayoutError::SizeOverflow(_) => Error::TooLargeType, 119 | } 120 | } 121 | } 122 | 123 | impl<'tcx> From> for Error { 124 | fn from(err: Box) -> Error { 125 | println!("bincode::ErrorKind = {}", err); 126 | Error::Serialize 127 | } 128 | } 129 | 130 | // TODO: Have a look at Rust's src/librustc_trans/context.rs , and how CodegenCx is built. 131 | impl<'a, 'tcx> Transpiler<'a, 'tcx> { 132 | pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>, fn_id: DefId, nb_promoted: usize) -> Self { 133 | Self { 134 | tcx: tcx, 135 | param_env: tcx.param_env(fn_id), 136 | blocks_map: HashMap::new(), 137 | // last_block: 0, 138 | blocks: vec![], 139 | locals_map: HashMap::new(), 140 | fp: 0, 141 | ret_local: None, 142 | statics: vec![], 143 | statics_size: 0, 144 | last_reg: 1, 145 | promoted_map: HashMap::new(), 146 | promoted_idx: nb_promoted, 147 | } 148 | } 149 | } 150 | 151 | /* 152 | impl<'a, 'tcx> ty::layout::HasDataLayout for &'a Transpiler<'a, 'tcx> { 153 | fn data_layout(&self) -> &ty::layout::TargetDataLayout { 154 | &self.tcx.data_layout 155 | } 156 | } 157 | 158 | impl<'a, 'tcx> ty::layout::HasTyCtxt<'tcx> for &'a Transpiler<'a, 'tcx> { 159 | fn tcx<'b>(&'b self) -> TyCtxt<'b, 'tcx, 'tcx> { 160 | self.tcx 161 | } 162 | } 163 | */ 164 | /* 165 | impl<'a, 'tcx> LayoutOf> for &'a Transpiler<'a, 'tcx> { 166 | type TyLayout = TyLayout<'tcx>; 167 | 168 | fn layout_of(self, ty: Ty<'tcx>) -> Self::TyLayout { 169 | self.tcx.layout_of(ty::ParamEnv::empty(traits::Reveal::All).and(ty)) 170 | .unwrap_or_else(|e| match e { 171 | LayoutError::SizeOverflow(_) => panic!("LayoutError::SizeOverflow"), 172 | _ => panic!("failed to get layout for `{}`: {}", ty, e) 173 | }) 174 | } 175 | } 176 | */ 177 | 178 | /// This type correspons to the sequences of instructions build by the 179 | /// statements content. Each have a return type and a return register. 180 | #[derive(Debug)] 181 | struct InstSeq<'tcx>(Vec, lir::Reg, ty::Ty<'tcx>); 182 | struct TermSeq(Vec, lir::Terminator); 183 | 184 | impl<'a, 'tcx> Transpiler<'a, 'tcx> { 185 | // This function output a vector of bytes which corresponds to the LIR, a 186 | // vector of rvalue which corresponds to all statics & promoted indexes, and 187 | // a vector of promoted blocks. 188 | pub fn convert(mut self, mir: &mir::Mir<'tcx>) -> Result<(Vec, Vec>, Vec>), Error> { 189 | let (args_defs, stack_size) = self.locals(mir)?; 190 | self.graph(mir, stack_size)?; 191 | 192 | let blocks = mem::replace(&mut self.blocks, Vec::new()); 193 | 194 | let lir = lir::CompilationUnit { 195 | stack_size: stack_size, 196 | args_defs: args_defs, 197 | blocks: blocks, 198 | }; 199 | println!("lir:\n{}\n", lir); 200 | let bytes : Vec = bincode::serialize(&lir, bincode::Infinite)?; 201 | 202 | // Copy promoted block to the constant, such that we can reference the 203 | // same value (which are not supposed to be mutable.) 204 | let mut promoted: Vec<_> = self.promoted_map.into_iter().map(|(tgt_idx, src_idx)| 205 | (tgt_idx, mir.promoted[src_idx].clone()) 206 | ).collect(); 207 | promoted.sort_by(|a, b| a.0.cmp(&b.0)); 208 | let promoted : Vec<_> = promoted.into_iter().map(|a| a.1).collect(); 209 | 210 | Ok(( 211 | bytes, 212 | self.statics, 213 | promoted 214 | )) 215 | } 216 | 217 | /* 218 | fn mir(&mut self) -> Result<(), Error> { 219 | Ok(()) 220 | } 221 | */ 222 | 223 | fn locals(&mut self, mir: &mir::Mir<'tcx>) -> Result<(Vec, usize), Error> { 224 | // Loop over arguments and locals to find out about their sizes 225 | // (librustc/ty/layout.rs), and where they should be allocated. 226 | // 227 | // see ty::layout::Layout::compute_uncached(tcx, ??, ty) 228 | // 229 | // let layout = ty.layout()?; 230 | // 231 | // see librustc_mir/transform/inline.rs (type_size_of) 232 | // 233 | let mut stack : usize = 0; 234 | let mut args_defs : Vec = Vec::with_capacity(mir.arg_count); 235 | for (local, decl) in mir.local_decls.iter_enumerated() { 236 | let layout = self.tcx.layout_of(self.param_env.and(decl.ty))?; // decl.ty.layout(self.tcx, self.param_env)?; 237 | let size = layout.size.bytes() as usize; 238 | let align = layout.align.pref() as usize; // (&self.tcx.data_layout) 239 | let local_kind = mir.local_kind(local); 240 | println!("local {:?} : {} =>: size: {} ; align: {:?} ; kind: {:?}", local, mir.local_decls[local].ty, size, align, local_kind); 241 | 242 | match local_kind { 243 | mir::LocalKind::ReturnPointer => 244 | self.ret_local = Some(local.clone()), 245 | _ => () 246 | }; 247 | 248 | // Record the aligned address of beginning of the local's 249 | // memory. (assumes the stack is growing down) 250 | let data = { 251 | match local_kind { 252 | mir::LocalKind::Arg => { 253 | // Bump the stack pointer with the size of the local. 254 | let (off, bump) = self.add_type(decl.ty, stack)?; 255 | stack = bump; 256 | let size = bump - off; 257 | 258 | // Add the size of the content which is being copied, 259 | // the JIT-compiler will have to infer if this is a 260 | // pointer type or the content of it :/ 261 | args_defs.push((off as lir::Imm, size, (size <= 8) as lir::ByValue)); 262 | 263 | Local { 264 | _idx: local, 265 | ty: decl.ty, 266 | off, size, 267 | reg: None, 268 | } 269 | }, 270 | mir::LocalKind::ReturnPointer | 271 | mir::LocalKind::Var | 272 | mir::LocalKind::Temp => { 273 | // Bump the stack pointer with the size of the local. 274 | let (off, bump) = self.add_type(decl.ty, stack)?; 275 | stack = bump; 276 | 277 | Local { 278 | _idx: local, 279 | ty: decl.ty, 280 | off: off, 281 | size: bump - off, 282 | reg: None, 283 | } 284 | }, 285 | } 286 | }; 287 | 288 | self.locals_map.insert(local, data); 289 | } 290 | 291 | Ok((args_defs, stack)) 292 | } 293 | 294 | fn new_block(&mut self) -> lir::BasicBlock { 295 | // let lir = self.last_block; 296 | // self.last_block += 1; 297 | self.blocks.push(lir::BasicBlockData{ 298 | input_regs: vec![], 299 | output_regs: vec![], 300 | insts: vec![], 301 | end: lir::Terminator::Unreachable, 302 | }); 303 | self.blocks.len() - 1 304 | } 305 | 306 | fn get_block(&mut self, mir: mir::BasicBlock) -> lir::BasicBlock { 307 | match self.blocks_map.get(&mir) { 308 | Some(lir) => return *lir, 309 | None => (), 310 | }; 311 | 312 | let lir = self.new_block(); 313 | let _id = self.blocks_map.insert(mir, lir); 314 | lir 315 | } 316 | 317 | fn graph(&mut self, mir: &mir::Mir<'tcx>, stack_size: usize) -> Result<(), Error> { 318 | for (bb, bb_data) in mir.basic_blocks().iter_enumerated() { 319 | let lbb = self.get_block(bb); 320 | let mut lblock_insts : Vec = vec![]; 321 | 322 | let inputs = if lbb == 0 { 323 | lblock_insts.append(&mut vec![ 324 | lir::Inst::SetFramePtr(self.fp, 8 /* size of frame ptr */, stack_size) 325 | ]); 326 | // The first block is assumed to copy all the arguments to 327 | // the stack, and these arguments should only be used once 328 | // in the entire graph, and marked as dead after the first 329 | // assignment. 330 | vec![] 331 | } else { 332 | vec![ (self.fp, 8 /* size of frame ptr */ ) ] 333 | }; 334 | 335 | // Append the instructions needed for the execution of every 336 | // staements. 337 | for statement in &bb_data.statements { 338 | let mut insts = match self.statement(statement) { 339 | Ok(res) => res, 340 | Err(Error::ValidateStmt) => continue, 341 | e => { e?; panic!("The impossible happened") } 342 | }; 343 | lblock_insts.append(&mut insts); 344 | }; 345 | 346 | let term = &bb_data.terminator; 347 | let term = term.as_ref().unwrap(); 348 | let TermSeq(mut term_insts, terminator) = 349 | self.terminator(term).or_else( 350 | report_nyi!("BBData( terminator: {:?} , .. )", bb_data.terminator))?; 351 | lblock_insts.append(&mut term_insts); 352 | 353 | let fp_reg = self.fp; 354 | self.blocks[lbb] = lir::BasicBlockData { 355 | input_regs: inputs, 356 | output_regs: vec![ fp_reg ], 357 | insts: lblock_insts, 358 | end: terminator, 359 | }; 360 | } 361 | 362 | Ok(()) 363 | } 364 | 365 | fn statement(&mut self, statement: &mir::Statement<'tcx>) -> Result, Error> { 366 | match statement.kind { 367 | mir::StatementKind::Validate(_, _) => { 368 | // Used by Miri as an assertion mechanism. 369 | Err(Error::ValidateStmt) 370 | } 371 | mir::StatementKind::Assign(ref lvalue, ref rvalue) => { 372 | // Collect the sequence of instruction to fetch the value. 373 | let InstSeq(rv_insts, rv_reg, rv_ty) = 374 | self.rvalue(rvalue).or_else( 375 | report_nyi!("StatementKind::Assign(_, {:?})", rvalue))?; 376 | 377 | // Collect the sequence of instruction which fetch the 378 | // memory location. 379 | let InstSeq(mut lv_insts, lv_reg, lv_ty) = 380 | self.lvalue(lvalue, PlaceCtx::Address).or_else( 381 | report_nyi!("StatementKind::Assign({:?}, _)", lvalue))?; 382 | 383 | let lv_ty = lv_ty.builtin_deref(true).unwrap().ty; 384 | let (_, lv_size) = self.add_type(lv_ty, 0)?; 385 | let (_, rv_size) = self.add_type(rv_ty, 0)?; 386 | 387 | self.check_same_size(lv_ty, rv_ty).or_else( 388 | report_nyi!("Assign size: {} <- {} {{ {:?} }}", lv_size, rv_size, statement))?; 389 | let mut insts = rv_insts; 390 | insts.append(&mut lv_insts); 391 | insts.append(&mut vec![ 392 | lir::Inst::Store(lv_reg, rv_reg, rv_size), 393 | lir::Inst::Dead(lv_reg), 394 | lir::Inst::Dead(rv_reg), 395 | ]); 396 | 397 | Ok(insts) 398 | } 399 | mir::StatementKind::SetDiscriminant{ .. } => { 400 | Err(Error::NYI) 401 | } 402 | mir::StatementKind::InlineAsm { .. } => { 403 | Err(Error::InlineAssembly) 404 | } 405 | 406 | // For the moment, let's consider all storages to be always 407 | // live. 408 | mir::StatementKind::StorageLive(_) | 409 | mir::StatementKind::StorageDead(_) | 410 | mir::StatementKind::EndRegion(_) | 411 | mir::StatementKind::Nop => Ok(vec![]), 412 | } 413 | } 414 | 415 | fn get_new_reg(&mut self) -> lir::Reg { 416 | let r = self.last_reg.clone(); 417 | self.last_reg += 1; 418 | r 419 | } 420 | 421 | fn reg_of_local(&self, index: mir::Local) -> Option { 422 | // println!("reg_of_local({:?}) == {:?}", index, self.locals_map[&index]); 423 | self.locals_map[&index].reg 424 | } 425 | fn type_of_local(&self, index: mir::Local) -> ty::Ty<'tcx> { 426 | self.locals_map[&index].ty 427 | } 428 | fn offset_of_local(&self, index: mir::Local) -> isize { 429 | 0 - (self.locals_map[&index].off as isize) - (self.locals_map[&index].size as isize) 430 | } 431 | fn size_of_local(&self, index: mir::Local) -> usize { 432 | self.locals_map[&index].size 433 | } 434 | 435 | fn offset_of(&self, ty: ty::Ty<'tcx>, field: &mir::Field) -> Result { 436 | let layout = self.tcx.layout_of(self.param_env.and(ty))?; 437 | let off = layout.fields.offset(field.index()).bytes(); 438 | println!("offset_of({:?}, {:?}) -> offset: {:?} {{ layout: {:?} }}", ty, field, off, layout); 439 | Ok(off as usize) 440 | } 441 | 442 | /// Given a type and the last bump size pointer, this function look at 443 | /// the alignment and the size of the type and returns a tuple which 444 | /// contains the offset of the given type, and the new bump-offset for 445 | /// futher allocations. 446 | fn add_type(&self, ty: ty::Ty<'tcx>, bump: usize) -> Result<(usize, usize), Error> { 447 | let layout = self.tcx.layout_of(self.param_env.and(ty))?; 448 | let size = layout.size.bytes() as usize; 449 | let align = layout.align.pref() as usize; 450 | 451 | // align the bump offset. 452 | let miss_align = bump & (align - 1); 453 | let missing = (align - miss_align) & (align - 1); 454 | let base = bump + missing; 455 | 456 | Ok((base, base + size)) 457 | } 458 | 459 | fn check_same_size(&self, lhs: ty::Ty<'tcx>, rhs: ty::Ty<'tcx>) -> Result<(), Error> { 460 | let (_, lsz) = self.add_type(lhs, 0)?; 461 | let (_, rsz) = self.add_type(rhs, 0)?; 462 | if lsz != rsz { 463 | println!("left: {} ({:?}) ; right: {} ({:?})", lsz, lhs, rsz, rhs); 464 | return Err(Error::NYI); 465 | } 466 | 467 | Ok(()) 468 | } 469 | 470 | fn register_static(&mut self, rvalue: &mir::Rvalue<'tcx>, ty: ty::Ty<'tcx>) -> Result<(lir::Imm, lir::Sz), Error> { 471 | self.statics.push(rvalue.clone()); 472 | let bump = self.statics_size; 473 | let (off, bump) = self.add_type(ty, bump)?; 474 | self.statics_size = bump; 475 | let layout = self.tcx.layout_of(self.param_env.and(ty))?; 476 | println!("register_static:\n: {:?}\n: {:?}\n: {:?}\n: {:?}", rvalue, ty, bump - off, layout); 477 | Ok((off as lir::Imm, bump - off as lir::Sz)) 478 | } 479 | 480 | fn register_promoted(&mut self, promoted: mir::Promoted) -> mir::Promoted { 481 | // This function does not clone the promoted MIR, but only keep the 482 | // index of which MIR needs to be cloned, such that when we reach back 483 | // the top of the function MIR, we can clone all the necessary promoted 484 | // MIR. 485 | let idx = mir::Promoted::new(self.promoted_idx); 486 | // (assume no duplicated?) 487 | self.promoted_map.insert(idx, promoted); 488 | self.promoted_idx += 1; 489 | idx 490 | } 491 | 492 | fn local(&mut self, index: mir::Local) -> Result, Error> 493 | { 494 | if let Some(reg) = self.reg_of_local(index) { 495 | let ty = self.type_of_local(index); 496 | let ptr_size = 8; // TODO: use proper pointer size. 497 | if self.size_of_local(index) > ptr_size { 498 | let val = self.get_new_reg(); 499 | return Ok(InstSeq(vec![ 500 | lir::Inst::Live(val), 501 | lir::Inst::Load(val, reg, self.size_of_local(index) as lir::Sz), 502 | lir::Inst::Dead(reg), 503 | ], val, ty)) 504 | } 505 | return Ok(InstSeq(vec![], reg, ty)); 506 | } 507 | let off = self.get_new_reg(); 508 | let ptr = self.get_new_reg(); 509 | let reg = self.get_new_reg(); 510 | Ok(InstSeq(vec![ 511 | lir::Inst::Live(off), 512 | // Compute the offset within the stack frame. 513 | lir::Inst::CopyImm(off, self.offset_of_local(index) as lir::Imm, 514 | 8 as lir::Sz /* size of pointer */), 515 | lir::Inst::Live(ptr), 516 | // Add the offset to the stack frame pointer. 517 | lir::Inst::Add(ptr, self.fp, off), 518 | lir::Inst::Dead(off), 519 | lir::Inst::Live(reg), 520 | // Add the offset to the stack frame pointer. 521 | lir::Inst::Load(reg, ptr, self.size_of_local(index) as lir::Sz), 522 | lir::Inst::Dead(ptr), 523 | ], reg, self.type_of_local(index))) 524 | } 525 | 526 | fn lvalue<'b>(&'b mut self, lvalue: &'b mir::Place<'tcx>, lvctx: PlaceCtx) -> Result, Error> 527 | { 528 | match (lvalue, lvctx) { 529 | (&mir::Place::Local(index), PlaceCtx::Address) => { 530 | if let Some(_reg) = self.reg_of_local(index) { 531 | return Err(Error::NYI); 532 | } 533 | let off = self.get_new_reg(); 534 | let reg = self.get_new_reg(); 535 | let ty = self.type_of_local(index); 536 | let ty = self.tcx.mk_imm_ref(self.tcx.types.re_erased, ty); 537 | // Check we return a pointer type. 538 | self.check_same_size(ty, self.tcx.types.usize)?; 539 | Ok(InstSeq(vec![ 540 | lir::Inst::Live(off), 541 | // Compute the offset within the stack frame. 542 | lir::Inst::CopyImm(off, self.offset_of_local(index) as lir::Imm, 543 | 8 as lir::Sz /* size of pointer */), 544 | lir::Inst::Live(reg), 545 | // Add the offset to the stack frame pointer. 546 | lir::Inst::Add(reg, self.fp, off), 547 | lir::Inst::Dead(off), 548 | ], reg, ty)) 549 | }, 550 | (&mir::Place::Local(index), PlaceCtx::Value) => { 551 | if let Some(reg) = self.reg_of_local(index) { 552 | let ty = self.type_of_local(index); 553 | let ptr_size = 8; // TODO: use proper pointer size. 554 | if self.size_of_local(index) > ptr_size { 555 | let val = self.get_new_reg(); 556 | return Ok(InstSeq(vec![ 557 | lir::Inst::Live(val), 558 | lir::Inst::Load(val, reg, self.size_of_local(index) as lir::Sz), 559 | lir::Inst::Dead(reg), 560 | ], val, ty)) 561 | } 562 | return Ok(InstSeq(vec![], reg, ty)); 563 | } 564 | let off = self.get_new_reg(); 565 | let ptr = self.get_new_reg(); 566 | let reg = self.get_new_reg(); 567 | Ok(InstSeq(vec![ 568 | lir::Inst::Live(off), 569 | // Compute the offset within the stack frame. 570 | lir::Inst::CopyImm(off, self.offset_of_local(index) as lir::Imm, 571 | 8 as lir::Sz /* size of pointer */), 572 | lir::Inst::Live(ptr), 573 | // Add the offset to the stack frame pointer. 574 | lir::Inst::Add(ptr, self.fp, off), 575 | lir::Inst::Dead(off), 576 | lir::Inst::Live(reg), 577 | // Add the offset to the stack frame pointer. 578 | lir::Inst::Load(reg, ptr, self.size_of_local(index) as lir::Sz), 579 | lir::Inst::Dead(ptr), 580 | ], reg, self.type_of_local(index))) 581 | }, 582 | (&mir::Place::Static(ref def), _) => { 583 | // Place::Static seems to be always wrapped under a 584 | // Rvalue::Ref, so forbid any lvalue of this type. 585 | println!("Place::Static(def_id: {:?}, ty: {:?}) within {:?}", def.def_id, def.ty, lvctx); 586 | unreachable!("Unexpected Place::Static") 587 | } 588 | (&mir::Place::Projection(ref proj), ref lvctx) => { 589 | self.lvalue_projection(&proj, *lvctx).or_else( 590 | report_nyi!("mir::Place::Projection(({:?})", proj)) 591 | } 592 | 593 | (_, PlaceCtx::RefSlice) => Err(Error::UnexpectedRefSliceCtx), 594 | } 595 | } 596 | 597 | fn lvalue_projection<'b>(&'b mut self, proj: &'b mir::PlaceProjection<'tcx>, lvctx: PlaceCtx) -> Result, Error> 598 | { 599 | // Projection<'tcx, Place<'tcx>, Operand<'tcx>, Ty<'tcx>> 600 | let mir::Projection { ref base, ref elem } = *proj; 601 | let InstSeq(mut base_insts, base_reg, base_ty) = 602 | match *elem { 603 | mir::ProjectionElem::Index(_) => 604 | self.lvalue(base, PlaceCtx::RefSlice)?, 605 | mir::ProjectionElem::Field(_, _) => 606 | self.lvalue(base, PlaceCtx::Address)?, 607 | _ => self.lvalue(base, PlaceCtx::Value)? 608 | }; 609 | match *elem { 610 | mir::ProjectionElem::Deref => { 611 | let InstSeq(addr_insts, addr_reg, addr_ty) = InstSeq(base_insts, base_reg, base_ty); 612 | 613 | match lvctx { 614 | PlaceCtx::Value => { 615 | let mut insts = addr_insts; 616 | let reg = self.get_new_reg(); 617 | let res_ty = addr_ty.builtin_deref(true).unwrap().ty; 618 | let (_, size) = self.add_type(res_ty, 0)?; 619 | insts.append(&mut vec![ 620 | lir::Inst::Live(reg), 621 | lir::Inst::Load(reg, addr_reg, size), 622 | lir::Inst::Dead(addr_reg) 623 | ]); 624 | Ok(InstSeq(insts, reg, res_ty)) 625 | } 626 | PlaceCtx::RefSlice => { 627 | // We are asking to dereference a fat-pointer, but 628 | // we will either request the pointer of it or the 629 | // length of it. 630 | assert!(addr_ty.is_slice()); 631 | Ok(InstSeq(addr_insts, addr_reg, addr_ty)) 632 | } 633 | PlaceCtx::Address => { 634 | Ok(InstSeq(addr_insts, addr_reg, addr_ty)) 635 | } 636 | } 637 | } 638 | mir::ProjectionElem::Field(ref field, ref ty) => { 639 | // Given a type, generate a field access for this type. 640 | let struct_ty = base_ty.builtin_deref(true).unwrap().ty; 641 | match lvctx { 642 | PlaceCtx::Value => { 643 | let mut insts = base_insts; 644 | let imm = self.get_new_reg(); 645 | let addr = self.get_new_reg(); 646 | let reg = self.get_new_reg(); 647 | let (_, size) = self.add_type(self.tcx.types.usize, 0)?; 648 | let (_, ty_sz) = self.add_type(ty, 0)?; 649 | // We are expecting a pointer, in both cases. 650 | self.check_same_size(base_ty, self.tcx.types.usize)?; 651 | 652 | insts.append(&mut vec![ 653 | lir::Inst::Live(imm), 654 | lir::Inst::CopyImm(imm, self.offset_of(struct_ty, field)? as lir::Imm, size as lir::Sz), 655 | lir::Inst::Live(addr), 656 | lir::Inst::Add(addr, base_reg, imm), 657 | lir::Inst::Dead(imm), 658 | lir::Inst::Dead(base_reg), 659 | lir::Inst::Live(reg), 660 | lir::Inst::Load(reg, addr, ty_sz), 661 | lir::Inst::Dead(addr), 662 | ]); 663 | Ok(InstSeq(insts, reg, ty)) 664 | } 665 | PlaceCtx::Address => { 666 | let mut insts = base_insts; 667 | let imm = self.get_new_reg(); 668 | let reg = self.get_new_reg(); 669 | let (_, size) = self.add_type(self.tcx.types.usize, 0)?; 670 | let res_ty = self.tcx.mk_mut_ptr(ty); 671 | // We are expecting a pointer, in both cases. 672 | self.check_same_size(base_ty, self.tcx.types.usize)?; 673 | self.check_same_size(base_ty, res_ty)?; 674 | 675 | insts.append(&mut vec![ 676 | lir::Inst::Live(imm), 677 | lir::Inst::CopyImm(imm, self.offset_of(struct_ty, field)? as lir::Imm, size as lir::Sz), 678 | lir::Inst::Live(reg), 679 | lir::Inst::Add(reg, base_reg, imm), 680 | lir::Inst::Dead(imm), 681 | lir::Inst::Dead(base_reg) 682 | ]); 683 | Ok(InstSeq(insts, reg, res_ty)) 684 | }, 685 | PlaceCtx::RefSlice => Err(Error::UnexpectedRefSliceCtx), 686 | } 687 | } 688 | mir::ProjectionElem::Index(ref index) => { 689 | // base [ operand ] 690 | let InstSeq(idx_insts, idx_reg, _idx_ty) = 691 | self.local(*index).or_else( 692 | report_nyi!("mir::ProjectionElem::Index({:?})", index))?; 693 | 694 | let InstSeq(mut base_insts, base_reg, base_ty) = { 695 | // Assert that base is FatPointer given by value. Note 696 | // we use the RefSlice type, to skip the Defer operation 697 | // made on the lvalue. 698 | assert!(base_ty.is_slice()); // TODO: add TyArray support? 699 | let slice_ty = base_ty.builtin_deref(true).unwrap().ty; 700 | let elem_ty = slice_ty.builtin_index().unwrap(); 701 | let res_ty = self.tcx.mk_mut_ptr(elem_ty); 702 | 703 | let layout = self.tcx.layout_of(self.param_env.and(base_ty))?; 704 | let offset = layout.fields.offset(ty::layout::FAT_PTR_ADDR); 705 | let (_, size) = self.add_type(res_ty, 0)?; 706 | 707 | let reg = self.get_new_reg(); 708 | base_insts.append(&mut vec![ 709 | lir::Inst::Live(reg), 710 | lir::Inst::LoadFrom(reg, base_reg, offset.bytes() as lir::Sz, size), 711 | lir::Inst::Dead(base_reg), 712 | ]); 713 | 714 | InstSeq(base_insts, reg, res_ty) 715 | }; 716 | 717 | // Compute the re-aligned size of the element. 718 | let res_ty = base_ty.builtin_deref(true).unwrap().ty; 719 | let elem_sz = self.tcx.layout_of(self.param_env.and(res_ty))?.size.bytes() as lir::Sz; 720 | 721 | // We are expecting a pointer, in both cases. 722 | self.check_same_size(base_ty, self.tcx.types.usize)?; 723 | let (_, idx_size) = self.add_type(self.tcx.types.usize, 0)?; 724 | 725 | match lvctx { 726 | PlaceCtx::Value => { 727 | let imm = self.get_new_reg(); 728 | let mul = self.get_new_reg(); 729 | let reg = self.get_new_reg(); 730 | let val = self.get_new_reg(); 731 | let mut insts = idx_insts; 732 | insts.append(&mut vec![ 733 | lir::Inst::Live(imm), 734 | lir::Inst::CopyImm(imm, elem_sz as lir::Imm, idx_size as lir::Sz), 735 | lir::Inst::Live(mul), 736 | lir::Inst::Mul(mul, idx_reg, imm), 737 | lir::Inst::Dead(idx_reg), 738 | lir::Inst::Dead(imm), 739 | ]); 740 | insts.append(&mut base_insts); 741 | insts.append(&mut vec![ 742 | lir::Inst::Add(reg, base_reg, mul), 743 | lir::Inst::Dead(base_reg), 744 | lir::Inst::Dead(mul), 745 | lir::Inst::Load(val, reg, elem_sz), 746 | lir::Inst::Dead(reg), 747 | ]); 748 | 749 | Ok(InstSeq(insts, val, res_ty)) 750 | } 751 | PlaceCtx::RefSlice => Err(Error::UnexpectedRefSliceCtx), 752 | PlaceCtx::Address => Err(Error::NYI), 753 | } 754 | } 755 | _ => Err(Error::NYI) 756 | } 757 | } 758 | 759 | fn rvalue<'b>(&'b mut self, rvalue: &'b mir::Rvalue<'tcx>) -> Result, Error> 760 | { 761 | match *rvalue { 762 | mir::Rvalue::Use(ref operand) => { 763 | Ok(self.operand(operand).or_else( 764 | report_nyi!("mir::Rvalue::Use({:?})", operand))?) 765 | } 766 | mir::Rvalue::Ref(ref region, _, ref lvalue) => { 767 | match lvalue { 768 | // Static are references to a static variable or 769 | // function, but the address of it is not knwon yet, as 770 | // it depends on the assembly of the statically compiled 771 | // program. 772 | // 773 | // Thus we have to fake a content of the same type, and 774 | // in the place-holder structure added by the jit! 775 | // macro, add a new reference to static variables. 776 | &mir::Place::Static(ref def) => { 777 | let ty = self.tcx.mk_imm_ref(region.clone(), def.ty); 778 | let reg = self.get_new_reg(); 779 | let (off, sz) = self.register_static(rvalue, ty)?; 780 | 781 | Ok(InstSeq(vec![ 782 | lir::Inst::Live(reg), 783 | lir::Inst::Static(reg, off, sz) 784 | ], reg, ty)) 785 | }, 786 | 787 | // Local are already returning the address of the 788 | // location in which the data is stored. So when a 789 | // rvalue request the location of the lvalue, then we 790 | // just return the unmodified lvalue. 791 | &mir::Place::Local(_) => 792 | self.lvalue(lvalue, PlaceCtx::Address).or_else( 793 | report_nyi!("mir::Rvalue::Ref(_, _, {:?})", lvalue)), 794 | 795 | _ => Err(Error::NYI) 796 | } 797 | } 798 | 799 | mir::Rvalue::Len(ref lvalue) => { 800 | let InstSeq(lv_insts, lv_reg, lv_ty) = 801 | self.lvalue(lvalue, PlaceCtx::RefSlice).or_else( 802 | report_nyi!("mir::Rvalue::Len({:?})", lvalue))?; 803 | 804 | let layout = self.tcx.layout_of(self.param_env.and(lv_ty))?; 805 | println!("mir::Rvalue::Len({:?})", lvalue); 806 | println!("ty: {:?} / layout: {:?}", lv_ty, layout); 807 | 808 | // Assert that base is FatPointer given by value. Note we 809 | // use the RefSlice type, to skip the Defer operation made 810 | // on the lvalue. 811 | assert!(lv_ty.is_slice()); 812 | 813 | //assert_eq!(layout.field_count(), 2); 814 | //assert_eq!(layout.field_type(&self.lcx, 1), self.tcx.types.usize); 815 | let offset = layout.fields.offset(ty::layout::FAT_PTR_EXTRA); 816 | let (_, size) = self.add_type(self.tcx.types.usize, 0)?; 817 | // We are expecting a pointer, in both cases. 818 | //self.check_same_size(lv_ty, self.tcx.types.usize)?; 819 | 820 | let reg = self.get_new_reg(); 821 | let mut insts = lv_insts; 822 | insts.append(&mut vec![ 823 | lir::Inst::Live(reg), 824 | lir::Inst::LoadFrom(reg, lv_reg, offset.bytes() as lir::Sz, size), 825 | lir::Inst::Dead(lv_reg), 826 | ]); 827 | 828 | Ok(InstSeq(insts, reg, self.tcx.types.usize)) 829 | } 830 | mir::Rvalue::Cast(ref kind, ref operand, ref cast_ty) => { 831 | let InstSeq(op_base, op_reg, _) = 832 | self.operand(operand).or_else( 833 | report_nyi!("mir::Rvalue::Cast(_, {:?}, _)", operand))?; 834 | match *kind { 835 | mir::CastKind::ReifyFnPointer => Err(Error::NYI), 836 | mir::CastKind::ClosureFnPointer => Err(Error::NYI), 837 | mir::CastKind::UnsafeFnPointer => Err(Error::NYI), 838 | mir::CastKind::Unsize => Err(Error::NYI), 839 | mir::CastKind::Misc => { 840 | let (_, size) = self.add_type(cast_ty, 0)?; 841 | let reg = self.get_new_reg(); 842 | let mut insts = op_base; 843 | insts.append(&mut vec![ 844 | lir::Inst::Resize(reg, op_reg, size), 845 | lir::Inst::Dead(op_reg), 846 | ]); 847 | Ok(InstSeq(insts, reg, cast_ty)) 848 | } 849 | } 850 | } 851 | mir::Rvalue::CheckedBinaryOp(op, ref lhs, ref rhs) => { 852 | let InstSeq(mut lhs_insts, lhs_reg, lhs_ty) = 853 | self.operand(lhs).or_else( 854 | report_nyi!("mir::Rvalue::CheckedBinaryOp({:?}, {:?}, _)", op, lhs))?; 855 | let InstSeq(mut rhs_insts, rhs_reg, rhs_ty) = 856 | self.operand(rhs).or_else( 857 | report_nyi!("mir::Rvalue::CheckedBinaryOp({:?}, _, {:?})", op, rhs))?; 858 | println!("mir::Rvalue::CheckedBinaryOp({:?}, {:?}, {:?})", op, lhs, rhs); 859 | let val_ty = op.ty(self.tcx, lhs_ty, rhs_ty); 860 | let ty = self.tcx.intern_tup(&[val_ty, self.tcx.types.bool], false); 861 | // Check that both operands have the same size. 862 | self.check_same_size(lhs_ty, rhs_ty)?; 863 | 864 | let chk_reg = self.get_new_reg(); 865 | let reg = self.get_new_reg(); 866 | let mut insts = vec![]; 867 | insts.append(&mut lhs_insts); 868 | insts.append(&mut rhs_insts); 869 | insts.push(lir::Inst::Live(reg)); 870 | insts.append(&mut {match op { 871 | mir::BinOp::Add => vec![ lir::Inst::Add(reg, lhs_reg, rhs_reg) ], 872 | mir::BinOp::Sub => vec![ lir::Inst::Sub(reg, lhs_reg, rhs_reg) ], 873 | mir::BinOp::Eq => vec![ lir::Inst::Eq (reg, lhs_reg, rhs_reg) ], 874 | mir::BinOp::Lt => vec![ lir::Inst::Lt (reg, lhs_reg, rhs_reg) ], 875 | mir::BinOp::Ge => vec![ lir::Inst::Ge (reg, lhs_reg, rhs_reg) ], 876 | _ => return Err(Error::NYI) 877 | }}); 878 | insts.append(&mut vec![ 879 | lir::Inst::Dead(lhs_reg), 880 | lir::Inst::Dead(rhs_reg), 881 | lir::Inst::Live(chk_reg), 882 | lir::Inst::Chk(chk_reg, reg), // x -> (x, bool) 883 | lir::Inst::Dead(reg), 884 | ]); 885 | 886 | Ok(InstSeq(insts, chk_reg, ty)) 887 | } 888 | mir::Rvalue::BinaryOp(op, ref lhs, ref rhs) => { 889 | let InstSeq(mut lhs_insts, lhs_reg, lhs_ty) = 890 | self.operand(lhs).or_else( 891 | report_nyi!("mir::Rvalue::BinaryOp({:?}, {:?}, _)", op, lhs))?; 892 | let InstSeq(mut rhs_insts, rhs_reg, rhs_ty) = 893 | self.operand(rhs).or_else( 894 | report_nyi!("mir::Rvalue::BinaryOp({:?}, _, {:?})", op, rhs))?; 895 | 896 | let ty = op.ty(self.tcx, lhs_ty, rhs_ty); 897 | // Check that both operands have the same size. 898 | self.check_same_size(lhs_ty, rhs_ty)?; 899 | let reg = self.get_new_reg(); 900 | let mut insts = vec![]; 901 | insts.append(&mut lhs_insts); 902 | insts.append(&mut rhs_insts); 903 | insts.push(lir::Inst::Live(reg)); 904 | insts.append(&mut {match op { 905 | mir::BinOp::Add => vec![ lir::Inst::Add(reg, lhs_reg, rhs_reg) ], 906 | mir::BinOp::Sub => vec![ lir::Inst::Sub(reg, lhs_reg, rhs_reg) ], 907 | mir::BinOp::Eq => vec![ lir::Inst::Eq (reg, lhs_reg, rhs_reg) ], 908 | mir::BinOp::Lt => vec![ lir::Inst::Lt (reg, lhs_reg, rhs_reg) ], 909 | mir::BinOp::Ge => vec![ lir::Inst::Ge (reg, lhs_reg, rhs_reg) ], 910 | _ => return Err(Error::NYI) 911 | }}); 912 | insts.append(&mut vec![ 913 | lir::Inst::Dead(lhs_reg), 914 | lir::Inst::Dead(rhs_reg) 915 | ]); 916 | 917 | Ok(InstSeq(insts, reg, ty)) 918 | } 919 | mir::Rvalue::Aggregate(ref kind, ref operands) => { 920 | let operands : Vec<_> = { 921 | let mut res = Vec::with_capacity(operands.len()); 922 | for op in operands { 923 | res.push( 924 | self.operand(op).or_else( 925 | report_nyi!("mir::Rvalue::Aggregate(_, [.. {:?} ..])", op))?) 926 | }; 927 | res 928 | }; 929 | 930 | let (ty, variant) = match **kind { 931 | mir::AggregateKind::Array(ty) => 932 | (self.tcx.mk_array(ty, operands.len() as u64), 0), 933 | mir::AggregateKind::Tuple => { 934 | let tys : Vec<_> = operands.iter().map(|op| { 935 | let &InstSeq(_, _, ty) = op; 936 | ty 937 | }).collect(); 938 | (self.tcx.intern_tup(&tys, false), 0) 939 | } 940 | mir::AggregateKind::Adt(def, variant, substs, _) => 941 | (self.tcx.mk_adt(def, substs), variant), 942 | _ => return Err(Error::NYI) 943 | }; 944 | 945 | let layout = self.tcx.layout_of(self.param_env.and(ty))?; 946 | let (_, size) = self.add_type(ty, 0)?; 947 | 948 | // Initialize the space for the type to 0. 949 | let reg = self.get_new_reg(); 950 | let mut insts = vec![ 951 | lir::Inst::Live(reg), 952 | lir::Inst::CopyImm(reg, 0 as lir::Imm, size as lir::Sz), 953 | ]; 954 | 955 | let fields = match &layout.variants { 956 | &ty::layout::Variants::Single { .. } => &layout.fields, 957 | // Layout::Univariant -> Variants::Tagged { .. smae thing .. } 958 | &ty::layout::Variants::Tagged { ref discr, ref variants, .. } => { 959 | // Initialize the discriminant 960 | let (_dty, sz) = match discr.value { 961 | ty::layout::Primitive::Int(ty::layout::Integer::I8, _) => (self.tcx.types.i8, 1), 962 | _ => { 963 | unreachable!("ty: {:?} / layout: {:?}", ty, layout); 964 | } 965 | }; 966 | 967 | let discr_reg = self.get_new_reg(); 968 | insts.append(&mut vec![ 969 | lir::Inst::Live(discr_reg), 970 | lir::Inst::CopyImm(discr_reg, variant as lir::Imm, sz as lir::Sz), 971 | lir::Inst::StoreInto(reg, discr_reg, 0, sz as lir::Sz), 972 | lir::Inst::Dead(discr_reg), 973 | ]); 974 | 975 | &variants[variant].fields 976 | } 977 | _ => { // Variants::NicheFilling 978 | return Err(Error::NYI); 979 | } 980 | }; 981 | 982 | // Add each operand 983 | for (i, InstSeq(mut op_insts, op_reg, op_ty)) in operands.into_iter().enumerate() { 984 | let (_, size) = self.add_type(op_ty, 0)?; 985 | let off = fields.offset(i).bytes(); 986 | insts.append(&mut op_insts); 987 | insts.append(&mut vec![ 988 | lir::Inst::StoreInto(reg, op_reg, 989 | off as lir::Sz, 990 | size as lir::Sz), 991 | lir::Inst::Dead(op_reg), 992 | ]); 993 | }; 994 | 995 | Ok(InstSeq(insts, reg, ty)) 996 | } 997 | mir::Rvalue::Discriminant(ref place) => { 998 | // Get the place as a value. 999 | let InstSeq(mut insts, reg, ty) = self.lvalue(place, PlaceCtx::Value)?; 1000 | // Extract the field which corresponds to the discriminant. 1001 | let layout = self.tcx.layout_of(self.param_env.and(ty))?; 1002 | // Read the discriminant of an ADT. 1003 | match &layout.variants { 1004 | // What?! Rustc produces a discriminant rvalue on a type 1005 | // which is neither a tagged place nor a niche, we should 1006 | // not generate anything for such assignment. 1007 | &ty::layout::Variants::Single { ref index } => { 1008 | let ret = self.get_new_reg(); 1009 | insts.append(&mut vec![ 1010 | lir::Inst::Dead(reg), 1011 | lir::Inst::CopyImm(ret, *index as lir::Imm, 1 as lir::Sz), 1012 | ]); 1013 | Ok(InstSeq(insts, ret, self.tcx.types.u8)) 1014 | } 1015 | _ => { 1016 | println!("rvalue: {:?}", rvalue); 1017 | println!("Layout = {:?}", layout); 1018 | Err(Error::NYI) 1019 | } 1020 | } 1021 | } 1022 | _ => { 1023 | println!("rvalue: {:?}", rvalue); 1024 | Err(Error::NYI) 1025 | } 1026 | } 1027 | } 1028 | 1029 | fn operand(&mut self, operand: &mir::Operand<'tcx>) -> Result, Error> { 1030 | match *operand { 1031 | mir::Operand::Copy(ref place) => { 1032 | Ok(self.lvalue(place, PlaceCtx::Value).or_else( 1033 | report_nyi!("mir::Operand::Copy({:?})", place))?) 1034 | } 1035 | mir::Operand::Move(ref place) => { 1036 | Ok(self.lvalue(place, PlaceCtx::Value).or_else( 1037 | report_nyi!("mir::Operand::Move({:?})", place))?) 1038 | } 1039 | mir::Operand::Constant(ref constant) => { 1040 | let res = match constant.literal.clone() { 1041 | mir::Literal::Value { ref value } if self.constval_use_static(&value.val) => { 1042 | 1043 | // Load the static in a register. 1044 | let reg = self.get_new_reg(); 1045 | let ty = { 1046 | if constant.ty.is_fn() { 1047 | // TyFnDecl has a 0-size, we want to save the 1048 | // address of the function, which has a 1049 | // pointer-size. 1050 | self.tcx.mk_fn_ptr(constant.ty.fn_sig(self.tcx)) 1051 | } else { 1052 | constant.ty 1053 | } 1054 | }; 1055 | 1056 | // Create a fake Rvalue which can be added in the 1057 | // list of statics. 1058 | let rv = { 1059 | if let ty::TyFnDef(_, _) = constant.ty.sty { 1060 | mir::Rvalue::Cast( 1061 | mir::CastKind::ReifyFnPointer, 1062 | operand.clone(), 1063 | ty 1064 | ) 1065 | } else { 1066 | mir::Rvalue::Use(operand.clone()) 1067 | } 1068 | }; 1069 | 1070 | let (off, sz) = self.register_static(&rv, ty)?; 1071 | Ok(InstSeq(vec![ 1072 | lir::Inst::Live(reg), 1073 | lir::Inst::Static(reg, off, sz), 1074 | ], reg, ty)) 1075 | }, 1076 | mir::Literal::Value { value } => { 1077 | Ok(self.constval(value.val, constant.ty).or_else( 1078 | report_nyi!("mir::Literal::Value: {:?} ", constant.literal))?) 1079 | }, 1080 | mir::Literal::Promoted { index } => { 1081 | // Duplicate the operand with the promoted value and 1082 | // register it to be known at runtime. 1083 | 1084 | let ty = constant.ty; 1085 | let index = self.register_promoted(index); 1086 | let operand = mir::Operand::Constant(Box::new(mir::Constant { 1087 | literal: mir::Literal::Promoted { index }, 1088 | ty: ty, 1089 | span: constant.span, 1090 | })); 1091 | let rv = mir::Rvalue::Use(operand); 1092 | let (off, sz) = self.register_static(&rv, ty)?; 1093 | let reg = self.get_new_reg(); 1094 | Ok(InstSeq(vec![ 1095 | lir::Inst::Live(reg), 1096 | lir::Inst::Static(reg, off, sz), 1097 | ], reg, ty)) 1098 | }, 1099 | }; 1100 | 1101 | Ok(res.or_else(report_nyi!("mir::Operand::Constant({:?})", constant))?) 1102 | } 1103 | } 1104 | } 1105 | 1106 | fn constval_use_static(&self, cv: &ConstVal) -> bool { 1107 | match cv { 1108 | &ConstVal::Function(_, _) => true, 1109 | &ConstVal::Str(_) => true, 1110 | _ => false, 1111 | } 1112 | } 1113 | 1114 | fn constval(&mut self, cv: ConstVal, ty: ty::Ty<'tcx>) -> Result, Error> { 1115 | let reg = self.get_new_reg(); 1116 | let mut insts = vec![ 1117 | lir::Inst::Live(reg), 1118 | ]; 1119 | let (_, size) = self.add_type(ty, 0)?; 1120 | let mut assign = match cv { 1121 | ConstVal::Bool(v) => vec![ 1122 | lir::Inst::CopyImm(reg, v as lir::Imm, size) 1123 | ], 1124 | ConstVal::Integral(ConstInt::I32(i)) => vec![ 1125 | lir::Inst::CopyImm(reg, i as lir::Imm, size) 1126 | ], 1127 | ConstVal::Integral(ConstInt::U8(i)) => vec![ 1128 | lir::Inst::CopyImm(reg, i as lir::Imm, size) 1129 | ], 1130 | ConstVal::Integral(ConstInt::Usize(ConstUsize::Us64(i))) => vec![ 1131 | lir::Inst::CopyImm(reg, i as lir::Imm, size) 1132 | ], 1133 | ConstVal::Function(_, _) | 1134 | ConstVal::Str(_) => 1135 | unreachable!("constval use static: cv: {:?} / ty: {:?}", cv, ty), 1136 | _ => { 1137 | println!("cv: {:?} / ty: {:?}", cv, ty); 1138 | return Err(Error::NYI) 1139 | } 1140 | }; 1141 | insts.append(&mut assign); 1142 | 1143 | Ok(InstSeq(insts, reg, ty)) 1144 | } 1145 | 1146 | fn terminator(&mut self, terminator: &mir::Terminator<'tcx>) -> Result { 1147 | let &mir::Terminator{ /* ref source_info,*/ ref kind, .. } = terminator; 1148 | match kind { 1149 | &mir::TerminatorKind::Resume => { 1150 | Ok(TermSeq(vec![], lir::Terminator::Unwind)) 1151 | } 1152 | &mir::TerminatorKind::Return => { 1153 | let (insts, value) = { 1154 | match self.ret_local { 1155 | Some(local) => { 1156 | let fake_rv = mir::Place::Local(local); 1157 | let InstSeq(insts, reg, _ty) = 1158 | self.lvalue(&fake_rv, PlaceCtx::Value).or_else( 1159 | report_nyi!("mir::TerminatorKind::Return"))?; 1160 | (insts, Some(reg)) 1161 | } 1162 | None => (vec![], None) 1163 | } 1164 | }; 1165 | Ok(TermSeq(insts, lir::Terminator::Return { 1166 | value: value 1167 | })) 1168 | } 1169 | &mir::TerminatorKind::Goto { ref target } => { 1170 | Ok(TermSeq(vec![], lir::Terminator::Goto { 1171 | target: self.get_block(*target) 1172 | })) 1173 | } 1174 | &mir::TerminatorKind::SwitchInt { 1175 | ref discr, 1176 | ref switch_ty, 1177 | ref values, 1178 | ref targets, 1179 | } => { 1180 | let InstSeq(idx_insts, idx_reg, _idx_ty) = 1181 | self.operand(discr).or_else( 1182 | report_nyi!("mir::TerminatorKind::SwitchInt(discr: {:?})", discr))?; 1183 | let range : lir::RangeInclusive = { 1184 | if switch_ty.sty == ty::TypeVariants::TyBool { 1185 | (0 as lir::Imm, 1 as lir::Imm) 1186 | } else { 1187 | let (_, size) = self.add_type(switch_ty, 0)?; 1188 | if size > ((0 as lir::Imm).count_zeros() as usize / 8) { 1189 | return Err(Error::NYI) 1190 | } 1191 | (isize::max_value() >> (8 - size), isize::min_value() >> (8 - size)) 1192 | } 1193 | }; 1194 | 1195 | assert_eq!(values.len() + 1, targets.len()); 1196 | Ok(TermSeq(idx_insts, lir::Terminator::SwitchInt { 1197 | value: idx_reg, 1198 | range: range, 1199 | targets: values.iter().zip(targets.iter()).map(|(v, t)| { 1200 | (v.to_u128_unchecked() as lir::Imm, self.get_block(*t)) 1201 | }).collect(), 1202 | otherwise: Some(self.get_block(*targets.iter().last().unwrap())), 1203 | })) 1204 | } 1205 | &mir::TerminatorKind::Call { 1206 | ref func, 1207 | ref args, 1208 | ref destination, 1209 | ref cleanup, 1210 | } => { 1211 | let InstSeq(mut insts, fun_reg, _fun_ty) = 1212 | self.operand(func).or_else( 1213 | report_nyi!("mir::TerminatorKind::Call(func: {:?})", func))?; 1214 | 1215 | // TODO: Follow what is done in librustc_trans/abi.rs to 1216 | // choose wether arguments are being transfered by value or 1217 | // by reference. 1218 | 1219 | // TODO: collect the ABI with: 1220 | // let sig = ty.fn_sig(self.tcx) 1221 | // let sig = bcx.tcx().erase_late_bound_regions_and_normalize(&sig); 1222 | // let abi = sig.abi; 1223 | 1224 | let mut args_reg = Vec::with_capacity(args.len() + 1); 1225 | for arg in args { 1226 | let InstSeq(mut arg_insts, arg_reg, arg_ty) = 1227 | self.operand(arg).or_else( 1228 | report_nyi!("mir::TerminatorKind::Call(args: [.. {:?} ..])", arg))?; 1229 | let (_, size) = self.add_type(arg_ty, 0)?; 1230 | // 0-size arguments are ignored. 1231 | if size != 0 { 1232 | insts.append(&mut arg_insts); 1233 | args_reg.push(arg_reg); 1234 | } 1235 | } 1236 | 1237 | let unwind_target = match cleanup { 1238 | &Some(ref cleanup_bb) => Some(self.get_block(*cleanup_bb)), 1239 | &None => None, 1240 | }; 1241 | 1242 | let return_target = match destination { 1243 | &Some((ref lvalue, ref bb)) => { 1244 | let resume = self.new_block(); 1245 | let target = self.get_block(*bb); 1246 | let InstSeq(mut ret_insts, ret_reg, ret_ty) = 1247 | self.lvalue(lvalue, PlaceCtx::Address).or_else( 1248 | report_nyi!("Call(destination: {:?}, _)", lvalue))?; 1249 | let ret_ty = ret_ty.builtin_deref(true).unwrap().ty; 1250 | 1251 | // TODO: check that the returned value is the same 1252 | // size as the lvalue storage space. 1253 | let (_, size) = self.add_type(ret_ty, 0)?; 1254 | 1255 | let is_fat_ptr = match ret_ty.sty { 1256 | ty::TyRawPtr(ref elem) | 1257 | ty::TyRef(_, ref elem) => !elem.ty.is_sized(self.tcx, self.param_env, DUMMY_SP), 1258 | ty::TyAdt(def, _) if def.is_box() => !ret_ty.boxed_ty().is_sized(self.tcx, self.param_env, DUMMY_SP), 1259 | _ => false, 1260 | }; 1261 | 1262 | if size <= 8 || is_fat_ptr { 1263 | // The returned values is returned by value, 1264 | // and fat-pointer are returned on 2 1265 | // registers. 1266 | let val_reg = self.get_new_reg(); 1267 | let ret_reg_def = (val_reg, size); 1268 | ret_insts.append(&mut vec![ 1269 | lir::Inst::Store(ret_reg, val_reg, size), 1270 | lir::Inst::Dead(val_reg), 1271 | lir::Inst::Dead(ret_reg), 1272 | ]); 1273 | 1274 | // Create a basic block in which the calls returns, 1275 | // and in which we set the lvalue with the returned 1276 | // value of the call. 1277 | let fp_reg = self.fp; 1278 | self.blocks[resume] = lir::BasicBlockData { 1279 | input_regs: vec![ 1280 | (fp_reg, 8 /* size of frame ptr */ ), 1281 | ret_reg_def 1282 | ], 1283 | output_regs: vec![ fp_reg ], 1284 | insts: ret_insts, 1285 | end: lir::Terminator::Goto { 1286 | target: target, 1287 | }, 1288 | }; 1289 | 1290 | Some(( Some(ret_reg_def), resume )) 1291 | } else { 1292 | // The address where the content should be 1293 | // initialized is given as the first 1294 | // argument of the function, and should be 1295 | // initialized by the callee. 1296 | // 1297 | // Note that the call will also return the 1298 | // same value, but we do not yet care about 1299 | // making it more efficient to read, thus we 1300 | // simply ignore the returned value for now. 1301 | insts.append(&mut ret_insts); 1302 | args_reg.insert(0, ret_reg); 1303 | 1304 | Some(( None, target )) 1305 | } 1306 | } 1307 | &None => None, 1308 | }; 1309 | 1310 | Ok(TermSeq(insts, lir::Terminator::Call { 1311 | function: fun_reg, 1312 | args: args_reg, 1313 | return_target, 1314 | unwind_target, 1315 | })) 1316 | } 1317 | &mir::TerminatorKind::Drop { ref location, target, unwind } => { 1318 | let InstSeq(lv_insts, lv_reg, lv_ty) = 1319 | self.lvalue(location, PlaceCtx::Address).or_else( 1320 | report_nyi!("Drop(location: {:?}, _)", location))?; 1321 | 1322 | // see resolve_drop_in_place 1323 | let def_id = self.tcx.require_lang_item(DropInPlaceFnLangItem); 1324 | let substs = self.tcx.intern_substs(&[ty::subst::Kind::from(lv_ty)]); 1325 | // see def_ty 1326 | let ty = self.tcx.type_of(def_id).subst(self.tcx, substs); 1327 | assert!(ty.is_fn()); 1328 | let ty = self.tcx.mk_fn_ptr(ty.fn_sig(self.tcx)); 1329 | 1330 | // Add the drop_in_place function address as a reference. 1331 | let rv = mir::Rvalue::Cast( 1332 | mir::CastKind::ReifyFnPointer, 1333 | mir::Operand::function_handle(self.tcx, def_id, substs, Default::default()), 1334 | ty 1335 | ); 1336 | let (off, sz) = self.register_static(&rv, ty)?; 1337 | 1338 | let fun_reg = self.get_new_reg(); 1339 | let mut insts = lv_insts; 1340 | insts.append(&mut vec![ 1341 | lir::Inst::Live(fun_reg), 1342 | lir::Inst::Static(fun_reg, off, sz), 1343 | ]); 1344 | 1345 | Ok(TermSeq(insts, lir::Terminator::Call { 1346 | function: fun_reg, 1347 | args: vec![lv_reg], 1348 | return_target: Some((None, self.get_block(target))), 1349 | unwind_target: unwind.map(|ub| self.get_block(ub)), 1350 | })) 1351 | } 1352 | &mir::TerminatorKind::Assert { 1353 | ref cond, expected, target, .. 1354 | } => { 1355 | let InstSeq(cond_insts, cond_reg, _cond_ty) = 1356 | self.operand(cond).or_else( 1357 | report_nyi!("Assert(cond: {:?}, _)", cond))?; 1358 | 1359 | // TODO: Add support for clean-up blocks, as well as for 1360 | // displaying error messages. 1361 | let assert_block = self.new_block(); 1362 | let fp_reg = self.fp; 1363 | self.blocks[assert_block] = lir::BasicBlockData { 1364 | input_regs: vec![ (fp_reg, 8 /* size of frame ptr */ ) ], 1365 | output_regs: vec![], 1366 | insts: vec![], 1367 | end: lir::Terminator::Unreachable, 1368 | }; 1369 | 1370 | let target_block = self.get_block(target); 1371 | let targets = { 1372 | if expected { 1373 | vec![ (0, assert_block), (1, target_block) ] 1374 | } else { 1375 | vec![ (0, target_block), (1, assert_block) ] 1376 | } 1377 | }; 1378 | 1379 | Ok(TermSeq(cond_insts, lir::Terminator::SwitchInt { 1380 | value: cond_reg, 1381 | range: (0 as lir::Imm, 1 as lir::Imm), 1382 | targets: targets, 1383 | otherwise: None, 1384 | })) 1385 | } 1386 | _ => Err(Error::NYI) 1387 | } 1388 | } 1389 | } 1390 | -------------------------------------------------------------------------------- /release.nix: -------------------------------------------------------------------------------- 1 | { nixpkgs ? 2 | , rust_overlay ? ~/.config/nixpkgs/overlays/nixpkgs-mozilla/rust-overlay.nix 3 | }: 4 | 5 | let 6 | rustChannel = { channel = "nightly"; date = "2018-02-19"; }; 7 | hj_overlay = self: super: { 8 | hj_rust = (super.rustChannelOf rustChannel).rust.override { 9 | extensions = [ "rust-src" ]; 10 | }; 11 | holyjit = super.callPackage ./default.nix { 12 | rust = self.hj_rust; 13 | }; 14 | }; 15 | pkgs = import nixpkgs { overlays = [ (import rust_overlay) hj_overlay ]; }; 16 | jobs = { 17 | inherit (pkgs) holyjit; 18 | }; 19 | in 20 | jobs 21 | -------------------------------------------------------------------------------- /rust-toolchain: -------------------------------------------------------------------------------- 1 | nightly-2018-02-19 2 | -------------------------------------------------------------------------------- /rustc.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | debug=true 4 | 5 | # CLI: rustc --crate name path/name.rs 6 | wrap=false; 7 | case $4 in 8 | tests/*) wrap=true;; 9 | examples/*) wrap=true;; 10 | benches/*) wrap=true;; 11 | esac 12 | 13 | if $wrap; then 14 | # Apparently, on MacOS/X we seems to fail to link against rustc libraries. 15 | # In the mean time, just add rust libraries to the LD_LIBRARY_PATH. 16 | #export LD_LIBRARY_PATH=$(rustc --print sysroot)/lib 17 | for arg; do 18 | case $arg in 19 | # .../target/debug/deps/libholyjit_lib-abcdef.rlib 20 | holyjit_lib=*) holyjit_lib=${arg#*=};; 21 | esac 22 | done 23 | 24 | test -z "$holyjit_lib" && \ 25 | echo 1>&2 "Unable to find holyjit_lib on the command line." 26 | 27 | holyjit=$(dirname $(dirname $holyjit_lib))/holyjit 28 | test \! -x $holyjit && \ 29 | echo 1>&2 "Unable to find $holyjit binary." 30 | 31 | if $debug; then 32 | log_dir=$(dirname $holyjit)/log 33 | mkdir -p $log_dir 34 | exec $holyjit "$@" -Z dump-mir=all -Z dump-mir-dir=$log_dir 35 | else 36 | exec $holyjit "$@" 37 | fi 38 | fi 39 | 40 | exec "$@" 41 | 42 | -------------------------------------------------------------------------------- /shell.nix: -------------------------------------------------------------------------------- 1 | (import ./release.nix {}).holyjit 2 | --------------------------------------------------------------------------------