├── .gitignore ├── CMakeLists.txt ├── LICENSE ├── README.md ├── config.hpp ├── cpu.hpp ├── cpu_types.hpp ├── examples ├── fib_iterative.hpp ├── fib_recursive.hpp ├── turing_machine.hpp └── turing_machine.py ├── instruction_def.hpp ├── instruction_util.hpp ├── instructions.hpp ├── main.cpp ├── type_list.hpp ├── util.hpp └── value_list.hpp /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | cmake-build-* 3 | venv 4 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.10) 2 | project(TemplateCpu) 3 | 4 | if (NOT CMAKE_BUILD_TYPE) 5 | set(CMAKE_BUILD_TYPE Release) 6 | endif (NOT CMAKE_BUILD_TYPE) 7 | 8 | set(CMAKE_CXX_STANDARD 20) 9 | 10 | set(CMAKE_CXX_FLAGS "-Wall -Wextra -Wpedantic -Werror -mtune=native -march=native") 11 | if (CMAKE_BUILD_TYPE STREQUAL "Debug") 12 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O0") 13 | else () 14 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3") 15 | endif () 16 | 17 | add_executable(${PROJECT_NAME} main.cpp) 18 | if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") # GCC 9 requires another flag for experimental concepts support. 19 | target_compile_options(${PROJECT_NAME} PUBLIC "-fconcepts") 20 | endif () 21 | 22 | # Change for larger programs, be careful with the maximum depth, 23 | # GCC will need lots of memory, clang will segfault at some point 24 | target_compile_options(${PROJECT_NAME} PUBLIC "-ftemplate-depth=2048") 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The DeclareProgram" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified DeclareProgram or a work based 90 | on the DeclareProgram. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the DeclareProgram, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified DeclareProgram. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the DeclareProgram's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the DeclareProgram. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the DeclareProgram, or the modifications to 211 | produce it from the DeclareProgram, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the DeclareProgram has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire DeclareProgram shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the DeclareProgram, that part may be used separately 351 | under those permissions, but the entire DeclareProgram remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the DeclareProgram as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the DeclareProgram. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the DeclareProgram or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the DeclareProgram or a work on which the DeclareProgram is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the DeclareProgram, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the DeclareProgram. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | DeclareProgram specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the DeclareProgram does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the DeclareProgram specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the DeclareProgram. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | DeclareProgram, unless a warranty or assumption of liability accompanies a 619 | copy of the DeclareProgram in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Template-CPU 2 | Implementing a CPU emulator using C++ Meta Programming with Concepts. 3 | The emulator can execute arbitrary programs written in Template-assembly (which 4 | is the C++ type system), under the limitations of the compiler. 5 | This proves the turing-completeness of the C++-Type-System. 6 | 7 | ## Build Instructions 8 | ### Compiler 9 | You need a C++-Compiler with support for Concepts (i.e. C++-20), for example: 10 | * GCC >= 9 11 | * Clang >= 10 12 | 13 | ### Building 14 | The project is a cmake project, for building execute (in the root directory of the repo): 15 | ```shell script 16 | mkdir build 17 | cd build 18 | cmake .. 19 | make 20 | ``` 21 | now there is an executable `TemplateCpu`. 22 | 23 | ## Syntax 24 | The syntax is pure C++, with classes which behave like instructions, see the examples 25 | below for more information on Template-Assembly. 26 | 27 | ### Instructions 28 | Below are all supported instructions, for most instructions there is also 29 | an Immediate version, denoted by an "I" at the end (so Add-Immediate is `AddI`), 30 | which takes a constant literal instead of a register as (last) argument. The full declaration of all Instruction 31 | with a more detailed explanation can be found in `instruction_def.hpp`. 32 | 33 | | Name | Description | Arguments | C++-Equivalent | 34 | | ----------- | ------------------------------------ | ---------------- | ------------------------- | 35 | | `Add` | Add | `res`,`a`,`b` | `res = a+b` | 36 | | `Sub` | Subtract | `res`,`a`,`b` | `res = a-b` | 37 | | `Mul` | Multiply | `res`,`a`,`b` | `res = a*b` | 38 | | `Div` | Divide (Exception at divide by zero) | `res`,`a`,`b` | `res = a/b` | 39 | | `And` | Bitwise And | `res`,`a`,`b` | `res = a & b` | 40 | | `Or` | Bitwise Or | `res`,`a`,`b` | `res = a \| b` | 41 | | `XOr` | Bitwise Exclusive-Or | `res`,`a`,`b` | `res = a ^ b` | 42 | | `Less` | Smaller comparison | `res`,`a`,`b` | `res = a < b` | 43 | | `Greater` | Greater comparison | `res`,`a`,`b` | `res = a > b` | 44 | | `Jump` | Jump to address in program | `reg` | `goto reg` | 45 | | `BranchEq` | Branch/Jump if equal | `a`,`b`,`reg` | `if (a == b) {goto reg;}` | 46 | | `BranchNEq` | Branch/Jump if not equal | `a`,`b`.`reg` | `if (a != b) {goto reg;}` | 47 | | `Store` | Store register to memory | `addr_reg`,`reg` | `*addr_reg = reg` | 48 | | `Load` | Load from memory into register | `reg`,`addr_reg` | `reg = *addr_reg` | 49 | 50 | ### Examples 51 | As an example there are two versions of a program to calculate the n-th fibonacci number additionally the last example 52 | is the implementation of a turing machine using Template-assembly. 53 | 54 | #### Running a program 55 | There are some utility functions to help debugging the Template-assembly code. 56 | A basic framework which shows some debug information looks like this: 57 | ```c++ 58 | #include "cpu.hpp" 59 | #include "util.hpp" 60 | 61 | using my_program = 62 | DeclareProgram< 63 | INSTRUCTIONS_HERE 64 | >; 65 | 66 | 67 | int main() { 68 | using result = Cpu::run; 69 | using printer = printer; 70 | 71 | if constexpr (result::is_breakpoint) { 72 | std::cout << "Stopped at breakpoint (pc=" << result::pc << ")" << std::endl; 73 | } 74 | 75 | std::cout << "Executed " << result::instr_count << " instructions\n" << std::endl; 76 | std::cout << "Registers:" << std::endl; 77 | printer::reg(); 78 | 79 | std::cout << "\nMemory:" << std::endl; 80 | printer::mem(); 81 | 82 | return 0; 83 | } 84 | ``` 85 | 86 | #### Fibonacci-Iterative 87 | The iterative solution calculates the fibonacci number using a loop. In (normal run-time) C++ 88 | the code would look like this: 89 | ```c++ 90 | int fib(int a) { 91 | int b = 1; 92 | int c = 0; 93 | int d = 0; 94 | int e = 1; 95 | 96 | do { 97 | ++b; 98 | c = d; 99 | d = e; 100 | e = c + d; 101 | } while (a != b); 102 | } 103 | 104 | fib(40); 105 | ``` 106 | 107 | In Template-Assembly the code looks like this: 108 | ```c++ 109 | using fib_iterative = 110 | DeclareProgram< 111 | AddI,// 0: a = 40 112 | AddI, // 1: b = 1 113 | AddI, // 2: c = 0 114 | AddI, // 3: d = 0 115 | AddI, // 4: e = 1 116 | AddI, // 5: b += 1 117 | Mov, // 6: c = d 118 | Mov, // 7: d = e 119 | Add,// 8: e = c + d 120 | BranchNEqI, // 9: if a != b -> jmp 5 121 | StoreI<0, Register::E> 122 | >; 123 | ``` 124 | 125 | #### Fibonacci-Recursive 126 | The recursive implementations demonstrates function calls and the stack. 127 | In (normal run-time) C++ the code would look like this: 128 | ```c++ 129 | int fib(int a) { 130 | if (a > 2) { 131 | return fib(a-1) + fib(a-2); 132 | } else { 133 | return 1; 134 | } 135 | } 136 | fib(8); 137 | ``` 138 | 139 | In template assembly the code looks like this: 140 | ```c++ 141 | /* 142 | * Stack Layout 143 | * STACK_PTR, RET, ARG, RES1 = FIB(ARG-1), ... 144 | */ 145 | using fib_recursive = 146 | DeclareProgram< 147 | // Init 148 | AddI, //0: set max value 149 | AddI, //1: store last address in RET 150 | 151 | // Check if base 152 | GreaterI, //2: LABEL_0 b = (a > 2) 153 | BranchNEqI, //3: if a > 2 -> jmp LABEL_1 154 | BranchEqI, //4: else -> jmp LABEL_2 155 | 156 | // Build up stack 157 | Store, //5: LABEL_1 (recursion) push STACK_PTR to stack 158 | AddI, //6: Forward stackptr to stack 159 | Store, //7: store ret on stack 160 | AddI, //8: Forward stackptr to stack 161 | Store, //9: push a to stack 162 | AddI, //10: Forward stackptr to stack by 2 163 | 164 | // Recursion 165 | AddI, //11: a -= 1 166 | AddI, //12: Store return address 167 | JumpI, //13: Recursion, jump to LABEL_0, result in e 168 | AddI, //14: b point to RES1 169 | Store, //15: Save e to RES1 170 | AddI, //16: b points to ARG on stack 171 | Load, //17: load ARG from stack into a 172 | AddI, //18: a -= 2 173 | AddI, //19: Store return address 174 | JumpI, //20, recursion, jump to LABEL_0, result in e 175 | 176 | // Final result 177 | AddI, //21: b points to RES1 178 | Load, //22: load RES1 into C 179 | Add, //23: e = e + c = fib(a-1) + fib(a-2) 180 | 181 | // Cleanup stack 182 | AddI, //24: b points to RET 183 | Load, //25: Restore RET 184 | AddI, //26: b points to STACK_PTR 185 | Load, //27: Restore RET 186 | JumpI, //28: jmp LABEL_3 187 | 188 | // Base 189 | AddI, //29: LABEL_2: e = 1 190 | 191 | // Return 192 | Jump //30: LABEL_3, return 193 | >; 194 | ``` 195 | 196 | #### Turing Machine 197 | There is also an emulator of a turing machine built upon the CPU emulator. The complete code can be found in 198 | `examples/turing_machine.hpp` there is also a python implementation of the same code located in 199 | `examples/turing_machine.py` this code is more readable, but is consistent to the template assembly implementation. 200 | Furthermore the python implementation allows the user to directly specify transitions without calculating memory 201 | addresses manually. The memory used for the python example can also be used to directly create the correct 202 | initialization code for the template assembly implementation. 203 | -------------------------------------------------------------------------------- /config.hpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file config.hpp 3 | * @author paul 4 | * @date 02.06.20 5 | * Definition of types and parameters of the CPU emulator. 6 | */ 7 | #ifndef TEMPLATE_CPU_CONFIG_HPP 8 | #define TEMPLATE_CPU_CONFIG_HPP 9 | 10 | #include 11 | 12 | using base_type = int; ///< The type used for registers and memory 13 | using mem_ptr_type = std::size_t; ///< The type used for enumerating addresses in the memory 14 | 15 | constexpr auto MEM_SIZE = 1024; ///< Size of the memory 16 | 17 | /** 18 | * Enum used for enumerating the registers 19 | */ 20 | enum class Register { 21 | ZERO, 22 | A, 23 | B, 24 | C, 25 | D, 26 | E, 27 | F, 28 | G, 29 | H, 30 | STACK_PTR, 31 | RET, 32 | LENGTH 33 | }; 34 | 35 | 36 | #endif //TEMPLATE_CPU_CONFIG_HPP 37 | -------------------------------------------------------------------------------- /cpu.hpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file cpu.hpp 3 | * @author paul 4 | * @date 25.05.20 5 | * Definition of the structs used for the main emulation loop. 6 | */ 7 | #ifndef TEMPLATE_CPU_CPU_HPP 8 | #define TEMPLATE_CPU_CPU_HPP 9 | 10 | #include "instructions.hpp" 11 | 12 | /** 13 | * Concept for a program as an alias for a type list 14 | * @tparam T the type to check 15 | */ 16 | template 17 | concept Program = IsTypeList::val; 18 | 19 | /** 20 | * Alias for declaring a program using a variadic template. 21 | * @tparam instructions the instructions 22 | */ 23 | template 24 | using DeclareProgram = typename FromVariadicType::type; 25 | 26 | /** 27 | * Struct containing the results of the execution of a program 28 | * @tparam registers the registers after execution 29 | * @tparam memory the memory after execution 30 | * @tparam PC_ the program counter after execution 31 | * @tparam instr_count_ the number of instructions executed 32 | * @tparam breakpoint true if the program was stopped due to a breakpoint 33 | */ 34 | template 35 | struct Result { 36 | using reg = registers; 37 | using mem = memory; 38 | static constexpr auto pc = PC_; 39 | static constexpr auto instr_count = instr_count_; 40 | static constexpr auto is_breakpoint = breakpoint; 41 | }; 42 | 43 | /** 44 | * Struct used for fetching the Instruction and running the Instruction on the current state. 45 | * @tparam program the program 46 | * @tparam old_pc the old/current program counter 47 | * @tparam registers the registers 48 | * @tparam memory the memory 49 | */ 50 | template 51 | struct ExecuteInstr { 52 | static constexpr auto pc = InstrImpl::type, registers, memory, old_pc>::pc; 53 | using reg = typename InstrImpl::type, registers, memory, old_pc>::reg; 54 | using mem = typename InstrImpl::type, registers, memory, old_pc>::mem; 55 | }; 56 | 57 | /** 58 | * The main struct for running the CPU emulation code. 59 | * @tparam program the program 60 | * @tparam size the size of the program (number of instructions) 61 | * @tparam PC the current program counter 62 | * @tparam registers the registers 63 | * @tparam memory the memory 64 | * @tparam instr_count the number of instructions which have been executed since start 65 | * @tparam max_instructions the maximum numbers of instructions to run 66 | */ 67 | template 68 | struct CpuState { 69 | using val = typename CpuState< 70 | program, 71 | size, 72 | ExecuteInstr::pc, 73 | typename ExecuteInstr::reg, 74 | typename ExecuteInstr::mem, 75 | instr_count + 1, 76 | max_instructions 77 | >::val; 78 | }; 79 | 80 | /** 81 | * Specialization if the program terminates normally 82 | */ 83 | template 84 | struct CpuState { 85 | using val = Result; 86 | }; 87 | 88 | /** 89 | * Specialization for breakpoints 90 | */ 91 | template 92 | struct CpuState { 93 | using val = Result; 94 | }; 95 | 96 | /** 97 | * Main struct for emulating a program. 98 | * @tparam program the program 99 | */ 100 | template 101 | struct Cpu { 102 | using run = typename CpuState< 103 | program, 104 | Size::val, 105 | 0, 106 | typename FillVal(Register::LENGTH), base_type, 0>::type, 107 | typename FillVal::type, 108 | 0, 109 | static_cast(-1) 110 | >::val; 111 | }; 112 | 113 | /** 114 | * Main struct for running a program until a certain number of instructions is executed. 115 | * @tparam program the program 116 | * @tparam instructions the number of instructions to run 117 | */ 118 | template 119 | struct CpuDebug { 120 | using run = typename CpuState< 121 | program, 122 | Size::val, 123 | 0, 124 | typename FillVal(Register::LENGTH), base_type, 0>::type, 125 | typename FillVal::type, 126 | 0, 127 | instructions 128 | >::val; 129 | }; 130 | 131 | #endif //TEMPLATE_CPU_CPU_HPP 132 | -------------------------------------------------------------------------------- /cpu_types.hpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file cpu_types.hpp 3 | * @author paul 4 | * @date 25.05.20 5 | * Types used for the cpu 6 | */ 7 | #ifndef TEMPLATE_CPU_CPU_TYPES_HPP 8 | #define TEMPLATE_CPU_CPU_TYPES_HPP 9 | 10 | #include "config.hpp" 11 | #include "value_list.hpp" 12 | 13 | /** 14 | * Registers are a value list of base_type type 15 | * @tparam T the type to check 16 | */ 17 | template 18 | concept Registers = IsValueList::val && ListOfType::val; 19 | 20 | /** 21 | * Memory is a value list of base_type type 22 | * @tparam T the type to check 23 | */ 24 | template 25 | concept Memory = IsValueList::val && ListOfType::val; 26 | 27 | #endif //TEMPLATE_CPU_CPU_TYPES_HPP 28 | -------------------------------------------------------------------------------- /examples/fib_iterative.hpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file fib_iterative.hpp 3 | * @author paul 4 | * @date 30.06.20 5 | * Implementation of an iterative algorithm for calculating fibonacci numbers, for more details see the README.md 6 | */ 7 | #ifndef TEMPLATE_CPU_FIB_ITERATIVE_HPP 8 | #define TEMPLATE_CPU_FIB_ITERATIVE_HPP 9 | 10 | #include "../cpu.hpp" 11 | 12 | using fib_iterative = 13 | DeclareProgram< 14 | AddI,// 0: a = 40 15 | AddI, // 1: b = 1 16 | AddI, // 2: c = 0 17 | AddI, // 3: d = 0 18 | AddI, // 4: e = 1 19 | AddI, // 5: b += 1 20 | Mov, // 6: c = d 21 | Mov, // 7: d = e 22 | Add,// 8: e = c + d 23 | BranchNEqI, // 9: if a != b -> jmp 5 24 | StoreI<0, Register::E> 25 | >; 26 | 27 | 28 | #endif //TEMPLATE_CPU_FIB_ITERATIVE_HPP 29 | -------------------------------------------------------------------------------- /examples/fib_recursive.hpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file fib_recursive.hpp 3 | * @author paul 4 | * @date 30.06.20 5 | * Implementation of an recursive algorithm for calculating fibonacci numbers, for more details see the README.md 6 | */ 7 | #ifndef TEMPLATE_CPU_FIB_RECURSIVE_HPP 8 | #define TEMPLATE_CPU_FIB_RECURSIVE_HPP 9 | 10 | #include "../cpu.hpp" 11 | 12 | /* 13 | * Stack Layout 14 | * STACK_PTR, RET, ARG, RES1 = FIB(ARG-1), ... 15 | */ 16 | using fib_recursive = 17 | DeclareProgram< 18 | // Init 19 | AddI, //0: set max value 20 | AddI, //1: store last address in RET 21 | 22 | // Check if base 23 | GreaterI, //2: LABEL_0 b = (a > 2) 24 | BranchNEqI, //3: if a > 2 -> jmp LABEL_1 25 | BranchEqI, //4: else -> jmp LABEL_2 26 | 27 | // Build up stack 28 | Store, //5: LABEL_1 (recursion) push STACK_PTR to stack 29 | AddI, //6: Forward stackptr to stack 30 | Store, //7: store ret on stack 31 | AddI, //8: Forward stackptr to stack 32 | Store, //9: push a to stack 33 | AddI, //10: Forward stackptr to stack by 2 34 | 35 | // Recursion 36 | AddI, //11: a -= 1 37 | AddI, //12: Store return address 38 | JumpI, //13: Recursion, jump to LABEL_0, result in e 39 | AddI, //14: b point to RES1 40 | Store, //15: Save e to RES1 41 | AddI, //16: b points to ARG on stack 42 | Load, //17: load ARG from stack into a 43 | AddI, //18: a -= 2 44 | AddI, //19: Store return address 45 | JumpI, //20, recursion, jump to LABEL_0, result in e 46 | 47 | // Final result 48 | AddI, //21: b points to RES1 49 | Load, //22: load RES1 into C 50 | Add, //23: e = e + c = fib(a-1) + fib(a-2) 51 | 52 | // Cleanup stack 53 | AddI, //24: b points to RET 54 | Load, //25: Restore RET 55 | AddI, //26: b points to STACK_PTR 56 | Load, //27: Restore RET 57 | JumpI, //28: jmp LABEL_3 58 | 59 | // Base 60 | AddI, //29: LABEL_2: e = 1 61 | 62 | // Return 63 | Jump //30: LABEL_3, return 64 | >; 65 | 66 | #endif //TEMPLATE_CPU_FIB_RECURSIVE_HPP 67 | -------------------------------------------------------------------------------- /examples/turing_machine.hpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file turing_machine.hpp 3 | * @author paul 4 | * @date 30.06.20 5 | * Implementation of a turing machine in template assembly. 6 | * 7 | * Memory layout: 8 | * The first TAPE_SIZE elements are the program (the tape) 9 | * 10 | * The next STATE_SIZE * SYMBOL_COUNT * 3 elements are the mapping of states and symbols to new symbol, 11 | * the new state and the head direction (0 is no movement, 1 is left, 2 is right) 12 | * 13 | * For a given state t and a symbol y the values can be calculated as: 14 | * new_symbol = TAPE_SIZE + SYMBOL_COUNT * state * 3 + symbol * 3 + 0 15 | * new_state = TAPE_SIZE + SYMBOL_COUNT * state * 3 + symbol * 3 + 1 16 | * head_direction = TAPE_SIZE + SYMBOL_COUNT * state * 3 + symbol * 3 + 2 17 | * 18 | * Register layout: 19 | * a is the current state 20 | * b is the index on the tape 21 | * 22 | * c is the value at the current position * 3 23 | * 24 | * e is new_symbol 25 | * f is new_state 26 | * g is head_direction (0: none, 1: left, 2: right) 27 | * 28 | * if the next state is 0 the program terminates. 29 | * 30 | * See: turing_machine.py for the same code in python (slightly more readable). Additionally the python code can 31 | * generate the correct memory initialization instructions and offset for the code. 32 | */ 33 | #ifndef TEMPLATE_CPU_TURING_MACHINE_HPP 34 | #define TEMPLATE_CPU_TURING_MACHINE_HPP 35 | 36 | #include "../cpu.hpp" 37 | 38 | constexpr auto TAPE_SIZE = 16; 39 | constexpr auto STATE_SIZE = 16; 40 | constexpr auto SYMBOL_COUNT = 16; 41 | 42 | static_assert(TAPE_SIZE + SYMBOL_COUNT * STATE_SIZE * 3 <= MEM_SIZE, "Program is to large!"); 43 | 44 | constexpr auto OFFSET = 23; // Generated from python script 45 | 46 | using turing_machine = 47 | DeclareProgram< 48 | // Memory initialization see turing_machine.py for the code for generating this initialization 49 | AddI, 50 | StoreI<16, Register::A>, 51 | AddI, 52 | StoreI<17, Register::A>, 53 | AddI, 54 | StoreI<18, Register::A>, 55 | AddI, 56 | StoreI<64, Register::A>, 57 | AddI, 58 | StoreI<65, Register::A>, 59 | AddI, 60 | StoreI<66, Register::A>, 61 | AddI, 62 | StoreI<112, Register::A>, 63 | AddI, 64 | StoreI<113, Register::A>, 65 | AddI, 66 | StoreI<114, Register::A>, 67 | AddI, 68 | StoreI<160, Register::A>, 69 | AddI, 70 | StoreI<162, Register::A>, 71 | AddI, 72 | 73 | // Turing machine implementation 74 | Load, // 0: c = *b; 75 | MulI, // 1: c *= 3; 76 | 77 | // Offset calculation 78 | MulI, // 2: e = a * 3 * SYMBOL_COUNT 79 | Add, // 3: e += c 80 | AddI, // 4: e += TAPE_SIZE 81 | 82 | // new state 83 | AddI, // 5: a = e + 1 84 | Load, // 6: a = *a 85 | 86 | // head_direction 87 | AddI, // 7: g = e + 2 88 | Load, // 8: g = *g 89 | 90 | // New symbol 91 | Load, // 9: e = *e 92 | Store, // 10: *b = e; 93 | 94 | // Head control 95 | BranchEqI, // 11: if (g == 0) goto LABEL_3 96 | LessI, // 12: g = g < 2 (<=> dir == 1) 97 | BranchNEqI, // 13: if (g != 0) goto LABEL_1 (<=> dir == 1) 98 | JumpI, // 14: else goto LABEL_2 99 | 100 | // Left 101 | SubI, // 15: LABEL_1: b -= 1 102 | JumpI, // 16: goto LABEL_3 103 | 104 | // Right 105 | AddI, // 17: LABEL_2: b += 1 106 | 107 | BranchEqI, // 18: LABEL_3 if (a == 0) break 108 | 109 | // while true 110 | JumpI // 19: goto 0 111 | 112 | >; 113 | 114 | #endif //TEMPLATE_CPU_TURING_MACHINE_HPP 115 | -------------------------------------------------------------------------------- /examples/turing_machine.py: -------------------------------------------------------------------------------- 1 | TAPE_SIZE = 16 2 | STATE_SIZE = 16 3 | SYMBOL_COUNT = 16 4 | mem = [0] * 1024 5 | 6 | none = 0 7 | left = 1 8 | right = 2 9 | 10 | 11 | def set_transition(state, symbol, new_state, new_symbol, direction): 12 | offset = TAPE_SIZE + SYMBOL_COUNT * state * 3 + symbol * 3 13 | mem[offset] = new_symbol 14 | mem[offset + 1] = new_state 15 | mem[offset + 2] = direction 16 | 17 | 18 | def print_mem_initialization(): 19 | c = 0 20 | for a, m in enumerate(mem): 21 | if m != 0: 22 | print(f"AddI,") 23 | print(f"StoreI<{a}, Register::A>,") 24 | c += 2 25 | 26 | print(f"AddI,") 27 | print() 28 | print(f"Offset: {c + 1}") 29 | 30 | 31 | set_transition(state=0, symbol=0, new_state=1, new_symbol=1, direction=right) 32 | set_transition(state=1, symbol=0, new_state=2, new_symbol=1, direction=right) 33 | set_transition(state=2, symbol=0, new_state=3, new_symbol=1, direction=right) 34 | set_transition(state=3, symbol=0, new_state=0, new_symbol=1, direction=right) 35 | 36 | print_mem_initialization() 37 | print() 38 | 39 | a_state = b_tape_index = c_value_at_index_x3 = e_new_symbol = f_new_state = g_head_direction = 0 40 | 41 | while True: 42 | c_value_at_index_x3 = mem[b_tape_index] 43 | c_value_at_index_x3 *= 3 44 | e_new_symbol = a_state * 3 * SYMBOL_COUNT 45 | e_new_symbol += c_value_at_index_x3 46 | e_new_symbol += TAPE_SIZE 47 | a_state = mem[e_new_symbol + 1] 48 | g_head_direction = mem[e_new_symbol + 2] 49 | e_new_symbol = mem[e_new_symbol] 50 | mem[b_tape_index] = e_new_symbol 51 | if g_head_direction == 1: 52 | b_tape_index -= 1 53 | elif g_head_direction == 2: 54 | b_tape_index += 1 55 | 56 | print(f"State: {a_state},\t" 57 | f"Tape Index: {b_tape_index},\t" 58 | f"Value at Index *3: {c_value_at_index_x3},\t" 59 | f"New symbol: {e_new_symbol},\t" 60 | f"New State: {f_new_state},\t" 61 | f"Head direction: {g_head_direction}") 62 | 63 | if a_state == 0: 64 | break 65 | -------------------------------------------------------------------------------- /instruction_def.hpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file instruction_def.hpp 3 | * @author paul 4 | * @date 27.05.20 5 | * Declaration of the instructions and the corresponding concept. 6 | */ 7 | #ifndef TEMPLATE_CPU_INSTRUCTION_DEF_HPP 8 | #define TEMPLATE_CPU_INSTRUCTION_DEF_HPP 9 | 10 | #include "config.hpp" 11 | 12 | /** 13 | * Addition Instruction: the register res is set to the value of the register a plus the value of register b 14 | * @tparam res result register 15 | * @tparam a register of first operand 16 | * @tparam b register of second operand 17 | */ 18 | template 19 | struct Add {}; 20 | 21 | /** 22 | * Addition with immediate Instruction: the register res is set to the value of the register a plus the value b 23 | * @tparam T the type of b 24 | * @tparam res the result register 25 | * @tparam a register of first operand 26 | * @tparam b value of the second operand 27 | */ 28 | template 29 | struct AddI {}; 30 | 31 | /** 32 | * Subtraction Instruction: the register res is set to the value of the register a minus the register b 33 | * @tparam res result register 34 | * @tparam a register of first operand 35 | * @tparam b register of second operand 36 | */ 37 | template 38 | struct Sub {}; 39 | 40 | /** 41 | * Subtraction with immediate Instruction: the register res is set to the value of the register a minus the value b 42 | * @tparam T the type of b 43 | * @tparam res the result register 44 | * @tparam a register of first operand 45 | * @tparam b value of the second operand 46 | */ 47 | template 48 | struct SubI {}; 49 | 50 | /** 51 | * Multiplication Instruction: the register res is set to the value of the register a times the register b 52 | * @tparam res result register 53 | * @tparam a register of first operand 54 | * @tparam b register of second operand 55 | */ 56 | template 57 | struct Mul {}; 58 | 59 | /** 60 | * Multiplication with immediate Instruction: the register res is set to the value of the register a times the value b 61 | * @tparam T the type of b 62 | * @tparam res the result register 63 | * @tparam a register of first operand 64 | * @tparam b value of the second operand 65 | */ 66 | template 67 | struct MulI {}; 68 | 69 | /** 70 | * Division Instruction: the register res is set to the value of the register a divided the register b. 71 | * If the value of the register b is zero a static_assert is triggered and the execution is stopped. 72 | * @tparam res result register 73 | * @tparam a register of first operand 74 | * @tparam b register of second operand 75 | */ 76 | template 77 | struct Div {}; 78 | 79 | /** 80 | * Division with immediate Instruction: the register res is set to the value of the register a divided by the value b. 81 | * If the b is zero a static_assert is triggered and the execution is stopped. 82 | * @tparam T the type of b 83 | * @tparam res the result register 84 | * @tparam a register of first operand 85 | * @tparam b value of the second operand 86 | */ 87 | template 88 | struct DivI {}; 89 | 90 | /** 91 | * Binary-And Instruction: the register res is set to the value of the binary and of the registers a and b. 92 | * @tparam res result register 93 | * @tparam a register of first operand 94 | * @tparam b register of second operand 95 | */ 96 | template 97 | struct And {}; 98 | 99 | /** 100 | * Binary-And with immediate Instruction: the register res is set to the value of the binary and of the register a and 101 | * the value b. 102 | * @tparam T the type of b 103 | * @tparam res the result register 104 | * @tparam a register of first operand 105 | * @tparam b value of the second operand 106 | */ 107 | template 108 | struct AndI {}; 109 | 110 | /** 111 | * Binary-Or Instruction: the register res is set to the value of the binary or of the registers a and b. 112 | * @tparam res result register 113 | * @tparam a register of first operand 114 | * @tparam b register of second operand 115 | */ 116 | template 117 | struct Or {}; 118 | 119 | /** 120 | * Binary-Or with immediate Instruction: the register res is set to the value of the binary or of the register a and 121 | * the value b. 122 | * @tparam T the type of b 123 | * @tparam res the result register 124 | * @tparam a register of first operand 125 | * @tparam b value of the second operand 126 | */ 127 | template 128 | struct OrI {}; 129 | 130 | /** 131 | * Binary-Exclusive-Or Instruction: the register res is set to the value of the binary xor of the registers a and b. 132 | * @tparam res result register 133 | * @tparam a register of first operand 134 | * @tparam b register of second operand 135 | */ 136 | template 137 | struct XOr {}; 138 | 139 | /** 140 | * Binary-Exclusive Or with immediate Instruction: the register res is set to the value of the binary or of the register 141 | * a and the value b. 142 | * @tparam T the type of b 143 | * @tparam res the result register 144 | * @tparam a register of first operand 145 | * @tparam b value of the second operand 146 | */ 147 | template 148 | struct XOrI {}; 149 | 150 | /** 151 | * Less Instruction: the register res is set to 1 of the value in register a is less than the one in register b. 152 | * @tparam res result register 153 | * @tparam a register of first operand 154 | * @tparam b register of second operand 155 | */ 156 | template 157 | struct Less {}; 158 | 159 | /** 160 | * Less with immediate Instruction: the register res is set to 1 of the value in register a is less than the value b. 161 | * @tparam T the type of b 162 | * @tparam res the result register 163 | * @tparam a register of first operand 164 | * @tparam b value of the second operand 165 | */ 166 | template 167 | struct LessI {}; 168 | 169 | /** 170 | * Greater Instruction: the register res is set to 1 of the value in register a is greater than the one in register b. 171 | * @tparam res result register 172 | * @tparam a register of first operand 173 | * @tparam b register of second operand 174 | */ 175 | template 176 | struct Greater {}; 177 | 178 | /** 179 | * Less with immediate Instruction: the register res is set to 1 of the value in register a is greater than the value b. 180 | * @tparam T the type of b 181 | * @tparam res the result register 182 | * @tparam a register of first operand 183 | * @tparam b value of the second operand 184 | */ 185 | template 186 | struct GreaterI {}; 187 | 188 | /** 189 | * Jump Instruction: sets the program counter to the value in register reg 190 | * @tparam reg contains the next program counter 191 | */ 192 | template 193 | struct Jump {}; 194 | 195 | /** 196 | * Jump with immediate Instruction: jumps to a fixed program counter address given by val 197 | * @tparam T the type of val 198 | * @tparam val the next program counter. 199 | */ 200 | template 201 | struct JumpI{}; 202 | 203 | /** 204 | * Branch on equal Instruction: jumps if the values in register a and b are equal. 205 | * @tparam a the first operand of the comparison 206 | * @tparam b the second operand of the comparison 207 | * @tparam target the register containing the program counter value at which to jump if the values are equal. 208 | */ 209 | template 210 | struct BranchEq {}; 211 | 212 | /** 213 | * Branch on equal with immediate Instruction: jumps if the values in register a and the value b are equal. 214 | * @tparam T the type of the target program counter 215 | * @tparam a the first operand of the comparison 216 | * @tparam b the second operand of the comparison 217 | * @tparam target the program counter value at which to jump if the values are equal. 218 | */ 219 | template 220 | struct BranchEqI {}; 221 | 222 | /** 223 | * Branch on not-equal Instruction: jumps if the values in register a and b are not equal. 224 | * @tparam a the first operand of the comparison 225 | * @tparam b the second operand of the comparison 226 | * @tparam target the register containing the program counter value at which to jump if the values are not equal. 227 | */ 228 | template 229 | struct BranchNEq {}; 230 | 231 | /** 232 | * Branch on not-equal with immediate Instruction: jumps if the values in register a and the value b are not equal. 233 | * @tparam T the type of the target program counter 234 | * @tparam a the first operand of the comparison 235 | * @tparam b the second operand of the comparison 236 | * @tparam target the program counter value at which to jump if the values are not equal. 237 | */ 238 | template 239 | struct BranchNEqI {}; 240 | 241 | /** 242 | * Store Instruction: Stores the value from a register into memory. 243 | * @tparam addr_reg the register containing the address to write to 244 | * @tparam reg the register containing the value to write 245 | */ 246 | template 247 | struct Store {}; 248 | 249 | /** 250 | * Store with immediate Instruction: Stores a value from register into memory. 251 | * @tparam addr the address at which to write 252 | * @tparam reg the register containing the value 253 | */ 254 | template 255 | struct StoreI {}; 256 | 257 | /** 258 | * Load Instruction: Loads a value from memory into a register. 259 | * @tparam reg the register in which to write 260 | * @tparam addr_reg the register containing the address to read from 261 | */ 262 | template 263 | struct Load {}; 264 | 265 | /** 266 | * Load with immediate Instruction: Loads a value from memory into a register. 267 | * @tparam reg the register in which to write 268 | * @tparam addr_reg the address to read from 269 | */ 270 | template 271 | struct LoadI {}; 272 | 273 | /** 274 | * Struct used for defining if a type is an Instruction. 275 | * @tparam T the type to check 276 | */ 277 | template 278 | struct is_instruction { 279 | static constexpr bool val = false; 280 | }; 281 | 282 | template 283 | struct is_instruction> { 284 | static constexpr bool val = true; 285 | }; 286 | 287 | template 288 | struct is_instruction> { 289 | static constexpr bool val = true; 290 | }; 291 | 292 | template 293 | struct is_instruction> { 294 | static constexpr bool val = true; 295 | }; 296 | 297 | template 298 | struct is_instruction> { 299 | static constexpr bool val = true; 300 | }; 301 | template 302 | struct is_instruction> { 303 | static constexpr bool val = true; 304 | }; 305 | 306 | template 307 | struct is_instruction> { 308 | static constexpr bool val = true; 309 | }; 310 | 311 | template 312 | struct is_instruction> { 313 | static constexpr bool val = true; 314 | }; 315 | 316 | template 317 | struct is_instruction> { 318 | static constexpr bool val = true; 319 | }; 320 | 321 | template 322 | struct is_instruction> { 323 | static constexpr bool val = true; 324 | }; 325 | 326 | template 327 | struct is_instruction> { 328 | static constexpr bool val = true; 329 | }; 330 | 331 | template 332 | struct is_instruction> { 333 | static constexpr bool val = true; 334 | }; 335 | 336 | template 337 | struct is_instruction> { 338 | static constexpr bool val = true; 339 | }; 340 | 341 | template 342 | struct is_instruction> { 343 | static constexpr bool val = true; 344 | }; 345 | 346 | template 347 | struct is_instruction> { 348 | static constexpr bool val = true; 349 | }; 350 | 351 | template 352 | struct is_instruction> { 353 | static constexpr bool val = true; 354 | }; 355 | 356 | template 357 | struct is_instruction> { 358 | static constexpr bool val = true; 359 | }; 360 | 361 | template 362 | struct is_instruction> { 363 | static constexpr bool val = true; 364 | }; 365 | 366 | template 367 | struct is_instruction> { 368 | static constexpr bool val = true; 369 | }; 370 | 371 | 372 | template 373 | struct is_instruction> { 374 | static constexpr bool val = true; 375 | }; 376 | 377 | template 378 | struct is_instruction> { 379 | static constexpr bool val = true; 380 | }; 381 | 382 | template 383 | struct is_instruction> { 384 | static constexpr bool val = true; 385 | }; 386 | 387 | template 388 | struct is_instruction> { 389 | static constexpr bool val = true; 390 | }; 391 | 392 | template 393 | struct is_instruction> { 394 | static constexpr bool val = true; 395 | }; 396 | 397 | template 398 | struct is_instruction> { 399 | static constexpr bool val = true; 400 | }; 401 | 402 | template 403 | struct is_instruction> { 404 | static constexpr bool val = true; 405 | }; 406 | 407 | template 408 | struct is_instruction> { 409 | static constexpr bool val = true; 410 | }; 411 | 412 | template 413 | struct is_instruction> { 414 | static constexpr bool val = true; 415 | }; 416 | 417 | template 418 | struct is_instruction> { 419 | static constexpr bool val = true; 420 | }; 421 | 422 | /** 423 | * Concept declaring an Instruction, that is one of the types listed above. 424 | * @tparam T the type to check 425 | */ 426 | template 427 | concept Instruction = is_instruction::val; 428 | 429 | #endif //TEMPLATE_CPU_INSTRUCTION_DEF_HPP 430 | -------------------------------------------------------------------------------- /instruction_util.hpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file instruction_util.hpp 3 | * @author paul 4 | * @date 04.06.20 5 | * Definition of utility structs for the implementation of instructions. 6 | */ 7 | #ifndef TEMPLATE_CPU_INSTRUCTION_UTIL_HPP 8 | #define TEMPLATE_CPU_INSTRUCTION_UTIL_HPP 9 | 10 | #include 11 | 12 | /** 13 | * Get the next program counter used for conditional jumps. 14 | * @tparam cond if the bool is false pc+1 is returned, else target is returned 15 | * @tparam PC the program counter for the if case 16 | * @tparam target the program counter for the else case 17 | */ 18 | template 19 | struct GetTarget { 20 | static constexpr std::size_t val = PC+1; 21 | }; 22 | 23 | /** 24 | * Specialization for GetTarget if cond==true 25 | */ 26 | template 27 | struct GetTarget { 28 | static constexpr std::size_t val = target; 29 | }; 30 | 31 | /** 32 | * Struct for implementing a division with exception if the result is undefined 33 | * @tparam T the type of the operands 34 | * @tparam a the numerator 35 | * @tparam b the denominator 36 | */ 37 | template 38 | struct DivWithException { 39 | static_assert(b != 0, "Division by zero!"); 40 | static constexpr auto val = a / b; 41 | }; 42 | 43 | 44 | #endif //TEMPLATE_CPU_INSTRUCTION_UTIL_HPP 45 | -------------------------------------------------------------------------------- /instructions.hpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file instructions.hpp 3 | * @author paul 4 | * @date 25.05.20 5 | * Implementation of all instructions. 6 | */ 7 | #ifndef TEMPLATE_CPU_INSTRUCTIONS_HPP 8 | #define TEMPLATE_CPU_INSTRUCTIONS_HPP 9 | 10 | #include "config.hpp" 11 | #include "cpu_types.hpp" 12 | #include "instruction_def.hpp" 13 | #include "instruction_util.hpp" 14 | 15 | /** 16 | * Struct used for implementing the different instructions 17 | * @tparam instr the Instruction to execute 18 | * @tparam registers the registers at the start of the execution 19 | * @tparam memory the memory at the start of the execution 20 | * @tparam old_pc the program counter at the start of the execution 21 | */ 22 | template 23 | struct InstrImpl {}; 24 | 25 | template 26 | struct InstrImpl, registers, memory, old_pc> { 27 | using reg = typename SetVal(res), 30 | GetVal(a)>::val 31 | + GetVal(b)>::val 32 | >::type; 33 | static constexpr auto pc = old_pc + 1; 34 | using mem = memory; 35 | }; 36 | 37 | template 38 | struct InstrImpl, registers, memory, old_pc> { 39 | using reg = typename SetVal(res), 42 | GetVal(a)>::val + b 43 | >::type; 44 | static constexpr auto pc = old_pc + 1; 45 | using mem = memory; 46 | }; 47 | 48 | template 49 | struct InstrImpl, registers, memory, old_pc> { 50 | using reg = typename SetVal(res), 53 | GetVal(a)>::val - GetVal(b)>::val 54 | >::type; 55 | static constexpr auto pc = old_pc + 1; 56 | using mem = memory; 57 | }; 58 | 59 | template 60 | struct InstrImpl, registers, memory, old_pc> { 61 | using reg = typename SetVal(res), 64 | GetVal(a)>::val - b 65 | >::type; 66 | static constexpr auto pc = old_pc + 1; 67 | using mem = memory; 68 | }; 69 | 70 | template 71 | struct InstrImpl, registers, memory, old_pc> { 72 | using reg = typename SetVal(res), 75 | GetVal(a)>::val * GetVal(b)>::val 76 | >::type; 77 | static constexpr auto pc = old_pc + 1; 78 | using mem = memory; 79 | }; 80 | 81 | template 82 | struct InstrImpl, registers, memory, old_pc> { 83 | using reg = typename SetVal(res), 86 | GetVal(a)>::val * b 87 | >::type; 88 | static constexpr auto pc = old_pc + 1; 89 | using mem = memory; 90 | }; 91 | 92 | template 93 | struct InstrImpl, registers, memory, old_pc> { 94 | using reg = typename SetVal(res), 97 | DivWithException(a)>::val, GetVal(b)>::val>::val 98 | >::type; 99 | static constexpr auto pc = old_pc + 1; 100 | using mem = memory; 101 | }; 102 | 103 | template 104 | struct InstrImpl, registers, memory, old_pc> { 105 | using reg = typename SetVal(res), 108 | DivWithException(a)>::val, b>::val 109 | >::type; 110 | static constexpr auto pc = old_pc + 1; 111 | using mem = memory; 112 | }; 113 | 114 | template 115 | struct InstrImpl, registers, memory, old_pc> { 116 | using reg = typename SetVal(res), 119 | GetVal(a)>::val & GetVal(b)>::val 120 | >::type; 121 | static constexpr auto pc = old_pc + 1; 122 | using mem = memory; 123 | }; 124 | 125 | template 126 | struct InstrImpl, registers, memory, old_pc> { 127 | using reg = typename SetVal(res), 130 | GetVal(a)>::val & b 131 | >::type; 132 | static constexpr auto pc = old_pc + 1; 133 | using mem = memory; 134 | }; 135 | 136 | template 137 | struct InstrImpl, registers, memory, old_pc> { 138 | using reg = typename SetVal(res), 141 | GetVal(a)>::val | GetVal(b)>::val 142 | >::type; 143 | static constexpr auto pc = old_pc + 1; 144 | using mem = memory; 145 | }; 146 | 147 | template 148 | struct InstrImpl, registers, memory, old_pc> { 149 | using reg = typename SetVal(res), 152 | GetVal(a)>::val | b 153 | >::type; 154 | static constexpr auto pc = old_pc + 1; 155 | using mem = memory; 156 | }; 157 | 158 | template 159 | struct InstrImpl, registers, memory, old_pc> { 160 | using reg = typename SetVal(res), 163 | GetVal(a)>::val ^ GetVal(b)>::val 164 | >::type; 165 | static constexpr auto pc = old_pc + 1; 166 | using mem = memory; 167 | }; 168 | 169 | template 170 | struct InstrImpl, registers, memory, old_pc> { 171 | using reg = typename SetVal(res), 174 | GetVal(a)>::val ^ b 175 | >::type; 176 | static constexpr auto pc = old_pc + 1; 177 | using mem = memory; 178 | }; 179 | 180 | template 181 | struct InstrImpl, registers, memory, old_pc> { 182 | using reg = typename SetVal(res), 185 | GetVal(a)>::val < GetVal(b)>::val 186 | >::type; 187 | static constexpr auto pc = old_pc + 1; 188 | using mem = memory; 189 | }; 190 | 191 | template 192 | struct InstrImpl, registers, memory, old_pc> { 193 | using reg = typename SetVal(res), 196 | GetVal(a)>::val < b 197 | >::type; 198 | static constexpr auto pc = old_pc + 1; 199 | using mem = memory; 200 | }; 201 | 202 | template 203 | struct InstrImpl, registers, memory, old_pc> { 204 | using reg = typename SetVal(res), 207 | GetVal(b)>::val < GetVal(a)>::val 208 | >::type; 209 | static constexpr auto pc = old_pc + 1; 210 | using mem = memory; 211 | }; 212 | 213 | template 214 | struct InstrImpl, registers, memory, old_pc> { 215 | using reg = typename SetVal(res), 218 | b < GetVal(a)>::val 219 | >::type; 220 | static constexpr auto pc = old_pc + 1; 221 | using mem = memory; 222 | }; 223 | 224 | template 225 | struct InstrImpl, registers, memory, old_pc> { 226 | using reg = registers; 227 | static constexpr std::size_t pc = GetVal(res)>::val; 228 | using mem = memory; 229 | }; 230 | 231 | template 232 | struct InstrImpl, registers, memory, old_pc> { 233 | using reg = registers; 234 | static constexpr std::size_t pc = val; 235 | using mem = memory; 236 | }; 237 | 238 | template 239 | struct InstrImpl, registers, memory, old_pc> { 240 | using reg = registers; 241 | static constexpr std::size_t pc = GetTarget< 242 | GetVal(a)>::val == GetVal(b)>::val, 243 | old_pc, 244 | GetVal(target)>::val 245 | >::val; 246 | using mem = memory; 247 | }; 248 | 249 | template 250 | struct InstrImpl, registers, memory, old_pc> { 251 | using reg = registers; 252 | static constexpr std::size_t pc = GetTarget< 253 | GetVal(a)>::val == GetVal(b)>::val, 254 | old_pc, 255 | target 256 | >::val; 257 | using mem = memory; 258 | }; 259 | 260 | template 261 | struct InstrImpl, registers, memory, old_pc> { 262 | using reg = registers; 263 | static constexpr std::size_t pc = GetTarget< 264 | GetVal(a)>::val != GetVal(b)>::val, 265 | old_pc, 266 | GetVal(target)>::val 267 | >::val; 268 | using mem = memory; 269 | }; 270 | 271 | template 272 | struct InstrImpl, registers, memory, old_pc> { 273 | using reg = registers; 274 | static constexpr std::size_t pc = GetTarget< 275 | GetVal(a)>::val != GetVal(b)>::val, 276 | old_pc, 277 | target 278 | >::val; 279 | using mem = memory; 280 | }; 281 | 282 | template 283 | struct InstrImpl, registers, memory, old_pc> { 284 | using reg = registers; 285 | static constexpr std::size_t pc = old_pc + 1; 286 | using mem = typename SetVal< 287 | base_type, 288 | memory, 289 | GetVal(addr_reg)>::val, 290 | GetVal(data_reg)>::val 291 | >::type; 292 | }; 293 | 294 | template 295 | struct InstrImpl, registers, memory, old_pc> { 296 | using reg = typename SetVal< 297 | base_type, 298 | registers, 299 | static_cast(data_reg), 300 | GetVal(addr_reg)>::val 302 | >::val 303 | >::type; 304 | static constexpr std::size_t pc = old_pc + 1; 305 | using mem = memory; 306 | }; 307 | 308 | template 309 | struct InstrImpl, registers, memory, old_pc> { 310 | using reg = registers; 311 | static constexpr std::size_t pc = old_pc + 1; 312 | using mem = typename SetVal(data_reg)>::val>::type; 313 | }; 314 | 315 | template 316 | struct InstrImpl, registers, memory, old_pc> { 317 | using reg = typename SetVal(data_reg), GetVal::val>::type; 318 | static constexpr std::size_t pc = old_pc + 1; 319 | using mem = memory; 320 | }; 321 | 322 | 323 | // Pseudo instructions 324 | 325 | /** 326 | * Pseudo Instruction for copying the value from a register into another. 327 | * @tparam a the register to copy to 328 | * @tparam b the register to copy from 329 | */ 330 | template 331 | using Mov = AddI; 332 | 333 | 334 | #endif //TEMPLATE_CPU_INSTRUCTIONS_HPP 335 | -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | #include "cpu.hpp" 2 | #include "util.hpp" 3 | 4 | #include "examples/turing_machine.hpp" 5 | 6 | int main() { 7 | using result = Cpu::run; 8 | using printer = printer; 9 | 10 | if constexpr (result::is_breakpoint) { 11 | std::cout << "Stopped at breakpoint (pc=" << result::pc << ")" << std::endl; 12 | } 13 | 14 | std::cout << "Executed " << result::instr_count << " instructions\n" << std::endl; 15 | std::cout << "Registers:" << std::endl; 16 | printer::reg(); 17 | 18 | std::cout << "\nMemory:" << std::endl; 19 | printer::mem(); 20 | 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /type_list.hpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file TypeList.hpp 3 | * @author paul 4 | * @date 25.05.20 5 | * Header used for the declaration of the type list and all related structs and concepts. 6 | */ 7 | #ifndef TEMPLATE_CPU_TYPE_LIST_HPP 8 | #define TEMPLATE_CPU_TYPE_LIST_HPP 9 | 10 | #include 11 | #include 12 | 13 | /** 14 | * Declaration of the type used for elements of a type list, which is a singly linked list. 15 | * @tparam T the type (i.e. element) at the current position 16 | * @tparam next_ the next element. Should be of type TypeListElem or ListEnd. 17 | */ 18 | template 19 | struct TypeListElem { 20 | using elem = T; 21 | using next = next_; 22 | }; 23 | 24 | /** 25 | * Declaration of the type used for signaling the end of a list, in normal runtime languages a nullptr would be used 26 | * here. 27 | */ 28 | struct ListEnd {}; 29 | 30 | // list concepts 31 | 32 | /** 33 | * Struct for specifying if a type is type list, i.e. if it is either a instantiation of TypeListElem or ListEnd. 34 | * This is the general type which is always false, for the correct types the struct is specialized. 35 | * @tparam T the type to check 36 | */ 37 | template 38 | struct IsTypeList { 39 | static constexpr bool val = false; 40 | }; 41 | 42 | /** 43 | * Specialization of IsTypeList for TypeListElem 44 | * @see IsTypeList 45 | * @see TypeListElem 46 | */ 47 | template 48 | struct IsTypeList> { 49 | static constexpr bool val = true; 50 | }; 51 | 52 | /** 53 | * Specialization of IsTypeList for ListEnd 54 | * @see IsTypeList 55 | * @see TypeListElem 56 | */ 57 | template<> 58 | struct IsTypeList { 59 | static constexpr bool val = true; 60 | }; 61 | 62 | /** 63 | * Concept that specifies whether a type is a type list 64 | * @see IsTypeList 65 | * @tparam T the type to check 66 | */ 67 | template 68 | concept TypeList = IsTypeList::val; 69 | 70 | // Helper functions 71 | 72 | /** 73 | * Returns the size / length of the list 74 | * @tparam list the list to use 75 | */ 76 | template 77 | struct Size { 78 | static constexpr std::size_t val = Size::val + 1; 79 | }; 80 | 81 | template<> 82 | struct Size { 83 | static constexpr std::size_t val = 0; 84 | }; 85 | 86 | /** 87 | * Get the type at an index 88 | * @tparam list the list 89 | * @tparam index the index needs to be less than the size of the list 90 | */ 91 | template 92 | struct GetType { 93 | static_assert(index < Size::val, "GetType out of bounds"); 94 | using type = typename GetType::type; 95 | }; 96 | 97 | template 98 | struct GetType { 99 | using type = typename list::elem; 100 | }; 101 | 102 | /** 103 | * Set the type at an index, a new, modified, list is returned 104 | * @tparam T the type to insert 105 | * @tparam list the list in which to insert 106 | * @tparam index the index at which to insert needs to be less than the size of the list 107 | */ 108 | template 109 | struct SetType { 110 | static_assert(index < Size::val, "SetType out of bounds"); 111 | using type = TypeListElem::type>; 112 | }; 113 | 114 | template 115 | struct SetType { 116 | using type = TypeListElem; 117 | }; 118 | 119 | /** 120 | * Create a list from a variadic type list. 121 | * @tparam T the first type 122 | * @tparam Ts the following types 123 | */ 124 | template 125 | struct FromVariadicType { 126 | using type = TypeListElem::type>; 127 | }; 128 | 129 | template 130 | struct FromVariadicType { 131 | using type = TypeListElem; 132 | }; 133 | 134 | /** 135 | * Create a list of a certain length of a certain type. 136 | * @tparam N the number of elements 137 | * @tparam T the type to use 138 | */ 139 | template 140 | struct FillType { 141 | using type = TypeListElem::type>; 142 | }; 143 | 144 | template 145 | struct FillType<0, T> { 146 | using type = ListEnd; 147 | }; 148 | 149 | #endif //TEMPLATE_CPU_TYPE_LIST_HPP 150 | -------------------------------------------------------------------------------- /util.hpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file util.hpp 3 | * @author paul 4 | * @date 25.05.20 5 | * Definition of utility functions for printing the results of program execution. 6 | */ 7 | #ifndef TEMPLATE_CPU_UTIL_HPP 8 | #define TEMPLATE_CPU_UTIL_HPP 9 | 10 | #include 11 | #include 12 | 13 | #include "config.hpp" 14 | 15 | /** 16 | * Macro for generating a case statement which returns the string representation of the enum value 17 | */ 18 | #define ADD_CASE(a) case Register::a: return #a; 19 | 20 | /** 21 | * Get the string representation of a register. 22 | * @param reg the register 23 | * @return a string, with the exact name as the enum value 24 | */ 25 | auto getRegisterName(Register reg) -> std::string { 26 | switch (reg) { 27 | ADD_CASE(ZERO) 28 | ADD_CASE(A) 29 | ADD_CASE(B) 30 | ADD_CASE(C) 31 | ADD_CASE(D) 32 | ADD_CASE(E) 33 | ADD_CASE(F) 34 | ADD_CASE(G) 35 | ADD_CASE(H) 36 | ADD_CASE(STACK_PTR) 37 | ADD_CASE(RET) 38 | default: return "ERROR"; 39 | } 40 | } 41 | 42 | /** 43 | * Implementation of a compile time loop for printing the registers. 44 | * @tparam registers the register map 45 | * @tparam c the index at which to print 46 | */ 47 | template 48 | struct registerPrinterImpl { 49 | static void print() { 50 | std::cout << getRegisterName(static_cast(c)) << " (" << c << "):\t" << GetVal::val << std::endl; 51 | registerPrinterImpl::print(); 52 | } 53 | }; 54 | 55 | template 56 | struct registerPrinterImpl { 57 | static void print() {} 58 | }; 59 | 60 | /** 61 | * Implementation of a compile time loop for printing the memory 62 | * @tparam memory the memory 63 | * @tparam c the index at which to print 64 | */ 65 | template 66 | struct memoryPrinterImpl { 67 | static void print() { 68 | constexpr auto WORDS_PER_LINE = 16; 69 | std::cout << std::setw(10) << GetVal::val; 70 | if (c % WORDS_PER_LINE == (WORDS_PER_LINE - 1)) { 71 | std::cout << std::endl; 72 | } 73 | memoryPrinterImpl::print(); 74 | } 75 | }; 76 | 77 | template 78 | struct memoryPrinterImpl { 79 | static void print() {} 80 | }; 81 | 82 | /** 83 | * Struct used for printing registers and memory from a program result 84 | * @tparam registers the registers 85 | * @tparam memory the memory 86 | */ 87 | template 88 | struct printer { 89 | /** 90 | * Runtime function to printing the registers 91 | */ 92 | static void reg() { 93 | registerPrinterImpl::print(); 94 | } 95 | 96 | /** 97 | * Runtime function for printing the memory 98 | */ 99 | static void mem() { 100 | memoryPrinterImpl::print(); 101 | } 102 | }; 103 | 104 | 105 | #endif //TEMPLATE_CPU_UTIL_HPP 106 | -------------------------------------------------------------------------------- /value_list.hpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @file ValueList.hpp 3 | * @author paul 4 | * @date 25.05.20 5 | * Header related to the value list and all related structs and concepts. 6 | */ 7 | #ifndef TEMPLATE_CPU_VALUE_LIST_HPP 8 | #define TEMPLATE_CPU_VALUE_LIST_HPP 9 | 10 | #include "type_list.hpp" 11 | 12 | /** 13 | * Container used to wrap a value into a type. 14 | * @tparam T the type of the value 15 | * @tparam val_ the value 16 | */ 17 | template 18 | struct ValueContainer { 19 | using type = T; 20 | static constexpr auto val = val_; 21 | }; 22 | 23 | // Concepts 24 | 25 | /** 26 | * Struct to check if a type is a value_container 27 | * @tparam T the type ti check 28 | */ 29 | template 30 | struct IsValueContainer { 31 | static constexpr auto val = false; 32 | }; 33 | 34 | template 35 | struct IsValueContainer> { 36 | static constexpr auto val = true; 37 | }; 38 | 39 | /** 40 | * Check if a type is a value list, that is a type list with elements which are value containers. 41 | * @tparam T the type to check 42 | */ 43 | template 44 | struct IsValueList { 45 | static constexpr auto val = IsValueContainer::val && IsValueList::val; 46 | }; 47 | 48 | template<> 49 | struct IsValueList { 50 | static constexpr auto val = true; 51 | }; 52 | 53 | /** 54 | * Concept for the definition of a value list based on IsValueList 55 | * @tparam T the type to check 56 | */ 57 | template 58 | concept ValueList = IsValueList::val; 59 | 60 | /** 61 | * Check if a value list is of a certain type (i.e. all types in the value containers are of the certain type). 62 | * @tparam T the type to check 63 | * @tparam list the list to check 64 | */ 65 | template 66 | struct ListOfType { 67 | static constexpr auto val = 68 | std::is_same::value && ListOfType::val; 69 | }; 70 | 71 | template 72 | struct ListOfType { 73 | static constexpr auto val = true; 74 | }; 75 | 76 | /** 77 | * Concept to check if a value list of type. 78 | * @tparam T the type 79 | * @tparam list the list 80 | */ 81 | template 82 | concept value_list_of_type = ListOfType::val; 83 | 84 | 85 | // Helper functions 86 | 87 | /** 88 | * Get the value at a certain index in a ValueList 89 | * @tparam list the list 90 | * @tparam index the index needs to be less than the size of the list 91 | */ 92 | template 93 | struct GetVal { 94 | static constexpr auto val = GetType::type::val; 95 | }; 96 | 97 | /** 98 | * Set a value inside a value list. This will return a new list with the changed value. 99 | * @tparam T the type of the new value 100 | * @tparam list the list on which to work 101 | * @tparam index the index at which to change 102 | * @tparam val the new value 103 | */ 104 | template requires value_list_of_type 105 | struct SetVal { 106 | using type = typename SetType, list, index>::type; 107 | }; 108 | 109 | /** 110 | * Create a value list of a single type of a variadic list of values. 111 | * @tparam T the type to use 112 | * @tparam t the first value 113 | * @tparam ts the other values 114 | */ 115 | template 116 | struct FromVariadicVal { 117 | using type = TypeListElem, typename FromVariadicVal::type>; 118 | }; 119 | 120 | template 121 | struct FromVariadicVal { 122 | using type = TypeListElem, ListEnd>; 123 | }; 124 | 125 | /** 126 | * Fill a value list with N values of a fixed type 127 | * @tparam N the number of elements 128 | * @tparam T the type of the elements 129 | * @tparam t the value of the elements 130 | */ 131 | template 132 | struct FillVal { 133 | using type = typename FillType>::type; 134 | }; 135 | 136 | #endif //TEMPLATE_CPU_VALUE_LIST_HPP 137 | --------------------------------------------------------------------------------