Initial commit

This commit is contained in:
Alexis Engelke
2019-05-05 19:20:06 +02:00
commit 9d834ce753
35 changed files with 6137 additions and 0 deletions
+3
View File
@@ -0,0 +1,3 @@
/build*
/subprojects/*/
*.sublime-workspace
+456
View File
@@ -0,0 +1,456 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
+20
View File
@@ -0,0 +1,20 @@
# Rellume — Lifts x86-64 to LLVM IR
Rellume is a lifter for x86-64 machine code to LLVM IR with focus on the performance of the lifted code. The generated LLVM IR can be compiled and executed again, for example using LLVM's JIT compiler, ideally having the same (or even better) performance as the original code. Special care is taken to model the SSE instructions and pointers in a way that the optimizer can generate efficient code. The lifter operates on function basis and functions currently have to obey the System V calling convention.
### Use Cases
- Binary rewriting:
- Performance improvement: specialization for runtime data, e.g. known parameters or memory locations. This is implemented in the LLVM back-end of [DBrew](https://github.com/caps-tum/dbrew/).
- Instrumentation: insert tracing and interception code in hot code paths, where high quality machine code is required.
- Binary analysis: existing tooling for analysis of LLVM IR code can be re-used for binary code.
### Example
See [examples/lifter.c](https://github.com/aengelke/rellume/blob/master/examples/lifter.c)
### Publications
- Alexis Engelke and Josef Weidendorfer. Using LLVM for Optimized Light-Weight Binary Re-Writing at Runtime. In Proceedings of the 22nd int. Workshop on High-Level Parallel Programming Models and Supportive Environments (HIPS 2017). Orlando, US, 2017 ([PDF of pre-print version](http://wwwi10.lrr.in.tum.de/~weidendo/pubs/hips17.pdf))
### License
LGPLv2.1+
+9
View File
@@ -0,0 +1,9 @@
{
"folders":
[
{
"path": ".",
"folder_exclude_patterns": ["build*", "subprojects/*"],
}
]
}
+92
View File
@@ -0,0 +1,92 @@
/**
* This file is part of Rellume.
*
* (c) 2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <llvm-c/Core.h>
#include <lldecoder.h>
#include <llfunc.h>
static
float
sample_func(size_t n, float* arr)
{
float res = 0;
for (size_t i = 0; i < n; i++)
res += arr[i];
return res;
}
int
main(void)
{
// Create LLVM module
LLVMModuleRef mod = LLVMModuleCreateWithName("lifter");
// Construct type of function in LLVM IR
LLVMTypeRef fnty_args[2] = {LLVMInt64Type(), LLVMPointerType(LLVMFloatType(), 0)};
LLVMTypeRef fnty = LLVMFunctionType(LLVMFloatType(), fnty_args, 2, false);
// Create function for lifting
LLFunc* fn = ll_func("sample_func", fnty, mod);
// Lift the whole function by following all direct jumps
ll_func_decode(fn, (uintptr_t) sample_func);
LLVMValueRef llvm_fn = ll_func_lift(fn);
LLVMDumpValue(llvm_fn);
return 0;
}
/*
Sample output:
define float @sample_func(i64, float*) {
%3 = icmp eq i64 %0, 0, !asm.flag.zf !0
br i1 %3, label %7, label %4
; <label>:4: ; preds = %2
%5 = bitcast float* %1 to i8*
%6 = getelementptr float, float* %1, i64 %0
br label %8
; <label>:7: ; preds = %8, %2
%merge = phi float [ 0.000000e+00, %2 ], [ %13, %8 ]
ret float %merge
; <label>:8: ; preds = %8, %4
%9 = phi i8* [ %5, %4 ], [ %14, %8 ], !asm.reg.rsi !0
%10 = phi float [ 0.000000e+00, %4 ], [ %13, %8 ], !asm.reg.xmm0 !0
%11 = bitcast i8* %9 to float*
%12 = load float, float* %11, align 4
%13 = fadd float %10, %12
%14 = getelementptr i8, i8* %9, i64 4, !asm.reg.rsi !0
%15 = bitcast float* %6 to i8*
%16 = icmp eq i8* %14, %15
br i1 %16, label %7, label %8
}
*/
+1
View File
@@ -0,0 +1 @@
executable('lifter', files('lifter.c'), dependencies: [librellume])
+37
View File
@@ -0,0 +1,37 @@
/**
* This file is part of Rellume.
*
* (c) 2016-2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
**/
#ifndef LL_BASICBLOCK_H
#define LL_BASICBLOCK_H
#include <llinstr.h>
struct LLBasicBlock;
typedef struct LLBasicBlock LLBasicBlock;
void ll_basic_block_add_inst(LLBasicBlock*, LLInstr*);
void ll_basic_block_add_branches(LLBasicBlock*, LLBasicBlock*, LLBasicBlock*);
#endif
+34
View File
@@ -0,0 +1,34 @@
/**
* This file is part of Rellume.
*
* (c) 2016-2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
**/
#ifndef LL_DECODER_H
#define LL_DECODER_H
#include <stdint.h>
#include <llfunc.h>
int ll_func_decode(LLFunc* func, uintptr_t addr);
#endif
+53
View File
@@ -0,0 +1,53 @@
/**
* This file is part of Rellume.
*
* (c) 2016-2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
**/
#ifndef LL_FUNC_H
#define LL_FUNC_H
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <llvm-c/Core.h>
#include <llbasicblock.h>
struct LLFunc;
typedef struct LLFunc LLFunc;
LLFunc* ll_func(const char* name, LLVMTypeRef ty, LLVMModuleRef mod);
void ll_func_enable_overflow_intrinsics(LLFunc* fn, bool enable);
void ll_func_enable_fast_math(LLFunc* fn, bool enable);
void ll_func_enable_full_loop_unroll(LLFunc* fn, bool enable);
void ll_func_set_global_base(LLFunc* fn, uintptr_t base, LLVMValueRef value);
LLBasicBlock* ll_func_add_block(LLFunc* fn);
LLVMValueRef ll_func_lift(LLFunc* fn);
void ll_func_dump(LLFunc*);
void ll_func_dispose(LLFunc*);
#endif
+109
View File
@@ -0,0 +1,109 @@
/**
* This file is part of Rellume.
*
* (c) 2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
**/
#ifndef LL_INSTR_H
#define LL_INSTR_H
#include <stdint.h>
enum LLInstrType {
LL_INS_None = 0,
LL_INS_Invalid = 1,
#define DEF_IT(opc,...) LL_INS_ ## opc,
#include <opcodes.inc>
#undef DEF_IT
LL_INS_Max
};
enum {
LL_RT_None = 0,
LL_RT_GP8Leg,
LL_RT_GP8,
LL_RT_GP16,
LL_RT_GP32,
LL_RT_GP64,
LL_RT_IP,
LL_RT_X87,
LL_RT_MMX,
LL_RT_XMM,
LL_RT_YMM,
LL_RT_ZMM,
LL_RT_SEG,
LL_RT_Max
};
// Names for register indexes. Warning: indexes for different types overlap!
enum {
LL_RI_None = 100, // assume no register type has more than 100 regs
// for LL_RT_GP8Leg (1st 8 from x86, but can address 16 regs in 64bit mode)
LL_RI_A = 0, LL_RI_C, LL_RI_D, LL_RI_B, LL_RI_SP, LL_RI_BP, LL_RI_SI, LL_RI_DI,
LL_RI_AH = 4, LL_RI_CH, LL_RI_DH, LL_RI_BH,
LL_RI_ES = 0, LL_RI_CS, LL_RI_SS, LL_RI_DS, LL_RI_FS, LL_RI_GS,
LL_RI_GPMax = 16,
LL_RI_XMMMax = 16,
};
typedef enum LLInstrType LLInstrType;
typedef struct { uint16_t rt; uint16_t ri; } LLReg;
enum {
LL_OP_NONE = 0,
LL_OP_REG,
LL_OP_IMM,
LL_OP_MEM,
};
struct LLInstrOp {
uint64_t val;
int type;
LLReg reg;
LLReg ireg;
int scale;
int seg;
int size;
};
typedef struct LLInstrOp LLInstrOp;
struct LLInstr {
LLInstrType type;
int operand_count;
int operand_size;
int address_size;
LLInstrOp dst;
LLInstrOp src;
LLInstrOp src2;
uintptr_t addr;
int len;
};
typedef struct LLInstr LLInstr;
#endif
+148
View File
@@ -0,0 +1,148 @@
/**
* This file is part of Rellume.
*
* (c) 2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
DEF_IT(NOP, CD_NOP())
// Defined in llinstruction-callret.c
DEF_IT(CALL, CD_FUNCTION(ll_instruction_call))
DEF_IT(RET, CD_FUNCTION(ll_instruction_ret))
// Defined in llinstruction-stack.c
DEF_IT(PUSH, CD_FUNCTION(ll_instruction_stack))
DEF_IT(PUSHFQ, CD_FUNCTION(ll_instruction_stack))
DEF_IT(POP, CD_FUNCTION(ll_instruction_stack))
DEF_IT(LEAVE, CD_FUNCTION(ll_instruction_stack))
// Defined in llinstruction-gp.c
DEF_IT(MOV, CD_FUNCTION(ll_instruction_movgp))
DEF_IT(MOVZX, CD_FUNCTION(ll_instruction_movgp))
DEF_IT(MOVSX, CD_FUNCTION(ll_instruction_movgp))
DEF_IT(ADD, CD_FUNCTION(ll_instruction_add))
DEF_IT(SUB, CD_FUNCTION(ll_instruction_sub))
DEF_IT(CMP, CD_FUNCTION(ll_instruction_cmp))
DEF_IT(LEA, CD_FUNCTION(ll_instruction_lea))
DEF_IT(NOT, CD_FUNCTION(ll_instruction_notneg))
DEF_IT(NEG, CD_FUNCTION(ll_instruction_notneg))
DEF_IT(INC, CD_FUNCTION(ll_instruction_incdec))
DEF_IT(DEC, CD_FUNCTION(ll_instruction_incdec))
DEF_IT(AND, CD_BINARY_INT_LLVM(LLVMBuildAnd, ll_flags_set_bit))
DEF_IT(OR, CD_BINARY_INT_LLVM(LLVMBuildOr, ll_flags_set_bit))
DEF_IT(XOR, CD_BINARY_INT_LLVM(LLVMBuildXor, ll_flags_set_bit))
DEF_IT(TEST, CD_FUNCTION(ll_instruction_test))
DEF_IT(IMUL, CD_FUNCTION(ll_instruction_mul))
DEF_IT(MUL, CD_FUNCTION(ll_instruction_mul))
DEF_IT(SHL, CD_FUNCTION(ll_instruction_shift))
DEF_IT(SHR, CD_FUNCTION(ll_instruction_shift))
DEF_IT(SAR, CD_FUNCTION(ll_instruction_shift))
DEF_IT(CLTQ, CD_FUNCTION(ll_instruction_cdqe))
DEF_IT(CMOVO, CD_FUNCTION(ll_instruction_cmov))
DEF_IT(CMOVNO, CD_FUNCTION(ll_instruction_cmov))
DEF_IT(CMOVC, CD_FUNCTION(ll_instruction_cmov))
DEF_IT(CMOVNC, CD_FUNCTION(ll_instruction_cmov))
DEF_IT(CMOVZ, CD_FUNCTION(ll_instruction_cmov))
DEF_IT(CMOVNZ, CD_FUNCTION(ll_instruction_cmov))
DEF_IT(CMOVBE, CD_FUNCTION(ll_instruction_cmov))
DEF_IT(CMOVA, CD_FUNCTION(ll_instruction_cmov))
DEF_IT(CMOVS, CD_FUNCTION(ll_instruction_cmov))
DEF_IT(CMOVNS, CD_FUNCTION(ll_instruction_cmov))
DEF_IT(CMOVP, CD_FUNCTION(ll_instruction_cmov))
DEF_IT(CMOVNP, CD_FUNCTION(ll_instruction_cmov))
DEF_IT(CMOVL, CD_FUNCTION(ll_instruction_cmov))
DEF_IT(CMOVGE, CD_FUNCTION(ll_instruction_cmov))
DEF_IT(CMOVLE, CD_FUNCTION(ll_instruction_cmov))
DEF_IT(CMOVG, CD_FUNCTION(ll_instruction_cmov))
DEF_IT(SETO, CD_FUNCTION(ll_instruction_setcc))
DEF_IT(SETNO, CD_FUNCTION(ll_instruction_setcc))
DEF_IT(SETC, CD_FUNCTION(ll_instruction_setcc))
DEF_IT(SETNC, CD_FUNCTION(ll_instruction_setcc))
DEF_IT(SETZ, CD_FUNCTION(ll_instruction_setcc))
DEF_IT(SETNZ, CD_FUNCTION(ll_instruction_setcc))
DEF_IT(SETBE, CD_FUNCTION(ll_instruction_setcc))
DEF_IT(SETA, CD_FUNCTION(ll_instruction_setcc))
DEF_IT(SETS, CD_FUNCTION(ll_instruction_setcc))
DEF_IT(SETNS, CD_FUNCTION(ll_instruction_setcc))
DEF_IT(SETP, CD_FUNCTION(ll_instruction_setcc))
DEF_IT(SETNP, CD_FUNCTION(ll_instruction_setcc))
DEF_IT(SETL, CD_FUNCTION(ll_instruction_setcc))
DEF_IT(SETGE, CD_FUNCTION(ll_instruction_setcc))
DEF_IT(SETLE, CD_FUNCTION(ll_instruction_setcc))
DEF_IT(SETG, CD_FUNCTION(ll_instruction_setcc))
// Defined in llinstruction-sse.c
DEF_IT(MOVD, CD_FUNCTION(ll_instruction_movq))
DEF_IT(MOVQ, CD_FUNCTION(ll_instruction_movq))
DEF_IT(MOVSS, CD_FUNCTION(ll_instruction_movs))
DEF_IT(MOVSD, CD_FUNCTION(ll_instruction_movs))
DEF_IT(MOVUPS, CD_FUNCTION(ll_instruction_movp))
DEF_IT(MOVUPD, CD_FUNCTION(ll_instruction_movp))
DEF_IT(MOVAPS, CD_FUNCTION(ll_instruction_movp))
DEF_IT(MOVAPD, CD_FUNCTION(ll_instruction_movp))
DEF_IT(MOVDQU, CD_FUNCTION(ll_instruction_movdq))
DEF_IT(MOVDQA, CD_FUNCTION(ll_instruction_movdq))
DEF_IT(MOVLPS, CD_FUNCTION(ll_instruction_movlp))
DEF_IT(MOVLPD, CD_FUNCTION(ll_instruction_movlp))
DEF_IT(MOVHPS, CD_FUNCTION(ll_instruction_movhps))
DEF_IT(MOVHPD, CD_FUNCTION(ll_instruction_movhpd))
DEF_IT(UNPCKLPS, CD_FUNCTION(ll_instruction_unpckl))
DEF_IT(UNPCKLPD, CD_FUNCTION(ll_instruction_unpckl))
DEF_IT(ADDSS, CD_BINARY_FP_LLVM(OP_SF32, REG_KEEP_UPPER, LLVMBuildFAdd, true))
DEF_IT(ADDSD, CD_BINARY_FP_LLVM(OP_SF64, REG_KEEP_UPPER, LLVMBuildFAdd, true))
DEF_IT(ADDPS, CD_BINARY_FP_LLVM(OP_VF32, REG_KEEP_UPPER, LLVMBuildFAdd, true))
DEF_IT(ADDPD, CD_BINARY_FP_LLVM(OP_VF64, REG_KEEP_UPPER, LLVMBuildFAdd, true))
DEF_IT(SUBSS, CD_BINARY_FP_LLVM(OP_SF32, REG_KEEP_UPPER, LLVMBuildFSub, true))
DEF_IT(SUBSD, CD_BINARY_FP_LLVM(OP_SF64, REG_KEEP_UPPER, LLVMBuildFSub, true))
DEF_IT(SUBPS, CD_BINARY_FP_LLVM(OP_VF32, REG_KEEP_UPPER, LLVMBuildFSub, true))
DEF_IT(SUBPD, CD_BINARY_FP_LLVM(OP_VF64, REG_KEEP_UPPER, LLVMBuildFSub, true))
DEF_IT(MULSS, CD_BINARY_FP_LLVM(OP_SF32, REG_KEEP_UPPER, LLVMBuildFMul, true))
DEF_IT(MULSD, CD_BINARY_FP_LLVM(OP_SF64, REG_KEEP_UPPER, LLVMBuildFMul, true))
DEF_IT(MULPS, CD_BINARY_FP_LLVM(OP_VF32, REG_KEEP_UPPER, LLVMBuildFMul, true))
DEF_IT(MULPD, CD_BINARY_FP_LLVM(OP_VF64, REG_KEEP_UPPER, LLVMBuildFMul, true))
DEF_IT(DIVSS, CD_BINARY_FP_LLVM(OP_SF32, REG_KEEP_UPPER, LLVMBuildFDiv, true))
DEF_IT(DIVSD, CD_BINARY_FP_LLVM(OP_SF64, REG_KEEP_UPPER, LLVMBuildFDiv, true))
DEF_IT(DIVPS, CD_BINARY_FP_LLVM(OP_VF32, REG_KEEP_UPPER, LLVMBuildFDiv, true))
DEF_IT(DIVPD, CD_BINARY_FP_LLVM(OP_VF64, REG_KEEP_UPPER, LLVMBuildFDiv, true))
DEF_IT(ORPS, CD_BINARY_FP_LLVM(OP_VI32, REG_KEEP_UPPER, LLVMBuildOr, false))
DEF_IT(ORPD, CD_BINARY_FP_LLVM(OP_VI64, REG_KEEP_UPPER, LLVMBuildOr, false))
DEF_IT(ANDPS, CD_BINARY_FP_LLVM(OP_VI32, REG_KEEP_UPPER, LLVMBuildAnd, false))
DEF_IT(ANDPD, CD_BINARY_FP_LLVM(OP_VI64, REG_KEEP_UPPER, LLVMBuildAnd, false))
DEF_IT(XORPS, CD_BINARY_FP_LLVM(OP_VI32, REG_KEEP_UPPER, LLVMBuildXor, false))
DEF_IT(XORPD, CD_BINARY_FP_LLVM(OP_VI64, REG_KEEP_UPPER, LLVMBuildXor, false))
DEF_IT(PXOR, CD_BINARY_FP_LLVM(OP_VI64, REG_KEEP_UPPER, LLVMBuildXor, false))
// Jumps are handled in the basic block generation code.
DEF_IT(JMP, CD_NOP())
DEF_IT(JO, CD_NOP())
DEF_IT(JNO, CD_NOP())
DEF_IT(JC, CD_NOP())
DEF_IT(JNC, CD_NOP())
DEF_IT(JZ, CD_NOP())
DEF_IT(JNZ, CD_NOP())
DEF_IT(JBE, CD_NOP())
DEF_IT(JA, CD_NOP())
DEF_IT(JS, CD_NOP())
DEF_IT(JNS, CD_NOP())
DEF_IT(JP, CD_NOP())
DEF_IT(JNP, CD_NOP())
DEF_IT(JL, CD_NOP())
DEF_IT(JGE, CD_NOP())
DEF_IT(JLE, CD_NOP())
DEF_IT(JG, CD_NOP())
+46
View File
@@ -0,0 +1,46 @@
project('libdbrew', ['c', 'cpp'],
default_options: [
'buildtype=debugoptimized',
'warning_level=3',
'c_std=gnu99',
'cpp_std=c++11',
])
if get_option('warning_level').to_int() >= 3
add_project_arguments(['-Wmissing-field-initializers',
'-Wunused-parameter',
'-Wold-style-definition',
'-Wmissing-declarations',
'-Wmissing-prototypes',
'-Wredundant-decls',
'-Wmissing-noreturn',
'-Wshadow',
'-Wpointer-arith',
'-Wwrite-strings',
'-Winline',
'-Wformat-nonliteral',
'-Wformat-security',
'-Wswitch-default',
'-Winit-self',
'-Wnested-externs',
'-Wstrict-prototypes',
'-Wmissing-include-dirs',
'-Wundef',
'-Wmissing-format-attribute'
], language: 'c')
endif
add_project_arguments(['-Wno-unused-parameter'], language: 'cpp')
libllvm = dependency('llvm', version: ['>=4', '<8'])
fadec_subproject = subproject('fadec', default_options: ['archmode=only64'])
fadec = fadec_subproject.get_variable('libx86decode')
rellume_inc = include_directories('include')
subdir('src')
librellume = declare_dependency(include_directories: rellume_inc,
link_with: librellume_lib,
dependencies: [libllvm])
subdir('examples')
+64
View File
@@ -0,0 +1,64 @@
/**
* This file is part of Rellume.
*
* (c) 2016-2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
**/
#ifndef LL_BASIC_BLOCK_H
#define LL_BASIC_BLOCK_H
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdlib.h>
#include <llvm-c/Core.h>
#include <llbasicblock.h>
#include <llcommon-internal.h>
#include <llregfile-internal.h>
LLBasicBlock* ll_basic_block_new(LLVMBasicBlockRef, LLState* state);
void ll_basic_block_dispose(LLBasicBlock*);
void ll_basic_block_add_predecessor(LLBasicBlock*, LLBasicBlock*);
void ll_basic_block_add_phis(LLBasicBlock*);
void ll_basic_block_terminate(LLBasicBlock*);
void ll_basic_block_fill_phis(LLBasicBlock*);
#define ll_get_register(reg,facet,state) ll_basic_block_get_register(state->currentBB,facet,reg,state)
#define ll_clear_register(reg,state) ll_basic_block_clear_register(state->currentBB,reg,state)
#define ll_set_register(reg,facet,value,clear,state) ll_basic_block_set_register(state->currentBB,facet,reg,value,clear,state)
#define ll_get_flag(reg,state) ll_basic_block_get_flag(state->currentBB,reg)
#define ll_set_flag(reg,value,state) ll_basic_block_set_flag(state->currentBB,reg,value)
#define ll_get_flag_cache(state) ll_basic_block_get_flag_cache(state->currentBB)
LLVMValueRef ll_basic_block_get_register(LLBasicBlock*, RegisterFacet, LLReg, LLState*);
void ll_basic_block_clear_register(LLBasicBlock*, LLReg, LLState*);
void ll_basic_block_zero_register(LLBasicBlock*, LLReg, LLState*);
void ll_basic_block_rename_register(LLBasicBlock*, LLReg, LLReg, LLState*);
void ll_basic_block_set_register(LLBasicBlock*, RegisterFacet, LLReg, LLVMValueRef, bool, LLState*);
LLVMValueRef ll_basic_block_get_flag(LLBasicBlock*, int);
void ll_basic_block_set_flag(LLBasicBlock*, int, LLVMValueRef);
LLFlagCache* ll_basic_block_get_flag_cache(LLBasicBlock*);
LLVMBasicBlockRef ll_basic_block_llvm(LLBasicBlock*);
#endif
+532
View File
@@ -0,0 +1,532 @@
/**
* This file is part of Rellume.
*
* (c) 2016-2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
**/
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <llvm-c/Core.h>
#include <llbasicblock-internal.h>
#include <llcommon-internal.h>
#include <llflags-internal.h>
#include <llinstr-internal.h>
#include <llinstruction-internal.h>
/**
* \defgroup LLBasicBlock Basic Block
* \brief Representation of a basic block
*
* @{
**/
struct LLRegister {
LLVMValueRef facets[FACET_COUNT];
};
typedef struct LLRegister LLRegister;
// typedef LLVMValueRef LLRegister[FACET_COUNT];
struct LLBasicBlock {
LLState* state;
/**
* \brief The branch basic block, or NULL
**/
LLBasicBlock* nextBranch;
/**
* \brief The fall-through basic block, or NULL
**/
LLBasicBlock* nextFallThrough;
// Predecessors needed for phi nodes
/**
* \brief The predecessor count
**/
size_t predCount;
/**
* \brief The number predecessors allocated
**/
size_t predsAllocated;
/**
* \brief The preceding basic blocks
**/
LLBasicBlock** preds;
/**
* \brief The LLVM basic block
**/
LLVMBasicBlockRef llvmBB;
/**
* \brief The register file for the basic block
**/
LLRegisterFile* regfile;
/**
* \brief The phi nodes for the registers
**/
LLRegister phiNodesGpRegisters[LL_RI_GPMax];
/**
* \brief The phi nodes for the registers
**/
LLRegister phiNodesSseRegisters[LL_RI_XMMMax];
/**
* \brief The phi nodes for the flags
**/
LLVMValueRef phiNodesFlags[RFLAG_Max];
LLInstrType endType;
};
/**
* Create a new basic block.
*
* \private
*
* \author Alexis Engelke
*
* \param address The address of the basic block
* \returns The new basic block
**/
LLBasicBlock*
ll_basic_block_new(LLVMBasicBlockRef llvmBB, LLState* state)
{
LLBasicBlock* bb;
bb = malloc(sizeof(LLBasicBlock));
bb->state = state;
bb->llvmBB = llvmBB;
bb->nextBranch = NULL;
bb->nextFallThrough = NULL;
bb->predCount = 0;
bb->predsAllocated = 0;
bb->endType = LL_INS_None;
bb->regfile = ll_regfile_new(bb);
return bb;
}
void
ll_basic_block_add_phis(LLBasicBlock* bb)
{
LLVMValueRef phiNode;
LLState* state = bb->state;
state->currentBB = bb;
LLVMPositionBuilderAtEnd(state->builder, bb->llvmBB);
for (int i = 0; i < LL_RI_GPMax; i++)
{
for (size_t k = 0; k < FACET_COUNT; k++)
{
phiNode = LLVMBuildPhi(state->builder, ll_register_facet_type(k, state), "");
ll_regfile_set(bb->regfile, k, ll_reg(LL_RT_GP64, i), phiNode, false, state);
bb->phiNodesGpRegisters[i].facets[k] = phiNode;
}
}
for (int i = 0; i < LL_RI_XMMMax; i++)
{
for (size_t k = 0; k < FACET_COUNT; k++)
{
phiNode = LLVMBuildPhi(state->builder, ll_register_facet_type(k, state), "");
ll_regfile_set(bb->regfile, k, ll_reg(LL_RT_XMM, i), phiNode, false, state);
bb->phiNodesSseRegisters[i].facets[k] = phiNode;
}
}
for (int i = 0; i < RFLAG_Max; i++)
{
phiNode = LLVMBuildPhi(state->builder, LLVMInt1TypeInContext(state->context), "");
ll_regfile_set_flag(bb->regfile, i, phiNode);
bb->phiNodesFlags[i] = phiNode;
}
}
/**
* Dispose a basic block.
*
* \private
*
* \author Alexis Engelke
*
* \param bb The basic block
**/
void
ll_basic_block_dispose(LLBasicBlock* bb)
{
ll_regfile_dispose(bb->regfile);
if (bb->predsAllocated != 0)
free(bb->preds);
free(bb);
}
/**
* Add a predecessor.
*
* \private
*
* \author Alexis Engelke
*
* \param bb The basic block
* \param pred The preceding basic block
**/
void
ll_basic_block_add_predecessor(LLBasicBlock* bb, LLBasicBlock* pred)
{
if (bb->predsAllocated == 0)
{
bb->preds = malloc(sizeof(LLBasicBlock*) * 10);
bb->predsAllocated = 10;
if (bb->preds == NULL)
warn_if_reached();
}
else if (bb->predsAllocated == bb->predCount)
{
bb->preds = realloc(bb->preds, sizeof(LLBasicBlock*) * bb->predsAllocated * 2);
bb->predsAllocated *= 2;
if (bb->preds == NULL)
warn_if_reached();
}
bb->preds[bb->predCount] = pred;
bb->predCount++;
}
/**
* Get the LLVM value of the basic block.
*
* \private
*
* \author Alexis Engelke
*
* \param bb The basic block
* \returns The LLVM basic block
**/
LLVMBasicBlockRef
ll_basic_block_llvm(LLBasicBlock* bb)
{
return bb->llvmBB;
}
/**
* Add branches to the basic block. This also registers them as predecessors.
*
* \private
*
* \author Alexis Engelke
*
* \param bb The basic block
* \param branch The active branch, or NULL
* \param fallThrough The fall-through branch, or NULL
**/
void
ll_basic_block_add_branches(LLBasicBlock* bb, LLBasicBlock* branch, LLBasicBlock* fallThrough)
{
if (branch != NULL)
{
ll_basic_block_add_predecessor(branch, bb);
bb->nextBranch = branch;
}
if (fallThrough != NULL)
{
ll_basic_block_add_predecessor(fallThrough, bb);
bb->nextFallThrough = fallThrough;
}
}
#define instrIsJcc(instr) ( \
(instr) == LL_INS_JO || \
(instr) == LL_INS_JNO || \
(instr) == LL_INS_JC || \
(instr) == LL_INS_JNC || \
(instr) == LL_INS_JZ || \
(instr) == LL_INS_JNZ || \
(instr) == LL_INS_JBE || \
(instr) == LL_INS_JA || \
(instr) == LL_INS_JS || \
(instr) == LL_INS_JNS || \
(instr) == LL_INS_JP || \
(instr) == LL_INS_JNP || \
(instr) == LL_INS_JL || \
(instr) == LL_INS_JGE || \
(instr) == LL_INS_JLE || \
(instr) == LL_INS_JG \
)
void
ll_basic_block_add_inst(LLBasicBlock* bb, LLInstr* inst)
{
LLState* state = bb->state;
state->currentBB = bb;
LLVMPositionBuilderAtEnd(state->builder, bb->llvmBB);
ll_generate_instruction(inst, state);
bb->endType = inst->type;
}
/**
* Build the LLVM IR.
*
* \private
*
* \author Alexis Engelke
*
* \param bb The basic block
* \param state The module state
**/
void
ll_basic_block_terminate(LLBasicBlock* bb)
{
LLState* state = bb->state;
LLVMValueRef branch = NULL;
state->currentBB = bb;
LLVMPositionBuilderAtEnd(state->builder, bb->llvmBB);
LLInstrType endType = bb->endType;
if (instrIsJcc(endType))
{
LLVMValueRef cond = ll_flags_condition(endType, LL_INS_JO, state);
branch = LLVMBuildCondBr(state->builder, cond, bb->nextBranch->llvmBB, bb->nextFallThrough->llvmBB);
}
else if (endType == LL_INS_JMP)
branch = LLVMBuildBr(state->builder, bb->nextBranch->llvmBB);
else if (endType != LL_INS_RET && endType != LL_INS_Invalid) // Any other instruction which is not a terminator
branch = LLVMBuildBr(state->builder, bb->nextFallThrough->llvmBB);
if (state->cfg.enableFullLoopUnroll && branch != NULL)
LLVMSetMetadata(branch, LLVMGetMDKindIDInContext(state->context, "llvm.loop", 9), state->unrollMD);
}
/**
* Fill PHI nodes after the IR for all basic blocks of the function is
* generated.
*
* \private
*
* \author Alexis Engelke
*
* \param bb The basic block
**/
void
ll_basic_block_fill_phis(LLBasicBlock* bb)
{
if (bb->predCount == 0)
return;
LLState* state = bb->state;
state->currentBB = NULL;
LLVMValueRef values[bb->predCount];
LLVMBasicBlockRef bbs[bb->predCount];
for (int j = 0; j < LL_RI_GPMax; j++)
{
for (size_t k = 0; k < FACET_COUNT; k++)
{
for (size_t i = 0; i < bb->predCount; i++)
{
bbs[i] = bb->preds[i]->llvmBB;
values[i] = ll_basic_block_get_register(bb->preds[i], k, ll_reg(LL_RT_GP64, j), state); //bb->preds[i]->gpRegisters[j].facets[k];
}
LLVMAddIncoming(bb->phiNodesGpRegisters[j].facets[k], values, bbs, bb->predCount);
}
}
for (int j = 0; j < LL_RI_XMMMax; j++)
{
for (size_t k = 0; k < FACET_COUNT; k++)
{
for (size_t i = 0; i < bb->predCount; i++)
{
bbs[i] = bb->preds[i]->llvmBB;
values[i] = ll_basic_block_get_register(bb->preds[i], k, ll_reg(LL_RT_XMM, j), state); //bb->preds[i]->gpRegisters[j].facets[k];
}
LLVMAddIncoming(bb->phiNodesSseRegisters[j].facets[k], values, bbs, bb->predCount);
}
}
for (int j = 0; j < RFLAG_Max; j++)
{
for (size_t i = 0; i < bb->predCount; i++)
{
bbs[i] = bb->preds[i]->llvmBB;
values[i] = ll_regfile_get_flag(bb->preds[i]->regfile, j);
}
LLVMAddIncoming(bb->phiNodesFlags[j], values, bbs, bb->predCount);
}
}
/**
* Get a register value of the basic block.
*
* \private
*
* \author Alexis Engelke
*
* \param bb The basic block
* \param reg The register
* \returns The register value in the given facet
**/
LLVMValueRef
ll_basic_block_get_register(LLBasicBlock* bb, RegisterFacet facet, LLReg reg, LLState* state)
{
return ll_regfile_get(bb->regfile, facet, reg, state);
}
/**
* Clear a register to undefined of the basic block.
*
* \private
*
* \author Alexis Engelke
*
* \param bb The basic block
* \param reg The register
* \param value The new value
**/
void
ll_basic_block_clear_register(LLBasicBlock* bb, LLReg reg, LLState* state)
{
ll_regfile_clear(bb->regfile, reg, state);
}
/**
* Set a register in all facets to zero within the basic block.
*
* \private
*
* \author Alexis Engelke
*
* \param bb The basic block
* \param reg The name of the new register
* \param state The state
**/
void
ll_basic_block_zero_register(LLBasicBlock* bb, LLReg reg, LLState* state)
{
ll_regfile_zero(bb->regfile, reg, state);
}
/**
* Rename a register to another register of the basic block.
*
* \private
*
* \author Alexis Engelke
*
* \param bb The basic block
* \param reg The name of the new register
* \param current The name of the current register
* \param state The state
**/
void
ll_basic_block_rename_register(LLBasicBlock* bb, LLReg reg, LLReg current, LLState* state)
{
ll_regfile_rename(bb->regfile, reg, current, state);
}
/**
* Set a register value of the basic block.
*
* \private
*
* \author Alexis Engelke
*
* \param bb The basic block
* \param reg The register
* \param value The new value
**/
void
ll_basic_block_set_register(LLBasicBlock* bb, RegisterFacet facet, LLReg reg, LLVMValueRef value, bool clearOthers, LLState* state)
{
ll_regfile_set(bb->regfile, facet, reg, value, clearOthers, state);
}
/**
* Get a flag value of the basic block.
*
* \private
*
* \author Alexis Engelke
*
* \param bb The basic block
* \param flag The flag
* \returns The current flag value
**/
LLVMValueRef
ll_basic_block_get_flag(LLBasicBlock* bb, int flag)
{
return ll_regfile_get_flag(bb->regfile, flag);
}
/**
* Set a flag value of the basic block.
*
* \private
*
* \author Alexis Engelke
*
* \param bb The basic block
* \param flag The flag
* \param value The new value
**/
void
ll_basic_block_set_flag(LLBasicBlock* bb, int flag, LLVMValueRef value)
{
ll_regfile_set_flag(bb->regfile, flag, value);
}
/**
* Get the flag cache.
*
* \private
*
* \author Alexis Engelke
*
* \param bb The basic block
* \returns The flag cache
**/
LLFlagCache*
ll_basic_block_get_flag_cache(LLBasicBlock* bb)
{
return ll_regfile_get_flag_cache(bb->regfile);
}
/**
* @}
**/
+124
View File
@@ -0,0 +1,124 @@
/**
* This file is part of Rellume.
*
* (c) 2016-2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
**/
#ifndef LL_COMMON_H
#define LL_COMMON_H
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <llvm-c/Core.h>
#include <llvm-c/ExecutionEngine.h>
#include <llbasicblock.h>
#include <llcommon-internal.h>
/**
* \brief Emit a warning and jump into a debugger
**/
#define warn_if_reached() do { printf("!WARN %s: Code should not be reached.\n", __func__); __asm__("int3"); } while (0)
/**
* \brief The size of a vector
**/
#define LL_VECTOR_REGISTER_SIZE 128
struct LLConfig {
size_t stackSize;
/**
* \brief Whether unsafe pointer optimizations are enabled.
**/
bool enableUnsafePointerOptimizations;
/**
* \brief Whether overflow intrinsics should be used.
**/
bool enableOverflowIntrinsics;
/**
* \brief Whether unsafe floating-point optimizations may be applied.
* Corresponds to -ffast-math.
**/
bool enableFastMath;
/**
* \brief Whether to force full loop unrolling on all loops
**/
bool enableFullLoopUnroll;
/**
* \brief The global offset base
**/
uintptr_t globalOffsetBase;
/**
* \brief The global variable used to access constant memory regions. Points
* to globalOffsetBase.
**/
LLVMValueRef globalBase;
};
typedef struct LLConfig LLConfig;
/**
* \brief The LLVM state of the back-end.
**/
struct LLState {
LLConfig cfg;
/**
* \brief The LLVM Context
**/
LLVMContextRef context;
/**
* \brief The LLVM Module
**/
LLVMModuleRef module;
/**
* \brief The LLVM Builder
**/
LLVMBuilderRef builder;
/**
* \brief The empty metadata node
**/
LLVMValueRef emptyMD;
/**
* \brief The loop unrolling metadata
**/
LLVMValueRef unrollMD;
/**
* \brief The current function
**/
// LLFunction* currentFunction;
LLVMValueRef llvm_function;
/**
* \brief The current basic block
**/
LLBasicBlock* currentBB;
};
typedef struct LLState LLState;
#endif
+367
View File
@@ -0,0 +1,367 @@
/**
* This file is part of Rellume.
*
* (c) 2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <deque>
#include <iostream>
#include <unordered_map>
#include <vector>
extern "C" {
#include <fadec.h>
}
extern "C" {
#include <lldecoder.h>
#include <llbasicblock.h>
#include <llinstr.h>
#include <llinstr-internal.h>
}
static LLReg
convert_reg(int size, int idx, int type)
{
if (idx == FD_REG_NONE)
return LLReg{ LL_RT_None, LL_RI_None };
if (idx == FD_REG_IP && type == FD_RT_GPL)
return LLReg{ LL_RT_IP, 0 };
if (type == FD_RT_GPL)
return ll_reg_gp(size, false, idx);
if (type == FD_RT_GPH)
return ll_reg_gp(size, true, idx);
if (type == FD_RT_VEC && size == 32)
return LLReg{ LL_RT_YMM, (uint16_t) idx };
if (type == FD_RT_VEC)
return LLReg{ LL_RT_XMM, (uint16_t) idx };
if (type == FD_RT_SEG)
return LLReg{ LL_RT_SEG, (uint16_t) idx };
printf("Unknown reg convert %d/%d\n", type, size);
abort();
}
static int
ll_decode_instr(LLInstr& llinst, uintptr_t addr)
{
FdInstr fdi;
int ret = fd_decode((uint8_t*) addr, 15, 64, addr, &fdi);
if (ret < 0)
return 1;
llinst.addr = addr;
llinst.len = FD_SIZE(&fdi);
LLInstrOp* ops[] = {&llinst.dst, &llinst.src, &llinst.src2};
llinst.operand_count = 0;
for (int i = 0; i < 3; i++)
{
switch (FD_OP_TYPE(&fdi, i))
{
case FD_OT_NONE:
goto end_ops;
case FD_OT_IMM:
ops[i]->type = LL_OP_IMM;
ops[i]->val = FD_OP_IMM(&fdi, i);
ops[i]->size = FD_OP_SIZE(&fdi, i);
break;
case FD_OT_REG:
ops[i]->type = LL_OP_REG;
ops[i]->size = FD_OP_SIZE(&fdi, i);
ops[i]->scale = 0;
ops[i]->val = 0;
ops[i]->reg = convert_reg(FD_OP_SIZE(&fdi, i), FD_OP_REG(&fdi, i),
FD_OP_REG_TYPE(&fdi, i));
break;
case FD_OT_MEM:
ops[i]->type = LL_OP_MEM;
ops[i]->seg = convert_reg(2, FD_SEGMENT(&fdi), FD_RT_SEG).ri;
ops[i]->val = FD_OP_DISP(&fdi, i);
ops[i]->reg = convert_reg(8, FD_OP_BASE(&fdi, i), FD_RT_GPL);
if (FD_OP_INDEX(&fdi, i) != FD_REG_NONE)
{
ops[i]->ireg = convert_reg(8, FD_OP_INDEX(&fdi, i), FD_RT_GPL);
ops[i]->scale = 1 << FD_OP_SCALE(&fdi, i);
}
else
{
ops[i]->scale = 0;
}
ops[i]->size = FD_OP_SIZE(&fdi, i);
break;
}
llinst.operand_count = i + 1;
}
end_ops:
switch (FD_TYPE(&fdi))
{
case FDI_NOP: llinst.type = LL_INS_NOP; break;
case FDI_CALL: llinst.type = LL_INS_CALL; break;
case FDI_RET: llinst.type = LL_INS_RET; break;
case FDI_PUSH: llinst.type = LL_INS_PUSH; break;
case FDI_PUSHF: llinst.type = LL_INS_PUSHFQ; break;
case FDI_POP: llinst.type = LL_INS_POP; break;
case FDI_LEAVE: llinst.type = LL_INS_LEAVE; break;
case FDI_MOV: llinst.type = LL_INS_MOV; break;
case FDI_MOV_IMM: llinst.type = LL_INS_MOV; break;
case FDI_MOVABS_IMM: llinst.type = LL_INS_MOV; break;
case FDI_MOVZX: llinst.type = LL_INS_MOVZX; break;
case FDI_MOVSX: llinst.type = LL_INS_MOVSX; break;
case FDI_ADD: llinst.type = LL_INS_ADD; break;
case FDI_ADD_IMM: llinst.type = LL_INS_ADD; break;
case FDI_SUB: llinst.type = LL_INS_SUB; break;
case FDI_SUB_IMM: llinst.type = LL_INS_SUB; break;
case FDI_CMP: llinst.type = LL_INS_CMP; break;
case FDI_CMP_IMM: llinst.type = LL_INS_CMP; break;
case FDI_LEA: llinst.type = LL_INS_LEA; break;
case FDI_NOT: llinst.type = LL_INS_NOT; break;
case FDI_NEG: llinst.type = LL_INS_NEG; break;
case FDI_INC: llinst.type = LL_INS_INC; break;
case FDI_DEC: llinst.type = LL_INS_DEC; break;
case FDI_AND: llinst.type = LL_INS_AND; break;
case FDI_AND_IMM: llinst.type = LL_INS_AND; break;
case FDI_OR: llinst.type = LL_INS_OR; break;
case FDI_OR_IMM: llinst.type = LL_INS_OR; break;
case FDI_XOR: llinst.type = LL_INS_XOR; break;
case FDI_XOR_IMM: llinst.type = LL_INS_XOR; break;
case FDI_TEST: llinst.type = LL_INS_TEST; break;
case FDI_IMUL: llinst.type = LL_INS_IMUL; break;
case FDI_IMUL2: llinst.type = LL_INS_IMUL; break;
case FDI_IMUL3: llinst.type = LL_INS_IMUL; break;
case FDI_MUL: llinst.type = LL_INS_MUL; break;
case FDI_SHL_IMM: llinst.type = LL_INS_SHL; break;
case FDI_SHL_CL: llinst.type = LL_INS_SHL; llinst.src.type = LL_OP_REG; llinst.src.size = 1; llinst.src.reg = ll_reg_gp(1, false, 1); llinst.operand_count = 2; break;
case FDI_SHR_IMM: llinst.type = LL_INS_SHR; break;
case FDI_SHR_CL: llinst.type = LL_INS_SHR; llinst.src.type = LL_OP_REG; llinst.src.size = 1; llinst.src.reg = ll_reg_gp(1, false, 1); llinst.operand_count = 2; break;
case FDI_SAR_IMM: llinst.type = LL_INS_SAR; break;
case FDI_SAR_CL: llinst.type = LL_INS_SAR; llinst.src.type = LL_OP_REG; llinst.src.size = 1; llinst.src.reg = ll_reg_gp(1, false, 1); llinst.operand_count = 2; break;
case FDI_CMOVO: llinst.type = LL_INS_CMOVO; break;
case FDI_CMOVNO: llinst.type = LL_INS_CMOVNO; break;
case FDI_CMOVC: llinst.type = LL_INS_CMOVC; break;
case FDI_CMOVNC: llinst.type = LL_INS_CMOVNC; break;
case FDI_CMOVZ: llinst.type = LL_INS_CMOVZ; break;
case FDI_CMOVNZ: llinst.type = LL_INS_CMOVNZ; break;
case FDI_CMOVBE: llinst.type = LL_INS_CMOVBE; break;
case FDI_CMOVA: llinst.type = LL_INS_CMOVA; break;
case FDI_CMOVS: llinst.type = LL_INS_CMOVS; break;
case FDI_CMOVNS: llinst.type = LL_INS_CMOVNS; break;
case FDI_CMOVP: llinst.type = LL_INS_CMOVP; break;
case FDI_CMOVNP: llinst.type = LL_INS_CMOVNP; break;
case FDI_CMOVL: llinst.type = LL_INS_CMOVL; break;
case FDI_CMOVGE: llinst.type = LL_INS_CMOVGE; break;
case FDI_CMOVLE: llinst.type = LL_INS_CMOVLE; break;
case FDI_CMOVG: llinst.type = LL_INS_CMOVG; break;
case FDI_SETO: llinst.type = LL_INS_SETO; break;
case FDI_SETNO: llinst.type = LL_INS_SETNO; break;
case FDI_SETC: llinst.type = LL_INS_SETC; break;
case FDI_SETNC: llinst.type = LL_INS_SETNC; break;
case FDI_SETZ: llinst.type = LL_INS_SETZ; break;
case FDI_SETNZ: llinst.type = LL_INS_SETNZ; break;
case FDI_SETBE: llinst.type = LL_INS_SETBE; break;
case FDI_SETA: llinst.type = LL_INS_SETA; break;
case FDI_SETS: llinst.type = LL_INS_SETS; break;
case FDI_SETNS: llinst.type = LL_INS_SETNS; break;
case FDI_SETP: llinst.type = LL_INS_SETP; break;
case FDI_SETNP: llinst.type = LL_INS_SETNP; break;
case FDI_SETL: llinst.type = LL_INS_SETL; break;
case FDI_SETGE: llinst.type = LL_INS_SETGE; break;
case FDI_SETLE: llinst.type = LL_INS_SETLE; break;
case FDI_SETG: llinst.type = LL_INS_SETG; break;
case FDI_SSE_MOVD_G2X: llinst.type = LL_INS_MOVD; break;
case FDI_SSE_MOVD_X2G: llinst.type = LL_INS_MOVD; break;
case FDI_SSE_MOVQ_G2X: llinst.type = LL_INS_MOVQ; break;
case FDI_SSE_MOVQ_X2G: llinst.type = LL_INS_MOVQ; break;
case FDI_SSE_MOVQ_X2X: llinst.type = LL_INS_MOVQ; break;
case FDI_SSE_MOVSS: llinst.type = LL_INS_MOVSS; break;
case FDI_SSE_MOVSD: llinst.type = LL_INS_MOVSD; break;
case FDI_SSE_MOVUPS: llinst.type = LL_INS_MOVUPS; break;
case FDI_SSE_MOVUPD: llinst.type = LL_INS_MOVUPD; break;
case FDI_SSE_MOVAPS: llinst.type = LL_INS_MOVAPS; break;
case FDI_SSE_MOVAPD: llinst.type = LL_INS_MOVAPD; break;
case FDI_SSE_MOVDQU: llinst.type = LL_INS_MOVDQU; break;
case FDI_SSE_MOVDQA: llinst.type = LL_INS_MOVDQA; break;
case FDI_SSE_MOVLPS: llinst.type = LL_INS_MOVLPS; break;
case FDI_SSE_MOVLPD: llinst.type = LL_INS_MOVLPD; break;
case FDI_SSE_MOVHPS: llinst.type = LL_INS_MOVHPS; break;
case FDI_SSE_MOVHPD: llinst.type = LL_INS_MOVHPD; break;
case FDI_SSE_UNPACKLPS: llinst.type = LL_INS_UNPCKLPS; break;
case FDI_SSE_UNPACKLPD: llinst.type = LL_INS_UNPCKLPD; break;
case FDI_SSE_ADDSS: llinst.type = LL_INS_ADDSS; break;
case FDI_SSE_ADDSD: llinst.type = LL_INS_ADDSD; break;
case FDI_SSE_ADDPS: llinst.type = LL_INS_ADDPS; break;
case FDI_SSE_ADDPD: llinst.type = LL_INS_ADDPD; break;
case FDI_SSE_SUBSS: llinst.type = LL_INS_SUBSS; break;
case FDI_SSE_SUBSD: llinst.type = LL_INS_SUBSD; break;
case FDI_SSE_SUBPS: llinst.type = LL_INS_SUBPS; break;
case FDI_SSE_SUBPD: llinst.type = LL_INS_SUBPD; break;
case FDI_SSE_MULSS: llinst.type = LL_INS_MULSS; break;
case FDI_SSE_MULSD: llinst.type = LL_INS_MULSD; break;
case FDI_SSE_MULPS: llinst.type = LL_INS_MULPS; break;
case FDI_SSE_MULPD: llinst.type = LL_INS_MULPD; break;
case FDI_SSE_DIVSS: llinst.type = LL_INS_DIVSS; break;
case FDI_SSE_DIVSD: llinst.type = LL_INS_DIVSD; break;
case FDI_SSE_DIVPS: llinst.type = LL_INS_DIVPS; break;
case FDI_SSE_DIVPD: llinst.type = LL_INS_DIVPD; break;
case FDI_SSE_ORPS: llinst.type = LL_INS_ORPS; break;
case FDI_SSE_ORPD: llinst.type = LL_INS_ORPD; break;
case FDI_SSE_ANDPS: llinst.type = LL_INS_ANDPS; break;
case FDI_SSE_ANDPD: llinst.type = LL_INS_ANDPD; break;
case FDI_SSE_XORPS: llinst.type = LL_INS_XORPS; break;
case FDI_SSE_XORPD: llinst.type = LL_INS_XORPD; break;
case FDI_SSE_PXOR: llinst.type = LL_INS_PXOR; break;
case FDI_JMP: llinst.type = LL_INS_JMP; break;
case FDI_JO: llinst.type = LL_INS_JO; break;
case FDI_JNO: llinst.type = LL_INS_JNO; break;
case FDI_JC: llinst.type = LL_INS_JC; break;
case FDI_JNC: llinst.type = LL_INS_JNC; break;
case FDI_JZ: llinst.type = LL_INS_JZ; break;
case FDI_JNZ: llinst.type = LL_INS_JNZ; break;
case FDI_JBE: llinst.type = LL_INS_JBE; break;
case FDI_JA: llinst.type = LL_INS_JA; break;
case FDI_JS: llinst.type = LL_INS_JS; break;
case FDI_JNS: llinst.type = LL_INS_JNS; break;
case FDI_JP: llinst.type = LL_INS_JP; break;
case FDI_JNP: llinst.type = LL_INS_JNP; break;
case FDI_JL: llinst.type = LL_INS_JL; break;
case FDI_JGE: llinst.type = LL_INS_JGE; break;
case FDI_JLE: llinst.type = LL_INS_JLE; break;
case FDI_JG: llinst.type = LL_INS_JG; break;
case FDI_C_EX: if (FD_OPSIZE(&fdi) == 8) llinst.type = LL_INS_CLTQ; break;
default: {
char buf[128];
fd_format(&fdi, buf, sizeof(buf));
printf("Cannot convert instruction %s\n", buf);
return 1;
}
}
return 0;
}
#define instrIsJcc(instr) ( \
(instr) == LL_INS_JO || \
(instr) == LL_INS_JNO || \
(instr) == LL_INS_JC || \
(instr) == LL_INS_JNC || \
(instr) == LL_INS_JZ || \
(instr) == LL_INS_JNZ || \
(instr) == LL_INS_JBE || \
(instr) == LL_INS_JA || \
(instr) == LL_INS_JS || \
(instr) == LL_INS_JNS || \
(instr) == LL_INS_JP || \
(instr) == LL_INS_JNP || \
(instr) == LL_INS_JL || \
(instr) == LL_INS_JGE || \
(instr) == LL_INS_JLE || \
(instr) == LL_INS_JG \
)
#define instrBreaks(instr) (instrIsJcc(instr) || (instr) == LL_INS_RET || \
(instr) == LL_INS_JMP || (instr) == LL_INS_CALL)
extern "C"
int
ll_func_decode(LLFunc* func, uintptr_t addr)
{
LLInstr inst;
std::deque<uintptr_t> addr_queue;
addr_queue.push_back(addr);
std::vector<LLInstr> insts;
// List of (start_idx,end_idx) (non-inclusive end)
std::vector<std::pair<size_t,size_t>> blocks;
// Mapping from address to (block_idx, instr_idx)
std::unordered_map<uintptr_t, std::pair<size_t,size_t>> addr_map;
std::deque<uintptr_t>::iterator addr_it = addr_queue.begin();
while (addr_it != addr_queue.end())
{
uintptr_t cur_addr = *addr_it;
addr_it = addr_queue.erase(addr_it);
size_t cur_block_start = insts.size();
auto cur_addr_entry = addr_map.find(cur_addr);
while (cur_addr_entry == addr_map.end())
{
if (ll_decode_instr(inst, cur_addr))
return 1;
addr_map[cur_addr] = std::make_pair(blocks.size(), insts.size());
insts.push_back(inst);
if (instrBreaks(inst.type))
{
if (instrIsJcc(inst.type) || inst.type == LL_INS_CALL)
addr_queue.push_back(cur_addr + inst.len);
if (instrIsJcc(inst.type) || inst.type == LL_INS_JMP)
addr_queue.push_back(inst.dst.val);
break;
}
cur_addr += inst.len;
cur_addr_entry = addr_map.find(cur_addr);
}
if (insts.size() != cur_block_start)
blocks.push_back(std::make_pair(cur_block_start, insts.size()));
if (cur_addr_entry != addr_map.end())
{
auto& other_blk = blocks[cur_addr_entry->second.first];
size_t split_idx = cur_addr_entry->second.second;
if (other_blk.first == split_idx)
continue;
size_t end = other_blk.second;
blocks.push_back(std::make_pair(split_idx, end));
blocks[cur_addr_entry->second.first].second = split_idx;
for (size_t j = split_idx; j < end; j++)
addr_map[insts[j].addr] = std::make_pair(blocks.size()-1, j);
}
}
std::vector<LLBasicBlock*> block_objs;
block_objs.reserve(blocks.size());
for (auto it = blocks.begin(); it != blocks.end(); it++)
{
LLBasicBlock* block = ll_func_add_block(func);
for (size_t j = it->first; j < it->second; j++)
ll_basic_block_add_inst(block, &insts[j]);
block_objs.push_back(block);
}
for (size_t j = 0; j < blocks.size(); j++)
{
LLInstr& inst = insts[blocks[j].second-1];
LLBasicBlock* fallthrough = NULL;
LLBasicBlock* branch = NULL;
if (inst.type != LL_INS_JMP && inst.type != LL_INS_RET)
fallthrough = block_objs[addr_map[inst.addr + inst.len].first];
if (instrIsJcc(inst.type) || inst.type == LL_INS_JMP)
branch = block_objs[addr_map[inst.dst.val].first];
ll_basic_block_add_branches(block_objs[j], branch, fallthrough);
}
return 0;
}
+55
View File
@@ -0,0 +1,55 @@
/**
* This file is part of Rellume.
*
* (c) 2016-2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
**/
#ifndef LL_FLAGS_INTERNAL_H
#define LL_FLAGS_INTERNAL_H
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <llvm-c/Core.h>
#include <llcommon-internal.h>
#include <llinstr-internal.h>
LLVMValueRef ll_flags_condition(LLInstrType, LLInstrType, LLState*);
void ll_flags_set_af(LLVMValueRef, LLVMValueRef, LLVMValueRef, LLState*);
void ll_flags_set_zf(LLVMValueRef, LLState*);
void ll_flags_set_sf(LLVMValueRef, LLState*);
void ll_flags_set_pf(LLVMValueRef, LLState*);
void ll_flags_set_of_sub(LLVMValueRef, LLVMValueRef, LLVMValueRef, LLState*);
void ll_flags_set_of_imul(LLVMValueRef, LLVMValueRef, LLVMValueRef, LLState*);
void ll_flags_set_sub(LLVMValueRef, LLVMValueRef, LLVMValueRef, LLState*);
void ll_flags_set_add(LLVMValueRef, LLVMValueRef, LLVMValueRef, LLState*);
void ll_flags_set_bit(LLState*, LLVMValueRef, LLVMValueRef, LLVMValueRef);
void ll_flags_set_inc(LLVMValueRef, LLVMValueRef, LLState*);
void ll_flags_set_dec(LLVMValueRef, LLVMValueRef, LLState*);
void ll_flags_set_shl(LLState*, LLVMValueRef, LLVMValueRef, LLVMValueRef);
void ll_flags_set_shr(LLState*, LLVMValueRef, LLVMValueRef, LLVMValueRef);
void ll_flags_set_sar(LLState*, LLVMValueRef, LLVMValueRef, LLVMValueRef);
void ll_flags_invalidate(LLState*);
#endif
+585
View File
@@ -0,0 +1,585 @@
/**
* This file is part of Rellume.
*
* (c) 2016-2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
**/
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <llvm-c/Core.h>
#include <llflags-internal.h>
#include <llbasicblock-internal.h>
#include <llcommon-internal.h>
#include <llinstr-internal.h>
#include <llsupport-internal.h>
/**
* \defgroup LLFlags Flags
* \brief Computation of X86 flags
*
* Ported from https://github.com/trailofbits/mcsema .
*
* @{
**/
/**
* Evaluate a condition based on the condition from the instruction type.
*
* \private
*
* \author Alexis Engelke
*
* \param type The instruction type
* \param base The base instruction type (this is the overflow variant)
* \param state The module state
**/
LLVMValueRef
ll_flags_condition(LLInstrType type, LLInstrType base, LLState* state)
{
int condition = type - base;
int conditionType = condition >> 1;
bool negate = condition & 1;
LLVMValueRef result;
LLFlagCache* flagCache = ll_get_flag_cache(state);
switch (conditionType)
{
case 0: // JO / JNO
result = ll_get_flag(RFLAG_OF, state);
break;
case 1: // JC / JNC
result = ll_get_flag(RFLAG_CF, state);
break;
case 2: // JZ / JNZ
result = ll_get_flag(RFLAG_ZF, state);
break;
case 3: // JBE / JA
if (flagCache->valid)
{
result = LLVMBuildICmp(state->builder, LLVMIntULE, flagCache->operand1, flagCache->operand2, "");
}
else
{
result = LLVMBuildOr(state->builder, ll_get_flag(RFLAG_CF, state), ll_get_flag(RFLAG_ZF, state), "");
}
break;
case 4: // JS / JNS
result = ll_get_flag(RFLAG_SF, state);
break;
case 5: // JP / JNP
result = ll_get_flag(RFLAG_PF, state);
break;
case 6: // JL / JGE
if (flagCache->valid)
{
result = LLVMBuildICmp(state->builder, LLVMIntSLT, flagCache->operand1, flagCache->operand2, "");
}
else
{
result = LLVMBuildICmp(state->builder, LLVMIntNE, ll_get_flag(RFLAG_SF, state), ll_get_flag(RFLAG_OF, state), "");
}
break;
case 7: // JLE / JG
if (flagCache->valid)
{
result = LLVMBuildICmp(state->builder, LLVMIntSLE, flagCache->operand1, flagCache->operand2, "");
}
else
{
result = LLVMBuildICmp(state->builder, LLVMIntNE, ll_get_flag(RFLAG_SF, state), ll_get_flag(RFLAG_OF, state), "");
result = LLVMBuildOr(state->builder, result, ll_get_flag(RFLAG_ZF, state), "");
}
break;
default:
result = NULL;
break;
}
if (negate)
{
result = LLVMBuildNot(state->builder, result, "");
}
return result;
}
/*
* Compute the RFLAGS of a subtraction
*
* Credits to https://github.com/trailofbits/mcsema
*/
/**
* Set the auxiliary flag.
*
* \private
*
* \author Alexis Engelke
*
* \param result The result of the operation
* \param lhs The first operand
* \param rhs The second operand
* \param state The module state
**/
void
ll_flags_set_af(LLVMValueRef result, LLVMValueRef lhs, LLVMValueRef rhs, LLState* state)
{
LLVMValueRef xor1 = LLVMBuildXor(state->builder, lhs, result, "");
LLVMValueRef xor2 = LLVMBuildXor(state->builder, xor1, rhs, "");
LLVMValueRef and1 = LLVMBuildAnd(state->builder, xor2, LLVMConstInt(LLVMTypeOf(result), 16, false), "");
ll_set_flag(RFLAG_AF, LLVMBuildICmp(state->builder, LLVMIntNE, and1, LLVMConstInt(LLVMTypeOf(result), 0, false), ""), state);
LLVMSetMetadata(ll_get_flag(RFLAG_AF, state), LLVMGetMDKindIDInContext(state->context, "asm.flag.af", 11), state->emptyMD);
}
/**
* Set the zero flag.
*
* \private
*
* \author Alexis Engelke
*
* \param result The result of the operation
* \param state The module state
**/
void
ll_flags_set_zf(LLVMValueRef result, LLState* state)
{
ll_set_flag(RFLAG_ZF, LLVMBuildICmp(state->builder, LLVMIntEQ, result, LLVMConstInt(LLVMTypeOf(result), 0, false), ""), state);
LLVMSetMetadata(ll_get_flag(RFLAG_ZF, state), LLVMGetMDKindIDInContext(state->context, "asm.flag.zf", 11), state->emptyMD);
}
/**
* Set the sign flag.
*
* \private
*
* \author Alexis Engelke
*
* \param result The result of the operation
* \param state The module state
**/
void
ll_flags_set_sf(LLVMValueRef result, LLState* state)
{
ll_set_flag(RFLAG_SF, LLVMBuildICmp(state->builder, LLVMIntSLT, result, LLVMConstInt(LLVMTypeOf(result), 0, false), ""), state);
LLVMSetMetadata(ll_get_flag(RFLAG_SF, state), LLVMGetMDKindIDInContext(state->context, "asm.flag.sf", 11), state->emptyMD);
}
/**
* Set the overflow flag for a subtraction.
*
* \private
*
* \author Alexis Engelke
*
* \param result The result of the operation
* \param lhs The first operand
* \param rhs The second operand
* \param state The module state
**/
void
ll_flags_set_of_sub(LLVMValueRef result, LLVMValueRef lhs, LLVMValueRef rhs, LLState* state)
{
LLVMTypeRef intType = LLVMTypeOf(result);
LLVMValueRef overflowFlag;
if (state->cfg.enableOverflowIntrinsics)
{
LLVMValueRef intrinsicSsubWithOverflow = ll_support_get_intrinsic(state->module, LL_INTRINSIC_SSUB_WITH_OVERFLOW, &intType, 1);
LLVMValueRef args[2] = { lhs, rhs };
LLVMValueRef packedData = LLVMBuildCall(state->builder, intrinsicSsubWithOverflow, args, 2, "");
overflowFlag = LLVMBuildExtractValue(state->builder, packedData, 1, "");
}
else
{
int width = LLVMGetIntTypeWidth(intType);
LLVMTypeRef i1 = LLVMInt1TypeInContext(state->context);
LLVMValueRef xor1 = LLVMBuildXor(state->builder, lhs, result, "");
LLVMValueRef xor2 = LLVMBuildXor(state->builder, lhs, rhs, "");
LLVMValueRef and = LLVMBuildAnd(state->builder, xor1, xor2, "");
LLVMValueRef overflow = LLVMBuildLShr(state->builder, and, LLVMConstInt(intType, width - 1, false), "");
overflowFlag = LLVMBuildTrunc(state->builder, overflow, i1, "");
}
ll_set_flag(RFLAG_OF, overflowFlag, state);
LLVMSetMetadata(ll_get_flag(RFLAG_OF, state), LLVMGetMDKindIDInContext(state->context, "asm.flag.of", 11), state->emptyMD);
}
/**
* Set the carry flag for a subtraction.
*
* \private
*
* \author Alexis Engelke
*
* \param lhs The first operand
* \param rhs The second operand
* \param state The module state
**/
static void
ll_flags_set_cf_sub(LLVMValueRef lhs, LLVMValueRef rhs, LLState* state)
{
ll_set_flag(RFLAG_CF, LLVMBuildICmp(state->builder, LLVMIntULT, lhs, rhs, ""), state);
LLVMSetMetadata(ll_get_flag(RFLAG_CF, state), LLVMGetMDKindIDInContext(state->context, "asm.flag.cf", 11), state->emptyMD);
}
/**
* Set the overflow flag for an addition.
*
* \private
*
* \author Alexis Engelke
*
* \param result The result of the operation
* \param lhs The first operand
* \param rhs The second operand
* \param state The module state
**/
static void
ll_flags_set_of_add(LLVMValueRef result, LLVMValueRef lhs, LLVMValueRef rhs, LLState* state)
{
LLVMTypeRef intType = LLVMTypeOf(result);
LLVMValueRef overflowFlag;
if (state->cfg.enableOverflowIntrinsics)
{
LLVMValueRef intrinsicSaddWithOverflow = ll_support_get_intrinsic(state->module, LL_INTRINSIC_SADD_WITH_OVERFLOW, &intType, 1);
LLVMValueRef args[2] = { lhs, rhs };
LLVMValueRef packedData = LLVMBuildCall(state->builder, intrinsicSaddWithOverflow, args, 2, "");
overflowFlag = LLVMBuildExtractValue(state->builder, packedData, 1, "");
}
else
{
int width = LLVMGetIntTypeWidth(intType);
LLVMTypeRef i1 = LLVMInt1TypeInContext(state->context);
LLVMValueRef xor1 = LLVMBuildXor(state->builder, lhs, result, "");
LLVMValueRef xor2 = LLVMBuildXor(state->builder, lhs, rhs, "");
LLVMValueRef not = LLVMBuildNot(state->builder, xor2, "");
LLVMValueRef and = LLVMBuildAnd(state->builder, xor1, not, "");
LLVMValueRef overflow = LLVMBuildLShr(state->builder, and, LLVMConstInt(intType, width - 1, false), "");
overflowFlag = LLVMBuildTrunc(state->builder, overflow, i1, "");
}
ll_set_flag(RFLAG_OF, overflowFlag, state);
LLVMSetMetadata(ll_get_flag(RFLAG_OF, state), LLVMGetMDKindIDInContext(state->context, "asm.flag.of", 11), state->emptyMD);
}
/**
* Set the carry flag for an addition.
*
* \private
*
* \author Alexis Engelke
*
* \param result The result of the operation
* \param lhs The first operand
* \param state The module state
**/
static void
ll_flags_set_cf_add(LLVMValueRef result, LLVMValueRef lhs, LLState* state)
{
ll_set_flag(RFLAG_CF, LLVMBuildICmp(state->builder, LLVMIntULT, result, lhs, ""), state);
LLVMSetMetadata(ll_get_flag(RFLAG_CF, state), LLVMGetMDKindIDInContext(state->context, "asm.flag.cf", 11), state->emptyMD);
}
void
ll_flags_set_of_imul(LLVMValueRef result, LLVMValueRef lhs, LLVMValueRef rhs, LLState* state)
{
LLVMTypeRef intType = LLVMTypeOf(lhs);
LLVMTypeRef intLargeType = LLVMIntTypeInContext(state->context, LLVMGetIntTypeWidth(intType) * 2);
LLVMValueRef overflowFlag;
if (state->cfg.enableOverflowIntrinsics)
{
LLVMValueRef intrinsicSmulWithOverflow = ll_support_get_intrinsic(state->module, LL_INTRINSIC_SMUL_WITH_OVERFLOW, &intType, 1);
LLVMValueRef args[2] = { lhs, rhs };
LLVMValueRef packedData = LLVMBuildCall(state->builder, intrinsicSmulWithOverflow, args, 2, "");
overflowFlag = LLVMBuildExtractValue(state->builder, packedData, 1, "");
}
else
{
LLVMValueRef longResult;
LLVMValueRef shortResult;
if (LLVMTypeOf(result) != intLargeType)
{
lhs = LLVMBuildCast(state->builder, LLVMSExt, lhs, intLargeType, "");
rhs = LLVMBuildCast(state->builder, LLVMSExt, rhs, intLargeType, "");
longResult = LLVMBuildMul(state->builder, lhs, rhs, "");
shortResult = result;
}
else
{
longResult = result;
shortResult = LLVMBuildTrunc(state->builder, result, intType, "");
}
shortResult = LLVMBuildSExt(state->builder, shortResult, intLargeType, "");
overflowFlag = LLVMBuildICmp(state->builder, LLVMIntNE, longResult, shortResult, "");
}
ll_set_flag(RFLAG_OF, overflowFlag, state);
ll_set_flag(RFLAG_CF, overflowFlag, state);
LLVMSetMetadata(overflowFlag, LLVMGetMDKindIDInContext(state->context, "asm.flag.of", 11), state->emptyMD);
}
/**
* Set the parity flag of a result. This is not really optimized since no one is
* using this anyway.
*
* \private
*
* \author Alexis Engelke
*
* \param result The result of the operation
* \param state The module state
**/
void
ll_flags_set_pf(LLVMValueRef result, LLState* state)
{
LLVMTypeRef i1 = LLVMInt1TypeInContext(state->context);
LLVMTypeRef i8 = LLVMInt8TypeInContext(state->context);
LLVMValueRef intrinsicCtpop8 = ll_support_get_intrinsic(state->module, LL_INTRINSIC_CTPOP, &i8, 1);
LLVMValueRef arg = LLVMBuildTruncOrBitCast(state->builder, result, i8, "");
LLVMValueRef count = LLVMBuildCall(state->builder, intrinsicCtpop8, &arg, 1, "");
LLVMValueRef bit = LLVMBuildTruncOrBitCast(state->builder, count, i1, "");
ll_set_flag(RFLAG_PF, LLVMBuildNot(state->builder, bit, ""), state);
LLVMSetMetadata(ll_get_flag(RFLAG_PF, state), LLVMGetMDKindIDInContext(state->context, "asm.flag.pf", 11), state->emptyMD);
}
/**
* Set the flags for a subtraction. The flag cache will be valid.
*
* \private
*
* \author Alexis Engelke
*
* \param result The result of the operation
* \param lhs The first operand
* \param rhs The second operand
* \param state The module state
**/
void
ll_flags_set_sub(LLVMValueRef result, LLVMValueRef lhs, LLVMValueRef rhs, LLState* state)
{
ll_flags_set_af(result, lhs, rhs, state);
ll_flags_set_zf(result, state);
ll_flags_set_sf(result, state);
ll_flags_set_cf_sub(lhs, rhs, state);
ll_flags_set_of_sub(result, lhs, rhs, state);
ll_flags_set_pf(result, state);
LLFlagCache* flagCache = ll_get_flag_cache(state);
flagCache->valid = true;
flagCache->operand1 = lhs;
flagCache->operand2 = rhs;
flagCache->result = result;
}
/**
* Set the flags for an addition. The flag cache will be invalidated.
*
* \private
*
* \author Alexis Engelke
*
* \param result The result of the operation
* \param lhs The first operand
* \param rhs The second operand
* \param state The module state
**/
void
ll_flags_set_add(LLVMValueRef result, LLVMValueRef lhs, LLVMValueRef rhs, LLState* state)
{
ll_flags_set_af(result, lhs, rhs, state);
ll_flags_set_zf(result, state);
ll_flags_set_sf(result, state);
ll_flags_set_cf_add(result, lhs, state);
ll_flags_set_of_add(result, lhs, rhs, state);
ll_flags_set_pf(result, state);
LLFlagCache* flagCache = ll_get_flag_cache(state);
flagCache->valid = false;
}
/**
* Set the flags for a bitwise operation. The flag cache will be invalidated.
*
* \private
*
* \author Alexis Engelke
*
* \param result The result of the operation
* \param state The module state
**/
void
ll_flags_set_bit(LLState* state, LLVMValueRef result, LLVMValueRef lhs, LLVMValueRef rhs)
{
LLVMTypeRef i1 = LLVMInt1TypeInContext(state->context);
ll_set_flag(RFLAG_AF, LLVMGetUndef(i1), state);
ll_set_flag(RFLAG_CF, LLVMConstInt(i1, 0, false), state);
ll_set_flag(RFLAG_OF, LLVMConstInt(i1, 0, false), state);
ll_flags_set_zf(result, state);
ll_flags_set_sf(result, state);
ll_flags_set_pf(result, state);
LLFlagCache* flagCache = ll_get_flag_cache(state);
flagCache->valid = false;
(void) lhs;
(void) rhs;
}
/**
* Set the flags for a increment operation. The flag cache will be invalidated.
*
* \private
*
* \author Alexis Engelke
*
* \param result The result of the operation
* \param lhs The operand to increment
* \param state The module state
**/
void
ll_flags_set_inc(LLVMValueRef result, LLVMValueRef lhs, LLState* state)
{
LLVMValueRef rhs = LLVMConstInt(LLVMTypeOf(lhs), 1, false);
ll_flags_set_af(result, lhs, rhs, state);
ll_flags_set_zf(result, state);
ll_flags_set_sf(result, state);
ll_flags_set_of_add(result, lhs, rhs, state);
ll_flags_set_pf(result, state);
LLFlagCache* flagCache = ll_get_flag_cache(state);
flagCache->valid = false;
}
/**
* Set the flags for a decrement operation. The flag cache will be invalidated.
*
* \private
*
* \author Alexis Engelke
*
* \param result The result of the operation
* \param lhs The operand to decrement
* \param state The module state
**/
void
ll_flags_set_dec(LLVMValueRef result, LLVMValueRef lhs, LLState* state)
{
LLVMValueRef rhs = LLVMConstInt(LLVMTypeOf(lhs), 1, false);
ll_flags_set_af(result, lhs, rhs, state);
ll_flags_set_zf(result, state);
ll_flags_set_sf(result, state);
ll_flags_set_of_sub(result, lhs, rhs, state);
ll_flags_set_pf(result, state);
LLFlagCache* flagCache = ll_get_flag_cache(state);
flagCache->valid = false;
}
void
ll_flags_set_shl(LLState* state, LLVMValueRef result, LLVMValueRef lhs, LLVMValueRef rhs)
{
// TODO
ll_flags_invalidate(state);
ll_flags_set_zf(result, state);
ll_flags_set_sf(result, state);
ll_flags_set_pf(result, state);
(void) lhs;
(void) rhs;
}
void
ll_flags_set_shr(LLState* state, LLVMValueRef result, LLVMValueRef lhs, LLVMValueRef rhs)
{
// TODO
ll_flags_invalidate(state);
ll_flags_set_zf(result, state);
ll_flags_set_sf(result, state);
ll_flags_set_pf(result, state);
(void) lhs;
(void) rhs;
}
void
ll_flags_set_sar(LLState* state, LLVMValueRef result, LLVMValueRef lhs, LLVMValueRef rhs)
{
// TODO
ll_flags_invalidate(state);
ll_flags_set_zf(result, state);
ll_flags_set_sf(result, state);
ll_flags_set_pf(result, state);
(void) lhs;
(void) rhs;
}
/**
* Invalidate the flags and the flag cache.
*
* \private
*
* \author Alexis Engelke
*
* \param state The module state
**/
void
ll_flags_invalidate(LLState* state)
{
LLVMTypeRef i1 = LLVMInt1TypeInContext(state->context);
ll_set_flag(RFLAG_AF, LLVMGetUndef(i1), state);
ll_set_flag(RFLAG_CF, LLVMGetUndef(i1), state);
ll_set_flag(RFLAG_OF, LLVMGetUndef(i1), state);
ll_set_flag(RFLAG_SF, LLVMGetUndef(i1), state);
ll_set_flag(RFLAG_ZF, LLVMGetUndef(i1), state);
ll_set_flag(RFLAG_PF, LLVMGetUndef(i1), state);
LLFlagCache* flagCache = ll_get_flag_cache(state);
flagCache->valid = false;
}
/**
* @}
**/
+346
View File
@@ -0,0 +1,346 @@
/**
* This file is part of Rellume.
*
* (c) 2016-2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
**/
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <llvm-c/Analysis.h>
#include <llvm-c/Core.h>
#include <llvm-c/Support.h>
#include <llvm-c/Transforms/IPO.h>
#include <llvm-c/Transforms/Scalar.h>
#include <llvm-c/Transforms/Vectorize.h>
#include <llfunc.h>
#include <llbasicblock-internal.h>
#include <llcommon-internal.h>
#include <lloperand-internal.h>
#include <llsupport-internal.h>
/**
* \defgroup LLFunc Func2
* \brief Representation of a function
*
* @{
**/
struct LLFunc {
LLVMValueRef llvm;
LLState state;
/**
* \brief The basic block count
**/
size_t bbCount;
/**
* \brief The allocated size for basic blocks
**/
size_t bbsAllocated;
/**
* \brief Array of basics blocks belonging to this function
**/
LLBasicBlock** bbs;
/**
* \brief The initial basic block, which is the entry point
**/
LLBasicBlock* initialBB;
};
LLFunc*
ll_func(const char* name, LLVMTypeRef ty, LLVMModuleRef mod)
{
LLFunc* fn = malloc(sizeof(LLFunc));
fn->llvm = LLVMAddFunction(mod, name, ty);
fn->bbCount = 0;
fn->bbs = NULL;
fn->bbsAllocated = 0;
LLState* state = &fn->state;
state->context = LLVMGetModuleContext(mod);
state->module = mod;
state->builder = LLVMCreateBuilderInContext(state->context);
state->llvm_function = fn->llvm;
state->emptyMD = LLVMMDNodeInContext(state->context, NULL, 0);
state->unrollMD = ll_support_metadata_loop_unroll(state->context);
state->cfg.globalBase = NULL;
state->cfg.stackSize = 128; // FIXME
state->cfg.enableUnsafePointerOptimizations = false;
state->cfg.enableOverflowIntrinsics = false;
state->cfg.enableFastMath = false;
state->cfg.enableFullLoopUnroll = false;
LLVMTypeRef i1 = LLVMInt1TypeInContext(state->context);
LLVMTypeRef i8 = LLVMInt8TypeInContext(state->context);
LLVMTypeRef i64 = LLVMInt64TypeInContext(state->context);
LLVMTypeRef iVec = LLVMIntTypeInContext(state->context, LL_VECTOR_REGISTER_SIZE);
size_t paramCount = LLVMCountParams(fn->llvm);
LLVMBasicBlockRef llvmBB = LLVMAppendBasicBlockInContext(state->context, fn->llvm, "");
LLBasicBlock* initialBB = ll_basic_block_new(llvmBB, &fn->state);
state->currentBB = initialBB;
// Position IR builder at a new basic block in the function
LLVMPositionBuilderAtEnd(state->builder, ll_basic_block_llvm(initialBB));
// Iterate over the parameters to initialize the registers.
LLVMValueRef params = LLVMGetFirstParam(fn->llvm);
// Set all registers to undef first.
for (int i = 0; i < LL_RI_GPMax; i++)
ll_set_register(ll_reg(LL_RT_GP64, i), FACET_I64, LLVMGetUndef(i64), true, state);
for (int i = 0; i < LL_RI_XMMMax; i++)
ll_set_register(ll_reg(LL_RT_XMM, i), FACET_IVEC, LLVMGetUndef(iVec), true, state);
for (int i = 0; i < RFLAG_Max; i++)
ll_basic_block_set_flag(initialBB, i, LLVMGetUndef(i1));
LLReg gpRegs[6] = {
ll_reg(LL_RT_GP64, LL_RI_DI),
ll_reg(LL_RT_GP64, LL_RI_SI),
ll_reg(LL_RT_GP64, LL_RI_D),
ll_reg(LL_RT_GP64, LL_RI_C),
ll_reg(LL_RT_GP64, 8),
ll_reg(LL_RT_GP64, 9),
};
int gpRegOffset = 0;
int fpRegOffset = 0;
for (size_t i = 0; i < paramCount; i++)
{
LLVMTypeKind paramTypeKind = LLVMGetTypeKind(LLVMTypeOf(params));
if (paramTypeKind == LLVMPointerTypeKind)
{
LLVMValueRef intValue = LLVMBuildPtrToInt(state->builder, params, i64, "");
ll_operand_store(OP_SI, ALIGN_MAXIMUM, getRegOp(gpRegs[gpRegOffset]), REG_DEFAULT, intValue, state);
gpRegOffset++;
}
else if (paramTypeKind == LLVMIntegerTypeKind)
{
ll_operand_store(OP_SI, ALIGN_MAXIMUM, getRegOp(gpRegs[gpRegOffset]), REG_DEFAULT, params, state);
gpRegOffset++;
}
else if (paramTypeKind == LLVMFloatTypeKind)
{
ll_operand_store(OP_SF32, ALIGN_MAXIMUM, getRegOp(ll_reg(LL_RT_XMM, fpRegOffset)), REG_ZERO_UPPER_SSE, params, state);
fpRegOffset++;
}
else if (paramTypeKind == LLVMDoubleTypeKind)
{
ll_operand_store(OP_SF64, ALIGN_MAXIMUM, getRegOp(ll_reg(LL_RT_XMM, fpRegOffset)), REG_ZERO_UPPER_SSE, params, state);
fpRegOffset++;
}
else
warn_if_reached();
params = LLVMGetNextParam(params);
}
// Setup virtual stack
LLVMValueRef stackSize = LLVMConstInt(i64, state->cfg.stackSize, false);
LLVMValueRef stack = LLVMBuildArrayAlloca(state->builder, i8, stackSize, "");
LLVMValueRef sp = LLVMBuildGEP(state->builder, stack, &stackSize, 1, "");
ll_basic_block_set_register(initialBB, FACET_PTR, ll_reg(LL_RT_GP64, LL_RI_SP), sp, true, state);
LLVMSetAlignment(stack, 16);
fn->initialBB = initialBB;
return fn;
}
/**
* Enable the usage of overflow intrinsics instead of bitwise operations when
* setting the overflow flag. For dynamic values this leads to better code which
* relies on the overflow flag again. However, immediate values are not folded
* when they are guaranteed to overflow.
*
* This function must be called before the IR of the function is built.
*
* \author Alexis Engelke
*
* \param state The module state
* \param enable Whether overflow intrinsics shall be used
**/
void
ll_func_enable_overflow_intrinsics(LLFunc* fn, bool enable)
{
fn->state.cfg.enableOverflowIntrinsics = enable;
}
/**
* Enable unsafe floating-point optimizations, similar to -ffast-math.
*
* This function must be called before the IR of the function is built.
*
* \author Alexis Engelke
*
* \param state The module state
* \param enable Whether unsafe floating-point optimizations may be performed
**/
void
ll_func_enable_fast_math(LLFunc* fn, bool enable)
{
fn->state.cfg.enableFastMath = enable;
}
/**
* Force loop unrolling whenever possible.
*
* \author Alexis Engelke
*
* \param state The module state
* \param enable Whether force loop unrolling
**/
void
ll_func_enable_full_loop_unroll(LLFunc* fn, bool enable)
{
fn->state.cfg.enableFullLoopUnroll = enable;
}
void
ll_func_set_global_base(LLFunc* fn, uintptr_t base, LLVMValueRef value)
{
fn->state.cfg.globalOffsetBase = base;
fn->state.cfg.globalBase = value;
}
/**
* Dispose a function.
*
* \author Alexis Engelke
*
* \param fn The function
**/
void
ll_func_dispose(LLFunc* fn)
{
LLVMDisposeBuilder(fn->state.builder);
if (fn->bbsAllocated != 0)
{
for (size_t i = 0; i < fn->bbCount; i++)
ll_basic_block_dispose(fn->bbs[i]);
free(fn->bbs);
}
free(fn);
}
/**
* Dump the LLVM IR of the function.
*
* \author Alexis Engelke
*
* \param state The function
**/
void
ll_func_dump(LLFunc* fn)
{
char* value = LLVMPrintValueToString(fn->llvm);
puts(value);
LLVMDisposeMessage(value);
}
static void
ll_func_add_basic_block(LLFunc* function, LLBasicBlock* bb)
{
if (function->bbsAllocated == 0)
{
function->bbs = malloc(sizeof(LLBasicBlock*) * 10);
function->bbsAllocated = 10;
if (function->bbs == NULL)
warn_if_reached();
ll_basic_block_add_predecessor(bb, function->initialBB);
}
else if (function->bbsAllocated == function->bbCount)
{
function->bbs = realloc(function->bbs, sizeof(LLBasicBlock*) * function->bbsAllocated * 2);
function->bbsAllocated *= 2;
if (function->bbs == NULL)
warn_if_reached();
}
function->bbs[function->bbCount] = bb;
function->bbCount++;
}
LLBasicBlock*
ll_func_add_block(LLFunc* fn)
{
LLVMBasicBlockRef llvmBB = LLVMAppendBasicBlockInContext(fn->state.context, fn->llvm, "");
LLBasicBlock* bb = ll_basic_block_new(llvmBB, &fn->state);
ll_basic_block_add_phis(bb);
ll_func_add_basic_block(fn, bb);
return bb;
}
LLVMValueRef
ll_func_lift(LLFunc* fn)
{
size_t bbCount = fn->bbCount;
LLVMPositionBuilderAtEnd(fn->state.builder, ll_basic_block_llvm(fn->initialBB));
LLVMBuildBr(fn->state.builder, ll_basic_block_llvm(fn->bbs[0]));
for (size_t i = 0; i < bbCount; i++)
{
ll_basic_block_terminate(fn->bbs[i]);
ll_basic_block_fill_phis(fn->bbs[i]);
}
bool error = LLVMVerifyFunction(fn->llvm, LLVMPrintMessageAction);
if (error)
return NULL;
// Run some optimization passes to remove most of the bloat
LLVMPassManagerRef pm = LLVMCreateFunctionPassManagerForModule(fn->state.module);
LLVMInitializeFunctionPassManager(pm);
LLVMAddEarlyCSEPass(pm);
LLVMAddGVNPass(pm);
LLVMAddCFGSimplificationPass(pm);
LLVMAddInstructionCombiningPass(pm);
LLVMAddAggressiveDCEPass(pm);
LLVMRunFunctionPassManager(pm, fn->llvm);
LLVMFinalizeFunctionPassManager(pm);
LLVMDisposePassManager(pm);
return fn->llvm;
}
/**
* @}
**/
+45
View File
@@ -0,0 +1,45 @@
/**
* This file is part of Rellume.
*
* (c) 2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LL_INSTR_INTERNAL_H
#define LL_INSTR_INTERNAL_H
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <llinstr.h>
#define ll_reg(t,i) ((LLReg) { .rt = t, .ri = i })
LLReg ll_reg_gp(size_t size, bool legacy, int index);
const char* ll_reg_name(LLReg reg);
size_t ll_reg_size(LLReg reg);
#define ll_reg_high(reg) ((reg).rt == LL_RT_GP8Leg && (reg).ri >= 4 && (reg).ri < 8)
#define regIsGP(r) ((r).rt == LL_RT_GP8Leg || (r).rt == LL_RT_GP8 || (r).rt == LL_RT_GP16 || (r).rt == LL_RT_GP32 || (r).rt == LL_RT_GP64)
#define regIsV(r) ((r).rt == LL_RT_XMM || (r).rt == LL_RT_YMM)
#define getRegOp(r) &((LLInstrOp) { .type = 1, .reg = (r), .val = 0, .ireg = ll_reg(LL_RT_None, LL_RI_None), .scale = 0, .seg = LL_RI_None, .size = ll_reg_size(r) })
#define instr2string(instr, ...) "<llinstr>"
#endif
+111
View File
@@ -0,0 +1,111 @@
/**
* This file is part of Rellume.
*
* (c) 2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
**/
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <llvm-c/Core.h>
#include <llinstr.h>
#include <llinstr-internal.h>
#include <llcommon-internal.h>
/**
* \defgroup LLInstr Instruction
* \brief Representation of an instruction
*
* @{
**/
LLReg
ll_reg_gp(size_t size, bool legacy, int index) {
switch (size) {
case 1: return ll_reg(legacy ? LL_RT_GP8Leg : LL_RT_GP8, index);
case 2: return ll_reg(LL_RT_GP16, index);
case 4: return ll_reg(LL_RT_GP32, index);
case 8: return ll_reg(LL_RT_GP64, index);
default: warn_if_reached(); return ll_reg(LL_RT_None, LL_RI_None);
}
}
static const char* names_reg_gp8 =
"al\0 cl\0 dl\0 bl\0 spl\0 bpl\0 sil\0 dil\0 "
"r8b\0 r9b\0 r10b\0 r11b\0 r12b\0 r13b\0 r14b\0 r15b\0 ";
static const char* names_reg_gp8leg =
"al\0 cl\0 dl\0 bl\0 ah\0 ch\0 dh\0 bh\0 "
"r8b\0 r9b\0 r10b\0 r11b\0 r12b\0 r13b\0 r14b\0 r15b\0 ";
static const char* names_reg_gp16 =
"ax\0 cx\0 dx\0 bx\0 sp\0 bp\0 si\0 di\0 "
"r8w\0 r9w\0 r10w\0 r11w\0 r12w\0 r13w\0 r14w\0 r15w\0 ";
static const char* names_reg_gp32 =
"eax\0 ecx\0 edx\0 ebx\0 esp\0 ebp\0 esi\0 edi\0 "
"r8d\0 r9d\0 r10d\0 r11d\0 r12d\0 r13d\0 r14d\0 r15d\0 ";
static const char* names_reg_gp64 =
"rax\0 rcx\0 rdx\0 rbx\0 rsp\0 rbp\0 rsi\0 rdi\0 "
"r8\0 r9\0 r10\0 r11\0 r12\0 r13\0 r14\0 r15\0 ";
static const char* names_reg_vec128 =
"xmm0\0 xmm1\0 xmm2\0 xmm3\0 xmm4\0 xmm5\0 xmm6\0 xmm7\0 "
"xmm8\0 xmm9\0 xmm10\0xmm11\0xmm12\0xmm13\0xmm14\0xmm15\0";
const char*
ll_reg_name(LLReg reg)
{
int max;
const char* table;
switch (reg.rt) {
case LL_RT_GP8: max = 16; table = names_reg_gp8; break;
case LL_RT_GP8Leg: max = 16; table = names_reg_gp8leg; break;
case LL_RT_GP16: max = 16; table = names_reg_gp16; break;
case LL_RT_GP32: max = 16; table = names_reg_gp32; break;
case LL_RT_GP64: max = 16; table = names_reg_gp64; break;
case LL_RT_IP: max = 1; table = "rip"; break;
case LL_RT_XMM: max = 16; table = names_reg_vec128; break;
default: max = 1; table = "(unk)"; break;
}
return reg.ri < max ? table + (reg.ri * 6) : "(inv)";
}
size_t
ll_reg_size(LLReg reg)
{
switch (reg.rt) {
case LL_RT_GP8: return 1;
case LL_RT_GP8Leg: return 1;
case LL_RT_GP16: return 2;
case LL_RT_GP32: return 4;
case LL_RT_GP64: return 8;
case LL_RT_IP: return 8;
case LL_RT_XMM: return 16;
default: return 0;
}
}
/**
* @}
**/
+145
View File
@@ -0,0 +1,145 @@
/**
* This file is part of Rellume.
*
* (c) 2016-2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
**/
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <llvm-c/Core.h>
#include <llinstruction-internal.h>
#include <llbasicblock-internal.h>
#include <llcommon-internal.h>
#include <llinstr-internal.h>
#include <lloperand-internal.h>
#include <llsupport-internal.h>
/**
* \defgroup LLInstructionCall Call/Ret Instructions
* \ingroup LLInstruction
*
* @{
**/
void
ll_instruction_call(LLInstr* instr, LLState* state)
{
(void) instr;
(void) state;
warn_if_reached();
#if 0
LLVMTypeRef i64 = LLVMInt64TypeInContext(state->context);
uintptr_t address = 0;
if (instr->dst.type == LL_OP_IMM)
address = instr->dst.val;
else if (instr->dst.type == LL_OP_REG && instr->dst.reg.rt == LL_RT_GP64)
{
LLVMValueRef value = ll_get_register(instr->dst.reg, FACET_I64, state);
if (ll_support_is_constant_int(value))
address = LLVMConstIntGetZExtValue(value);
}
if (address == 0)
warn_if_reached();
// Find function with corresponding address.
LLFunction* function = NULL;
for (size_t i = 0; i < state->functionCount; i++)
if (state->functions[i]->address == address)
function = state->functions[i];
if (function == NULL)
return;
// warn_if_reached();
LLVMValueRef llvmFunction = function->llvmFunction;
LLVMAddAttributeAtIndex(llvmFunction, -1, ll_support_get_enum_attr(state->context, "inlinehint"));
// Construct arguments.
LLVMTypeRef fnType = LLVMGetElementType(LLVMTypeOf(llvmFunction));
size_t argCount = LLVMCountParamTypes(fnType);
LLVMValueRef args[argCount];
ll_operand_construct_args(fnType, args, state);
LLVMValueRef result = LLVMBuildCall(state->builder, llvmFunction, args, argCount, "");
if (LLVMGetTypeKind(LLVMTypeOf(result)) == LLVMPointerTypeKind)
result = LLVMBuildPtrToInt(state->builder, result, i64, "");
if (LLVMTypeOf(result) != i64)
warn_if_reached();
// TODO: Handle return values except for i64!
ll_set_register(ll_reg(LL_RT_GP64, LL_RI_A), FACET_I64, result, true, state);
// Clobber registers.
ll_clear_register(ll_reg(LL_RT_GP64, LL_RI_C), state);
ll_clear_register(ll_reg(LL_RT_GP64, LL_RI_D), state);
ll_clear_register(ll_reg(LL_RT_GP64, LL_RI_SI), state);
ll_clear_register(ll_reg(LL_RT_GP64, LL_RI_DI), state);
ll_clear_register(ll_reg(LL_RT_GP64, 8), state);
ll_clear_register(ll_reg(LL_RT_GP64, 9), state);
ll_clear_register(ll_reg(LL_RT_GP64, 10), state);
ll_clear_register(ll_reg(LL_RT_GP64, 11), state);
#endif
}
void
ll_instruction_ret(LLInstr* instr, LLState* state)
{
LLVMTypeRef fnType = LLVMGetElementType(LLVMTypeOf(state->llvm_function));
LLVMTypeRef retType = LLVMGetReturnType(fnType);
LLVMTypeKind retTypeKind = LLVMGetTypeKind(retType);
LLVMValueRef result = NULL;
if (retTypeKind == LLVMPointerTypeKind)
result = ll_get_register(ll_reg(LL_RT_GP64, LL_RI_A), FACET_PTR, state);
else if (retTypeKind == LLVMIntegerTypeKind)
// TODO: Non 64-bit integers!
result = ll_get_register(ll_reg(LL_RT_GP64, LL_RI_A), FACET_I64, state);
else if (retTypeKind == LLVMFloatTypeKind)
result = ll_get_register(ll_reg(LL_RT_XMM, 0), FACET_F32, state);
else if (retTypeKind == LLVMDoubleTypeKind)
result = ll_get_register(ll_reg(LL_RT_XMM, 0), FACET_F64, state);
else if (retTypeKind == LLVMVoidTypeKind)
result = NULL;
else
warn_if_reached();
if (result != NULL)
LLVMBuildRet(state->builder, result);
else
LLVMBuildRetVoid(state->builder);
(void) instr;
}
/**
* @}
**/
+388
View File
@@ -0,0 +1,388 @@
/**
* This file is part of Rellume.
*
* (c) 2016-2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
**/
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <llvm-c/Core.h>
#include <llinstruction-internal.h>
#include <llbasicblock-internal.h>
#include <llcommon-internal.h>
#include <llflags-internal.h>
#include <llinstr-internal.h>
#include <lloperand-internal.h>
#include <llsupport-internal.h>
/**
* \defgroup LLInstructionGP General Purpose Instructions
* \ingroup LLInstruction
*
* @{
**/
void
ll_instruction_movgp(LLInstr* instr, LLState* state)
{
if (instr->dst.type == LL_OP_REG && instr->src.type == LL_OP_REG && instr->dst.size == 8 && instr->src.size == 8)
ll_basic_block_rename_register(state->currentBB, instr->dst.reg, instr->src.reg, state);
else
{
LLVMTypeRef targetType = LLVMIntTypeInContext(state->context, instr->dst.size * 8);
LLVMValueRef operand1 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, &instr->src, state);
if (instr->type == LL_INS_MOVZX)
operand1 = LLVMBuildZExtOrBitCast(state->builder, operand1, targetType, "");
else if (instr->type == LL_INS_MOVSX) // There was a case when MOV was sign-extending, too...
operand1 = LLVMBuildSExtOrBitCast(state->builder, operand1, targetType, "");
ll_operand_store(OP_SI, ALIGN_MAXIMUM, &instr->dst, REG_DEFAULT, operand1, state);
}
}
void
ll_instruction_add(LLInstr* instr, LLState* state)
{
LLVMValueRef operand1 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, &instr->dst, state);
LLVMValueRef operand2 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, &instr->src, state);
operand2 = LLVMBuildSExtOrBitCast(state->builder, operand2, LLVMTypeOf(operand1), "");
LLVMValueRef result = LLVMBuildAdd(state->builder, operand1, operand2, "");
if (LLVMGetIntTypeWidth(LLVMTypeOf(operand1)) == 64 && instr->dst.type == LL_OP_REG)
{
LLVMValueRef ptr = ll_get_register(instr->dst.reg, FACET_PTR, state);
LLVMValueRef gep = LLVMBuildGEP(state->builder, ptr, &operand2, 1, "");
ll_set_register(instr->dst.reg, FACET_I64, result, true, state);
ll_set_register(instr->dst.reg, FACET_PTR, gep, false, state);
}
else
ll_operand_store(OP_SI, ALIGN_MAXIMUM, &instr->dst, REG_DEFAULT, result, state);
ll_flags_set_add(result, operand1, operand2, state);
}
void
ll_instruction_sub(LLInstr* instr, LLState* state)
{
LLVMValueRef operand1 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, &instr->dst, state);
LLVMValueRef operand2 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, &instr->src, state);
operand2 = LLVMBuildSExtOrBitCast(state->builder, operand2, LLVMTypeOf(operand1), "");
LLVMValueRef result = LLVMBuildSub(state->builder, operand1, operand2, "");
if (LLVMGetIntTypeWidth(LLVMTypeOf(operand1)) == 64 && instr->dst.type == LL_OP_REG)
{
LLVMValueRef sub = LLVMBuildNeg(state->builder, operand2, "");
LLVMValueRef ptr = ll_get_register(instr->dst.reg, FACET_PTR, state);
LLVMValueRef gep = LLVMBuildGEP(state->builder, ptr, &sub, 1, "");
ll_set_register(instr->dst.reg, FACET_I64, result, true, state);
ll_set_register(instr->dst.reg, FACET_PTR, gep, false, state);
}
else
ll_operand_store(OP_SI, ALIGN_MAXIMUM, &instr->dst, REG_DEFAULT, result, state);
ll_flags_set_sub(result, operand1, operand2, state);
}
void
ll_instruction_cmp(LLInstr* instr, LLState* state)
{
LLVMValueRef operand1 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, &instr->dst, state);
LLVMValueRef operand2 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, &instr->src, state);
operand2 = LLVMBuildSExtOrBitCast(state->builder, operand2, LLVMTypeOf(operand1), "");
LLVMValueRef result = LLVMBuildSub(state->builder, operand1, operand2, "");
ll_flags_set_sub(result, operand1, operand2, state);
if (LLVMGetIntTypeWidth(LLVMTypeOf(operand1)) == 64 &&
instr->dst.type == LL_OP_REG &&instr->src.type == LL_OP_REG)
{
LLVMValueRef ptr1 = ll_get_register(instr->dst.reg, FACET_PTR, state);
LLVMValueRef ptr2 = ll_get_register(instr->src.reg, FACET_PTR, state);
LLVMTypeRef i64 = LLVMInt64TypeInContext(state->context);
operand1 = LLVMBuildPtrToInt(state->builder, ptr1, i64, "");
operand2 = LLVMBuildPtrToInt(state->builder, ptr2, i64, "");
ll_set_flag(RFLAG_ZF, LLVMBuildICmp(state->builder, LLVMIntEQ, operand1, operand2, ""), state);
}
}
void
ll_instruction_test(LLInstr* instr, LLState* state)
{
LLVMValueRef operand1 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, &instr->dst, state);
LLVMValueRef operand2 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, &instr->src, state);
operand2 = LLVMBuildSExtOrBitCast(state->builder, operand2, LLVMTypeOf(operand1), "");
LLVMValueRef result = LLVMBuildAnd(state->builder, operand1, operand2, "");
ll_flags_set_bit(state, result, NULL, NULL);
}
void
ll_instruction_notneg(LLInstr* instr, LLState* state)
{
LLVMValueRef operand1 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, &instr->dst, state);
LLVMValueRef result = NULL;
if (instr->type == LL_INS_NEG)
{
result = LLVMBuildNeg(state->builder, operand1, "");
LLVMValueRef zero = LLVMConstNull(LLVMTypeOf(operand1));
LLVMValueRef cf = LLVMBuildICmp(state->builder, LLVMIntNE, operand1, zero, "");
ll_flags_invalidate(state);
ll_set_flag(RFLAG_CF, cf, state);
ll_flags_set_pf(result, state);
ll_flags_set_zf(result, state);
ll_flags_set_sf(result, state);
ll_flags_set_af(result, zero, operand1, state);
ll_flags_set_of_sub(result, zero, operand1, state);
}
else // LL_INS_NOT
result = LLVMBuildNot(state->builder, operand1, "");
ll_operand_store(OP_SI, ALIGN_MAXIMUM, &instr->dst, REG_DEFAULT, result, state);
}
void
ll_instruction_incdec(LLInstr* instr, LLState* state)
{
LLVMValueRef operand1 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, &instr->dst, state);
LLVMValueRef operand2 = LLVMConstInt(LLVMTypeOf(operand1), 1, false);
LLVMValueRef result = NULL;
if (instr->type == LL_INS_INC)
{
result = LLVMBuildAdd(state->builder, operand1, operand2, "");
ll_flags_set_inc(result, operand1, state);
}
else // LL_INS_DEC
{
result = LLVMBuildSub(state->builder, operand1, operand2, "");
ll_flags_set_dec(result, operand1, state);
}
ll_operand_store(OP_SI, ALIGN_MAXIMUM, &instr->dst, REG_DEFAULT, result, state);
}
void
ll_instruction_shift(LLInstr* instr, LLState* state)
{
LLVMValueRef operand1 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, &instr->dst, state);
LLVMValueRef operand2;
LLVMValueRef result = NULL;
if (instr->operand_count == 1)
{
// DBrew decodes shifts with a implicit shift of 1 with only one operand
operand2 = LLVMConstInt(LLVMTypeOf(operand1), 1, false);
}
else
{
operand2 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, &instr->src, state);
// In x86, the second operand is always one byte, but in LLVM it must
// have the same type as the first operand.
operand2 = LLVMBuildZExtOrBitCast(state->builder, operand2, LLVMTypeOf(operand1), "");
// x86 also masks the shift operands, depending on operand size. Note
// that for 8/16-bit operands the mask is 0x1f as well.
uint64_t mask_value = 0x3f;
if (LLVMGetIntTypeWidth(LLVMTypeOf(operand1)) != 64)
{
mask_value = 0x1f;
}
LLVMValueRef mask = LLVMConstInt(LLVMTypeOf(operand1), mask_value, false);
operand2 = LLVMBuildAnd(state->builder, operand2, mask, "");
}
if (instr->type == LL_INS_SHL)
{
result = LLVMBuildShl(state->builder, operand1, operand2, "");
ll_flags_set_shl(state, result, operand1, operand2);
}
else if (instr->type == LL_INS_SHR)
{
result = LLVMBuildLShr(state->builder, operand1, operand2, "");
ll_flags_set_shr(state, result, operand1, operand2);
}
else if (instr->type == LL_INS_SAR)
{
result = LLVMBuildAShr(state->builder, operand1, operand2, "");
ll_flags_set_sar(state, result, operand1, operand2);
}
ll_operand_store(OP_SI, ALIGN_MAXIMUM, &instr->dst, REG_DEFAULT, result, state);
}
void
ll_instruction_mul(LLInstr* instr, LLState* state)
{
LLVMValueRef operand1;
LLVMValueRef operand2;
LLVMValueRef result = NULL;
ll_flags_invalidate(state);
if (instr->operand_count == 1) // This covers LL_INS_MUL as well
{
LLVMOpcode ext = instr->type == LL_INS_IMUL ? LLVMSExt : LLVMZExt;
LLVMOpcode shift = instr->type == LL_INS_IMUL ? LLVMAShr : LLVMLShr;
LLVMTypeRef targetHalfType = LLVMIntTypeInContext(state->context, instr->dst.size * 8);
LLVMTypeRef targetType = LLVMIntTypeInContext(state->context, instr->dst.size * 16);
LLInstrOp* regOp = getRegOp(ll_reg_gp(instr->dst.size, false, LL_RI_A));
operand1 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, &instr->dst, state);
operand2 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, regOp, state);
LLVMValueRef largeOperand1 = LLVMBuildCast(state->builder, ext, operand1, targetType, "");
LLVMValueRef largeOperand2 = LLVMBuildCast(state->builder, ext, operand2, targetType, "");
result = LLVMBuildMul(state->builder, largeOperand1, largeOperand2, "");
LLVMValueRef resultA = LLVMBuildTrunc(state->builder, result, targetHalfType, "");
LLVMValueRef resultD = LLVMBuildBinOp(state->builder, shift, result, LLVMConstInt(targetType, instr->dst.size * 8, false), "");
resultD = LLVMBuildTrunc(state->builder, resultD, targetHalfType, "");
if (instr->dst.size == 1)
{
ll_operand_store(OP_SI, ALIGN_MAXIMUM, getRegOp(ll_reg(LL_RT_GP16, LL_RI_A)), REG_DEFAULT, result, state);
}
else
{
regOp = getRegOp(ll_reg_gp(instr->dst.size, false, LL_RI_A));
ll_operand_store(OP_SI, ALIGN_MAXIMUM, regOp, REG_DEFAULT, resultA, state);
regOp = getRegOp(ll_reg_gp(instr->dst.size, false, LL_RI_D));
ll_operand_store(OP_SI, ALIGN_MAXIMUM, regOp, REG_DEFAULT, resultD, state);
}
if (instr->type == LL_INS_MUL)
{
LLVMValueRef of = LLVMBuildICmp(state->builder, LLVMIntNE, resultD, LLVMConstNull(targetHalfType), "");
ll_set_flag(RFLAG_OF, of, state);
ll_set_flag(RFLAG_CF, of, state);
}
else // LL_INS_IMUL
{
ll_flags_set_sf(resultA, state);
ll_flags_set_of_imul(result, operand1, operand2, state);
}
}
else if (instr->operand_count == 2)
{
operand1 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, &instr->dst, state);
operand2 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, &instr->src, state);
operand2 = LLVMBuildSExtOrBitCast(state->builder, operand2, LLVMTypeOf(operand1), "");
result = LLVMBuildMul(state->builder, operand1, operand2, "");
ll_operand_store(OP_SI, ALIGN_MAXIMUM, &instr->dst, REG_DEFAULT, result, state);
ll_flags_set_sf(result, state);
ll_flags_set_of_imul(result, operand1, operand2, state);
}
else if (instr->operand_count == 3)
{
operand1 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, &instr->src, state);
operand2 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, &instr->src2, state);
operand2 = LLVMBuildSExtOrBitCast(state->builder, operand2, LLVMTypeOf(operand1), "");
result = LLVMBuildMul(state->builder, operand1, operand2, "");
ll_operand_store(OP_SI, ALIGN_MAXIMUM, &instr->dst, REG_DEFAULT, result, state);
ll_flags_set_sf(result, state);
ll_flags_set_of_imul(result, operand1, operand2, state);
}
else
{
warn_if_reached();
}
}
void
ll_instruction_lea(LLInstr* instr, LLState* state)
{
LLVMTypeRef i8 = LLVMInt8TypeInContext(state->context);
LLVMTypeRef i64 = LLVMInt64TypeInContext(state->context);
LLVMTypeRef targetType = LLVMIntTypeInContext(state->context, instr->dst.size * 8);
LLVMTypeRef pi8 = LLVMPointerType(i8, 0);
if (instr->src.type != LL_OP_MEM)
warn_if_reached();
if (instr->dst.type != LL_OP_REG)
warn_if_reached();
LLVMValueRef result = ll_operand_get_address(OP_SI, &instr->src, state);
result = LLVMBuildPointerCast(state->builder, result, pi8, "");
LLVMValueRef base = LLVMConstInt(i64, instr->src.val, false);
if (instr->src.reg.rt != LL_RT_None)
base = LLVMBuildAdd(state->builder, base, ll_get_register(instr->src.reg, FACET_I64, state), "");
if (instr->src.scale != 0)
{
LLVMValueRef offset = ll_get_register(instr->src.ireg, FACET_I64, state);
offset = LLVMBuildMul(state->builder, offset, LLVMConstInt(i64, instr->src.scale, false), "");
base = LLVMBuildAdd(state->builder, base, offset, "");
}
base = LLVMBuildTruncOrBitCast(state->builder, base, targetType, "");
ll_operand_store(OP_SI, ALIGN_MAXIMUM, &instr->dst, REG_DEFAULT, base, state);
if (instr->dst.reg.rt == LL_RT_GP64)
ll_set_register(instr->dst.reg, FACET_PTR, result, false, state);
}
void
ll_instruction_cmov(LLInstr* instr, LLState* state)
{
LLVMValueRef cond = ll_flags_condition(instr->type, LL_INS_CMOVO, state);
LLVMValueRef operand1 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, &instr->src, state);
LLVMValueRef operand2 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, &instr->dst, state);
LLVMValueRef result = LLVMBuildSelect(state->builder, cond, operand1, operand2, "");
ll_operand_store(OP_SI, ALIGN_MAXIMUM, &instr->dst, REG_DEFAULT, result, state);
}
void
ll_instruction_setcc(LLInstr* instr, LLState* state)
{
LLVMTypeRef i8 = LLVMInt8TypeInContext(state->context);
LLVMValueRef cond = ll_flags_condition(instr->type, LL_INS_SETO, state);
LLVMValueRef result = LLVMBuildZExtOrBitCast(state->builder, cond, i8, "");
ll_operand_store(OP_SI, ALIGN_MAXIMUM, &instr->dst, REG_DEFAULT, result, state);
}
void
ll_instruction_cdqe(LLInstr* instr, LLState* state)
{
LLVMValueRef operand1 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, getRegOp(ll_reg(LL_RT_GP32, LL_RI_A)), state);
ll_operand_store(OP_SI, ALIGN_MAXIMUM, getRegOp(ll_reg(LL_RT_GP64, LL_RI_A)), REG_DEFAULT, operand1, state);
(void) instr;
}
/**
* @}
**/
+65
View File
@@ -0,0 +1,65 @@
/**
* This file is part of Rellume.
*
* (c) 2016-2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
**/
#ifndef LL_INSTRUCTION_H
#define LL_INSTRUCTION_H
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <llcommon-internal.h>
#include <llinstr-internal.h>
void ll_instruction_movgp(LLInstr*, LLState*);
void ll_instruction_add(LLInstr*, LLState*);
void ll_instruction_sub(LLInstr*, LLState*);
void ll_instruction_cmp(LLInstr*, LLState*);
void ll_instruction_test(LLInstr*, LLState*);
void ll_instruction_notneg(LLInstr*, LLState*);
void ll_instruction_incdec(LLInstr*, LLState*);
void ll_instruction_shift(LLInstr*, LLState*);
void ll_instruction_mul(LLInstr*, LLState*);
void ll_instruction_rotate(LLInstr*, LLState*);
void ll_instruction_lea(LLInstr*, LLState*);
void ll_instruction_cmov(LLInstr*, LLState*);
void ll_instruction_setcc(LLInstr*, LLState*);
void ll_instruction_cdqe(LLInstr*, LLState*);
void ll_instruction_call(LLInstr*, LLState*);
void ll_instruction_ret(LLInstr*, LLState*);
void ll_instruction_stack(LLInstr*, LLState*);
void ll_instruction_movq(LLInstr* instr, LLState* state);
void ll_instruction_movs(LLInstr* instr, LLState* state);
void ll_instruction_movp(LLInstr* instr, LLState* state);
void ll_instruction_movdq(LLInstr* instr, LLState* state);
void ll_instruction_movlp(LLInstr* instr, LLState* state);
void ll_instruction_movhps(LLInstr* instr, LLState* state);
void ll_instruction_movhpd(LLInstr* instr, LLState* state);
void ll_instruction_unpckl(LLInstr* instr, LLState* state);
void ll_generate_instruction(LLInstr*, LLState*);
#endif
+218
View File
@@ -0,0 +1,218 @@
/**
* This file is part of Rellume.
*
* (c) 2016-2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
**/
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <llvm-c/Core.h>
#include <llinstruction-internal.h>
#include <llbasicblock-internal.h>
#include <llcommon-internal.h>
#include <llflags-internal.h>
#include <llinstr-internal.h>
#include <lloperand-internal.h>
#include <llsupport-internal.h>
/**
* \defgroup LLInstructionSSE SSE Instructions
* \ingroup LLInstruction
*
* @{
**/
void
ll_instruction_movq(LLInstr* instr, LLState* state)
{
OperandDataType type = instr->type == LL_INS_MOVQ ? OP_SI64 : OP_SI32;
LLVMValueRef operand1 = ll_operand_load(type, ALIGN_MAXIMUM, &instr->src, state);
if (instr->dst.type == LL_OP_REG && regIsV(instr->dst.reg))
ll_operand_store(type, ALIGN_MAXIMUM, &instr->dst, REG_ZERO_UPPER_SSE, operand1, state);
else
ll_operand_store(type, ALIGN_MAXIMUM, &instr->dst, REG_DEFAULT, operand1, state);
}
void
ll_instruction_movs(LLInstr* instr, LLState* state)
{
OperandDataType type = instr->type == LL_INS_MOVSS ? OP_SF32 : OP_SF64;
LLVMValueRef operand1 = ll_operand_load(type, ALIGN_MAXIMUM, &instr->src, state);
if (instr->src.type == LL_OP_MEM)
ll_operand_store(type, ALIGN_MAXIMUM, &instr->dst, REG_ZERO_UPPER_SSE, operand1, state);
else
ll_operand_store(type, ALIGN_MAXIMUM, &instr->dst, REG_KEEP_UPPER, operand1, state);
}
void
ll_instruction_movp(LLInstr* instr, LLState* state)
{
Alignment alignment = instr->type == LL_INS_MOVAPS || instr->type == LL_INS_MOVAPD ? ALIGN_MAXIMUM : ALIGN_8;
OperandDataType type = instr->type == LL_INS_MOVAPS || instr->type == LL_INS_MOVUPS ? OP_VF32 : OP_VF64;
LLVMValueRef operand1 = ll_operand_load(type, alignment, &instr->src, state);
ll_operand_store(type, alignment, &instr->dst, REG_KEEP_UPPER, operand1, state);
}
void
ll_instruction_movdq(LLInstr* instr, LLState* state)
{
Alignment alignment = instr->type == LL_INS_MOVDQA ? ALIGN_MAXIMUM : ALIGN_8;
LLVMValueRef operand1 = ll_operand_load(OP_VI64, alignment, &instr->src, state);
ll_operand_store(OP_VI64, alignment, &instr->dst, REG_KEEP_UPPER, operand1, state);
}
void
ll_instruction_movlp(LLInstr* instr, LLState* state)
{
OperandDataType type = instr->type == LL_INS_MOVLPS ? OP_VF32 : OP_SF64;
// XXX: Hack for XED. Should use OP_V2F32.
instr->dst.size = 8;
if (instr->src.type == LL_OP_REG)
instr->src.size = 8;
LLVMValueRef operand1 = ll_operand_load(type, ALIGN_MAXIMUM, &instr->src, state);
ll_operand_store(type, ALIGN_MAXIMUM, &instr->dst, REG_KEEP_UPPER, operand1, state);
}
void
ll_instruction_movhps(LLInstr* instr, LLState* state)
{
LLVMTypeRef i32 = LLVMInt32TypeInContext(state->context);
if (instr->dst.type == LL_OP_REG)
{
// XXX: Hack for XED. Even though only 64 bits are written, they are in
// the upper half of the register.
instr->dst.size = 16;
instr->dst.reg.rt = LL_RT_XMM;
// opOverwriteType(&instr->dst, VT_128);
// XXX: Hack to make life more simple... this is actually illegal.
instr->src.size = 16;
// opOverwriteType(&instr->src, VT_128);
LLVMValueRef maskElements[4];
maskElements[0] = LLVMConstInt(i32, 0, false);
maskElements[1] = LLVMConstInt(i32, 1, false);
maskElements[2] = LLVMConstInt(i32, 4, false);
maskElements[3] = LLVMConstInt(i32, 5, false);
LLVMValueRef mask = LLVMConstVector(maskElements, 4);
LLVMValueRef operand1 = ll_operand_load(OP_VF32, ALIGN_MAXIMUM, &instr->dst, state);
LLVMValueRef operand2 = ll_operand_load(OP_VF32, ALIGN_MAXIMUM, &instr->src, state);
LLVMValueRef result = LLVMBuildShuffleVector(state->builder, operand1, operand2, mask, "");
ll_operand_store(OP_VF32, ALIGN_MAXIMUM, &instr->dst, REG_KEEP_UPPER, result, state);
}
else
{
// XXX: Hack for DBrew. Ensure that the destination receives <2 x float>.
instr->dst.size = 8;
//opOverwriteType(&instr->dst, VT_64);
LLVMValueRef maskElements[2];
maskElements[0] = LLVMConstInt(i32, 2, false);
maskElements[1] = LLVMConstInt(i32, 3, false);
LLVMValueRef mask = LLVMConstVector(maskElements, 2);
LLVMValueRef operand1 = ll_operand_load(OP_VF32, ALIGN_MAXIMUM, &instr->src, state);
LLVMValueRef result = LLVMBuildShuffleVector(state->builder, operand1, LLVMGetUndef(LLVMTypeOf(operand1)), mask, "");
ll_operand_store(OP_VF32, ALIGN_MAXIMUM, &instr->dst, REG_KEEP_UPPER, result, state);
}
}
void
ll_instruction_movhpd(LLInstr* instr, LLState* state)
{
LLVMTypeRef i32 = LLVMInt32TypeInContext(state->context);
if (instr->dst.type == LL_OP_REG)
{
// XXX: Hack for XED. Even though only 64 bits are written, they are in
// the upper half of the register.
instr->dst.size = 16;
instr->dst.reg.rt = LL_RT_XMM;
// opOverwriteType(&instr->dst, VT_128);
LLVMValueRef operand1 = ll_operand_load(OP_VF64, ALIGN_MAXIMUM, &instr->dst, state);
LLVMValueRef operand2 = ll_operand_load(OP_SF64, ALIGN_MAXIMUM, &instr->src, state);
LLVMValueRef result = LLVMBuildInsertElement(state->builder, operand1, operand2, LLVMConstInt(i32, 1, false), "");
ll_operand_store(OP_VF64, ALIGN_MAXIMUM, &instr->dst, REG_KEEP_UPPER, result, state);
}
else
{
// XXX: Hack for XED. Even though only 64 bits are written, they are in
// the upper half of the register.
instr->dst.size = 16;
// opOverwriteType(&instr->src, VT_128);
LLVMValueRef operand1 = ll_operand_load(OP_VF64, ALIGN_MAXIMUM, &instr->src, state);
LLVMValueRef result = LLVMBuildExtractElement(state->builder, operand1, LLVMConstInt(i32, 1, false), "");
ll_operand_store(OP_SF64, ALIGN_MAXIMUM, &instr->dst, REG_KEEP_UPPER, result, state);
}
}
void
ll_instruction_unpckl(LLInstr* instr, LLState* state)
{
LLVMTypeRef i32 = LLVMInt32TypeInContext(state->context);
OperandDataType type = instr->type == LL_INS_UNPCKLPS ? OP_VF32 : OP_VF64;
LLVMValueRef maskElements[4];
LLVMValueRef mask;
// This is actually legal as an implementation "MAY only fetch 64-bit".
// See Intel SDM Vol. 2B 4-696 (Dec. 2016).
instr->src.size = 16;
if (instr->src.type == LL_OP_REG)
instr->src.reg.rt = LL_RT_XMM;
// opOverwriteType(&instr->src, VT_128);
if (instr->type == LL_INS_UNPCKLPS)
{
maskElements[0] = LLVMConstInt(i32, 0, false);
maskElements[1] = LLVMConstInt(i32, 4, false);
maskElements[2] = LLVMConstInt(i32, 1, false);
maskElements[3] = LLVMConstInt(i32, 5, false);
mask = LLVMConstVector(maskElements, 4);
}
else // LL_INS_UNPCKLPD
{
maskElements[0] = LLVMConstInt(i32, 0, false);
maskElements[1] = LLVMConstInt(i32, 2, false);
mask = LLVMConstVector(maskElements, 2);
}
LLVMValueRef operand1 = ll_operand_load(type, ALIGN_MAXIMUM, &instr->dst, state);
LLVMValueRef operand2 = ll_operand_load(type, ALIGN_MAXIMUM, &instr->src, state);
LLVMValueRef result = LLVMBuildShuffleVector(state->builder, operand1, operand2, mask, "");
ll_operand_store(type, ALIGN_MAXIMUM, &instr->dst, REG_KEEP_UPPER, result, state);
}
/**
* @}
**/
+124
View File
@@ -0,0 +1,124 @@
/**
* This file is part of Rellume.
*
* (c) 2016-2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
**/
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <llvm-c/Core.h>
#include <llinstruction-internal.h>
#include <llbasicblock-internal.h>
#include <llcommon-internal.h>
#include <llinstr-internal.h>
#include <lloperand-internal.h>
#include <llsupport-internal.h>
/**
* \defgroup LLInstructionStack Push/Pop/Leave Instructions
* \ingroup LLInstruction
*
* @{
**/
static LLVMValueRef
ll_instruction_get_flags(bool fullSized, LLState* state)
{
static const int flags[] = {
RFLAG_CF, -1, RFLAG_PF, -1,
RFLAG_AF, -1, RFLAG_ZF, RFLAG_SF,
-1, -1, -1, RFLAG_OF,
-1, -1, -1, -1,
};
LLVMTypeRef intType = LLVMIntTypeInContext(state->context, fullSized ? 64 : 16);
LLVMValueRef flagRegister = LLVMConstNull(intType);
for (size_t i = 0; i < sizeof(flags) / sizeof(flags[0]); i++)
{
if (flags[i] < 0)
continue;
LLVMValueRef flag = LLVMBuildZExt(state->builder, ll_get_flag(flags[i], state), intType, "");
flag = LLVMBuildShl(state->builder, flag, LLVMConstInt(intType, i, false), "");
flagRegister = LLVMBuildOr(state->builder, flagRegister, flag, "");
}
return flagRegister;
}
void
ll_instruction_stack(LLInstr* instr, LLState* state)
{
LLVMTypeRef i8 = LLVMInt8TypeInContext(state->context);
LLVMTypeRef i64 = LLVMInt64TypeInContext(state->context);
LLVMTypeRef pi8 = LLVMPointerType(i8, 0);
LLVMTypeRef pi64 = LLVMPointerType(i64, 0);
// In case of a leave instruction, we basically pop the new base pointer
// from RBP and store the new value as stack pointer.
int spRegIndex = instr->type == LL_INS_LEAVE ? LL_RI_BP : LL_RI_SP;
LLVMValueRef spReg = ll_get_register(ll_reg(LL_RT_GP64, spRegIndex), FACET_PTR, state);
LLVMValueRef sp = LLVMBuildPointerCast(state->builder, spReg, pi64, "");
LLVMValueRef newSp = NULL;
LLVMValueRef value;
if (instr->type == LL_INS_PUSH || instr->type == LL_INS_PUSHFQ)
{
// Decrement Stack Pointer via a GEP instruction
LLVMValueRef constSub = LLVMConstInt(i64, -1, false);
newSp = LLVMBuildGEP(state->builder, sp, &constSub, 1, "");
if (instr->type == LL_INS_PUSH)
value = ll_operand_load(OP_SI, ALIGN_MAXIMUM, &instr->dst, state);
else
value = ll_instruction_get_flags(true, state);
value = LLVMBuildSExtOrBitCast(state->builder, value, i64, "");
LLVMBuildStore(state->builder, value, newSp);
}
else if (instr->type == LL_INS_POP || instr->type == LL_INS_LEAVE)
{
LLInstrOp* operand = instr->type == LL_INS_LEAVE
? getRegOp(ll_reg(LL_RT_GP64, LL_RI_BP))
: &instr->dst;
value = LLVMBuildLoad(state->builder, sp, "");
ll_operand_store(OP_SI, ALIGN_MAXIMUM, operand, REG_DEFAULT, value, state);
// Advance Stack pointer via a GEP
LLVMValueRef constAdd = LLVMConstInt(i64, 1, false);
newSp = LLVMBuildGEP(state->builder, sp, &constAdd, 1, "");
}
else
warn_if_reached();
// Cast back to int for register store
LLVMValueRef newSpReg = LLVMBuildPointerCast(state->builder, newSp, pi8, "");
LLVMSetMetadata(newSpReg, LLVMGetMDKindIDInContext(state->context, "asm.reg.rsp", 11), state->emptyMD);
ll_set_register(ll_reg(LL_RT_GP64, LL_RI_SP), FACET_PTR, newSpReg, true, state);
}
/**
* @}
**/
+108
View File
@@ -0,0 +1,108 @@
/**
* This file is part of Rellume.
*
* (c) 2016-2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
**/
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <llvm-c/Core.h>
#include <llinstruction-internal.h>
#include <llbasicblock-internal.h>
#include <llcommon-internal.h>
#include <llflags-internal.h>
#include <llinstr-internal.h>
#include <lloperand-internal.h>
#include <llsupport-internal.h>
/**
* \defgroup LLInstruction Instruction
* \brief Handling of X86-64 instructions
*
* @{
**/
/**
* Handling of an instruction.
*
* \todo Support other return types than i64, float and double
*
* \private
*
* \author Alexis Engelke
*
* \param instr The push instruction
* \param state The module state
**/
void
ll_generate_instruction(LLInstr* instr, LLState* state)
{
// Set new instruction pointer register
uintptr_t rip = instr->addr + instr->len;
LLVMValueRef ripValue = LLVMConstInt(LLVMInt64TypeInContext(state->context), rip, false);
ll_set_register(ll_reg(LL_RT_IP, 0), FACET_I64, ripValue, true, state);
// Add Metadata for debugging.
LLVMValueRef intrinsicDoNothing = ll_support_get_intrinsic(state->module, LL_INTRINSIC_DO_NOTHING, NULL, 0);
const char* instructionName = instr2string(instr, 0, NULL);
LLVMValueRef mdCall = LLVMBuildCall(state->builder, intrinsicDoNothing, NULL, 0, "");
LLVMValueRef mdNode = LLVMMDStringInContext(state->context, instructionName, strlen(instructionName));
LLVMSetMetadata(mdCall, LLVMGetMDKindIDInContext(state->context, "asm.instr", 9), mdNode);
switch (instr->type)
{
LLVMValueRef operand1;
LLVMValueRef operand2;
LLVMValueRef result;
#define CD_FUNCTION(fn,...) fn(instr, state, ##__VA_ARGS__)
#define CD_NOP()
#define CD_BINARY_INT_LLVM(build_fn,flag_fn) \
operand1 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, &instr->dst, state); \
operand2 = ll_operand_load(OP_SI, ALIGN_MAXIMUM, &instr->src, state); \
result = build_fn(state->builder, operand1, operand2, ""); \
flag_fn(state, result, operand1, operand2); \
ll_operand_store(OP_SI, ALIGN_MAXIMUM, &instr->dst, REG_DEFAULT, result, state);
#define CD_BINARY_FP_LLVM(data_type,prh,build_fn,fastmath) \
operand1 = ll_operand_load(data_type, ALIGN_MAXIMUM, &instr->dst, state); \
operand2 = ll_operand_load(data_type, ALIGN_MAXIMUM, &instr->src, state); \
result = build_fn(state->builder, operand1, operand2, ""); \
if (fastmath && state->cfg.enableFastMath) \
ll_support_enable_fast_math(result); \
ll_operand_store(data_type, ALIGN_MAXIMUM, &instr->dst, prh, result, state);
#define DEF_IT(opc,handler) case LL_INS_ ## opc : handler; break;
#include <opcodes.inc>
#undef DEF_IT
default:
printf("Could not handle instruction: %s\n", instr2string(instr, 0, NULL));
warn_if_reached();
break;
}
}
/**
* @}
**/
+148
View File
@@ -0,0 +1,148 @@
/**
* This file is part of Rellume.
*
* (c) 2016-2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
**/
#ifndef LL_OPERAND_H
#define LL_OPERAND_H
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <llvm-c/Core.h>
#include <llcommon-internal.h>
#include <llinstr-internal.h>
/**
* \ingroup LLInstrOp
* \brief The data type of an operand
**/
enum OperandDataType {
/**
* \brief Single Integer, length chosen appropriately
**/
OP_SI,
/**
* \brief Single 32-bit Integer
**/
OP_SI32,
/**
* \brief Single 64-bit Integer
**/
OP_SI64,
/**
* \brief Vector of 8-bit integers
**/
OP_VI8,
/**
* \brief Vector of 32-bit integers
**/
OP_VI32,
/**
* \brief Vector of 8-bit integers
**/
OP_VI64,
/**
* \brief Single 32-bit Real
**/
OP_SF32,
/**
* \brief Single 64-bit Real
**/
OP_SF64,
/**
* \brief Vector of floats
**/
OP_VF32,
/**
* \brief Vector of doubles
**/
OP_VF64,
};
typedef enum OperandDataType OperandDataType;
/**
* \ingroup LLInstrOp
* \brief The alignment of an operand
**/
enum Alignment {
/**
* \brief Maximum alignment based on data type size
**/
ALIGN_MAXIMUM = 0,
/**
* \brief 1-byte alignment
**/
ALIGN_1 = 1,
/**
* \brief 2-byte alignment
**/
ALIGN_2 = 2,
/**
* \brief 4-byte alignment
**/
ALIGN_4 = 4,
/**
* \brief 8-byte alignment
**/
ALIGN_8 = 8,
};
typedef enum Alignment Alignment;
/**
* \ingroup LLInstrOp
* \brief The handling when storing a partial register
**/
enum PartialRegisterHandling {
/**
* \brief Default handling for general purpose registers
*
* For general purpose registers with a 32-bit operand the upper part is
* zeroed, otherwise it is kept. For SSE registers, this is handling is not
* allowed since there is no default (depending on VEX prefix).
**/
REG_DEFAULT,
/**
* \brief Zero the unused half of the SSE register.
**/
REG_ZERO_UPPER_SSE,
/**
* \brief Zero the unused half of the full SSE/AVX register.
**/
REG_ZERO_UPPER_AVX,
/**
* \brief Keep the unused half. This might produce less optimizable code.
**/
REG_KEEP_UPPER
};
typedef enum PartialRegisterHandling PartialRegisterHandling;
LLVMValueRef ll_operand_get_address(OperandDataType, LLInstrOp*, LLState*);
LLVMValueRef ll_operand_load(OperandDataType, Alignment, LLInstrOp*, LLState*);
void ll_operand_store(OperandDataType, Alignment, LLInstrOp*, PartialRegisterHandling, LLVMValueRef, LLState*);
void ll_operand_construct_args(LLVMTypeRef, LLVMValueRef*, LLState*);
#endif
+658
View File
@@ -0,0 +1,658 @@
/**
* This file is part of Rellume.
*
* (c) 2016-2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
**/
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <llvm-c/Core.h>
#include <lloperand-internal.h>
#include <llbasicblock-internal.h>
#include <llcommon-internal.h>
#include <llinstr-internal.h>
#include <llregfile-internal.h>
/**
* \defgroup LLInstrOp LLInstrOp
* \brief Handling of instruction operands
*
* @{
**/
/**
* Infer the size of the operand.
*
* \private
*
* \author Alexis Engelke
*
* \param dataType The data type
* \param operand The operand
* \returns The bit length of the operand
**/
static int
ll_operand_get_type_length(OperandDataType dataType, LLInstrOp* operand)
{
int bits = -1;
switch (dataType)
{
case OP_SI:
case OP_VI8:
case OP_VI64:
case OP_VI32:
case OP_VF32:
case OP_VF64:
bits = operand->size * 8;
break;
case OP_SI32:
case OP_SF32:
bits = 32;
break;
case OP_SI64:
case OP_SF64:
bits = 64;
break;
default:
warn_if_reached();
break;
}
return bits;
}
static RegisterFacet
ll_operand_get_facet(OperandDataType dataType, LLInstrOp* operand)
{
int bits = operand->size * 8;
switch (dataType)
{
case OP_SI:
if (bits == 8)
return ll_reg_high(operand->reg) ? FACET_I8H : FACET_I8;
if (bits == 16) return FACET_I16;
if (bits == 32) return FACET_I32;
if (bits == 64) return FACET_I64;
warn_if_reached();
break;
case OP_SI32: return FACET_I32;
case OP_SI64: return FACET_I64;
case OP_VI8:
if (bits == 128) return FACET_V16I8;
warn_if_reached();
break;
case OP_VI32:
if (bits == 128) return FACET_V4I32;
warn_if_reached();
break;
case OP_VI64:
if (bits == 128) return FACET_V2I64;
warn_if_reached();
break;
case OP_VF32:
if (bits == 64) return FACET_V2F32;
if (bits == 128) return FACET_V4F32;
warn_if_reached();
break;
case OP_VF64:
if (bits == 128) return FACET_V2F64;
warn_if_reached();
break;
case OP_SF32: return FACET_F32;
case OP_SF64: return FACET_F64;
default:
warn_if_reached();
}
return INT32_MAX;
}
/**
* Infer the LLVM type from the requested data type and the number of bits.
*
* \private
*
* \author Alexis Engelke
*
* \param dataType The data type
* \param bits The number of bits
* \param state The module state
* \returns An LLVM type matching the data type and the number of bits
**/
static LLVMTypeRef
ll_operand_get_type(OperandDataType dataType, int bits, LLState* state)
{
LLVMTypeRef type = NULL;
switch (dataType)
{
case OP_SI:
type = LLVMIntTypeInContext(state->context, bits);
break;
case OP_SI32:
type = LLVMInt32TypeInContext(state->context);
break;
case OP_SI64:
type = LLVMInt64TypeInContext(state->context);
break;
case OP_VI8:
if (bits % 8 == 0)
type = LLVMVectorType(LLVMInt8TypeInContext(state->context), bits / 8);
else
warn_if_reached();
break;
case OP_VI64:
if (bits % 64 == 0)
type = LLVMVectorType(LLVMInt64TypeInContext(state->context), bits / 64);
else
warn_if_reached();
break;
case OP_VI32:
if (bits % 32 == 0)
type = LLVMVectorType(LLVMInt32TypeInContext(state->context), bits / 32);
else
warn_if_reached();
break;
case OP_SF32:
type = LLVMFloatTypeInContext(state->context);
break;
case OP_SF64:
type = LLVMDoubleTypeInContext(state->context);
break;
case OP_VF32:
if (bits % 32 == 0)
type = LLVMVectorType(LLVMFloatTypeInContext(state->context), bits / 32);
else
warn_if_reached();
break;
case OP_VF64:
if (bits % 64 == 0)
type = LLVMVectorType(LLVMDoubleTypeInContext(state->context), bits / 64);
else
warn_if_reached();
break;
default:
warn_if_reached();
break;
}
return type;
}
/**
* Store a value in a general purpose register.
*
* \private
*
* \author Alexis Engelke
*
* \param value The value to cast
* \param dataType The data type
* \param operand The register operand
* \param state The module state
**/
static void
ll_operand_store_gp(LLVMValueRef value, OperandDataType dataType, LLInstrOp* operand, LLState* state)
{
int operandWidth = ll_operand_get_type_length(dataType, operand);
LLVMTypeRef i64 = LLVMInt64TypeInContext(state->context);
LLVMTypeRef operandIntType = LLVMIntTypeInContext(state->context, operandWidth);
LLVMValueRef result = NULL;
value = LLVMBuildSExtOrBitCast(state->builder, value, operandIntType, "");
LLVMValueRef value64 = LLVMBuildZExtOrBitCast(state->builder, value, i64, "");
if (operand->reg.rt == LL_RT_GP32 || operand->reg.rt == LL_RT_GP64)
result = value64;
else
{
uint64_t mask = 0;
if (ll_reg_high(operand->reg))
{
mask = 0xff00;
value64 = LLVMBuildShl(state->builder, value64, LLVMConstInt(i64, 8, false), "");
}
else if (operand->reg.rt == LL_RT_GP8 || operand->reg.rt == LL_RT_GP8Leg)
mask = 0xff;
else if (operand->reg.rt == LL_RT_GP16)
mask = 0xffff;
else
warn_if_reached();
LLVMValueRef current = ll_get_register(operand->reg, FACET_I64, state);
LLVMValueRef masked = LLVMBuildAnd(state->builder, current, LLVMConstInt(i64, ~mask, false), "");
result = LLVMBuildOr(state->builder, masked, value64, "");
}
ll_set_register(operand->reg, FACET_I64, result, true, state);
if (operand->reg.rt == LL_RT_GP32)
ll_set_register(operand->reg, FACET_I32, value, false, state);
if (operand->reg.rt == LL_RT_GP16)
ll_set_register(operand->reg, FACET_I16, value, false, state);
if (operand->reg.rt == LL_RT_GP8)
ll_set_register(operand->reg, FACET_I8, value, false, state);
if (operand->reg.rt == LL_RT_GP8Leg)
ll_set_register(operand->reg, FACET_I8H, value, false, state);
}
/**
* Store a value in a vector (SSE/AVX) register.
*
* \private
*
* \author Alexis Engelke
*
* \param value The value to cast
* \param dataType The data type
* \param operand The register operand
* \param zeroHandling Handling of unused upper parts of the register
* \param state The module state
**/
static void
ll_operand_store_vreg(LLVMValueRef value, OperandDataType dataType, LLInstrOp* operand, PartialRegisterHandling zeroHandling, LLState* state)
{
LLVMTypeRef i32 = LLVMInt32TypeInContext(state->context);
LLVMTypeRef i64 = LLVMInt64TypeInContext(state->context);
int operandWidth = ll_operand_get_type_length(dataType, operand);
LLVMValueRef result = NULL;
LLVMTypeRef iVec = LLVMIntTypeInContext(state->context, LL_VECTOR_REGISTER_SIZE);
LLVMTypeRef i128 = LLVMIntTypeInContext(state->context, 128);
LLVMValueRef current = ll_get_register(operand->reg, FACET_IVEC, state);
if (zeroHandling == REG_ZERO_UPPER_AVX)
{
current = LLVMConstNull(iVec);
}
else if (zeroHandling == REG_ZERO_UPPER_SSE)
{
// Ehem, we have to construct the mask first.
// It is all-ones with the lowest 128-bit being zero.
LLVMValueRef mask = LLVMConstNot(LLVMConstZExtOrBitCast(LLVMConstAllOnes(i128), iVec));
current = LLVMBuildAnd(state->builder, current, mask, "");
}
#if LL_VECTOR_REGISTER_SIZE >= 256
LLVMValueRef current128 = ll_get_register(operand->reg, FACET_I128, state);
if (zeroHandling == REG_ZERO_UPPER_AVX || zeroHandling == REG_ZERO_UPPER_SSE)
current128 = LLVMConstNull(i128);
#endif
LLVMTypeRef valueType = LLVMTypeOf(value);
bool valueIsVector = LLVMGetTypeKind(valueType) == LLVMVectorTypeKind;
int elementCount = valueIsVector ? LLVMGetVectorSize(valueType) : 1;
int totalCount = elementCount * LL_VECTOR_REGISTER_SIZE / operandWidth;
if (valueIsVector)
{
LLVMTypeRef vectorType = LLVMVectorType(LLVMGetElementType(valueType), totalCount);
LLVMValueRef vectorCurrent = LLVMBuildBitCast(state->builder, current, vectorType, "");
LLVMValueRef maskElements[totalCount];
for (int i = 0; i < totalCount; i++)
maskElements[i] = LLVMConstInt(i32, i, false);
for (int i = elementCount; i < totalCount; i++)
maskElements[i] = LLVMConstInt(i32, elementCount, false);
LLVMValueRef mask = LLVMConstVector(maskElements, totalCount);
LLVMValueRef enlarged = LLVMBuildShuffleVector(state->builder, value, LLVMGetUndef(valueType), mask, "");
for (int i = elementCount; i < totalCount; i++)
maskElements[i] = LLVMConstInt(i32, totalCount + i, false);
mask = LLVMConstVector(maskElements, totalCount);
result = LLVMBuildShuffleVector(state->builder, enlarged, vectorCurrent, mask, "");
result = LLVMBuildBitCast(state->builder, result, iVec, "");
ll_set_register(operand->reg, FACET_IVEC, result, true, state);
#if LL_VECTOR_REGISTER_SIZE >= 256
// Induce some common facets via i128 for better SSE support
if (operandWidth == 128)
{
LLVMValueRef sseReg = LLVMBuildBitCast(state->builder, value, i128, "");
ll_set_register(operand->reg, FACET_I128, sseReg, false, state);
}
#endif
}
else
{
LLVMTypeRef vectorType = LLVMVectorType(valueType, totalCount);
LLVMValueRef vectorCurrent = LLVMBuildBitCast(state->builder, current, vectorType, "");
LLVMValueRef constZero = LLVMConstInt(i64, 0, false);
result = LLVMBuildInsertElement(state->builder, vectorCurrent, value, constZero, "");
result = LLVMBuildBitCast(state->builder, result, iVec, "");
ll_set_register(operand->reg, FACET_IVEC, result, true, state);
#if LL_VECTOR_REGISTER_SIZE >= 256
// Induce some common facets via i128 for better SSE support
LLVMTypeRef vectorType128 = LLVMVectorType(valueType, 128 / operandWidth);
LLVMValueRef vectorCurrent128 = LLVMBuildBitCast(state->builder, current128, vectorType128, "");
LLVMValueRef sseReg = LLVMBuildInsertElement(state->builder, vectorCurrent128, value, constZero, "");
sseReg = LLVMBuildBitCast(state->builder, sseReg, i128, "");
ll_set_register(operand->reg, FACET_I128, sseReg, false, state);
#endif
}
}
/**
* Get a pointer to the a known global constant
*
* \private
*
* \author Alexis Engelke
*
* \param constGlobal The constant global address
* \param state The module state
* \returns A pointer of the given type which represents the address
**/
static LLVMValueRef
ll_get_const_pointer(uintptr_t ptr, LLState* state)
{
LLVMTypeRef i8 = LLVMInt8TypeInContext(state->context);
LLVMTypeRef i64 = LLVMInt64TypeInContext(state->context);
LLVMTypeRef pi8 = LLVMPointerType(i8, 0);
if (ptr == 0)
return LLVMConstPointerNull(pi8);
// if (state->globalOffsetBase == 0)
// {
// state->globalOffsetBase = ptr;
// state->globalBase = LLVMAddGlobal(state->module, i8, "__ll_global_base__");
// LLVMAddGlobalMapping(state->engine, state->globalBase, (void*) ptr);
// }
LLVMValueRef pointer;
if (state->cfg.globalBase != NULL)
{
uintptr_t offset = ptr - state->cfg.globalOffsetBase;
LLVMValueRef llvmOffset = LLVMConstInt(i64, offset, false);
pointer = LLVMBuildGEP(state->builder, state->cfg.globalBase, &llvmOffset, 1, "");
}
else
{
LLVMValueRef llvmOffset = LLVMConstInt(i64, ptr, false);
pointer = LLVMBuildIntToPtr(state->builder, llvmOffset, pi8, "");
}
return pointer;
}
/**
* Get the pointer corresponding to an operand.
*
* \private
*
* \author Alexis Engelke
*
* \param dataType The data type used to create the appropriate pointer type
* \param operand The operand, must be Ind32 or Ind64
* \param state The module state
* \returns The pointer which corresponds to the operand
**/
LLVMValueRef
ll_operand_get_address(OperandDataType dataType, LLInstrOp* operand, LLState* state)
{
LLVMValueRef result;
LLVMTypeRef i64 = LLVMInt64TypeInContext(state->context);
LLVMTypeRef pointerType;
int addrspace;
int bits = ll_operand_get_type_length(dataType, operand);
switch (operand->seg)
{
case LL_RI_None:
addrspace = 0;
break;
case LL_RI_GS:
addrspace = 256;
break;
case LL_RI_FS:
addrspace = 257;
break;
default:
addrspace = 0;
warn_if_reached();
break;
}
pointerType = LLVMPointerType(ll_operand_get_type(dataType, bits, state), addrspace);
if (operand->reg.rt != LL_RT_None)
{
result = ll_get_register(operand->reg, FACET_PTR, state);
if (LLVMIsConstant(result))
{
result = ll_get_register(operand->reg, FACET_I64, state);
if (!LLVMIsConstant(result))
warn_if_reached();
uintptr_t constPtr = LLVMConstIntGetZExtValue(result);
result = ll_get_const_pointer(constPtr + operand->val, state);
}
else if (operand->val != 0)
{
LLVMValueRef offset = LLVMConstInt(i64, operand->val, false);
if (operand->scale != 0 && (operand->val % operand->scale) == 0)
{
LLVMTypeRef scaleType = LLVMPointerType(LLVMIntTypeInContext(state->context, operand->scale * 8), 0);
result = LLVMBuildPointerCast(state->builder, result, scaleType, "");
offset = LLVMConstInt(i64, operand->val / operand->scale, false);
}
result = LLVMBuildGEP(state->builder, result, &offset, 1, "");
}
}
else
{
result = ll_get_const_pointer(operand->val, state);
}
if (operand->scale != 0)
{
LLVMValueRef offset = ll_get_register(operand->ireg, FACET_I64, state);
if (LLVMIsNull(result))
{
// Fallback to inttoptr if this is definitly not-a-pointer.
// Therefore, we don't need to use ll_get_const_pointer.
offset = LLVMBuildMul(state->builder, offset, LLVMConstInt(i64, operand->scale, false), "");
result = LLVMBuildIntToPtr(state->builder, offset, pointerType, "");
}
else
{
LLVMTypeRef scaleType = LLVMPointerType(LLVMIntTypeInContext(state->context, operand->scale * 8), 0);
if (operand->scale * 8 == bits)
scaleType = pointerType;
result = LLVMBuildPointerCast(state->builder, result, scaleType, "");
result = LLVMBuildGEP(state->builder, result, &offset, 1, "");
}
}
result = LLVMBuildPointerCast(state->builder, result, pointerType, "");
return result;
}
/**
* Create the value corresponding to an operand.
*
* \private
*
* \author Alexis Engelke
*
* \param dataType The data type used to create the appropriate type
* \param alignment Additional alignment information
* \param operand The operand
* \param state The module state
* \returns The value which corresponds to the operand
**/
LLVMValueRef
ll_operand_load(OperandDataType dataType, Alignment alignment, LLInstrOp* operand, LLState* state)
{
int operandWidth = ll_operand_get_type_length(dataType, operand);
LLVMValueRef result = NULL;
if (operand->type == LL_OP_IMM)
{
LLVMTypeRef type = ll_operand_get_type(dataType, operandWidth, state);
result = LLVMConstInt(type, operand->val, false);
}
else if (operand->type == LL_OP_REG)
{
result = ll_get_register(operand->reg, ll_operand_get_facet(dataType, operand), state);
}
else if (operand->type == LL_OP_MEM)
{
LLVMValueRef address = ll_operand_get_address(dataType, operand, state);
result = LLVMBuildLoad(state->builder, address, "");
if (alignment == ALIGN_MAXIMUM)
LLVMSetAlignment(result, operandWidth / 8);
else
LLVMSetAlignment(result, alignment);
}
else
{
warn_if_reached();
}
return result;
}
/**
* Store the value in an operand.
*
* \private
*
* \author Alexis Engelke
*
* \param dataType The data type used to create the pointer type, if necessary
* \param alignment Additional alignment information
* \param operand The operand
* \param zeroHandling Handling of unused upper parts of the register
* \param value The value to store
* \param state The module state
**/
void
ll_operand_store(OperandDataType dataType, Alignment alignment, LLInstrOp* operand, PartialRegisterHandling zeroHandling, LLVMValueRef value, LLState* state)
{
if (operand->type == LL_OP_REG)
{
if (zeroHandling == REG_DEFAULT)
ll_operand_store_gp(value, dataType, operand, state);
else
ll_operand_store_vreg(value, dataType, operand, zeroHandling, state);
}
else if (operand->type == LL_OP_MEM)
{
int operandWidth = ll_operand_get_type_length(dataType, operand);
LLVMValueRef address = ll_operand_get_address(dataType, operand, state);
LLVMValueRef result = LLVMBuildBitCast(state->builder, value, LLVMGetElementType(LLVMTypeOf(address)), "");
LLVMValueRef store = LLVMBuildStore(state->builder, result, address);
if (alignment == ALIGN_MAXIMUM)
LLVMSetAlignment(store, operandWidth / 8);
else
LLVMSetAlignment(store, alignment);
}
else
{
warn_if_reached();
}
}
void
ll_operand_construct_args(LLVMTypeRef fnType, LLVMValueRef* args, LLState* state)
{
LLReg gpRegisters[6] = {
ll_reg(LL_RT_GP64, LL_RI_DI),
ll_reg(LL_RT_GP64, LL_RI_SI),
ll_reg(LL_RT_GP64, LL_RI_D),
ll_reg(LL_RT_GP64, LL_RI_C),
ll_reg(LL_RT_GP64, 8),
ll_reg(LL_RT_GP64, 9),
};
int gpRegisterIndex = 0;
size_t argCount = LLVMCountParamTypes(fnType);
LLVMTypeRef argTypes[argCount];
LLVMGetParamTypes(fnType, argTypes);
for (uintptr_t i = 0; i < argCount; i++)
{
LLVMTypeKind argTypeKind = LLVMGetTypeKind(argTypes[i]);
switch (argTypeKind)
{
case LLVMIntegerTypeKind:
case LLVMPointerTypeKind:
{
if (gpRegisterIndex >= 6)
warn_if_reached();
LLVMValueRef reg = ll_get_register(gpRegisters[gpRegisterIndex], FACET_I64, state);
gpRegisterIndex++;
if (argTypeKind == LLVMIntegerTypeKind)
args[i] = LLVMBuildTruncOrBitCast(state->builder, reg, argTypes[i], "");
else
args[i] = LLVMBuildIntToPtr(state->builder, reg, argTypes[i], "");
}
break;
case LLVMVoidTypeKind:
case LLVMHalfTypeKind:
case LLVMFloatTypeKind:
case LLVMDoubleTypeKind:
case LLVMX86_FP80TypeKind:
case LLVMFP128TypeKind:
case LLVMPPC_FP128TypeKind:
case LLVMLabelTypeKind:
case LLVMFunctionTypeKind:
case LLVMStructTypeKind:
case LLVMArrayTypeKind:
case LLVMVectorTypeKind:
case LLVMMetadataTypeKind:
case LLVMX86_MMXTypeKind:
case LLVMTokenTypeKind:
default:
warn_if_reached();
}
}
}
/**
* @}
**/
+167
View File
@@ -0,0 +1,167 @@
/**
* This file is part of Rellume.
*
* (c) 2016-2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
**/
#ifndef LL_REGFILE_H
#define LL_REGFILE_H
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdlib.h>
#include <llvm-c/Core.h>
#include <llcommon-internal.h>
#include <llinstr-internal.h>
/**
* \ingroup LLRegFile
**/
enum {
/**
* \brief The zero flag
**/
RFLAG_ZF = 0,
/**
* \brief The sign flag
**/
RFLAG_SF,
/**
* \brief The parity flag
**/
RFLAG_PF,
/**
* \brief The carry flag
**/
RFLAG_CF,
/**
* \brief The overflow flag
**/
RFLAG_OF,
/**
* \brief The auxiliary carry flag
**/
RFLAG_AF,
RFLAG_Max
};
/**
* \ingroup LLRegFile
* \brief Flag cache storing additional information about the flag register
**/
struct LLFlagCache {
/**
* \brief Whether the information is valid
**/
bool valid;
/**
* \brief The first operand of the subtraction
**/
LLVMValueRef operand1;
/**
* \brief The second operand of the subtraction
**/
LLVMValueRef operand2;
/**
* \brief The result of the subtraction
**/
LLVMValueRef result;
};
typedef struct LLFlagCache LLFlagCache;
/**
* \ingroup LLRegFile
**/
enum RegisterFacet {
FACET_PTR,
FACET_I8,
FACET_I8H,
FACET_I16,
FACET_I32,
FACET_I64,
FACET_I128,
FACET_I256,
FACET_F32,
FACET_F64,
FACET_V2F32,
FACET_V16I8,
FACET_V8I16,
FACET_V4I32,
FACET_V2I64,
FACET_V4F32,
FACET_V2F64,
#if LL_VECTOR_REGISTER_SIZE >= 256
FACET_V32I8,
FACET_V16I16,
FACET_V8I32,
FACET_V4I64,
FACET_V8F32,
FACET_V4F64,
#endif
FACET_COUNT,
};
#if LL_VECTOR_REGISTER_SIZE == 128
#define FACET_IVEC FACET_I128
#define FACET_VI8 FACET_V16I8
#define FACET_VI16 FACET_V8I16
#define FACET_VI32 FACET_V4I32
#define FACET_VI64 FACET_V2I64
#define FACET_VF32 FACET_V4F32
#define FACET_VF64 FACET_V2F64
#elif LL_VECTOR_REGISTER_SIZE == 256
#define FACET_IVEC FACET_I256
#define FACET_VI8 FACET_V32I8
#define FACET_VI16 FACET_V16I16
#define FACET_VI32 FACET_V8I32
#define FACET_VI64 FACET_V4I64
#define FACET_VF32 FACET_V8F32
#define FACET_VF64 FACET_V4F64
#endif
typedef enum RegisterFacet RegisterFacet;
struct LLRegisterFile;
typedef struct LLRegisterFile LLRegisterFile;
LLRegisterFile* ll_regfile_new(LLBasicBlock*);
void ll_regfile_dispose(LLRegisterFile*);
LLVMValueRef ll_regfile_get(LLRegisterFile*, RegisterFacet, LLReg, LLState*);
void ll_regfile_clear(LLRegisterFile*, LLReg, LLState*);
void ll_regfile_zero(LLRegisterFile*, LLReg, LLState*);
void ll_regfile_rename(LLRegisterFile*, LLReg, LLReg, LLState*);
void ll_regfile_set(LLRegisterFile*, RegisterFacet, LLReg, LLVMValueRef, bool, LLState*);
LLVMValueRef ll_regfile_get_flag(LLRegisterFile*, int);
void ll_regfile_set_flag(LLRegisterFile*, int, LLVMValueRef);
LLFlagCache* ll_regfile_get_flag_cache(LLRegisterFile*);
LLVMTypeRef ll_register_facet_type(RegisterFacet, LLState*);
#endif
+616
View File
@@ -0,0 +1,616 @@
/**
* This file is part of Rellume.
*
* (c) 2016-2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
**/
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <llvm-c/Core.h>
#include <llregfile-internal.h>
#include <llbasicblock-internal.h>
#include <llcommon-internal.h>
#include <llflags-internal.h>
#include <llinstr-internal.h>
#include <llinstruction-internal.h>
/**
* \defgroup LLRegFile Register File
* \brief Representation of a register file
*
* @{
**/
struct LLRegister {
LLVMValueRef facets[FACET_COUNT];
};
typedef struct LLRegister LLRegister;
struct LLRegisterFile {
LLBasicBlock* bb;
/**
* \brief The LLVM values of the architectural general purpose registers
*
* The registers always store integers with 64 bits length.
**/
LLRegister gpRegisters[LL_RI_GPMax];
/**
* \brief The LLVM values of the SSE registers
*
* The vector length depends on #LL_VECTOR_REGISTER_SIZE.
**/
LLRegister sseRegisters[LL_RI_XMMMax];
/**
* \brief The LLVM values of the architectural general purpose registers
**/
LLVMValueRef flags[RFLAG_Max];
/**
* \brief The LLVM value of the current instruction address
**/
LLRegister ipRegister;
/**
* \brief The flag cache
**/
LLFlagCache flagCache;
};
LLVMTypeRef
ll_register_facet_type(RegisterFacet facet, LLState* state)
{
LLVMTypeRef i8 = LLVMInt8TypeInContext(state->context);
LLVMTypeRef i16 = LLVMInt16TypeInContext(state->context);
LLVMTypeRef i32 = LLVMInt32TypeInContext(state->context);
LLVMTypeRef i64 = LLVMInt64TypeInContext(state->context);
LLVMTypeRef f32 = LLVMFloatTypeInContext(state->context);
LLVMTypeRef f64 = LLVMDoubleTypeInContext(state->context);
switch (facet)
{
case FACET_I8: return i8;
case FACET_I8H: return i8;
case FACET_I16: return i16;
case FACET_I32: return i32;
case FACET_I64: return i64;
case FACET_I128: return LLVMIntTypeInContext(state->context, 128);
case FACET_I256: return LLVMIntTypeInContext(state->context, 256);
case FACET_F32: return f32;
case FACET_F64: return f64;
case FACET_V16I8: return LLVMVectorType(i8, 16);
case FACET_V8I16: return LLVMVectorType(i16, 8);
case FACET_V4I32: return LLVMVectorType(i32, 4);
case FACET_V2I64: return LLVMVectorType(i64, 2);
case FACET_V2F32: return LLVMVectorType(f32, 2);
case FACET_V4F32: return LLVMVectorType(f32, 4);
case FACET_V2F64: return LLVMVectorType(f64, 2);
#if LL_VECTOR_REGISTER_SIZE >= 256
case FACET_V32I8: return LLVMVectorType(i8, 32);
case FACET_V16I16: return LLVMVectorType(i16, 16);
case FACET_V8I32: return LLVMVectorType(i32, 8);
case FACET_V4I64: return LLVMVectorType(i64, 4);
case FACET_V8F32: return LLVMVectorType(f32, 8);
case FACET_V4F64: return LLVMVectorType(f64, 4);
#endif
case FACET_PTR: return LLVMPointerType(LLVMInt8TypeInContext(state->context), 0);
case FACET_COUNT:
default:
warn_if_reached();
}
return NULL;
}
static const char*
ll_register_name_for_facet(RegisterFacet facet, LLReg reg)
{
if (regIsGP(reg))
{
switch (facet)
{
case FACET_I8: return ll_reg_name(ll_reg(LL_RT_GP8, reg.ri));
case FACET_I8H:
if (reg.rt == LL_RT_GP8Leg)
return ll_reg_name(reg);
else if (reg.ri < 4)
return ll_reg_name(ll_reg(LL_RT_GP8Leg, reg.ri + LL_RI_AH));
else
return "XXX";
case FACET_I16: return ll_reg_name(ll_reg(LL_RT_GP16, reg.ri));
case FACET_I32: return ll_reg_name(ll_reg(LL_RT_GP32, reg.ri));
case FACET_I64:
case FACET_PTR:
case FACET_I128:
case FACET_I256:
case FACET_F32:
case FACET_F64:
case FACET_V16I8:
case FACET_V8I16:
case FACET_V4I32:
case FACET_V2I64:
case FACET_V2F32:
case FACET_V4F32:
case FACET_V2F64:
#if LL_VECTOR_REGISTER_SIZE >= 256
case FACET_V32I8:
case FACET_V16I16:
case FACET_V8I32:
case FACET_V4I64:
case FACET_V8F32:
case FACET_V4F64:
#endif
return ll_reg_name(ll_reg(LL_RT_GP64, reg.ri));
case FACET_COUNT:
default:
warn_if_reached();
}
}
else if (regIsV(reg))
{
switch (facet)
{
case FACET_I8:
case FACET_I8H:
case FACET_I16:
case FACET_I32:
case FACET_I64:
case FACET_PTR:
case FACET_I128:
case FACET_F32:
case FACET_F64:
case FACET_V16I8:
case FACET_V8I16:
case FACET_V4I32:
case FACET_V2I64:
case FACET_V2F32:
case FACET_V4F32:
case FACET_V2F64:
return ll_reg_name(ll_reg(LL_RT_XMM, reg.ri));
case FACET_I256:
#if LL_VECTOR_REGISTER_SIZE >= 256
case FACET_V32I8:
case FACET_V16I16:
case FACET_V8I32:
case FACET_V4I64:
case FACET_V8F32:
case FACET_V4F64:
#endif
return ll_reg_name(ll_reg(LL_RT_YMM, reg.ri));
case FACET_COUNT:
default:
warn_if_reached();
}
}
return ll_reg_name(reg);
}
LLRegisterFile*
ll_regfile_new(LLBasicBlock* bb)
{
LLRegisterFile* regfile = malloc(sizeof(LLRegisterFile));
regfile->bb = bb;
regfile->flagCache.valid = false;
return regfile;
}
void
ll_regfile_dispose(LLRegisterFile* regfile)
{
free(regfile);
}
/**
* Get a pointer for a given register in the register file.
*
* \private
*
* \author Alexis Engelke
*
* \param regfile The register file
* \param reg The register
* \returns A pointer to the LLVM value in the register file.
**/
static LLRegister*
ll_regfile_get_ptr(LLRegisterFile* regfile, LLReg reg)
{
switch (reg.rt)
{
case LL_RT_GP8:
case LL_RT_GP16:
case LL_RT_GP32:
case LL_RT_GP64:
return &regfile->gpRegisters[reg.ri];
case LL_RT_GP8Leg:
if (ll_reg_high(reg))
return &regfile->gpRegisters[reg.ri - LL_RI_AH];
return &regfile->gpRegisters[reg.ri];
case LL_RT_XMM:
case LL_RT_YMM:
return &regfile->sseRegisters[reg.ri];
case LL_RT_IP:
return &regfile->ipRegister;
case LL_RT_X87:
case LL_RT_MMX:
case LL_RT_ZMM:
case LL_RT_Max:
case LL_RT_None:
default:
warn_if_reached();
}
return NULL;
}
/**
* Get a register value of the register file.
*
* \private
*
* \author Alexis Engelke
*
* \param regfile The register file
* \param reg The register
* \returns The register value in the given facet
**/
LLVMValueRef
ll_regfile_get(LLRegisterFile* regfile, RegisterFacet facet, LLReg reg, LLState* state)
{
LLRegister* regFileEntry = ll_regfile_get_ptr(regfile, reg);
LLVMTypeRef facetType = ll_register_facet_type(facet, state);
LLVMValueRef value = regFileEntry->facets[facet];
if (value != NULL)
{
if (LLVMTypeOf(value) != facetType)
warn_if_reached();
return value;
}
LLVMValueRef terminator = LLVMGetBasicBlockTerminator(ll_basic_block_llvm(regfile->bb));
if (terminator != NULL)
LLVMPositionBuilderBefore(state->builder, terminator);
else
LLVMPositionBuilderAtEnd(state->builder, ll_basic_block_llvm(regfile->bb));
LLVMTypeRef i8 = LLVMInt8TypeInContext(state->context);
LLVMTypeRef i32 = LLVMInt32TypeInContext(state->context);
LLVMTypeRef i128 = LLVMIntTypeInContext(state->context, 128);
LLVMTypeRef pi8 = LLVMPointerType(i8, 0);
if (regIsGP(reg) || reg.rt == LL_RT_IP)
{
LLVMValueRef native = regFileEntry->facets[FACET_I64];
switch (facet)
{
case FACET_PTR:
value = LLVMBuildIntToPtr(state->builder, native, pi8, "");
break;
case FACET_I8:
case FACET_I16:
case FACET_I32:
value = LLVMBuildTrunc(state->builder, native, facetType, "");
break;
case FACET_I8H:
value = LLVMBuildLShr(state->builder, native, LLVMConstInt(LLVMTypeOf(native), 8, false), "");
value = LLVMBuildTrunc(state->builder, value, i8, "");
break;
case FACET_I64:
case FACET_I128:
case FACET_I256:
case FACET_F32:
case FACET_F64:
case FACET_V2F32:
case FACET_V16I8:
case FACET_V8I16:
case FACET_V4I32:
case FACET_V2I64:
case FACET_V4F32:
case FACET_V2F64:
#if LL_VECTOR_REGISTER_SIZE >= 256
case FACET_V32I8:
case FACET_V16I16:
case FACET_V8I32:
case FACET_V4I64:
case FACET_V8F32:
case FACET_V4F64:
#endif
case FACET_COUNT:
default:
value = LLVMGetUndef(ll_register_facet_type(facet, state));
}
}
else if (regIsV(reg))
{
int targetBits = 0;
switch (facet)
{
case FACET_I8:
value = ll_regfile_get(regfile, FACET_V16I8, reg, state);
value = LLVMBuildExtractElement(state->builder, value, LLVMConstInt(i32, 0, false), "");
break;
case FACET_I16:
value = ll_regfile_get(regfile, FACET_V8I16, reg, state);
value = LLVMBuildExtractElement(state->builder, value, LLVMConstInt(i32, 0, false), "");
break;
case FACET_I32:
value = ll_regfile_get(regfile, FACET_V4I32, reg, state);
value = LLVMBuildExtractElement(state->builder, value, LLVMConstInt(i32, 0, false), "");
break;
case FACET_I64:
value = ll_regfile_get(regfile, FACET_V2I64, reg, state);
value = LLVMBuildExtractElement(state->builder, value, LLVMConstInt(i32, 0, false), "");
break;
case FACET_F32:
value = ll_regfile_get(regfile, FACET_V4F32, reg, state);
value = LLVMBuildExtractElement(state->builder, value, LLVMConstInt(i32, 0, false), "");
break;
case FACET_F64:
value = ll_regfile_get(regfile, FACET_V2F64, reg, state);
value = LLVMBuildExtractElement(state->builder, value, LLVMConstInt(i32, 0, false), "");
break;
case FACET_V2F32:
targetBits = 64;
break;
case FACET_V16I8:
case FACET_V8I16:
case FACET_V4I32:
case FACET_V2I64:
case FACET_V4F32:
case FACET_V2F64:
targetBits = 128;
break;
#if LL_VECTOR_REGISTER_SIZE >= 256
case FACET_V32I8:
case FACET_V16I16:
case FACET_V8I32:
case FACET_V4I64:
case FACET_V8F32:
case FACET_V4F64:
targetBits = 256;
break;
#endif
case FACET_I128:
// TODO: Try to induce from other 128-bit facets first
value = LLVMBuildTruncOrBitCast(state->builder, regFileEntry->facets[FACET_IVEC], i128, "");
break;
case FACET_PTR:
case FACET_I8H:
case FACET_I256:
case FACET_COUNT:
default:
value = LLVMGetUndef(ll_register_facet_type(facet, state));
}
// Its a vector.
#if LL_VECTOR_REGISTER_SIZE >= 256
if (value == NULL && targetBits == 128 && regFileEntry->facets[FACET_I128] != NULL)
{
LLVMValueRef native = regFileEntry->facets[FACET_I128];
value = LLVMBuildBitCast(state->builder, native, facetType, "");
}
#endif
if (value == NULL)
{
LLVMValueRef native = regFileEntry->facets[FACET_IVEC];
int targetCount = LLVMGetVectorSize(facetType);
int nativeCount = targetCount * LL_VECTOR_REGISTER_SIZE / targetBits;
LLVMTypeRef elementType = LLVMGetElementType(facetType);
LLVMTypeRef nativeVectorType = LLVMVectorType(elementType, nativeCount);
value = LLVMBuildBitCast(state->builder, native, nativeVectorType, "");
if (nativeCount > targetCount)
{
LLVMValueRef maskElements[targetCount];
for (int i = 0; i < targetCount; i++)
maskElements[i] = LLVMConstInt(i32, i, false);
LLVMValueRef mask = LLVMConstVector(maskElements, targetCount);
value = LLVMBuildShuffleVector(state->builder, value, LLVMGetUndef(nativeVectorType), mask, "");
}
}
}
if (value == NULL || LLVMTypeOf(value) != facetType)
warn_if_reached();
regFileEntry->facets[facet] = value;
return value;
}
/**
* Clear a register to undefined of the register file.
*
* \private
*
* \author Alexis Engelke
*
* \param regfile The register file
* \param reg The register
* \param value The new value
**/
void
ll_regfile_clear(LLRegisterFile* regfile, LLReg reg, LLState* state)
{
LLRegister* regFileEntry = ll_regfile_get_ptr(regfile, reg);
for (size_t i = 0; i < FACET_COUNT; i++)
regFileEntry->facets[i] = LLVMGetUndef(ll_register_facet_type(i, state));
}
/**
* Set a register in all facets to zero within the register file.
*
* \private
*
* \author Alexis Engelke
*
* \param regfile The register file
* \param reg The name of the new register
* \param state The state
**/
void
ll_regfile_zero(LLRegisterFile* regfile, LLReg reg, LLState* state)
{
LLRegister* regFileEntry = ll_regfile_get_ptr(regfile, reg);
for (size_t i = 0; i < FACET_COUNT; i++)
regFileEntry->facets[i] = LLVMConstNull(ll_register_facet_type(i, state));
}
/**
* Rename a register to another register of the register file.
*
* \private
*
* \author Alexis Engelke
*
* \param regfile The register file
* \param reg The name of the new register
* \param current The name of the current register
* \param state The state
**/
void
ll_regfile_rename(LLRegisterFile* regfile, LLReg reg, LLReg current, LLState* state)
{
LLRegister* regFileEntry1 = ll_regfile_get_ptr(regfile, reg);
LLRegister* regFileEntry2 = ll_regfile_get_ptr(regfile, current);
memcpy(regFileEntry1, regFileEntry2, sizeof(LLRegister));
(void) state;
}
/**
* Set a register value of the register file.
*
* \private
*
* \author Alexis Engelke
*
* \param regfile The register file
* \param reg The register
* \param value The new value
**/
void
ll_regfile_set(LLRegisterFile* regfile, RegisterFacet facet, LLReg reg, LLVMValueRef value, bool clearOthers, LLState* state)
{
if (!LLVMIsConstant(value))
{
char buffer[20];
int len = snprintf(buffer, sizeof(buffer), "asm.reg.%s", ll_register_name_for_facet(facet, reg));
LLVMSetMetadata(value, LLVMGetMDKindIDInContext(state->context, buffer, len), state->emptyMD);
}
if (LLVMTypeOf(value) != ll_register_facet_type(facet, state))
warn_if_reached();
LLRegister* regFileEntry = ll_regfile_get_ptr(regfile, reg);
if (clearOthers)
{
for (size_t i = 0; i < FACET_COUNT; i++)
regFileEntry->facets[i] = NULL;
if (regIsGP(reg) && facet != FACET_I64)
{
if (facet != FACET_PTR)
warn_if_reached();
LLVMTypeRef i64 = LLVMInt64TypeInContext(state->context);
regFileEntry->facets[FACET_I64] = LLVMBuildPtrToInt(state->builder, value, i64, "");
}
else if (regIsV(reg) && facet != FACET_IVEC)
warn_if_reached();
}
regFileEntry->facets[facet] = value;
}
/**
* Get a flag value of the register file.
*
* \private
*
* \author Alexis Engelke
*
* \param regfile The register file
* \param flag The flag
* \returns The current flag value
**/
LLVMValueRef
ll_regfile_get_flag(LLRegisterFile* regfile, int flag)
{
return regfile->flags[flag];
}
/**
* Set a flag value of the register file.
*
* \private
*
* \author Alexis Engelke
*
* \param regfile The register file
* \param flag The flag
* \param value The new value
**/
void
ll_regfile_set_flag(LLRegisterFile* regfile, int flag, LLVMValueRef value)
{
regfile->flags[flag] = value;
}
/**
* Get the flag cache.
*
* \private
*
* \author Alexis Engelke
*
* \param regfile The register file
* \returns The flag cache
**/
LLFlagCache*
ll_regfile_get_flag_cache(LLRegisterFile* regfile)
{
return &regfile->flagCache;
}
/**
* @}
**/
+57
View File
@@ -0,0 +1,57 @@
/**
* This file is part of Rellume.
*
* (c) 2016-2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
**/
#ifndef LL_SUPPORT_H
#define LL_SUPPORT_H
#include <llvm-c/Core.h>
#include <llvm-c/Transforms/PassManagerBuilder.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* \ingroup LLSupport
**/
enum LLSupportIntrinsics {
LL_INTRINSIC_DO_NOTHING,
LL_INTRINSIC_CTPOP,
LL_INTRINSIC_SADD_WITH_OVERFLOW,
LL_INTRINSIC_SSUB_WITH_OVERFLOW,
LL_INTRINSIC_SMUL_WITH_OVERFLOW,
};
typedef enum LLSupportIntrinsics LLSupportIntrinsics;
LLVMValueRef ll_support_get_intrinsic(LLVMModuleRef, LLSupportIntrinsics, LLVMTypeRef*, unsigned);
LLVMAttributeRef ll_support_get_enum_attr(LLVMContextRef, const char*);
void ll_support_enable_fast_math(LLVMValueRef);
LLVMBool ll_support_is_constant_int(LLVMValueRef);
LLVMValueRef ll_support_metadata_loop_unroll(LLVMContextRef);
#ifdef __cplusplus
}
#endif
#endif
+178
View File
@@ -0,0 +1,178 @@
/**
* This file is part of Rellume.
*
* (c) 2016-2019, Alexis Engelke <alexis.engelke@googlemail.com>
*
* Rellume is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL)
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* Rellume is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Rellume. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file
**/
#include <llvm/ADT/ArrayRef.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/IR/DataLayout.h>
#include <llvm/IR/Intrinsics.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Operator.h>
#include <llvm/Support/CommandLine.h>
#include <llvm/Transforms/IPO/PassManagerBuilder.h>
#include <llvm-c/ExecutionEngine.h>
#include <llvm-c/Transforms/PassManagerBuilder.h>
#include <llsupport-internal.h>
/**
* \defgroup LLSupport Support
* \brief Support functions for the LLVM API
*
* @{
**/
/**
* Get the declaration of an LLVM intrinsic with the given types.
*
* \private
*
* \author Alexis Engelke
*
* \param module The LLVM module
* \param intrinsic The intrinsic
* \param types The types of the instantiation, or NULL
* \param typeCount The number of types
* \returns A declaration of the requested intrinsic
**/
extern "C"
LLVMValueRef
ll_support_get_intrinsic(LLVMModuleRef module, LLSupportIntrinsics intrinsic, LLVMTypeRef* types, unsigned typeCount)
{
llvm::ArrayRef<llvm::Type*> Tys(llvm::unwrap(types), typeCount);
llvm::Intrinsic::ID intrinsicId;
switch (intrinsic)
{
case LL_INTRINSIC_DO_NOTHING: intrinsicId = llvm::Intrinsic::donothing; break;
case LL_INTRINSIC_CTPOP: intrinsicId = llvm::Intrinsic::ctpop; break;
case LL_INTRINSIC_SADD_WITH_OVERFLOW: intrinsicId = llvm::Intrinsic::sadd_with_overflow; break;
case LL_INTRINSIC_SSUB_WITH_OVERFLOW: intrinsicId = llvm::Intrinsic::ssub_with_overflow; break;
case LL_INTRINSIC_SMUL_WITH_OVERFLOW: intrinsicId = llvm::Intrinsic::smul_with_overflow; break;
default: intrinsicId = llvm::Intrinsic::not_intrinsic; break;
}
return llvm::wrap(llvm::Intrinsic::getDeclaration(llvm::unwrap(module), intrinsicId, Tys));
}
extern "C"
LLVMAttributeRef
ll_support_get_enum_attr(LLVMContextRef context, const char* name)
{
unsigned len = strlen(name);
unsigned id = LLVMGetEnumAttributeKindForName(name, len);
assert(id != 0);
return LLVMCreateEnumAttribute(context, id, 0);
}
/**
* Enable vectorization on a pass manager builder.
*
* \private
*
* \author Alexis Engelke
*
* \param PMB The pass manager builder
* \param value Whether to enable vectorization
**/
extern "C"
void
ll_support_pass_manager_builder_set_enable_vectorize(LLVMPassManagerBuilderRef PMB, LLVMBool value)
{
llvm::PassManagerBuilder* Builder = reinterpret_cast<llvm::PassManagerBuilder*>(PMB);
Builder->SLPVectorize = value;
Builder->LoopVectorize = value;
}
/**
* Enable unsafe algebra on the result of a floating-point instruction.
*
* \private
*
* \author Alexis Engelke
*
* \param value The result of a supported floating-point instruction
**/
extern "C"
void
ll_support_enable_fast_math(LLVMValueRef value)
{
#if LL_LLVM_MAJOR >= 6
llvm::unwrap<llvm::Instruction>(value)->setFast(true);
#else
llvm::unwrap<llvm::Instruction>(value)->setHasUnsafeAlgebra(true);
#endif
}
/**
* Whether a value is a constant integer
*
* \private
*
* \author Alexis Engelke
*
* \param value The value to check
* \returns Whether the value is a constant integer
**/
extern "C"
LLVMBool
ll_support_is_constant_int(LLVMValueRef value)
{
return llvm::isa<llvm::ConstantInt>(llvm::unwrap(value));
}
/**
* Construct a metadata node to force full loop unrolling.
*
* \private
*
* \author Alexis Engelke
*
* \param context The LLVM context
* \returns A metadata node
**/
extern "C"
LLVMValueRef
ll_support_metadata_loop_unroll(LLVMContextRef context)
{
llvm::SmallVector<llvm::Metadata *, 1> unrollElts;
llvm::SmallVector<llvm::Metadata *, 2> loopElts;
llvm::LLVMContext* C = llvm::unwrap(context);
llvm::MDString* unrollString = llvm::MDString::get(*C, "llvm.loop.unroll.full");
unrollElts.push_back(unrollString);
llvm::MDNode* unrollNode = llvm::MDTuple::get(*C, unrollElts);
llvm::TempMDNode temp = llvm::MDNode::getTemporary(*C, unrollElts);
loopElts.push_back(temp.get());
loopElts.push_back(unrollNode);
llvm::MDNode* loopNode = llvm::MDTuple::get(*C, loopElts);
temp->replaceAllUsesWith(loopNode);
return llvm::wrap(llvm::MetadataAsValue::get(*C, loopNode));
}
/**
* @}
**/
+24
View File
@@ -0,0 +1,24 @@
sources = [
'llbasicblock.c',
'lldecoder.cc',
'llflags.c',
'llfunc.c',
'llinstr.c',
'llinstruction-callret.c',
'llinstruction-gp.c',
'llinstruction-sse.c',
'llinstruction-stack.c',
'llinstruction.c',
'lloperand.c',
'llregfile.c',
'llsupport.cc',
]
rellume_inc_priv = include_directories('.')
rellume_flags = ['-DLL_LLVM_MAJOR='+libllvm.version().split('.')[0]]
librellume_lib = static_library('rellume', sources,
include_directories: [rellume_inc, rellume_inc_priv],
dependencies: [libllvm, fadec],
c_args: rellume_flags,
cpp_args: rellume_flags)
+4
View File
@@ -0,0 +1,4 @@
[wrap-git]
directory=fadec
url=https://github.com/aengelke/fadec.git
revision=head