first commit

This commit is contained in:
Nils Hölscher 2022-04-25 10:02:23 +02:00
commit 3500bf8dde
47719 changed files with 12370616 additions and 0 deletions

1129
CMakeLists.txt Normal file

File diff suppressed because it is too large Load Diff

241
CODE_OWNERS.TXT Normal file
View File

@ -0,0 +1,241 @@
This file is a list of the people responsible for ensuring that patches for a
particular part of LLVM are reviewed, either by themself or by someone else.
They are also the gatekeepers for their part of LLVM, with the final word on
what goes in or not.
The list is sorted by surname and formatted to allow easy grepping and
beautification by scripts. The fields are: name (N), email (E), web-address
(W), PGP key ID and fingerprint (P), description (D), snail-mail address
(S) and (I) IRC handle. Each entry should contain at least the (N), (E) and
(D) fields.
N: Paul C. Anagnostopoulos
E: paul@windfall.com
D: TableGen
N: Matt Arsenault
E: Matthew.Arsenault@amd.com
E: arsenm2@gmail.com
I: arsenm
D: InferAddressSpaces
N: Simon Atanasyan
E: simon@atanasyan.com
D: MIPS Backend (lib/Target/Mips/*)
N: Justin Bogner
E: mail@justinbogner.com
D: InstrProfiling and related parts of ProfileData
D: SelectionDAG (lib/CodeGen/SelectionDAG/*)
N: Alex Bradbury
E: asb@lowrisc.org
D: RISC-V backend (lib/Target/RISCV/*)
N: Matthias Braun
E: matze@braunis.de
I: MatzeB
D: Instruction Scheduling
N: Chandler Carruth
E: chandlerc@gmail.com
E: chandlerc@google.com
D: Config, ADT, Support, inlining & related passes, SROA/mem2reg & related passes, CMake, library layering
N: Evan Cheng
E: evan.cheng@apple.com
D: parts of code generator not covered by someone else
N: Eric Christopher
E: echristo@gmail.com
D: Debug Information, inline assembly
N: Andrey Churbanov
E: andrey.churbanov@intel.com
D: OpenMP runtime library
N: Greg Clayton
E: clayborg@gmail.com
D: LLDB
N: Pete Couperus
E: petecoup@synopsys.com
D: ARC backend (lib/Target/ARC/*)
N: Philip Reames
E: listmail@philipreames.com
D: IndVar Simplify, Scalar Evolution
N: Marshall Clow
E: mclow.lists@gmail.com
D: libc++
N: Peter Collingbourne
E: peter@pcc.me.uk
D: libLTO (lib/LTO/* tools/lto/*), LLVM Bitcode (lib/Bitcode/* include/llvm/Bitcode/*)
N: Quentin Colombet
E: quentin.colombet@gmail.com
D: Loop Strength Reduction, Register allocators
N: Andrea Di Biagio
E: andrea.dibiagio@sony.com
E: andrea.dibiagio@gmail.com
D: MCA, llvm-mca
N: Duncan P. N. Exon Smith
E: dexonsmith@apple.com
D: Branch weights and BlockFrequencyInfo
N: Hal Finkel
E: hfinkel@anl.gov
D: The loop reroller and alias analysis
N: Nemanja Ivanovic
E: nemanja.i.ibm@gmail.com
D: PowerPC Backend
N: Dan Gohman
E: llvm@sunfishcode.online
D: WebAssembly Backend (lib/Target/WebAssembly/*)
N: Renato Golin
E: renato.golin@linaro.org
D: ARM Linux support
N: Venkatraman Govindaraju
E: venkatra@cs.wisc.edu
D: Sparc Backend (lib/Target/Sparc/*)
N: Tobias Grosser
E: tobias@grosser.es
D: Polly
N: James Grosbach
E: grosbach@apple.com
D: MC layer
N: Justin Holewinski
E: jholewinski@nvidia.com
D: NVPTX Target (lib/Target/NVPTX/*)
N: Lang Hames
E: lhames@gmail.com
D: MCJIT, RuntimeDyld and JIT event listeners, Orcish Warchief
N: Teresa Johnson
E: tejohnson@google.com
D: Gold plugin (tools/gold/*) and IR Linker
N: Galina Kistanova
E: gkistanova@gmail.com
D: LLVM Buildbot
N: Anton Korobeynikov
E: anton@korobeynikov.info
D: Exception handling, Windows codegen, ARM EABI
N: Benjamin Kramer
E: benny.kra@gmail.com
D: DWARF Parser
N: Michael Kuperstein
E: mkuper@google.com
D: Loop Vectorizer
N: Sergei Larin
E: slarin@codeaurora.org
D: VLIW Instruction Scheduling, Packetization
N: Chris Lattner
E: sabre@nondot.org
W: http://nondot.org/~sabre/
D: Everything not covered by someone else
N: David Majnemer
E: david.majnemer@gmail.com
D: IR Constant Folder, InstCombine
N: Dylan McKay
E: me@dylanmckay.io
D: AVR Backend
N: Simon Moll
E: simon.moll@emea.nec.com
D: VE Backend
N: Tim Northover
E: t.p.northover@gmail.com
D: AArch64 backend, misc ARM backend
N: Diego Novillo
E: dnovillo@google.com
D: SampleProfile and related parts of ProfileData
N: Krzysztof Parzyszek
E: kparzysz@quicinc.com
D: Hexagon Backend
N: Nigel Perks
E: nigelp@xmos.com
D: XCore Backend
N: Jacques Pienaar
E: jpienaar@google.com
D: Lanai Backend
N: Paul Robinson
E: paul_robinson@playstation.sony.com
D: Sony PlayStation®4 support
N: Chad Rosier
E: mcrosier@codeaurora.org
D: Fast-Isel
N: Duncan Sands
E: baldrick@free.fr
D: DragonEgg
N: Kostya Serebryany
E: kcc@google.com
D: AddressSanitizer, ThreadSanitizer (LLVM parts)
N: Michael Spencer
E: bigcheesegs@gmail.com
D: Windows parts of Support, Object, ar, nm, objdump, ranlib, size
N: Alexei Starovoitov
E: alexei.starovoitov@gmail.com
D: BPF backend
N: Tom Stellard
E: tstellar@redhat.com
D: Stable release management (x.y.[1-9] releases), AMDGPU Backend, libclc
N: Evgeniy Stepanov
E: eugenis@google.com
D: MemorySanitizer (LLVM part)
N: Craig Topper
E: craig.topper@gmail.com
D: X86 Backend
N: Ulrich Weigand
E: uweigand@de.ibm.com
D: SystemZ Backend
N: Hans Wennborg
E: hans@chromium.org
D: Release management (x.y.0 releases)
N: Jake Ehrlich
E: jakehehrlich@google.com
D: llvm-objcopy (tools/llvm-objcopy)
N: Martin Storsjö
E: martin@martin.st
D: MinGW
N: Zi Xuan Wu (Zeson)
E: zixuan.wu@linux.alibaba.com
D: C-SKY backend (lib/Target/CSKY/*)

551
CREDITS.TXT Normal file
View File

@ -0,0 +1,551 @@
This file is a partial list of people who have contributed to the LLVM
project. If you have contributed a patch or made some other contribution to
LLVM, please submit a patch to this file to add yourself, and it will be
done!
The list is sorted by surname and formatted to allow easy grepping and
beautification by scripts. The fields are: name (N), email (E), web-address
(W), PGP key ID and fingerprint (P), description (D), snail-mail address
(S), and (I) IRC handle.
N: Vikram Adve
E: vadve@cs.uiuc.edu
W: http://www.cs.uiuc.edu/~vadve/
D: The Sparc64 backend, provider of much wisdom, and motivator for LLVM
N: Owen Anderson
E: resistor@mac.com
D: LCSSA pass and related LoopUnswitch work
D: GVNPRE pass, DataLayout refactoring, random improvements
N: Henrik Bach
D: MingW Win32 API portability layer
N: Aaron Ballman
E: aaron@aaronballman.com
D: Clang frontend, frontend attributes, Windows support, general bug fixing
I: AaronBallman
N: Nate Begeman
E: natebegeman@mac.com
D: PowerPC backend developer
D: Target-independent code generator and analysis improvements
N: Daniel Berlin
E: dberlin@dberlin.org
D: ET-Forest implementation.
D: Sparse bitmap
N: Geoff Berry
E: gberry@codeaurora.org
E: gcb@acm.org
D: AArch64 backend improvements
D: Added EarlyCSE MemorySSA support
D: CodeGen improvements
N: David Blaikie
E: dblaikie@gmail.com
D: General bug fixing/fit & finish, mostly in Clang
N: Neil Booth
E: neil@daikokuya.co.uk
D: APFloat implementation.
N: Alex Bradbury
E: asb@lowrisc.org
D: RISC-V backend
N: Misha Brukman
E: brukman+llvm@uiuc.edu
W: http://misha.brukman.net
D: Portions of X86 and Sparc JIT compilers, PowerPC backend
D: Incremental bitcode loader
N: Cameron Buschardt
E: buschard@uiuc.edu
D: The `mem2reg' pass - promotes values stored in memory to registers
N: Brendon Cahoon
E: bcahoon@codeaurora.org
D: Loop unrolling with run-time trip counts.
N: Chandler Carruth
E: chandlerc@gmail.com
E: chandlerc@google.com
D: Hashing algorithms and interfaces
D: Inline cost analysis
D: Machine block placement pass
D: SROA
N: Casey Carter
E: ccarter@uiuc.edu
D: Fixes to the Reassociation pass, various improvement patches
N: Evan Cheng
E: evan.cheng@apple.com
D: ARM and X86 backends
D: Instruction scheduler improvements
D: Register allocator improvements
D: Loop optimizer improvements
D: Target-independent code generator improvements
N: Dan Villiom Podlaski Christiansen
E: danchr@gmail.com
E: danchr@cs.au.dk
W: http://villiom.dk
D: LLVM Makefile improvements
D: Clang diagnostic & driver tweaks
S: Aarhus, Denmark
N: Jeff Cohen
E: jeffc@jolt-lang.org
W: http://jolt-lang.org
D: Native Win32 API portability layer
N: John T. Criswell
E: criswell@uiuc.edu
D: Original Autoconf support, documentation improvements, bug fixes
N: Anshuman Dasgupta
E: adasgupt@codeaurora.org
D: Deterministic finite automaton based infrastructure for VLIW packetization
N: Stefanus Du Toit
E: stefanus.du.toit@intel.com
D: Bug fixes and minor improvements
N: Rafael Avila de Espindola
E: rafael@espindo.la
D: MC and LLD work
N: Dave Estes
E: cestes@codeaurora.org
D: AArch64 machine description for Cortex-A53
N: Alkis Evlogimenos
E: alkis@evlogimenos.com
D: Linear scan register allocator, many codegen improvements, Java frontend
N: Hal Finkel
E: hfinkel@anl.gov
D: Basic-block autovectorization, PowerPC backend improvements
N: Eric Fiselier
E: eric@efcs.ca
D: LIT patches and documentation
N: Ryan Flynn
E: pizza@parseerror.com
D: Miscellaneous bug fixes
N: Brian Gaeke
E: gaeke@uiuc.edu
W: http://www.students.uiuc.edu/~gaeke/
D: Portions of X86 static and JIT compilers; initial SparcV8 backend
D: Dynamic trace optimizer
D: FreeBSD/X86 compatibility fixes, the llvm-nm tool
N: Nicolas Geoffray
E: nicolas.geoffray@lip6.fr
W: http://www-src.lip6.fr/homepages/Nicolas.Geoffray/
D: PPC backend fixes for Linux
N: Louis Gerbarg
E: lgg@apple.com
D: Portions of the PowerPC backend
N: Saem Ghani
E: saemghani@gmail.com
D: Callgraph class cleanups
N: Mikhail Glushenkov
E: foldr@codedgers.com
D: Author of llvmc2
N: Dan Gohman
E: llvm@sunfishcode.online
D: Miscellaneous bug fixes
D: WebAssembly Backend
N: Renato Golin
E: rengolin@systemcall.eu
E: renato.golin@linaro.org
E: rengolin@gmail.com
D: ARM/AArch64 back-end improvements
D: Loop Vectorizer improvements
D: Regression and Test Suite improvements
D: Linux compatibility (GNU, musl, etc)
D: Initial Linux kernel / Android support effort
I: rengolin
N: David Goodwin
E: david@goodwinz.net
D: Thumb-2 code generator
N: David Greene
E: greened@obbligato.org
D: Miscellaneous bug fixes
D: Register allocation refactoring
N: Gabor Greif
E: ggreif@gmail.com
D: Improvements for space efficiency
N: James Grosbach
E: grosbach@apple.com
I: grosbach
D: SjLj exception handling support
D: General fixes and improvements for the ARM back-end
D: MCJIT
D: ARM integrated assembler and assembly parser
D: Led effort for the backend formerly known as ARM64
N: Lang Hames
E: lhames@gmail.com
D: PBQP-based register allocator
N: Gordon Henriksen
E: gordonhenriksen@mac.com
D: Pluggable GC support
D: C interface
D: Ocaml bindings
N: Raul Fernandes Herbster
E: raul@dsc.ufcg.edu.br
D: JIT support for ARM
N: Paolo Invernizzi
E: arathorn@fastwebnet.it
D: Visual C++ compatibility fixes
N: Patrick Jenkins
E: patjenk@wam.umd.edu
D: Nightly Tester
N: Tony(Yanjun) Jiang
E: jtony@ca.ibm.com
D: PowerPC Backend Developer
D: Improvements to the PPC backend and miscellaneous bug fixes
N: Dale Johannesen
E: dalej@apple.com
D: ARM constant islands improvements
D: Tail merging improvements
D: Rewrite X87 back end
D: Use APFloat for floating point constants widely throughout compiler
D: Implement X87 long double
N: Brad Jones
E: kungfoomaster@nondot.org
D: Support for packed types
N: Rod Kay
E: rkay@auroraux.org
D: Author of LLVM Ada bindings
N: Erich Keane
E: erich.keane@intel.com
D: A variety of Clang contributions including function multiversioning, regcall/vectorcall.
I: ErichKeane
N: Eric Kidd
W: http://randomhacks.net/
D: llvm-config script
N: Anton Korobeynikov
E: anton at korobeynikov dot info
D: Mingw32 fixes, cross-compiling support, stdcall/fastcall calling conv.
D: x86/linux PIC codegen, aliases, regparm/visibility attributes
D: Switch lowering refactoring
N: Sumant Kowshik
E: kowshik@uiuc.edu
D: Author of the original C backend
N: Benjamin Kramer
E: benny.kra@gmail.com
D: Miscellaneous bug fixes
N: Sundeep Kushwaha
E: sundeepk@codeaurora.org
D: Implemented DFA-based target independent VLIW packetizer
N: Christopher Lamb
E: christopher.lamb@gmail.com
D: aligned load/store support, parts of noalias and restrict support
D: vreg subreg infrastructure, X86 codegen improvements based on subregs
D: address spaces
N: Jim Laskey
E: jlaskey@apple.com
D: Improvements to the PPC backend, instruction scheduling
D: Debug and Dwarf implementation
D: Auto upgrade mangler
D: llvm-gcc4 svn wrangler
N: Chris Lattner
E: sabre@nondot.org
W: http://nondot.org/~sabre/
D: Primary architect of LLVM
N: Tanya Lattner (Tanya Brethour)
E: tonic@nondot.org
W: http://nondot.org/~tonic/
D: The initial llvm-ar tool, converted regression testsuite to dejagnu
D: Modulo scheduling in the SparcV9 backend
D: Release manager (1.7+)
N: Sylvestre Ledru
E: sylvestre@debian.org
W: http://sylvestre.ledru.info/
W: https://apt.llvm.org/
D: Debian and Ubuntu packaging
D: Continuous integration with jenkins
N: Andrew Lenharth
E: alenhar2@cs.uiuc.edu
W: http://www.lenharth.org/~andrewl/
D: Alpha backend
D: Sampling based profiling
N: Nick Lewycky
E: nicholas@mxc.ca
D: PredicateSimplifier pass
N: Tony Linthicum, et. al.
E: tlinth@codeaurora.org
D: Backend for Qualcomm's Hexagon VLIW processor.
N: Bruno Cardoso Lopes
E: bruno.cardoso@gmail.com
I: bruno
W: http://brunocardoso.cc
D: Mips backend
D: Random ARM integrated assembler and assembly parser improvements
D: General X86 AVX1 support
N: Duraid Madina
E: duraid@octopus.com.au
W: http://kinoko.c.u-tokyo.ac.jp/~duraid/
D: IA64 backend, BigBlock register allocator
N: John McCall
E: rjmccall@apple.com
D: Clang semantic analysis and IR generation
N: Michael McCracken
E: michael.mccracken@gmail.com
D: Line number support for llvmgcc
N: Fanbo Meng
E: fanbo.meng@ibm.com
D: z/OS support
N: Vladimir Merzliakov
E: wanderer@rsu.ru
D: Test suite fixes for FreeBSD
N: Scott Michel
E: scottm@aero.org
D: Added STI Cell SPU backend.
N: Kai Nacke
E: kai@redstar.de
D: Support for implicit TLS model used with MS VC runtime
D: Dumping of Win64 EH structures
N: Takumi Nakamura
I: chapuni
E: geek4civic@gmail.com
E: chapuni@hf.rim.or.jp
D: Maintaining the Git monorepo
W: https://github.com/llvm-project/
S: Ebina, Japan
N: Edward O'Callaghan
E: eocallaghan@auroraux.org
W: http://www.auroraux.org
D: Add Clang support with various other improvements to utils/NewNightlyTest.pl
D: Fix and maintain Solaris & AuroraUX support for llvm, various build warnings
D: and error clean ups.
N: Morten Ofstad
E: morten@hue.no
D: Visual C++ compatibility fixes
N: Jakob Stoklund Olesen
E: stoklund@2pi.dk
D: Machine code verifier
D: Blackfin backend
D: Fast register allocator
D: Greedy register allocator
N: Richard Osborne
E: richard@xmos.com
D: XCore backend
N: Piotr Padlewski
E: piotr.padlewski@gmail.com
D: !invariant.group metadata and other intrinsics for devirtualization in clang
N: Devang Patel
E: dpatel@apple.com
D: LTO tool, PassManager rewrite, Loop Pass Manager, Loop Rotate
D: GCC PCH Integration (llvm-gcc), llvm-gcc improvements
D: Optimizer improvements, Loop Index Split
N: Ana Pazos
E: apazos@codeaurora.org
D: Fixes and improvements to the AArch64 backend
N: Wesley Peck
E: peckw@wesleypeck.com
W: http://wesleypeck.com/
D: MicroBlaze backend
N: Francois Pichet
E: pichet2000@gmail.com
D: MSVC support
N: Adrian Prantl
E: aprantl@apple.com
D: Debug Information
N: Vladimir Prus
W: http://vladimir_prus.blogspot.com
E: ghost@cs.msu.su
D: Made inst_iterator behave like a proper iterator, LowerConstantExprs pass
N: QIU Chaofan
E: qiucofan@cn.ibm.com
D: PowerPC Backend Developer
N: Kalle Raiskila
E: kalle.rasikila@nokia.com
D: Some bugfixes to CellSPU
N: Xerxes Ranby
E: xerxes@zafena.se
D: Cmake dependency chain and various bug fixes
N: Alex Rosenberg
E: alexr@leftfield.org
I: arosenberg
D: ARM calling conventions rewrite, hard float support
N: Chad Rosier
E: mcrosier@codeaurora.org
I: mcrosier
D: AArch64 fast instruction selection pass
D: Fixes and improvements to the ARM fast-isel pass
D: Fixes and improvements to the AArch64 backend
N: Nadav Rotem
E: nadav.rotem@me.com
D: X86 code generation improvements, Loop Vectorizer, SLP Vectorizer
N: Roman Samoilov
E: roman@codedgers.com
D: MSIL backend
N: Duncan Sands
E: baldrick@free.fr
I: baldrick
D: Ada support in llvm-gcc
D: Dragonegg plugin
D: Exception handling improvements
D: Type legalizer rewrite
N: Ruchira Sasanka
E: sasanka@uiuc.edu
D: Graph coloring register allocator for the Sparc64 backend
N: Arnold Schwaighofer
E: arnold.schwaighofer@gmail.com
D: Tail call optimization for the x86 backend
N: Shantonu Sen
E: ssen@apple.com
D: Miscellaneous bug fixes
N: Anand Shukla
E: ashukla@cs.uiuc.edu
D: The `paths' pass
N: Michael J. Spencer
E: bigcheesegs@gmail.com
D: Shepherding Windows COFF support into MC.
D: Lots of Windows stuff.
N: Reid Spencer
E: rspencer@reidspencer.com
W: http://reidspencer.com/
D: Lots of stuff, see: http://wiki.llvm.org/index.php/User:Reid
N: Abhina Sreeskantharajan
E: Abhina.Sreeskantharajan@ibm.com
D: z/OS support
N: Alp Toker
E: alp@nuanti.com
W: http://atoker.com/
D: C++ frontend next generation standards implementation
N: Craig Topper
E: craig.topper@gmail.com
D: X86 codegen and disassembler improvements. AVX2 support.
N: Edwin Torok
E: edwintorok@gmail.com
D: Miscellaneous bug fixes
N: Adam Treat
E: manyoso@yahoo.com
D: C++ bugs filed, and C++ front-end bug fixes.
N: Andrew Trick
E: atrick@apple.com
D: Instruction Scheduling, ...
N: Lauro Ramos Venancio
E: lauro.venancio@indt.org.br
D: ARM backend improvements
D: Thread Local Storage implementation
N: Bill Wendling
I: wendling
E: isanbard@gmail.com
D: Release manager, IR Linker, LTO.
D: Bunches of stuff.
N: Bob Wilson
E: bob.wilson@acm.org
D: Advanced SIMD (NEON) support in the ARM backend.
N: QingShan Zhang
E: qshanz@cn.ibm.com
D: PowerPC Backend Developer
N: Li Jia He
E: hljhehlj@cn.ibm.com
D: PowerPC Backend Developer
N: Zi Xuan Wu
N: Zeson
E: zixuan.wu@linux.alibaba.com
N: Kang Zhang
E: shkzhang@cn.ibm.com
D: PowerPC Backend Developer
N: Zheng Chen
E: czhengsz@cn.ibm.com
D: PowerPC Backend Developer
N: Djordje Todorovic
E: djordje.todorovic@rt-rk.com
D: Debug Information
N: Biplob Mishra
E: biplmish@in.ibm.com
D: PowerPC Analysis

279
LICENSE.TXT Normal file
View File

@ -0,0 +1,279 @@
==============================================================================
The LLVM Project is under the Apache License v2.0 with LLVM Exceptions:
==============================================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
---- LLVM Exceptions to the Apache 2.0 License ----
As an exception, if, as a result of your compiling your source code, portions
of this Software are embedded into an Object form of such source code, you
may redistribute such embedded portions in such Object form without complying
with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
In addition, if you combine or link compiled forms of this Software with
software that is licensed under the GPLv2 ("Combined Software") and if a
court of competent jurisdiction determines that the patent provision (Section
3), the indemnity provision (Section 9) or other Section of the License
conflicts with the conditions of the GPLv2, you may retroactively and
prospectively choose to deem waived or otherwise exclude such Section(s) of
the License, but only in their entirety and only with respect to the Combined
Software.
==============================================================================
Software from third parties included in the LLVM Project:
==============================================================================
The LLVM Project contains third party software which is under different license
terms. All such code will be identified clearly using at least one of two
mechanisms:
1) It will be in a separate directory tree with its own `LICENSE.txt` or
`LICENSE` file at the top containing the specific license and restrictions
which apply to that software, or
2) It will contain specific license and restriction terms at the top of every
file.
==============================================================================
Legacy LLVM License (https://llvm.org/docs/DeveloperPolicy.html#legacy):
==============================================================================
University of Illinois/NCSA
Open Source License
Copyright (c) 2003-2019 University of Illinois at Urbana-Champaign.
All rights reserved.
Developed by:
LLVM Team
University of Illinois at Urbana-Champaign
http://llvm.org
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal with
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimers.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimers in the
documentation and/or other materials provided with the distribution.
* Neither the names of the LLVM Team, University of Illinois at
Urbana-Champaign, nor the names of its contributors may be used to
endorse or promote products derived from this Software without specific
prior written permission.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
SOFTWARE.

17
README.txt Normal file
View File

@ -0,0 +1,17 @@
The LLVM Compiler Infrastructure
================================
This directory and its subdirectories contain source code for LLVM,
a toolkit for the construction of highly optimized compilers,
optimizers, and runtime environments.
LLVM is open source software. You may freely distribute it under the terms of
the license agreement found in LICENSE.txt.
Please see the documentation provided in docs/ for further
assistance with LLVM, and in particular docs/GettingStarted.rst for getting
started with LLVM and docs/README.txt for an overview of LLVM's
documentation setup.
If you are writing a package for LLVM, see docs/Packaging.rst for our
suggestions.

47
RELEASE_TESTERS.TXT Normal file
View File

@ -0,0 +1,47 @@
This file is a list of the people responsible for ensuring that targets and
environments get tested and validated during the release process.
They will also, in conjunction with the release manager and the code owners,
accept patches into stable release branches, tag critical bugs and release
stoppers as well as make sure that no regressions were observed on their
targets since the last release.
N: Ben Pope
E: benpope81@gmail.com
T: x86
O: Ubuntu
N: Sylvestre Ledru
E: sylvestre@debian.org
T: All supported archs Debian/Ubuntu
O: Debian/Ubuntu packages
N: Nikola Smiljanic
E: popizdeh@gmail.com
T: x86
O: OpenSUSE, Fedora
N: Brian Cain
E: brian.cain@gmail.com
T: x86
O: SuSE Enterprise, CentOS
N: Bernhard Rosenkränzer
E: bero@linaro.org
T: x86
O: OpenMandriva
N: Dimitry Andric
E: dimitry@andric.com
T: x86
O: FreeBSD
N: Hans Wennborg
E: hans@chromium.org
T: x86
O: Windows
N: Diana Picus, Yvan Roux
E: diana.picus@linaro.org, yvan.roux@linaro.org
T: ARM, AArch64
O: Linux

View File

@ -0,0 +1,4 @@
set(LLVM_LINK_COMPONENTS
Support)
add_benchmark(DummyYAML DummyYAML.cpp)

13
benchmarks/DummyYAML.cpp Normal file
View File

@ -0,0 +1,13 @@
#include "benchmark/benchmark.h"
#include "llvm/Support/YAMLTraits.h"
static void BM_YAMLDummyIsNumeric(benchmark::State& state) {
std::string x = "hello";
for (auto _ : state) {
std::string copy(x);
llvm::yaml::isNumeric(copy);
}
}
BENCHMARK(BM_YAMLDummyIsNumeric);
BENCHMARK_MAIN();

3
bindings/README.txt Normal file
View File

@ -0,0 +1,3 @@
This directory contains bindings for the LLVM compiler infrastructure to allow
programs written in languages other than C or C++ to take advantage of the LLVM
infrastructure--for instance, a self-hosted compiler front-end.

61
bindings/go/README.txt Normal file
View File

@ -0,0 +1,61 @@
This directory contains LLVM bindings for the Go programming language
(http://golang.org).
Prerequisites
-------------
* Go 1.2+.
* CMake (to build LLVM).
Using the bindings
------------------
The package path "llvm.org/llvm/bindings/go/llvm" can be used to
import the latest development version of LLVM from SVN. Paths such as
"llvm.org/llvm.v36/bindings/go/llvm" refer to released versions of LLVM.
It is recommended to use the "-d" flag with "go get" to download the
package or a dependency, as an additional step is required to build LLVM
(see "Building LLVM" below).
Building LLVM
-------------
The script "build.sh" in this directory can be used to build LLVM and prepare
it to be used by the bindings. If you receive an error message from "go build"
like this:
./analysis.go:4:84: fatal error: llvm-c/Analysis.h: No such file or directory
#include <llvm-c/Analysis.h> // If you are getting an error here read bindings/go/README.txt
or like this:
./llvm_dep.go:5: undefined: run_build_sh
it means that LLVM needs to be built or updated by running the script.
$ $GOPATH/src/llvm.org/llvm/bindings/go/build.sh
Any command line arguments supplied to the script are passed to LLVM's CMake
build system. A good set of arguments to use during development are:
$ $GOPATH/src/llvm.org/llvm/bindings/go/build.sh -DCMAKE_BUILD_TYPE=Debug -DLLVM_TARGETS_TO_BUILD=host -DBUILD_SHARED_LIBS=ON
Note that CMake keeps a cache of build settings so once you have built
LLVM there is no need to pass these arguments again after updating.
Alternatively, you can build LLVM yourself, but you must then set the
CGO_CPPFLAGS, CGO_CXXFLAGS and CGO_LDFLAGS environment variables:
$ export CGO_CPPFLAGS="`/path/to/llvm-build/bin/llvm-config --cppflags`"
$ export CGO_CXXFLAGS=-std=c++14
$ export CGO_LDFLAGS="`/path/to/llvm-build/bin/llvm-config --ldflags --libs --system-libs all`"
$ go build -tags byollvm
If you see a compilation error while compiling your code with Go 1.9.4 or later as follows,
go build llvm.org/llvm/bindings/go/llvm: invalid flag in #cgo LDFLAGS: -Wl,-headerpad_max_install_names
you need to setup $CGO_LDFLAGS_ALLOW to allow a compiler to specify some linker options:
$ export CGO_LDFLAGS_ALLOW='-Wl,(-search_paths_first|-headerpad_max_install_names)'

28
bindings/go/build.sh Executable file
View File

@ -0,0 +1,28 @@
#!/bin/sh -xe
gollvmdir=$(dirname "$0")/llvm
workdir=$gollvmdir/workdir
llvmdir=$gollvmdir/../../..
llvm_builddir=$workdir/llvm_build
mkdir -p $llvm_builddir
cmake_flags="../../../../.. $@"
llvm_config="$llvm_builddir/bin/llvm-config"
llvm_go="$llvm_builddir/bin/llvm-go"
if test -n "`which ninja`" ; then
# If Ninja is available, we can speed up the build by building only the
# required subset of LLVM.
(cd $llvm_builddir && cmake -G Ninja $cmake_flags)
ninja -C $llvm_builddir llvm-config llvm-go
llvm_components="$($llvm_go print-components)"
llvm_buildtargets="$($llvm_config --libs $llvm_components | sed -e 's/-l//g')"
ninja -C $llvm_builddir $llvm_buildtargets FileCheck
else
(cd $llvm_builddir && cmake $cmake_flags)
make -C $llvm_builddir -j4
fi
$llvm_go print-config > $gollvmdir/llvm_config.go

16
bindings/go/conftest.go Normal file
View File

@ -0,0 +1,16 @@
package main
import (
"go/build"
"os"
)
// Tests that the Go compiler is at least version 1.2.
func main() {
for _, tag := range build.Default.ReleaseTags {
if tag == "go1.2" {
os.Exit(0)
}
}
os.Exit(1)
}

View File

@ -0,0 +1,75 @@
//===- IRBindings.cpp - Additional bindings for ir ------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines additional C bindings for the ir component.
//
//===----------------------------------------------------------------------===//
#include "IRBindings.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
using namespace llvm;
LLVMMetadataRef LLVMConstantAsMetadata(LLVMValueRef C) {
return wrap(ConstantAsMetadata::get(unwrap<Constant>(C)));
}
LLVMMetadataRef LLVMMDString2(LLVMContextRef C, const char *Str, unsigned SLen) {
return wrap(MDString::get(*unwrap(C), StringRef(Str, SLen)));
}
LLVMMetadataRef LLVMMDNode2(LLVMContextRef C, LLVMMetadataRef *MDs,
unsigned Count) {
return wrap(
MDNode::get(*unwrap(C), ArrayRef<Metadata *>(unwrap(MDs), Count)));
}
void LLVMAddNamedMetadataOperand2(LLVMModuleRef M, const char *name,
LLVMMetadataRef Val) {
NamedMDNode *N = unwrap(M)->getOrInsertNamedMetadata(name);
if (!N)
return;
if (!Val)
return;
N->addOperand(unwrap<MDNode>(Val));
}
void LLVMSetMetadata2(LLVMValueRef Inst, unsigned KindID, LLVMMetadataRef MD) {
MDNode *N = MD ? unwrap<MDNode>(MD) : nullptr;
unwrap<Instruction>(Inst)->setMetadata(KindID, N);
}
void LLVMGoSetCurrentDebugLocation(LLVMBuilderRef Bref, unsigned Line,
unsigned Col, LLVMMetadataRef Scope,
LLVMMetadataRef InlinedAt) {
if (!Scope)
unwrap(Bref)->SetCurrentDebugLocation(DebugLoc());
else
unwrap(Bref)->SetCurrentDebugLocation(DILocation::get(
unwrap<MDNode>(Scope)->getContext(), Line, Col, unwrap<MDNode>(Scope),
InlinedAt ? unwrap<MDNode>(InlinedAt) : nullptr));
}
LLVMDebugLocMetadata LLVMGoGetCurrentDebugLocation(LLVMBuilderRef Bref) {
const auto& Loc = unwrap(Bref)->getCurrentDebugLocation();
const auto* InlinedAt = Loc.getInlinedAt();
const LLVMDebugLocMetadata md{
Loc.getLine(),
Loc.getCol(),
wrap(Loc.getScope()),
InlinedAt == nullptr ? nullptr : wrap(InlinedAt->getRawInlinedAt()),
};
return md;
}

View File

@ -0,0 +1,57 @@
//===- IRBindings.h - Additional bindings for IR ----------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines additional C bindings for the IR component.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_BINDINGS_GO_LLVM_IRBINDINGS_H
#define LLVM_BINDINGS_GO_LLVM_IRBINDINGS_H
#include "llvm-c/Core.h"
#include "llvm-c/DebugInfo.h"
#ifdef __cplusplus
#include "llvm/IR/Metadata.h"
#include "llvm/Support/CBindingWrapping.h"
#endif
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
struct LLVMDebugLocMetadata{
unsigned Line;
unsigned Col;
LLVMMetadataRef Scope;
LLVMMetadataRef InlinedAt;
};
LLVMMetadataRef LLVMConstantAsMetadata(LLVMValueRef Val);
LLVMMetadataRef LLVMMDString2(LLVMContextRef C, const char *Str, unsigned SLen);
LLVMMetadataRef LLVMMDNode2(LLVMContextRef C, LLVMMetadataRef *MDs,
unsigned Count);
void LLVMAddNamedMetadataOperand2(LLVMModuleRef M, const char *name,
LLVMMetadataRef Val);
void LLVMSetMetadata2(LLVMValueRef Inst, unsigned KindID, LLVMMetadataRef MD);
void LLVMGoSetCurrentDebugLocation(LLVMBuilderRef Bref, unsigned Line,
unsigned Col, LLVMMetadataRef Scope,
LLVMMetadataRef InlinedAt);
struct LLVMDebugLocMetadata LLVMGoGetCurrentDebugLocation(LLVMBuilderRef Bref);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,48 @@
//===- InstrumentationBindings.cpp - instrumentation bindings -------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines C bindings for the instrumentation component.
//
//===----------------------------------------------------------------------===//
#include "InstrumentationBindings.h"
#include "llvm-c/Core.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/Transforms/Instrumentation.h"
#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
using namespace llvm;
void LLVMAddAddressSanitizerFunctionPass(LLVMPassManagerRef PM) {
unwrap(PM)->add(createAddressSanitizerFunctionPass());
}
void LLVMAddAddressSanitizerModulePass(LLVMPassManagerRef PM) {
unwrap(PM)->add(createModuleAddressSanitizerLegacyPassPass());
}
void LLVMAddThreadSanitizerPass(LLVMPassManagerRef PM) {
unwrap(PM)->add(createThreadSanitizerLegacyPassPass());
}
void LLVMAddMemorySanitizerLegacyPassPass(LLVMPassManagerRef PM) {
unwrap(PM)->add(createMemorySanitizerLegacyPassPass());
}
void LLVMAddDataFlowSanitizerPass(LLVMPassManagerRef PM,
int ABIListFilesNum,
const char **ABIListFiles) {
std::vector<std::string> ABIListFilesVec;
for (int i = 0; i != ABIListFilesNum; ++i) {
ABIListFilesVec.push_back(ABIListFiles[i]);
}
unwrap(PM)->add(createDataFlowSanitizerLegacyPassPass(ABIListFilesVec));
}

View File

@ -0,0 +1,37 @@
//===- InstrumentationBindings.h - instrumentation bindings -----*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines C bindings for the Transforms/Instrumentation component.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_BINDINGS_GO_LLVM_INSTRUMENTATIONBINDINGS_H
#define LLVM_BINDINGS_GO_LLVM_INSTRUMENTATIONBINDINGS_H
#include "llvm-c/Core.h"
#ifdef __cplusplus
extern "C" {
#endif
// FIXME: These bindings shouldn't be Go-specific and should eventually move to
// a (somewhat) less stable collection of C APIs for use in creating bindings of
// LLVM in other languages.
void LLVMAddAddressSanitizerFunctionPass(LLVMPassManagerRef PM);
void LLVMAddAddressSanitizerModulePass(LLVMPassManagerRef PM);
void LLVMAddThreadSanitizerPass(LLVMPassManagerRef PM);
void LLVMAddMemorySanitizerLegacyPassPass(LLVMPassManagerRef PM);
void LLVMAddDataFlowSanitizerPass(LLVMPassManagerRef PM, int ABIListFilesNum,
const char **ABIListFiles);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,25 @@
//===- SupportBindings.cpp - Additional bindings for support --------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines additional C bindings for the support component.
//
//===----------------------------------------------------------------------===//
#include "SupportBindings.h"
#include "llvm/Support/DynamicLibrary.h"
#include <stdlib.h>
#include <string.h>
void LLVMLoadLibraryPermanently2(const char *Filename, char **ErrMsg) {
std::string ErrMsgStr;
if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Filename, &ErrMsgStr)) {
*ErrMsg = static_cast<char *>(malloc(ErrMsgStr.size() + 1));
memcpy(static_cast<void *>(*ErrMsg),
static_cast<const void *>(ErrMsgStr.c_str()), ErrMsgStr.size() + 1);
}
}

View File

@ -0,0 +1,29 @@
//===- SupportBindings.h - Additional bindings for Support ------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines additional C bindings for the Support component.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_BINDINGS_GO_LLVM_SUPPORTBINDINGS_H
#define LLVM_BINDINGS_GO_LLVM_SUPPORTBINDINGS_H
#ifdef __cplusplus
extern "C" {
#endif
// This function duplicates the LLVMLoadLibraryPermanently function in the
// stable C API and adds an extra ErrMsg parameter to retrieve the error
// message.
void LLVMLoadLibraryPermanently2(const char *Filename, char **ErrMsg);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,68 @@
//===- analysis.go - Bindings for analysis --------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines bindings for the analysis component.
//
//===----------------------------------------------------------------------===//
package llvm
/*
#include "llvm-c/Analysis.h" // If you are getting an error here read bindings/go/README.txt
#include "llvm-c/Core.h"
#include <stdlib.h>
*/
import "C"
import "errors"
type VerifierFailureAction C.LLVMVerifierFailureAction
const (
// verifier will print to stderr and abort()
AbortProcessAction VerifierFailureAction = C.LLVMAbortProcessAction
// verifier will print to stderr and return 1
PrintMessageAction VerifierFailureAction = C.LLVMPrintMessageAction
// verifier will just return 1
ReturnStatusAction VerifierFailureAction = C.LLVMReturnStatusAction
)
// Verifies that a module is valid, taking the specified action if not.
// Optionally returns a human-readable description of any invalid constructs.
func VerifyModule(m Module, a VerifierFailureAction) error {
var cmsg *C.char
broken := C.LLVMVerifyModule(m.C, C.LLVMVerifierFailureAction(a), &cmsg)
// C++'s verifyModule means isModuleBroken, so it returns false if
// there are no errors
if broken != 0 {
err := errors.New(C.GoString(cmsg))
C.LLVMDisposeMessage(cmsg)
return err
}
return nil
}
var verifyFunctionError = errors.New("Function is broken")
// Verifies that a single function is valid, taking the specified action.
// Useful for debugging.
func VerifyFunction(f Value, a VerifierFailureAction) error {
broken := C.LLVMVerifyFunction(f.C, C.LLVMVerifierFailureAction(a))
// C++'s verifyFunction means isFunctionBroken, so it returns false if
// there are no errors
if broken != 0 {
return verifyFunctionError
}
return nil
}
// Open up a ghostview window that displays the CFG of the current function.
// Useful for debugging.
func ViewFunctionCFG(f Value) { C.LLVMViewFunctionCFG(f.C) }
func ViewFunctionCFGOnly(f Value) { C.LLVMViewFunctionCFGOnly(f.C) }

View File

@ -0,0 +1,50 @@
//===- bitreader.go - Bindings for bitreader ------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines bindings for the bitreader component.
//
//===----------------------------------------------------------------------===//
package llvm
/*
#include "llvm-c/BitReader.h"
#include "llvm-c/Core.h"
#include <stdlib.h>
*/
import "C"
import (
"errors"
"unsafe"
)
// ParseBitcodeFile parses the LLVM IR (bitcode) in the file with the
// specified name, and returns a new LLVM module.
func ParseBitcodeFile(name string) (Module, error) {
var buf C.LLVMMemoryBufferRef
var errmsg *C.char
var cfilename *C.char = C.CString(name)
defer C.free(unsafe.Pointer(cfilename))
result := C.LLVMCreateMemoryBufferWithContentsOfFile(cfilename, &buf, &errmsg)
if result != 0 {
err := errors.New(C.GoString(errmsg))
C.free(unsafe.Pointer(errmsg))
return Module{}, err
}
defer C.LLVMDisposeMemoryBuffer(buf)
var m Module
if C.LLVMParseBitcode2(buf, &m.C) == 0 {
return m, nil
}
err := errors.New(C.GoString(errmsg))
C.free(unsafe.Pointer(errmsg))
return Module{}, err
}

View File

@ -0,0 +1,38 @@
//===- bitwriter.go - Bindings for bitwriter ------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines bindings for the bitwriter component.
//
//===----------------------------------------------------------------------===//
package llvm
/*
#include "llvm-c/BitWriter.h"
#include <stdlib.h>
*/
import "C"
import "os"
import "errors"
var writeBitcodeToFileErr = errors.New("Failed to write bitcode to file")
func WriteBitcodeToFile(m Module, file *os.File) error {
fail := C.LLVMWriteBitcodeToFD(m.C, C.int(file.Fd()), C.int(0), C.int(0))
if fail != 0 {
return writeBitcodeToFileErr
}
return nil
}
func WriteBitcodeToMemoryBuffer(m Module) MemoryBuffer {
mb := C.LLVMWriteBitcodeToMemoryBuffer(m.C)
return MemoryBuffer{mb}
}
// TODO(nsf): Figure out way how to make it work with io.Writer

View File

@ -0,0 +1,711 @@
//===- dibuilder.go - Bindings for DIBuilder ------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines bindings for the DIBuilder class.
//
//===----------------------------------------------------------------------===//
package llvm
/*
#include "IRBindings.h"
#include <stdlib.h>
*/
import "C"
import (
"debug/dwarf"
"unsafe"
)
type DwarfTag uint32
const (
DW_TAG_lexical_block DwarfTag = 0x0b
DW_TAG_compile_unit DwarfTag = 0x11
DW_TAG_variable DwarfTag = 0x34
DW_TAG_base_type DwarfTag = 0x24
DW_TAG_pointer_type DwarfTag = 0x0F
DW_TAG_structure_type DwarfTag = 0x13
DW_TAG_subroutine_type DwarfTag = 0x15
DW_TAG_file_type DwarfTag = 0x29
DW_TAG_subprogram DwarfTag = 0x2E
DW_TAG_auto_variable DwarfTag = 0x100
DW_TAG_arg_variable DwarfTag = 0x101
)
const (
FlagPrivate = 1 << iota
FlagProtected
FlagFwdDecl
FlagAppleBlock
FlagReserved
FlagVirtual
FlagArtificial
FlagExplicit
FlagPrototyped
FlagObjcClassComplete
FlagObjectPointer
FlagVector
FlagStaticMember
FlagIndirectVariable
)
type DwarfLang uint32
const (
// http://dwarfstd.org/ShowIssue.php?issue=101014.1&type=open
DW_LANG_Go DwarfLang = 0x0016
)
type DwarfTypeEncoding uint32
const (
DW_ATE_address DwarfTypeEncoding = 0x01
DW_ATE_boolean DwarfTypeEncoding = 0x02
DW_ATE_complex_float DwarfTypeEncoding = 0x03
DW_ATE_float DwarfTypeEncoding = 0x04
DW_ATE_signed DwarfTypeEncoding = 0x05
DW_ATE_signed_char DwarfTypeEncoding = 0x06
DW_ATE_unsigned DwarfTypeEncoding = 0x07
DW_ATE_unsigned_char DwarfTypeEncoding = 0x08
DW_ATE_imaginary_float DwarfTypeEncoding = 0x09
DW_ATE_packed_decimal DwarfTypeEncoding = 0x0a
DW_ATE_numeric_string DwarfTypeEncoding = 0x0b
DW_ATE_edited DwarfTypeEncoding = 0x0c
DW_ATE_signed_fixed DwarfTypeEncoding = 0x0d
DW_ATE_unsigned_fixed DwarfTypeEncoding = 0x0e
DW_ATE_decimal_float DwarfTypeEncoding = 0x0f
DW_ATE_UTF DwarfTypeEncoding = 0x10
DW_ATE_lo_user DwarfTypeEncoding = 0x80
DW_ATE_hi_user DwarfTypeEncoding = 0xff
)
// DIBuilder is a wrapper for the LLVM DIBuilder class.
type DIBuilder struct {
ref C.LLVMDIBuilderRef
m Module
}
// NewDIBuilder creates a new DIBuilder, associated with the given module.
func NewDIBuilder(m Module) *DIBuilder {
d := C.LLVMCreateDIBuilder(m.C)
return &DIBuilder{ref: d, m: m}
}
// Destroy destroys the DIBuilder.
func (d *DIBuilder) Destroy() {
C.LLVMDisposeDIBuilder(d.ref)
}
// FInalize finalizes the debug information generated by the DIBuilder.
func (d *DIBuilder) Finalize() {
C.LLVMDIBuilderFinalize(d.ref)
}
// DICompileUnit holds the values for creating compile unit debug metadata.
type DICompileUnit struct {
Language DwarfLang
File string
Dir string
Producer string
Optimized bool
Flags string
RuntimeVersion int
SysRoot string
SDK string
}
// CreateCompileUnit creates compile unit debug metadata.
func (d *DIBuilder) CreateCompileUnit(cu DICompileUnit) Metadata {
file := C.CString(cu.File)
defer C.free(unsafe.Pointer(file))
dir := C.CString(cu.Dir)
defer C.free(unsafe.Pointer(dir))
producer := C.CString(cu.Producer)
defer C.free(unsafe.Pointer(producer))
flags := C.CString(cu.Flags)
defer C.free(unsafe.Pointer(flags))
sysroot := C.CString(cu.SysRoot)
defer C.free(unsafe.Pointer(sysroot))
sdk := C.CString(cu.SDK)
defer C.free(unsafe.Pointer(sdk))
result := C.LLVMDIBuilderCreateCompileUnit(
d.ref,
C.LLVMDWARFSourceLanguage(cu.Language),
C.LLVMDIBuilderCreateFile(d.ref, file, C.size_t(len(cu.File)), dir, C.size_t(len(cu.Dir))),
producer, C.size_t(len(cu.Producer)),
C.LLVMBool(boolToCInt(cu.Optimized)),
flags, C.size_t(len(cu.Flags)),
C.unsigned(cu.RuntimeVersion),
/*SplitName=*/ nil, 0,
C.LLVMDWARFEmissionFull,
/*DWOId=*/ 0,
/*SplitDebugInlining*/ C.LLVMBool(boolToCInt(true)),
/*DebugInfoForProfiling*/ C.LLVMBool(boolToCInt(false)),
sysroot, C.size_t(len(cu.SysRoot)),
sdk, C.size_t(len(cu.SDK)),
)
return Metadata{C: result}
}
// CreateFile creates file debug metadata.
func (d *DIBuilder) CreateFile(filename, dir string) Metadata {
cfilename := C.CString(filename)
defer C.free(unsafe.Pointer(cfilename))
cdir := C.CString(dir)
defer C.free(unsafe.Pointer(cdir))
result := C.LLVMDIBuilderCreateFile(d.ref,
cfilename, C.size_t(len(filename)),
cdir, C.size_t(len(dir)))
return Metadata{C: result}
}
// DILexicalBlock holds the values for creating lexical block debug metadata.
type DILexicalBlock struct {
File Metadata
Line int
Column int
}
// CreateLexicalBlock creates lexical block debug metadata.
func (d *DIBuilder) CreateLexicalBlock(diScope Metadata, b DILexicalBlock) Metadata {
result := C.LLVMDIBuilderCreateLexicalBlock(
d.ref,
diScope.C,
b.File.C,
C.unsigned(b.Line),
C.unsigned(b.Column),
)
return Metadata{C: result}
}
func (d *DIBuilder) CreateLexicalBlockFile(diScope Metadata, diFile Metadata, discriminator int) Metadata {
result := C.LLVMDIBuilderCreateLexicalBlockFile(d.ref, diScope.C, diFile.C,
C.unsigned(discriminator))
return Metadata{C: result}
}
// DIFunction holds the values for creating function debug metadata.
type DIFunction struct {
Name string
LinkageName string
File Metadata
Line int
Type Metadata
LocalToUnit bool
IsDefinition bool
ScopeLine int
Flags int
Optimized bool
}
// CreateFunction creates function debug metadata.
func (d *DIBuilder) CreateFunction(diScope Metadata, f DIFunction) Metadata {
name := C.CString(f.Name)
defer C.free(unsafe.Pointer(name))
linkageName := C.CString(f.LinkageName)
defer C.free(unsafe.Pointer(linkageName))
result := C.LLVMDIBuilderCreateFunction(
d.ref,
diScope.C,
name, C.size_t(len(f.Name)),
linkageName, C.size_t(len(f.LinkageName)),
f.File.C,
C.unsigned(f.Line),
f.Type.C,
C.LLVMBool(boolToCInt(f.LocalToUnit)),
C.LLVMBool(boolToCInt(f.IsDefinition)),
C.unsigned(f.ScopeLine),
C.LLVMDIFlags(f.Flags),
C.LLVMBool(boolToCInt(f.Optimized)),
)
return Metadata{C: result}
}
// DIAutoVariable holds the values for creating auto variable debug metadata.
type DIAutoVariable struct {
Name string
File Metadata
Line int
Type Metadata
AlwaysPreserve bool
Flags int
AlignInBits uint32
}
// CreateAutoVariable creates local variable debug metadata.
func (d *DIBuilder) CreateAutoVariable(scope Metadata, v DIAutoVariable) Metadata {
name := C.CString(v.Name)
defer C.free(unsafe.Pointer(name))
result := C.LLVMDIBuilderCreateAutoVariable(
d.ref,
scope.C,
name, C.size_t(len(v.Name)),
v.File.C,
C.unsigned(v.Line),
v.Type.C,
C.LLVMBool(boolToCInt(v.AlwaysPreserve)),
C.LLVMDIFlags(v.Flags),
C.uint32_t(v.AlignInBits),
)
return Metadata{C: result}
}
// DIParameterVariable holds the values for creating parameter variable debug metadata.
type DIParameterVariable struct {
Name string
File Metadata
Line int
Type Metadata
AlwaysPreserve bool
Flags int
// ArgNo is the 1-based index of the argument in the function's
// parameter list.
ArgNo int
}
// CreateParameterVariable creates parameter variable debug metadata.
func (d *DIBuilder) CreateParameterVariable(scope Metadata, v DIParameterVariable) Metadata {
name := C.CString(v.Name)
defer C.free(unsafe.Pointer(name))
result := C.LLVMDIBuilderCreateParameterVariable(
d.ref,
scope.C,
name, C.size_t(len(v.Name)),
C.unsigned(v.ArgNo),
v.File.C,
C.unsigned(v.Line),
v.Type.C,
C.LLVMBool(boolToCInt(v.AlwaysPreserve)),
C.LLVMDIFlags(v.Flags),
)
return Metadata{C: result}
}
// DIBasicType holds the values for creating basic type debug metadata.
type DIBasicType struct {
Name string
SizeInBits uint64
Encoding DwarfTypeEncoding
}
// CreateBasicType creates basic type debug metadata.
func (d *DIBuilder) CreateBasicType(t DIBasicType) Metadata {
name := C.CString(t.Name)
defer C.free(unsafe.Pointer(name))
result := C.LLVMDIBuilderCreateBasicType(
d.ref,
name,
C.size_t(len(t.Name)),
C.uint64_t(t.SizeInBits),
C.LLVMDWARFTypeEncoding(t.Encoding),
C.LLVMDIFlags(0),
)
return Metadata{C: result}
}
// DIPointerType holds the values for creating pointer type debug metadata.
type DIPointerType struct {
Pointee Metadata
SizeInBits uint64
AlignInBits uint32 // optional
AddressSpace uint32
Name string // optional
}
// CreatePointerType creates a type that represents a pointer to another type.
func (d *DIBuilder) CreatePointerType(t DIPointerType) Metadata {
name := C.CString(t.Name)
defer C.free(unsafe.Pointer(name))
result := C.LLVMDIBuilderCreatePointerType(
d.ref,
t.Pointee.C,
C.uint64_t(t.SizeInBits),
C.uint32_t(t.AlignInBits),
C.unsigned(t.AddressSpace),
name,
C.size_t(len(t.Name)),
)
return Metadata{C: result}
}
// DISubroutineType holds the values for creating subroutine type debug metadata.
type DISubroutineType struct {
// File is the file in which the subroutine type is defined.
File Metadata
// Parameters contains the subroutine parameter types,
// including the return type at the 0th index.
Parameters []Metadata
Flags int
}
// CreateSubroutineType creates subroutine type debug metadata.
func (d *DIBuilder) CreateSubroutineType(t DISubroutineType) Metadata {
params, length := llvmMetadataRefs(t.Parameters)
result := C.LLVMDIBuilderCreateSubroutineType(
d.ref,
t.File.C,
params,
length,
C.LLVMDIFlags(t.Flags),
)
return Metadata{C: result}
}
// DIStructType holds the values for creating struct type debug metadata.
type DIStructType struct {
Name string
File Metadata
Line int
SizeInBits uint64
AlignInBits uint32
Flags int
DerivedFrom Metadata
Elements []Metadata
VTableHolder Metadata // optional
UniqueID string
}
// CreateStructType creates struct type debug metadata.
func (d *DIBuilder) CreateStructType(scope Metadata, t DIStructType) Metadata {
elements, length := llvmMetadataRefs(t.Elements)
name := C.CString(t.Name)
uniqueID := C.CString(t.UniqueID)
defer C.free(unsafe.Pointer(name))
defer C.free(unsafe.Pointer(uniqueID))
result := C.LLVMDIBuilderCreateStructType(
d.ref,
scope.C,
name,
C.size_t(len(t.Name)),
t.File.C,
C.unsigned(t.Line),
C.uint64_t(t.SizeInBits),
C.uint32_t(t.AlignInBits),
C.LLVMDIFlags(t.Flags),
t.DerivedFrom.C,
elements,
length,
C.unsigned(0), // Optional Objective-C runtime version.
t.VTableHolder.C,
uniqueID,
C.size_t(len(t.UniqueID)),
)
return Metadata{C: result}
}
// DIReplaceableCompositeType holds the values for creating replaceable
// composite type debug metadata.
type DIReplaceableCompositeType struct {
Tag dwarf.Tag
Name string
File Metadata
Line int
RuntimeLang int
SizeInBits uint64
AlignInBits uint32
Flags int
UniqueID string
}
// CreateReplaceableCompositeType creates replaceable composite type debug metadata.
func (d *DIBuilder) CreateReplaceableCompositeType(scope Metadata, t DIReplaceableCompositeType) Metadata {
name := C.CString(t.Name)
uniqueID := C.CString(t.UniqueID)
defer C.free(unsafe.Pointer(name))
defer C.free(unsafe.Pointer(uniqueID))
result := C.LLVMDIBuilderCreateReplaceableCompositeType(
d.ref,
C.unsigned(t.Tag),
name,
C.size_t(len(t.Name)),
scope.C,
t.File.C,
C.unsigned(t.Line),
C.unsigned(t.RuntimeLang),
C.uint64_t(t.SizeInBits),
C.uint32_t(t.AlignInBits),
C.LLVMDIFlags(t.Flags),
uniqueID,
C.size_t(len(t.UniqueID)),
)
return Metadata{C: result}
}
// DIMemberType holds the values for creating member type debug metadata.
type DIMemberType struct {
Name string
File Metadata
Line int
SizeInBits uint64
AlignInBits uint32
OffsetInBits uint64
Flags int
Type Metadata
}
// CreateMemberType creates struct type debug metadata.
func (d *DIBuilder) CreateMemberType(scope Metadata, t DIMemberType) Metadata {
name := C.CString(t.Name)
defer C.free(unsafe.Pointer(name))
result := C.LLVMDIBuilderCreateMemberType(
d.ref,
scope.C,
name,
C.size_t(len(t.Name)),
t.File.C,
C.unsigned(t.Line),
C.uint64_t(t.SizeInBits),
C.uint32_t(t.AlignInBits),
C.uint64_t(t.OffsetInBits),
C.LLVMDIFlags(t.Flags),
t.Type.C,
)
return Metadata{C: result}
}
// DISubrange describes an integer value range.
type DISubrange struct {
Lo int64
Count int64
}
// DIArrayType holds the values for creating array type debug metadata.
type DIArrayType struct {
SizeInBits uint64
AlignInBits uint32
ElementType Metadata
Subscripts []DISubrange
}
// CreateArrayType creates struct type debug metadata.
func (d *DIBuilder) CreateArrayType(t DIArrayType) Metadata {
subscriptsSlice := make([]Metadata, len(t.Subscripts))
for i, s := range t.Subscripts {
subscriptsSlice[i] = d.getOrCreateSubrange(s.Lo, s.Count)
}
subscripts, length := llvmMetadataRefs(subscriptsSlice)
result := C.LLVMDIBuilderCreateArrayType(
d.ref,
C.uint64_t(t.SizeInBits),
C.uint32_t(t.AlignInBits),
t.ElementType.C,
subscripts,
length,
)
return Metadata{C: result}
}
// DITypedef holds the values for creating typedef type debug metadata.
type DITypedef struct {
Type Metadata
Name string
File Metadata
Line int
Context Metadata
AlignInBits uint32
}
// CreateTypedef creates typedef type debug metadata.
func (d *DIBuilder) CreateTypedef(t DITypedef) Metadata {
name := C.CString(t.Name)
defer C.free(unsafe.Pointer(name))
result := C.LLVMDIBuilderCreateTypedef(
d.ref,
t.Type.C,
name,
C.size_t(len(t.Name)),
t.File.C,
C.unsigned(t.Line),
t.Context.C,
C.uint32_t(t.AlignInBits),
)
return Metadata{C: result}
}
// getOrCreateSubrange gets a metadata node for the specified subrange,
// creating if required.
func (d *DIBuilder) getOrCreateSubrange(lo, count int64) Metadata {
result := C.LLVMDIBuilderGetOrCreateSubrange(d.ref, C.int64_t(lo), C.int64_t(count))
return Metadata{C: result}
}
// getOrCreateArray gets a metadata node containing the specified values,
// creating if required.
func (d *DIBuilder) getOrCreateArray(values []Metadata) Metadata {
if len(values) == 0 {
return Metadata{}
}
data, length := llvmMetadataRefs(values)
result := C.LLVMDIBuilderGetOrCreateArray(d.ref, data, C.size_t(length))
return Metadata{C: result}
}
// getOrCreateTypeArray gets a metadata node for a type array containing the
// specified values, creating if required.
func (d *DIBuilder) getOrCreateTypeArray(values []Metadata) Metadata {
if len(values) == 0 {
return Metadata{}
}
data, length := llvmMetadataRefs(values)
result := C.LLVMDIBuilderGetOrCreateTypeArray(d.ref, data, C.size_t(length))
return Metadata{C: result}
}
// CreateExpression creates a new descriptor for the specified
// variable which has a complex address expression for its address.
func (d *DIBuilder) CreateExpression(addr []int64) Metadata {
var data *C.int64_t
if len(addr) > 0 {
data = (*C.int64_t)(unsafe.Pointer(&addr[0]))
}
result := C.LLVMDIBuilderCreateExpression(d.ref, data, C.size_t(len(addr)))
return Metadata{C: result}
}
// InsertDeclareAtEnd inserts a call to llvm.dbg.declare at the end of the
// specified basic block for the given value and associated debug metadata.
func (d *DIBuilder) InsertDeclareAtEnd(v Value, diVarInfo, expr Metadata, l DebugLoc, bb BasicBlock) Value {
loc := C.LLVMDIBuilderCreateDebugLocation(
d.m.Context().C, C.uint(l.Line), C.uint(l.Col), l.Scope.C, l.InlinedAt.C)
result := C.LLVMDIBuilderInsertDeclareAtEnd(d.ref, v.C, diVarInfo.C, expr.C, loc, bb.C)
return Value{C: result}
}
// InsertValueAtEnd inserts a call to llvm.dbg.value at the end of the
// specified basic block for the given value and associated debug metadata.
func (d *DIBuilder) InsertValueAtEnd(v Value, diVarInfo, expr Metadata, l DebugLoc, bb BasicBlock) Value {
loc := C.LLVMDIBuilderCreateDebugLocation(
d.m.Context().C, C.uint(l.Line), C.uint(l.Col), l.Scope.C, l.InlinedAt.C)
result := C.LLVMDIBuilderInsertDbgValueAtEnd(d.ref, v.C, diVarInfo.C, expr.C, loc, bb.C)
return Value{C: result}
}
func (v Value) SetSubprogram(sp Metadata) {
C.LLVMSetSubprogram(v.C, sp.C)
}
func (v Value) Subprogram() (md Metadata) {
md.C = C.LLVMGetSubprogram(v.C)
return
}
func boolToCInt(v bool) C.int {
if v {
return 1
}
return 0
}
//-------------------------------------------------------------------------
// llvm.Metadata
//-------------------------------------------------------------------------
func (c Context) TemporaryMDNode(mds []Metadata) (md Metadata) {
ptr, nvals := llvmMetadataRefs(mds)
md.C = C.LLVMTemporaryMDNode(c.C, ptr, C.size_t(nvals))
return
}
func (md Metadata) ReplaceAllUsesWith(new Metadata) {
C.LLVMMetadataReplaceAllUsesWith(md.C, new.C)
}
type MetadataKind C.LLVMMetadataKind
const (
MDStringMetadataKind = C.LLVMMDStringMetadataKind
ConstantAsMetadataMetadataKind = C.LLVMConstantAsMetadataMetadataKind
LocalAsMetadataMetadataKind = C.LLVMLocalAsMetadataMetadataKind
DistinctMDOperandPlaceholderMetadataKind = C.LLVMDistinctMDOperandPlaceholderMetadataKind
MDTupleMetadataKind = C.LLVMMDTupleMetadataKind
DILocationMetadataKind = C.LLVMDILocationMetadataKind
DIExpressionMetadataKind = C.LLVMDIExpressionMetadataKind
DIGlobalVariableExpressionMetadataKind = C.LLVMDIGlobalVariableExpressionMetadataKind
GenericDINodeMetadataKind = C.LLVMGenericDINodeMetadataKind
DISubrangeMetadataKind = C.LLVMDISubrangeMetadataKind
DIEnumeratorMetadataKind = C.LLVMDIEnumeratorMetadataKind
DIBasicTypeMetadataKind = C.LLVMDIBasicTypeMetadataKind
DIDerivedTypeMetadataKind = C.LLVMDIDerivedTypeMetadataKind
DICompositeTypeMetadataKind = C.LLVMDICompositeTypeMetadataKind
DISubroutineTypeMetadataKind = C.LLVMDISubroutineTypeMetadataKind
DIFileMetadataKind = C.LLVMDIFileMetadataKind
DICompileUnitMetadataKind = C.LLVMDICompileUnitMetadataKind
DISubprogramMetadataKind = C.LLVMDISubprogramMetadataKind
DILexicalBlockMetadataKind = C.LLVMDILexicalBlockMetadataKind
DILexicalBlockFileMetadataKind = C.LLVMDILexicalBlockFileMetadataKind
DINamespaceMetadataKind = C.LLVMDINamespaceMetadataKind
DIModuleMetadataKind = C.LLVMDIModuleMetadataKind
DITemplateTypeParameterMetadataKind = C.LLVMDITemplateTypeParameterMetadataKind
DITemplateValueParameterMetadataKind = C.LLVMDITemplateValueParameterMetadataKind
DIGlobalVariableMetadataKind = C.LLVMDIGlobalVariableMetadataKind
DILocalVariableMetadataKind = C.LLVMDILocalVariableMetadataKind
DILabelMetadataKind = C.LLVMDILabelMetadataKind
DIObjCPropertyMetadataKind = C.LLVMDIObjCPropertyMetadataKind
DIImportedEntityMetadataKind = C.LLVMDIImportedEntityMetadataKind
DIMacroMetadataKind = C.LLVMDIMacroMetadataKind
DIMacroFileMetadataKind = C.LLVMDIMacroFileMetadataKind
DICommonBlockMetadataKind = C.LLVMDICommonBlockMetadataKind
)
// Kind returns the metadata kind.
func (md Metadata) Kind() MetadataKind {
return MetadataKind(C.LLVMGetMetadataKind(md.C))
}
// FileDirectory returns the directory of a DIFile metadata node.
func (md Metadata) FileDirectory() string {
var length C.unsigned
ptr := C.LLVMDIFileGetDirectory(md.C, &length)
return string(((*[1 << 20]byte)(unsafe.Pointer(ptr)))[:length:length])
}
// FileFilename returns the filename of a DIFile metadata node.
func (md Metadata) FileFilename() string {
var length C.unsigned
ptr := C.LLVMDIFileGetFilename(md.C, &length)
return string(((*[1 << 20]byte)(unsafe.Pointer(ptr)))[:length:length])
}
// FileSource returns the source of a DIFile metadata node.
func (md Metadata) FileSource() string {
var length C.unsigned
ptr := C.LLVMDIFileGetSource(md.C, &length)
return string(((*[1 << 20]byte)(unsafe.Pointer(ptr)))[:length:length])
}
// LocationLine returns the line number of a DILocation.
func (md Metadata) LocationLine() uint {
return uint(C.LLVMDILocationGetLine(md.C))
}
// LocationColumn returns the column (offset from the start of the line) of a
// DILocation.
func (md Metadata) LocationColumn() uint {
return uint(C.LLVMDILocationGetColumn(md.C))
}
// LocationScope returns the local scope associated with this debug location.
func (md Metadata) LocationScope() Metadata {
return Metadata{C.LLVMDILocationGetScope(md.C)}
}
// LocationInlinedAt return the "inline at" location associated with this debug
// location.
func (md Metadata) LocationInlinedAt() Metadata {
return Metadata{C.LLVMDILocationGetInlinedAt(md.C)}
}
// ScopeFile returns the file (DIFile) of a given scope.
func (md Metadata) ScopeFile() Metadata {
return Metadata{C.LLVMDIScopeGetFile(md.C)}
}

View File

@ -0,0 +1,177 @@
//===- executionengine.go - Bindings for executionengine ------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines bindings for the executionengine component.
//
//===----------------------------------------------------------------------===//
package llvm
/*
#include "llvm-c/Core.h"
#include "llvm-c/ExecutionEngine.h"
#include <stdlib.h>
*/
import "C"
import "unsafe"
import "errors"
func LinkInMCJIT() { C.LLVMLinkInMCJIT() }
func LinkInInterpreter() { C.LLVMLinkInInterpreter() }
type GenericValue struct {
C C.LLVMGenericValueRef
}
type ExecutionEngine struct {
C C.LLVMExecutionEngineRef
}
type MCJITCompilerOptions struct {
C C.struct_LLVMMCJITCompilerOptions
}
func (options *MCJITCompilerOptions) SetMCJITOptimizationLevel(level uint) {
options.C.OptLevel = C.uint(level)
}
func (options *MCJITCompilerOptions) SetMCJITNoFramePointerElim(nfp bool) {
options.C.NoFramePointerElim = boolToLLVMBool(nfp)
}
func (options *MCJITCompilerOptions) SetMCJITEnableFastISel(fastisel bool) {
options.C.EnableFastISel = boolToLLVMBool(fastisel)
}
func (options *MCJITCompilerOptions) SetMCJITCodeModel(CodeModel CodeModel) {
options.C.CodeModel = C.LLVMCodeModel(CodeModel)
}
// helpers
func llvmGenericValueRefPtr(t *GenericValue) *C.LLVMGenericValueRef {
return (*C.LLVMGenericValueRef)(unsafe.Pointer(t))
}
//-------------------------------------------------------------------------
// llvm.GenericValue
//-------------------------------------------------------------------------
func NewGenericValueFromInt(t Type, n uint64, signed bool) (g GenericValue) {
g.C = C.LLVMCreateGenericValueOfInt(t.C, C.ulonglong(n), boolToLLVMBool(signed))
return
}
func NewGenericValueFromPointer(p unsafe.Pointer) (g GenericValue) {
g.C = C.LLVMCreateGenericValueOfPointer(p)
return
}
func NewGenericValueFromFloat(t Type, n float64) (g GenericValue) {
g.C = C.LLVMCreateGenericValueOfFloat(t.C, C.double(n))
return
}
func (g GenericValue) IntWidth() int { return int(C.LLVMGenericValueIntWidth(g.C)) }
func (g GenericValue) Int(signed bool) uint64 {
return uint64(C.LLVMGenericValueToInt(g.C, boolToLLVMBool(signed)))
}
func (g GenericValue) Float(t Type) float64 {
return float64(C.LLVMGenericValueToFloat(t.C, g.C))
}
func (g GenericValue) Pointer() unsafe.Pointer {
return C.LLVMGenericValueToPointer(g.C)
}
func (g GenericValue) Dispose() { C.LLVMDisposeGenericValue(g.C) }
//-------------------------------------------------------------------------
// llvm.ExecutionEngine
//-------------------------------------------------------------------------
func NewExecutionEngine(m Module) (ee ExecutionEngine, err error) {
var cmsg *C.char
fail := C.LLVMCreateExecutionEngineForModule(&ee.C, m.C, &cmsg)
if fail != 0 {
ee.C = nil
err = errors.New(C.GoString(cmsg))
C.LLVMDisposeMessage(cmsg)
}
return
}
func NewInterpreter(m Module) (ee ExecutionEngine, err error) {
var cmsg *C.char
fail := C.LLVMCreateInterpreterForModule(&ee.C, m.C, &cmsg)
if fail != 0 {
ee.C = nil
err = errors.New(C.GoString(cmsg))
C.LLVMDisposeMessage(cmsg)
}
return
}
func NewMCJITCompilerOptions() MCJITCompilerOptions {
var options C.struct_LLVMMCJITCompilerOptions
C.LLVMInitializeMCJITCompilerOptions(&options, C.size_t(unsafe.Sizeof(C.struct_LLVMMCJITCompilerOptions{})))
return MCJITCompilerOptions{options}
}
func NewMCJITCompiler(m Module, options MCJITCompilerOptions) (ee ExecutionEngine, err error) {
var cmsg *C.char
fail := C.LLVMCreateMCJITCompilerForModule(&ee.C, m.C, &options.C, C.size_t(unsafe.Sizeof(C.struct_LLVMMCJITCompilerOptions{})), &cmsg)
if fail != 0 {
ee.C = nil
err = errors.New(C.GoString(cmsg))
C.LLVMDisposeMessage(cmsg)
}
return
}
func (ee ExecutionEngine) Dispose() { C.LLVMDisposeExecutionEngine(ee.C) }
func (ee ExecutionEngine) RunStaticConstructors() { C.LLVMRunStaticConstructors(ee.C) }
func (ee ExecutionEngine) RunStaticDestructors() { C.LLVMRunStaticDestructors(ee.C) }
func (ee ExecutionEngine) RunFunction(f Value, args []GenericValue) (g GenericValue) {
nargs := len(args)
var argptr *GenericValue
if nargs > 0 {
argptr = &args[0]
}
g.C = C.LLVMRunFunction(ee.C, f.C,
C.unsigned(nargs), llvmGenericValueRefPtr(argptr))
return
}
func (ee ExecutionEngine) FreeMachineCodeForFunction(f Value) {
C.LLVMFreeMachineCodeForFunction(ee.C, f.C)
}
func (ee ExecutionEngine) AddModule(m Module) { C.LLVMAddModule(ee.C, m.C) }
func (ee ExecutionEngine) RemoveModule(m Module) {
var modtmp C.LLVMModuleRef
C.LLVMRemoveModule(ee.C, m.C, &modtmp, nil)
}
func (ee ExecutionEngine) FindFunction(name string) (f Value) {
cname := C.CString(name)
defer C.free(unsafe.Pointer(cname))
C.LLVMFindFunction(ee.C, cname, &f.C)
return
}
func (ee ExecutionEngine) RecompileAndRelinkFunction(f Value) unsafe.Pointer {
return C.LLVMRecompileAndRelinkFunction(ee.C, f.C)
}
func (ee ExecutionEngine) TargetData() (td TargetData) {
td.C = C.LLVMGetExecutionEngineTargetData(ee.C)
return
}
func (ee ExecutionEngine) AddGlobalMapping(global Value, addr unsafe.Pointer) {
C.LLVMAddGlobalMapping(ee.C, global.C, addr)
}
func (ee ExecutionEngine) PointerToGlobal(global Value) unsafe.Pointer {
return C.LLVMGetPointerToGlobal(ee.C, global.C)
}

View File

@ -0,0 +1,95 @@
//===- executionengine_test.go - Tests for executionengine ----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file tests bindings for the executionengine component.
//
//===----------------------------------------------------------------------===//
package llvm
import (
"testing"
)
func TestFactorial(t *testing.T) {
LinkInMCJIT()
InitializeNativeTarget()
InitializeNativeAsmPrinter()
mod := NewModule("fac_module")
fac_args := []Type{Int32Type()}
fac_type := FunctionType(Int32Type(), fac_args, false)
fac := AddFunction(mod, "fac", fac_type)
fac.SetFunctionCallConv(CCallConv)
n := fac.Param(0)
entry := AddBasicBlock(fac, "entry")
iftrue := AddBasicBlock(fac, "iftrue")
iffalse := AddBasicBlock(fac, "iffalse")
end := AddBasicBlock(fac, "end")
builder := NewBuilder()
defer builder.Dispose()
builder.SetInsertPointAtEnd(entry)
If := builder.CreateICmp(IntEQ, n, ConstInt(Int32Type(), 0, false), "cmptmp")
builder.CreateCondBr(If, iftrue, iffalse)
builder.SetInsertPointAtEnd(iftrue)
res_iftrue := ConstInt(Int32Type(), 1, false)
builder.CreateBr(end)
builder.SetInsertPointAtEnd(iffalse)
n_minus := builder.CreateSub(n, ConstInt(Int32Type(), 1, false), "subtmp")
call_fac_args := []Value{n_minus}
call_fac := builder.CreateCall(fac, call_fac_args, "calltmp")
res_iffalse := builder.CreateMul(n, call_fac, "multmp")
builder.CreateBr(end)
builder.SetInsertPointAtEnd(end)
res := builder.CreatePHI(Int32Type(), "result")
phi_vals := []Value{res_iftrue, res_iffalse}
phi_blocks := []BasicBlock{iftrue, iffalse}
res.AddIncoming(phi_vals, phi_blocks)
builder.CreateRet(res)
err := VerifyModule(mod, ReturnStatusAction)
if err != nil {
t.Errorf("Error verifying module: %s", err)
return
}
options := NewMCJITCompilerOptions()
options.SetMCJITOptimizationLevel(2)
options.SetMCJITEnableFastISel(true)
options.SetMCJITNoFramePointerElim(true)
options.SetMCJITCodeModel(CodeModelJITDefault)
engine, err := NewMCJITCompiler(mod, options)
if err != nil {
t.Errorf("Error creating JIT: %s", err)
return
}
defer engine.Dispose()
pass := NewPassManager()
defer pass.Dispose()
pass.AddInstructionCombiningPass()
pass.AddPromoteMemoryToRegisterPass()
pass.AddGVNPass()
pass.AddCFGSimplificationPass()
pass.Run(mod)
exec_args := []GenericValue{NewGenericValueFromInt(Int32Type(), 10, false)}
exec_res := engine.RunFunction(fac, exec_args)
var fac10 uint64 = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1
if exec_res.Int(false) != fac10 {
t.Errorf("Expected %d, got %d", fac10, exec_res.Int(false))
}
}

2016
bindings/go/llvm/ir.go Normal file

File diff suppressed because it is too large Load Diff

164
bindings/go/llvm/ir_test.go Normal file
View File

@ -0,0 +1,164 @@
//===- ir_test.go - Tests for ir ------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file tests bindings for the ir component.
//
//===----------------------------------------------------------------------===//
package llvm
import (
"strings"
"testing"
)
func testAttribute(t *testing.T, name string) {
mod := NewModule("")
defer mod.Dispose()
ftyp := FunctionType(VoidType(), nil, false)
fn := AddFunction(mod, "foo", ftyp)
kind := AttributeKindID(name)
attr := mod.Context().CreateEnumAttribute(kind, 0)
fn.AddFunctionAttr(attr)
newattr := fn.GetEnumFunctionAttribute(kind)
if attr != newattr {
t.Errorf("got attribute %p, want %p", newattr.C, attr.C)
}
text := mod.String()
if !strings.Contains(text, " "+name+" ") {
t.Errorf("expected attribute '%s', got:\n%s", name, text)
}
fn.RemoveEnumFunctionAttribute(kind)
newattr = fn.GetEnumFunctionAttribute(kind)
if !newattr.IsNil() {
t.Errorf("got attribute %p, want 0", newattr.C)
}
}
func TestAttributes(t *testing.T) {
// Tests that our attribute constants haven't drifted from LLVM's.
attrTests := []string{
"sanitize_address",
"alwaysinline",
"builtin",
"convergent",
"inalloca",
"inlinehint",
"inreg",
"jumptable",
"minsize",
"naked",
"nest",
"noalias",
"nobuiltin",
"nocapture",
"noduplicate",
"noimplicitfloat",
"noinline",
"nonlazybind",
"nonnull",
"noredzone",
"noreturn",
"nounwind",
"optnone",
"optsize",
"readnone",
"readonly",
"returned",
"returns_twice",
"signext",
"safestack",
"ssp",
"sspreq",
"sspstrong",
"sanitize_thread",
"sanitize_memory",
"uwtable",
"zeroext",
"cold",
"nocf_check",
}
for _, name := range attrTests {
testAttribute(t, name)
}
}
func TestDebugLoc(t *testing.T) {
mod := NewModule("")
defer mod.Dispose()
ctx := mod.Context()
b := ctx.NewBuilder()
defer b.Dispose()
d := NewDIBuilder(mod)
defer func() {
d.Destroy()
}()
file := d.CreateFile("dummy_file", "dummy_dir")
voidInfo := d.CreateBasicType(DIBasicType{Name: "void"})
typeInfo := d.CreateSubroutineType(DISubroutineType{
File: file,
Parameters: []Metadata{voidInfo},
Flags: 0,
})
scope := d.CreateFunction(file, DIFunction{
Name: "foo",
LinkageName: "foo",
Line: 10,
ScopeLine: 10,
Type: typeInfo,
File: file,
IsDefinition: true,
})
b.SetCurrentDebugLocation(10, 20, scope, Metadata{})
loc := b.GetCurrentDebugLocation()
if loc.Line != 10 {
t.Errorf("Got line %d, though wanted 10", loc.Line)
}
if loc.Col != 20 {
t.Errorf("Got column %d, though wanted 20", loc.Col)
}
if loc.Scope.C != scope.C {
t.Errorf("Got metadata %v as scope, though wanted %v", loc.Scope.C, scope.C)
}
}
func TestSubtypes(t *testing.T) {
cont := NewContext()
defer cont.Dispose()
int_pointer := PointerType(cont.Int32Type(), 0)
int_inner := int_pointer.Subtypes()
if len(int_inner) != 1 {
t.Errorf("Got size %d, though wanted 1", len(int_inner))
}
if int_inner[0] != cont.Int32Type() {
t.Errorf("Expected int32 type")
}
st_pointer := cont.StructType([]Type{cont.Int32Type(), cont.Int8Type()}, false)
st_inner := st_pointer.Subtypes()
if len(st_inner) != 2 {
t.Errorf("Got size %d, though wanted 2", len(int_inner))
}
if st_inner[0] != cont.Int32Type() {
t.Errorf("Expected first struct field to be int32")
}
if st_inner[1] != cont.Int8Type() {
t.Errorf("Expected second struct field to be int8")
}
}

View File

@ -0,0 +1,30 @@
//===- linker.go - Bindings for linker ------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines bindings for the linker component.
//
//===----------------------------------------------------------------------===//
package llvm
/*
#include "llvm-c/Core.h"
#include "llvm-c/Linker.h"
#include <stdlib.h>
*/
import "C"
import "errors"
func LinkModules(Dest, Src Module) error {
failed := C.LLVMLinkModules2(Dest.C, Src.C)
if failed != 0 {
err := errors.New("Linking failed")
return err
}
return nil
}

View File

@ -0,0 +1,12 @@
// +build !byollvm
package llvm
/*
#cgo CXXFLAGS: -std=c++14
#cgo CPPFLAGS: @LLVM_CFLAGS@
#cgo LDFLAGS: @LLVM_LDFLAGS@
*/
import "C"
type (run_build_sh int)

View File

@ -0,0 +1,18 @@
//===- llvm_dep.go - creates LLVM dependency ------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file ensures that the LLVM libraries are built before using the
// bindings.
//
//===----------------------------------------------------------------------===//
// +build !byollvm
package llvm
var _ run_build_sh

106
bindings/go/llvm/string.go Normal file
View File

@ -0,0 +1,106 @@
//===- string.go - Stringer implementation for Type -----------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the Stringer interface for the Type type.
//
//===----------------------------------------------------------------------===//
package llvm
import "fmt"
func (t TypeKind) String() string {
switch t {
case VoidTypeKind:
return "VoidTypeKind"
case FloatTypeKind:
return "FloatTypeKind"
case DoubleTypeKind:
return "DoubleTypeKind"
case X86_FP80TypeKind:
return "X86_FP80TypeKind"
case FP128TypeKind:
return "FP128TypeKind"
case PPC_FP128TypeKind:
return "PPC_FP128TypeKind"
case LabelTypeKind:
return "LabelTypeKind"
case IntegerTypeKind:
return "IntegerTypeKind"
case FunctionTypeKind:
return "FunctionTypeKind"
case StructTypeKind:
return "StructTypeKind"
case ArrayTypeKind:
return "ArrayTypeKind"
case PointerTypeKind:
return "PointerTypeKind"
case MetadataTypeKind:
return "MetadataTypeKind"
case VectorTypeKind:
return "VectorTypeKind"
case ScalableVectorTypeKind:
return "ScalableVectorTypeKind"
}
panic("unreachable")
}
func (t Type) String() string {
ts := typeStringer{s: make(map[Type]string)}
return ts.typeString(t)
}
type typeStringer struct {
s map[Type]string
}
func (ts *typeStringer) typeString(t Type) string {
if s, ok := ts.s[t]; ok {
return s
}
k := t.TypeKind()
s := k.String()
s = s[:len(s)-len("Kind")]
switch k {
case ArrayTypeKind:
s += fmt.Sprintf("(%v[%v])", ts.typeString(t.ElementType()), t.ArrayLength())
case PointerTypeKind:
s += fmt.Sprintf("(%v)", ts.typeString(t.ElementType()))
case FunctionTypeKind:
params := t.ParamTypes()
s += "("
if len(params) > 0 {
s += fmt.Sprintf("%v", ts.typeString(params[0]))
for i := 1; i < len(params); i++ {
s += fmt.Sprintf(", %v", ts.typeString(params[i]))
}
}
s += fmt.Sprintf("):%v", ts.typeString(t.ReturnType()))
case StructTypeKind:
if name := t.StructName(); name != "" {
ts.s[t] = "%" + name
s = fmt.Sprintf("%%%s: %s", name, s)
}
etypes := t.StructElementTypes()
s += "("
if n := len(etypes); n > 0 {
s += ts.typeString(etypes[0])
for i := 1; i < n; i++ {
s += fmt.Sprintf(", %v", ts.typeString(etypes[i]))
}
}
s += ")"
case IntegerTypeKind:
s += fmt.Sprintf("(%d bits)", t.IntTypeWidth())
}
ts.s[t] = s
return s
}

View File

@ -0,0 +1,27 @@
//===- string_test.go - test Stringer implementation for Type -------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file tests the Stringer interface for the Type type.
//
//===----------------------------------------------------------------------===//
package llvm
import (
"testing"
)
func TestStringRecursiveType(t *testing.T) {
ctx := NewContext()
defer ctx.Dispose()
s := ctx.StructCreateNamed("recursive")
s.StructSetBody([]Type{s, s}, false)
if str := s.String(); str != "%recursive: StructType(%recursive, %recursive)" {
t.Errorf("incorrect string result %q", str)
}
}

View File

@ -0,0 +1,53 @@
//===- support.go - Bindings for support ----------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines bindings for the support component.
//
//===----------------------------------------------------------------------===//
package llvm
/*
#include "llvm-c/Support.h"
#include "SupportBindings.h"
#include <stdlib.h>
*/
import "C"
import (
"errors"
"unsafe"
)
// Loads a dynamic library such that it may be used as an LLVM plugin.
// See llvm::sys::DynamicLibrary::LoadLibraryPermanently.
func LoadLibraryPermanently(lib string) error {
var errstr *C.char
libstr := C.CString(lib)
defer C.free(unsafe.Pointer(libstr))
C.LLVMLoadLibraryPermanently2(libstr, &errstr)
if errstr != nil {
err := errors.New(C.GoString(errstr))
C.free(unsafe.Pointer(errstr))
return err
}
return nil
}
// Parse the given arguments using the LLVM command line parser.
// See llvm::cl::ParseCommandLineOptions.
func ParseCommandLineOptions(args []string, overview string) {
argstrs := make([]*C.char, len(args))
for i, arg := range args {
argstrs[i] = C.CString(arg)
defer C.free(unsafe.Pointer(argstrs[i]))
}
overviewstr := C.CString(overview)
defer C.free(unsafe.Pointer(overviewstr))
C.LLVMParseCommandLineOptions(C.int(len(args)), &argstrs[0], overviewstr)
}

296
bindings/go/llvm/target.go Normal file
View File

@ -0,0 +1,296 @@
//===- target.go - Bindings for target ------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines bindings for the target component.
//
//===----------------------------------------------------------------------===//
package llvm
/*
#include "llvm-c/Core.h"
#include "llvm-c/Target.h"
#include "llvm-c/TargetMachine.h"
#include <stdlib.h>
*/
import "C"
import "unsafe"
import "errors"
type (
TargetData struct {
C C.LLVMTargetDataRef
}
Target struct {
C C.LLVMTargetRef
}
TargetMachine struct {
C C.LLVMTargetMachineRef
}
ByteOrdering C.enum_LLVMByteOrdering
RelocMode C.LLVMRelocMode
CodeGenOptLevel C.LLVMCodeGenOptLevel
CodeGenFileType C.LLVMCodeGenFileType
CodeModel C.LLVMCodeModel
)
const (
BigEndian ByteOrdering = C.LLVMBigEndian
LittleEndian ByteOrdering = C.LLVMLittleEndian
)
const (
RelocDefault RelocMode = C.LLVMRelocDefault
RelocStatic RelocMode = C.LLVMRelocStatic
RelocPIC RelocMode = C.LLVMRelocPIC
RelocDynamicNoPic RelocMode = C.LLVMRelocDynamicNoPic
)
const (
CodeGenLevelNone CodeGenOptLevel = C.LLVMCodeGenLevelNone
CodeGenLevelLess CodeGenOptLevel = C.LLVMCodeGenLevelLess
CodeGenLevelDefault CodeGenOptLevel = C.LLVMCodeGenLevelDefault
CodeGenLevelAggressive CodeGenOptLevel = C.LLVMCodeGenLevelAggressive
)
const (
CodeModelDefault CodeModel = C.LLVMCodeModelDefault
CodeModelJITDefault CodeModel = C.LLVMCodeModelJITDefault
CodeModelTiny CodeModel = C.LLVMCodeModelTiny
CodeModelSmall CodeModel = C.LLVMCodeModelSmall
CodeModelKernel CodeModel = C.LLVMCodeModelKernel
CodeModelMedium CodeModel = C.LLVMCodeModelMedium
CodeModelLarge CodeModel = C.LLVMCodeModelLarge
)
const (
AssemblyFile CodeGenFileType = C.LLVMAssemblyFile
ObjectFile CodeGenFileType = C.LLVMObjectFile
)
// InitializeAllTargetInfos - The main program should call this function if it
// wants access to all available targets that LLVM is configured to support.
func InitializeAllTargetInfos() { C.LLVMInitializeAllTargetInfos() }
// InitializeAllTargets - The main program should call this function if it wants
// to link in all available targets that LLVM is configured to support.
func InitializeAllTargets() { C.LLVMInitializeAllTargets() }
func InitializeAllTargetMCs() { C.LLVMInitializeAllTargetMCs() }
func InitializeAllAsmParsers() { C.LLVMInitializeAllAsmParsers() }
func InitializeAllAsmPrinters() { C.LLVMInitializeAllAsmPrinters() }
var initializeNativeTargetError = errors.New("Failed to initialize native target")
// InitializeNativeTarget - The main program should call this function to
// initialize the native target corresponding to the host. This is useful
// for JIT applications to ensure that the target gets linked in correctly.
func InitializeNativeTarget() error {
fail := C.LLVMInitializeNativeTarget()
if fail != 0 {
return initializeNativeTargetError
}
return nil
}
func InitializeNativeAsmPrinter() error {
fail := C.LLVMInitializeNativeAsmPrinter()
if fail != 0 {
return initializeNativeTargetError
}
return nil
}
//-------------------------------------------------------------------------
// llvm.TargetData
//-------------------------------------------------------------------------
// Creates target data from a target layout string.
// See the constructor llvm::TargetData::TargetData.
func NewTargetData(rep string) (td TargetData) {
crep := C.CString(rep)
defer C.free(unsafe.Pointer(crep))
td.C = C.LLVMCreateTargetData(crep)
return
}
// Converts target data to a target layout string. The string must be disposed
// with LLVMDisposeMessage.
// See the constructor llvm::TargetData::TargetData.
func (td TargetData) String() (s string) {
cmsg := C.LLVMCopyStringRepOfTargetData(td.C)
s = C.GoString(cmsg)
C.LLVMDisposeMessage(cmsg)
return
}
// Returns the byte order of a target, either BigEndian or LittleEndian.
// See the method llvm::TargetData::isLittleEndian.
func (td TargetData) ByteOrder() ByteOrdering { return ByteOrdering(C.LLVMByteOrder(td.C)) }
// Returns the pointer size in bytes for a target.
// See the method llvm::TargetData::getPointerSize.
func (td TargetData) PointerSize() int { return int(C.LLVMPointerSize(td.C)) }
// Returns the integer type that is the same size as a pointer on a target.
// See the method llvm::TargetData::getIntPtrType.
func (td TargetData) IntPtrType() (t Type) { t.C = C.LLVMIntPtrType(td.C); return }
// Computes the size of a type in bytes for a target.
// See the method llvm::TargetData::getTypeSizeInBits.
func (td TargetData) TypeSizeInBits(t Type) uint64 {
return uint64(C.LLVMSizeOfTypeInBits(td.C, t.C))
}
// Computes the storage size of a type in bytes for a target.
// See the method llvm::TargetData::getTypeStoreSize.
func (td TargetData) TypeStoreSize(t Type) uint64 {
return uint64(C.LLVMStoreSizeOfType(td.C, t.C))
}
// Computes the ABI size of a type in bytes for a target.
// See the method llvm::TargetData::getTypeAllocSize.
func (td TargetData) TypeAllocSize(t Type) uint64 {
return uint64(C.LLVMABISizeOfType(td.C, t.C))
}
// Computes the ABI alignment of a type in bytes for a target.
// See the method llvm::TargetData::getABITypeAlignment.
func (td TargetData) ABITypeAlignment(t Type) int {
return int(C.LLVMABIAlignmentOfType(td.C, t.C))
}
// Computes the call frame alignment of a type in bytes for a target.
// See the method llvm::TargetData::getCallFrameTypeAlignment.
func (td TargetData) CallFrameTypeAlignment(t Type) int {
return int(C.LLVMCallFrameAlignmentOfType(td.C, t.C))
}
// Computes the preferred alignment of a type in bytes for a target.
// See the method llvm::TargetData::getPrefTypeAlignment.
func (td TargetData) PrefTypeAlignment(t Type) int {
return int(C.LLVMPreferredAlignmentOfType(td.C, t.C))
}
// Computes the preferred alignment of a global variable in bytes for a target.
// See the method llvm::TargetData::getPreferredAlignment.
func (td TargetData) PreferredAlignment(g Value) int {
return int(C.LLVMPreferredAlignmentOfGlobal(td.C, g.C))
}
// Computes the structure element that contains the byte offset for a target.
// See the method llvm::StructLayout::getElementContainingOffset.
func (td TargetData) ElementContainingOffset(t Type, offset uint64) int {
return int(C.LLVMElementAtOffset(td.C, t.C, C.ulonglong(offset)))
}
// Computes the byte offset of the indexed struct element for a target.
// See the method llvm::StructLayout::getElementOffset.
func (td TargetData) ElementOffset(t Type, element int) uint64 {
return uint64(C.LLVMOffsetOfElement(td.C, t.C, C.unsigned(element)))
}
// Deallocates a TargetData.
// See the destructor llvm::TargetData::~TargetData.
func (td TargetData) Dispose() { C.LLVMDisposeTargetData(td.C) }
//-------------------------------------------------------------------------
// llvm.Target
//-------------------------------------------------------------------------
func FirstTarget() Target {
return Target{C.LLVMGetFirstTarget()}
}
func (t Target) NextTarget() Target {
return Target{C.LLVMGetNextTarget(t.C)}
}
func GetTargetFromTriple(triple string) (t Target, err error) {
var errstr *C.char
ctriple := C.CString(triple)
defer C.free(unsafe.Pointer(ctriple))
fail := C.LLVMGetTargetFromTriple(ctriple, &t.C, &errstr)
if fail != 0 {
err = errors.New(C.GoString(errstr))
C.free(unsafe.Pointer(errstr))
}
return
}
func (t Target) Name() string {
return C.GoString(C.LLVMGetTargetName(t.C))
}
func (t Target) Description() string {
return C.GoString(C.LLVMGetTargetDescription(t.C))
}
//-------------------------------------------------------------------------
// llvm.TargetMachine
//-------------------------------------------------------------------------
// CreateTargetMachine creates a new TargetMachine.
func (t Target) CreateTargetMachine(Triple string, CPU string, Features string,
Level CodeGenOptLevel, Reloc RelocMode,
CodeModel CodeModel) (tm TargetMachine) {
cTriple := C.CString(Triple)
defer C.free(unsafe.Pointer(cTriple))
cCPU := C.CString(CPU)
defer C.free(unsafe.Pointer(cCPU))
cFeatures := C.CString(Features)
defer C.free(unsafe.Pointer(cFeatures))
tm.C = C.LLVMCreateTargetMachine(t.C, cTriple, cCPU, cFeatures,
C.LLVMCodeGenOptLevel(Level),
C.LLVMRelocMode(Reloc),
C.LLVMCodeModel(CodeModel))
return
}
// CreateTargetData returns a new TargetData describing the TargetMachine's
// data layout. The returned TargetData is owned by the caller, who is
// responsible for disposing of it by calling the TargetData.Dispose method.
func (tm TargetMachine) CreateTargetData() TargetData {
return TargetData{C.LLVMCreateTargetDataLayout(tm.C)}
}
// Triple returns the triple describing the machine (arch-vendor-os).
func (tm TargetMachine) Triple() string {
cstr := C.LLVMGetTargetMachineTriple(tm.C)
return C.GoString(cstr)
}
func (tm TargetMachine) EmitToMemoryBuffer(m Module, ft CodeGenFileType) (MemoryBuffer, error) {
var errstr *C.char
var mb MemoryBuffer
fail := C.LLVMTargetMachineEmitToMemoryBuffer(tm.C, m.C, C.LLVMCodeGenFileType(ft), &errstr, &mb.C)
if fail != 0 {
err := errors.New(C.GoString(errstr))
C.free(unsafe.Pointer(errstr))
return MemoryBuffer{}, err
}
return mb, nil
}
func (tm TargetMachine) AddAnalysisPasses(pm PassManager) {
C.LLVMAddAnalysisPasses(tm.C, pm.C)
}
// Dispose releases resources related to the TargetMachine.
func (tm TargetMachine) Dispose() {
C.LLVMDisposeTargetMachine(tm.C)
}
func DefaultTargetTriple() (triple string) {
cTriple := C.LLVMGetDefaultTargetTriple()
defer C.free(unsafe.Pointer(cTriple))
triple = C.GoString(cTriple)
return
}

View File

@ -0,0 +1,23 @@
//===- transforms_coroutines.go - Bindings for coroutines -----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines bindings for the coroutines component.
//
//===----------------------------------------------------------------------===//
package llvm
/*
#include "llvm-c/Transforms/Coroutines.h"
*/
import "C"
func (pm PassManager) AddCoroEarlyPass() { C.LLVMAddCoroEarlyPass(pm.C) }
func (pm PassManager) AddCoroSplitPass() { C.LLVMAddCoroSplitPass(pm.C) }
func (pm PassManager) AddCoroElidePass() { C.LLVMAddCoroElidePass(pm.C) }
func (pm PassManager) AddCoroCleanupPass() { C.LLVMAddCoroCleanupPass(pm.C) }

View File

@ -0,0 +1,45 @@
//===- transforms_instrumentation.go - Bindings for instrumentation -------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines bindings for the instrumentation component.
//
//===----------------------------------------------------------------------===//
package llvm
/*
#include "InstrumentationBindings.h"
#include <stdlib.h>
*/
import "C"
import "unsafe"
func (pm PassManager) AddAddressSanitizerFunctionPass() {
C.LLVMAddAddressSanitizerFunctionPass(pm.C)
}
func (pm PassManager) AddAddressSanitizerModulePass() {
C.LLVMAddAddressSanitizerModulePass(pm.C)
}
func (pm PassManager) AddThreadSanitizerPass() {
C.LLVMAddThreadSanitizerPass(pm.C)
}
func (pm PassManager) AddMemorySanitizerLegacyPassPass() {
C.LLVMAddMemorySanitizerLegacyPassPass(pm.C)
}
func (pm PassManager) AddDataFlowSanitizerPass(abilist []string) {
abiliststrs := make([]*C.char, len(abilist))
for i, arg := range abilist {
abiliststrs[i] = C.CString(arg)
defer C.free(unsafe.Pointer(abiliststrs[i]))
}
C.LLVMAddDataFlowSanitizerPass(pm.C, C.int(len(abilist)), &abiliststrs[0])
}

View File

@ -0,0 +1,40 @@
//===- transforms_ipo.go - Bindings for ipo -------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines bindings for the ipo component.
//
//===----------------------------------------------------------------------===//
package llvm
/*
#include "llvm-c/Transforms/IPO.h"
*/
import "C"
// helpers
func boolToUnsigned(b bool) C.unsigned {
if b {
return 1
}
return 0
}
func (pm PassManager) AddArgumentPromotionPass() { C.LLVMAddArgumentPromotionPass(pm.C) }
func (pm PassManager) AddConstantMergePass() { C.LLVMAddConstantMergePass(pm.C) }
func (pm PassManager) AddDeadArgEliminationPass() { C.LLVMAddDeadArgEliminationPass(pm.C) }
func (pm PassManager) AddFunctionAttrsPass() { C.LLVMAddFunctionAttrsPass(pm.C) }
func (pm PassManager) AddFunctionInliningPass() { C.LLVMAddFunctionInliningPass(pm.C) }
func (pm PassManager) AddGlobalDCEPass() { C.LLVMAddGlobalDCEPass(pm.C) }
func (pm PassManager) AddGlobalOptimizerPass() { C.LLVMAddGlobalOptimizerPass(pm.C) }
func (pm PassManager) AddPruneEHPass() { C.LLVMAddPruneEHPass(pm.C) }
func (pm PassManager) AddIPSCCPPass() { C.LLVMAddIPSCCPPass(pm.C) }
func (pm PassManager) AddInternalizePass(allButMain bool) {
C.LLVMAddInternalizePass(pm.C, boolToUnsigned(allButMain))
}
func (pm PassManager) AddStripDeadPrototypesPass() { C.LLVMAddStripDeadPrototypesPass(pm.C) }

View File

@ -0,0 +1,72 @@
//===- transforms_pmbuilder.go - Bindings for PassManagerBuilder ----------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines bindings for the PassManagerBuilder class.
//
//===----------------------------------------------------------------------===//
package llvm
/*
#include "llvm-c/Transforms/PassManagerBuilder.h"
#include "llvm-c/Transforms/Coroutines.h"
*/
import "C"
type PassManagerBuilder struct {
C C.LLVMPassManagerBuilderRef
}
func NewPassManagerBuilder() (pmb PassManagerBuilder) {
pmb.C = C.LLVMPassManagerBuilderCreate()
return
}
func (pmb PassManagerBuilder) SetOptLevel(level int) {
C.LLVMPassManagerBuilderSetOptLevel(pmb.C, C.uint(level))
}
func (pmb PassManagerBuilder) SetSizeLevel(level int) {
C.LLVMPassManagerBuilderSetSizeLevel(pmb.C, C.uint(level))
}
func (pmb PassManagerBuilder) Populate(pm PassManager) {
C.LLVMPassManagerBuilderPopulateModulePassManager(pmb.C, pm.C)
}
func (pmb PassManagerBuilder) PopulateFunc(pm PassManager) {
C.LLVMPassManagerBuilderPopulateFunctionPassManager(pmb.C, pm.C)
}
func (pmb PassManagerBuilder) PopulateLTOPassManager(pm PassManager, internalize bool, runInliner bool) {
C.LLVMPassManagerBuilderPopulateLTOPassManager(pmb.C, pm.C, boolToLLVMBool(internalize), boolToLLVMBool(runInliner))
}
func (pmb PassManagerBuilder) Dispose() {
C.LLVMPassManagerBuilderDispose(pmb.C)
}
func (pmb PassManagerBuilder) SetDisableUnitAtATime(val bool) {
C.LLVMPassManagerBuilderSetDisableUnitAtATime(pmb.C, boolToLLVMBool(val))
}
func (pmb PassManagerBuilder) SetDisableUnrollLoops(val bool) {
C.LLVMPassManagerBuilderSetDisableUnrollLoops(pmb.C, boolToLLVMBool(val))
}
func (pmb PassManagerBuilder) SetDisableSimplifyLibCalls(val bool) {
C.LLVMPassManagerBuilderSetDisableSimplifyLibCalls(pmb.C, boolToLLVMBool(val))
}
func (pmb PassManagerBuilder) UseInlinerWithThreshold(threshold uint) {
C.LLVMPassManagerBuilderUseInlinerWithThreshold(pmb.C, C.uint(threshold))
}
func (pmb PassManagerBuilder) AddCoroutinePassesToExtensionPoints() {
C.LLVMPassManagerBuilderAddCoroutinePassesToExtensionPoints(pmb.C);
}

View File

@ -0,0 +1,44 @@
//===- transforms_scalar.go - Bindings for scalaropts ---------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines bindings for the scalaropts component.
//
//===----------------------------------------------------------------------===//
package llvm
/*
#include "llvm-c/Transforms/Scalar.h"
#include "llvm-c/Transforms/Utils.h"
*/
import "C"
func (pm PassManager) AddAggressiveDCEPass() { C.LLVMAddAggressiveDCEPass(pm.C) }
func (pm PassManager) AddCFGSimplificationPass() { C.LLVMAddCFGSimplificationPass(pm.C) }
func (pm PassManager) AddDeadStoreEliminationPass() { C.LLVMAddDeadStoreEliminationPass(pm.C) }
func (pm PassManager) AddGVNPass() { C.LLVMAddGVNPass(pm.C) }
func (pm PassManager) AddIndVarSimplifyPass() { C.LLVMAddIndVarSimplifyPass(pm.C) }
func (pm PassManager) AddInstructionCombiningPass() { C.LLVMAddInstructionCombiningPass(pm.C) }
func (pm PassManager) AddJumpThreadingPass() { C.LLVMAddJumpThreadingPass(pm.C) }
func (pm PassManager) AddLICMPass() { C.LLVMAddLICMPass(pm.C) }
func (pm PassManager) AddLoopDeletionPass() { C.LLVMAddLoopDeletionPass(pm.C) }
func (pm PassManager) AddLoopRotatePass() { C.LLVMAddLoopRotatePass(pm.C) }
func (pm PassManager) AddLoopUnrollPass() { C.LLVMAddLoopUnrollPass(pm.C) }
func (pm PassManager) AddLoopUnswitchPass() { C.LLVMAddLoopUnswitchPass(pm.C) }
func (pm PassManager) AddMemCpyOptPass() { C.LLVMAddMemCpyOptPass(pm.C) }
func (pm PassManager) AddPromoteMemoryToRegisterPass() { C.LLVMAddPromoteMemoryToRegisterPass(pm.C) }
func (pm PassManager) AddReassociatePass() { C.LLVMAddReassociatePass(pm.C) }
func (pm PassManager) AddSCCPPass() { C.LLVMAddSCCPPass(pm.C) }
func (pm PassManager) AddScalarReplAggregatesPass() { C.LLVMAddScalarReplAggregatesPass(pm.C) }
func (pm PassManager) AddScalarReplAggregatesPassWithThreshold(threshold int) {
C.LLVMAddScalarReplAggregatesPassWithThreshold(pm.C, C.int(threshold))
}
func (pm PassManager) AddSimplifyLibCallsPass() { C.LLVMAddSimplifyLibCallsPass(pm.C) }
func (pm PassManager) AddTailCallEliminationPass() { C.LLVMAddTailCallEliminationPass(pm.C) }
func (pm PassManager) AddDemoteMemoryToRegisterPass() { C.LLVMAddDemoteMemoryToRegisterPass(pm.C) }
func (pm PassManager) AddVerifierPass() { C.LLVMAddVerifierPass(pm.C) }

View File

@ -0,0 +1,20 @@
//===- version.go - LLVM version info -------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines LLVM version information.
//
//===----------------------------------------------------------------------===//
package llvm
/*
#include "llvm/Config/llvm-config.h"
*/
import "C"
const Version = C.LLVM_VERSION_STRING

View File

@ -0,0 +1,11 @@
add_subdirectory(llvm)
add_subdirectory(all_backends)
add_subdirectory(analysis)
add_subdirectory(backends)
add_subdirectory(bitreader)
add_subdirectory(bitwriter)
add_subdirectory(irreader)
add_subdirectory(linker)
add_subdirectory(target)
add_subdirectory(transforms)
add_subdirectory(executionengine)

29
bindings/ocaml/README.txt Normal file
View File

@ -0,0 +1,29 @@
This directory contains LLVM bindings for the OCaml programming language
(http://ocaml.org).
Prerequisites
-------------
* OCaml 4.00.0+.
* ctypes 0.4+.
* oUnit 2+ (only required for tests).
* CMake (to build LLVM).
Building the bindings
---------------------
If all dependencies are present, the bindings will be built and installed
as a part of the default CMake configuration, with no further action.
They will only work with the specific OCaml compiler detected during the build.
The bindings can also be built out-of-tree, i.e. targeting a preinstalled
LLVM. To do this, configure the LLVM build tree as follows:
$ cmake -DLLVM_OCAML_OUT_OF_TREE=TRUE \
-DCMAKE_INSTALL_PREFIX=[OCaml install prefix] \
[... any other options]
then build and install it as:
$ make ocaml_all
$ cmake -P bindings/ocaml/cmake_install.cmake

View File

@ -0,0 +1,5 @@
add_ocaml_library(llvm_all_backends
OCAML llvm_all_backends
OCAMLDEP llvm
C all_backends_ocaml
LLVM ${LLVM_TARGETS_TO_BUILD})

View File

@ -0,0 +1,32 @@
/*===-- all_backends_ocaml.c - LLVM OCaml Glue ------------------*- C++ -*-===*\
|* *|
|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *|
|* Exceptions. *|
|* See https://llvm.org/LICENSE.txt for license information. *|
|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This file glues LLVM's OCaml interface to its C interface. These functions *|
|* are by and large transparent wrappers to the corresponding C functions. *|
|* *|
|* Note that these functions intentionally take liberties with the CAMLparamX *|
|* macros, since most of the parameters are not GC heap objects. *|
|* *|
\*===----------------------------------------------------------------------===*/
#include "llvm-c/Target.h"
#include "caml/alloc.h"
#include "caml/fail.h"
#include "caml/memory.h"
#include "caml/custom.h"
/* unit -> unit */
CAMLprim value llvm_initialize_all(value Unit) {
LLVMInitializeAllTargetInfos();
LLVMInitializeAllTargets();
LLVMInitializeAllTargetMCs();
LLVMInitializeAllAsmPrinters();
LLVMInitializeAllAsmParsers();
return Val_unit;
}

View File

@ -0,0 +1,9 @@
(*===-- llvm_all_backends.ml - LLVM OCaml Interface -----------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
external initialize : unit -> unit = "llvm_initialize_all"

View File

@ -0,0 +1,10 @@
(*===-- llvm_all_backends.mli - LLVM OCaml Interface ----------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
(** Initialize all the backends targets *)
val initialize : unit -> unit

View File

@ -0,0 +1,5 @@
add_ocaml_library(llvm_analysis
OCAML llvm_analysis
OCAMLDEP llvm
C analysis_ocaml
LLVM Analysis)

View File

@ -0,0 +1,72 @@
/*===-- analysis_ocaml.c - LLVM OCaml Glue ----------------------*- C++ -*-===*\
|* *|
|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *|
|* Exceptions. *|
|* See https://llvm.org/LICENSE.txt for license information. *|
|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This file glues LLVM's OCaml interface to its C interface. These functions *|
|* are by and large transparent wrappers to the corresponding C functions. *|
|* *|
|* Note that these functions intentionally take liberties with the CAMLparamX *|
|* macros, since most of the parameters are not GC heap objects. *|
|* *|
\*===----------------------------------------------------------------------===*/
#include "llvm-c/Analysis.h"
#include "llvm-c/Core.h"
#include "caml/alloc.h"
#include "caml/mlvalues.h"
#include "caml/memory.h"
/* Llvm.llmodule -> string option */
CAMLprim value llvm_verify_module(LLVMModuleRef M) {
CAMLparam0();
CAMLlocal2(String, Option);
char *Message;
int Result = LLVMVerifyModule(M, LLVMReturnStatusAction, &Message);
if (0 == Result) {
Option = Val_int(0);
} else {
Option = alloc(1, 0);
String = copy_string(Message);
Store_field(Option, 0, String);
}
LLVMDisposeMessage(Message);
CAMLreturn(Option);
}
/* Llvm.llvalue -> bool */
CAMLprim value llvm_verify_function(LLVMValueRef Fn) {
return Val_bool(LLVMVerifyFunction(Fn, LLVMReturnStatusAction) == 0);
}
/* Llvm.llmodule -> unit */
CAMLprim value llvm_assert_valid_module(LLVMModuleRef M) {
LLVMVerifyModule(M, LLVMAbortProcessAction, 0);
return Val_unit;
}
/* Llvm.llvalue -> unit */
CAMLprim value llvm_assert_valid_function(LLVMValueRef Fn) {
LLVMVerifyFunction(Fn, LLVMAbortProcessAction);
return Val_unit;
}
/* Llvm.llvalue -> unit */
CAMLprim value llvm_view_function_cfg(LLVMValueRef Fn) {
LLVMViewFunctionCFG(Fn);
return Val_unit;
}
/* Llvm.llvalue -> unit */
CAMLprim value llvm_view_function_cfg_only(LLVMValueRef Fn) {
LLVMViewFunctionCFGOnly(Fn);
return Val_unit;
}

View File

@ -0,0 +1,21 @@
(*===-- llvm_analysis.ml - LLVM OCaml Interface ---------------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
external verify_module : Llvm.llmodule -> string option = "llvm_verify_module"
external verify_function : Llvm.llvalue -> bool = "llvm_verify_function"
external assert_valid_module : Llvm.llmodule -> unit
= "llvm_assert_valid_module"
external assert_valid_function : Llvm.llvalue -> unit
= "llvm_assert_valid_function"
external view_function_cfg : Llvm.llvalue -> unit = "llvm_view_function_cfg"
external view_function_cfg_only : Llvm.llvalue -> unit
= "llvm_view_function_cfg_only"

View File

@ -0,0 +1,45 @@
(*===-- llvm_analysis.mli - LLVM OCaml Interface --------------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
(** Intermediate representation analysis.
This interface provides an OCaml API for LLVM IR analyses, the classes in
the Analysis library. *)
(** [verify_module m] returns [None] if the module [m] is valid, and
[Some reason] if it is invalid. [reason] is a string containing a
human-readable validation report. See [llvm::verifyModule]. *)
external verify_module : Llvm.llmodule -> string option = "llvm_verify_module"
(** [verify_function f] returns [None] if the function [f] is valid, and
[Some reason] if it is invalid. [reason] is a string containing a
human-readable validation report. See [llvm::verifyFunction]. *)
external verify_function : Llvm.llvalue -> bool = "llvm_verify_function"
(** [verify_module m] returns if the module [m] is valid, but prints a
validation report to [stderr] and aborts the program if it is invalid. See
[llvm::verifyModule]. *)
external assert_valid_module : Llvm.llmodule -> unit
= "llvm_assert_valid_module"
(** [verify_function f] returns if the function [f] is valid, but prints a
validation report to [stderr] and aborts the program if it is invalid. See
[llvm::verifyFunction]. *)
external assert_valid_function : Llvm.llvalue -> unit
= "llvm_assert_valid_function"
(** [view_function_cfg f] opens up a ghostscript window displaying the CFG of
the current function with the code for each basic block inside.
See [llvm::Function::viewCFG]. *)
external view_function_cfg : Llvm.llvalue -> unit = "llvm_view_function_cfg"
(** [view_function_cfg_only f] works just like [view_function_cfg], but does not
include the contents of basic blocks into the nodes.
See [llvm::Function::viewCFGOnly]. *)
external view_function_cfg_only : Llvm.llvalue -> unit
= "llvm_view_function_cfg_only"

View File

@ -0,0 +1,27 @@
foreach(TARGET ${LLVM_TARGETS_TO_BUILD})
set(OCAML_LLVM_TARGET ${TARGET})
foreach( ext ml mli )
configure_file(
"${CMAKE_CURRENT_SOURCE_DIR}/llvm_backend.${ext}.in"
"${CMAKE_CURRENT_BINARY_DIR}/llvm_${TARGET}.${ext}")
endforeach()
configure_file(
"${CMAKE_CURRENT_SOURCE_DIR}/backend_ocaml.c"
"${CMAKE_CURRENT_BINARY_DIR}/${TARGET}_ocaml.c")
add_ocaml_library(llvm_${TARGET}
OCAML llvm_${TARGET}
C ${TARGET}_ocaml
CFLAGS -DTARGET=${TARGET}
LLVM ${TARGET}
NOCOPY)
configure_file(
"${CMAKE_CURRENT_SOURCE_DIR}/META.llvm_backend.in"
"${LLVM_LIBRARY_DIR}/ocaml/META.llvm_${TARGET}")
install(FILES "${LLVM_LIBRARY_DIR}/ocaml/META.llvm_${TARGET}"
DESTINATION "${LLVM_OCAML_INSTALL_PATH}")
endforeach()

View File

@ -0,0 +1,7 @@
name = "llvm_@TARGET@"
version = "@PACKAGE_VERSION@"
description = "@TARGET@ Backend for LLVM"
requires = "llvm"
archive(byte) = "llvm_@TARGET@.cma"
archive(native) = "llvm_@TARGET@.cmxa"
directory = "llvm"

View File

@ -0,0 +1,38 @@
/*===-- backend_ocaml.c - LLVM OCaml Glue -----------------------*- C++ -*-===*\
|* *|
|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *|
|* Exceptions. *|
|* See https://llvm.org/LICENSE.txt for license information. *|
|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This file glues LLVM's OCaml interface to its C interface. These functions *|
|* are by and large transparent wrappers to the corresponding C functions. *|
|* *|
|* Note that these functions intentionally take liberties with the CAMLparamX *|
|* macros, since most of the parameters are not GC heap objects. *|
|* *|
\*===----------------------------------------------------------------------===*/
#include "llvm-c/Target.h"
#include "caml/alloc.h"
#include "caml/memory.h"
/* TODO: Figure out how to call these only for targets which support them.
* LLVMInitialize ## target ## AsmPrinter();
* LLVMInitialize ## target ## AsmParser();
* LLVMInitialize ## target ## Disassembler();
*/
#define INITIALIZER1(target) \
CAMLprim value llvm_initialize_ ## target(value Unit) { \
LLVMInitialize ## target ## TargetInfo(); \
LLVMInitialize ## target ## Target(); \
LLVMInitialize ## target ## TargetMC(); \
return Val_unit; \
}
#define INITIALIZER(target) INITIALIZER1(target)
INITIALIZER(TARGET)

View File

@ -0,0 +1,9 @@
(*===-- llvm_backend.ml.in - LLVM OCaml Interface -------------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
external initialize : unit -> unit = "llvm_initialize_@TARGET@"

View File

@ -0,0 +1,18 @@
(*===-- llvm_backend.mli.in - LLVM OCaml Interface ------------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
(** @TARGET@ Initialization.
This interface provides an OCaml API for initialization of
the @TARGET@ LLVM target. By referencing this module, you will cause
OCaml to load or link in the LLVM libraries corresponding to the target.
By calling [initialize], you will register components of this target
in the target registry, which is necessary in order to emit assembly,
object files, and so on. *)
external initialize : unit -> unit = "llvm_initialize_@TARGET@"

View File

@ -0,0 +1,5 @@
add_ocaml_library(llvm_bitreader
OCAML llvm_bitreader
OCAMLDEP llvm
C bitreader_ocaml
LLVM BitReader)

View File

@ -0,0 +1,42 @@
/*===-- bitwriter_ocaml.c - LLVM OCaml Glue ---------------------*- C++ -*-===*\
|* *|
|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *|
|* Exceptions. *|
|* See https://llvm.org/LICENSE.txt for license information. *|
|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This file glues LLVM's OCaml interface to its C interface. These functions *|
|* are by and large transparent wrappers to the corresponding C functions. *|
|* *|
\*===----------------------------------------------------------------------===*/
#include "llvm-c/BitReader.h"
#include "llvm-c/Core.h"
#include "caml/alloc.h"
#include "caml/fail.h"
#include "caml/memory.h"
#include "caml/callback.h"
void llvm_raise(value Prototype, char *Message);
/* Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule */
CAMLprim LLVMModuleRef llvm_get_module(LLVMContextRef C, LLVMMemoryBufferRef MemBuf) {
LLVMModuleRef M;
if (LLVMGetBitcodeModuleInContext2(C, MemBuf, &M))
llvm_raise(*caml_named_value("Llvm_bitreader.Error"), LLVMCreateMessage(""));
return M;
}
/* Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule */
CAMLprim LLVMModuleRef llvm_parse_bitcode(LLVMContextRef C, LLVMMemoryBufferRef MemBuf) {
LLVMModuleRef M;
if (LLVMParseBitcodeInContext2(C, MemBuf, &M))
llvm_raise(*caml_named_value("Llvm_bitreader.Error"), LLVMCreateMessage(""));
return M;
}

View File

@ -0,0 +1,18 @@
(*===-- llvm_bitreader.ml - LLVM OCaml Interface --------------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
exception Error of string
let () = Callback.register_exception "Llvm_bitreader.Error" (Error "")
external get_module
: Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule
= "llvm_get_module"
external parse_bitcode
: Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule
= "llvm_parse_bitcode"

View File

@ -0,0 +1,26 @@
(*===-- llvm_bitreader.mli - LLVM OCaml Interface -------------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
(** Bitcode reader.
This interface provides an OCaml API for the LLVM bitcode reader, the
classes in the Bitreader library. *)
exception Error of string
(** [get_module context mb] reads the bitcode for a new module [m] from the
memory buffer [mb] in the context [context]. Returns [m] if successful, or
raises [Error msg] otherwise, where [msg] is a description of the error
encountered. See the function [llvm::getBitcodeModule]. *)
val get_module : Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule
(** [parse_bitcode context mb] parses the bitcode for a new module [m] from the
memory buffer [mb] in the context [context]. Returns [m] if successful, or
raises [Error msg] otherwise, where [msg] is a description of the error
encountered. See the function [llvm::ParseBitcodeFile]. *)
val parse_bitcode : Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule

View File

@ -0,0 +1,5 @@
add_ocaml_library(llvm_bitwriter
OCAML llvm_bitwriter
OCAMLDEP llvm
C bitwriter_ocaml
LLVM BitWriter)

View File

@ -0,0 +1,48 @@
/*===-- bitwriter_ocaml.c - LLVM OCaml Glue ---------------------*- C++ -*-===*\
|* *|
|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *|
|* Exceptions. *|
|* See https://llvm.org/LICENSE.txt for license information. *|
|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This file glues LLVM's OCaml interface to its C interface. These functions *|
|* are by and large transparent wrappers to the corresponding C functions. *|
|* *|
|* Note that these functions intentionally take liberties with the CAMLparamX *|
|* macros, since most of the parameters are not GC heap objects. *|
|* *|
\*===----------------------------------------------------------------------===*/
#include "llvm-c/BitWriter.h"
#include "llvm-c/Core.h"
#include "caml/alloc.h"
#include "caml/mlvalues.h"
#include "caml/memory.h"
/* Llvm.llmodule -> string -> bool */
CAMLprim value llvm_write_bitcode_file(LLVMModuleRef M, value Path) {
int Result = LLVMWriteBitcodeToFile(M, String_val(Path));
return Val_bool(Result == 0);
}
/* ?unbuffered:bool -> Llvm.llmodule -> Unix.file_descr -> bool */
CAMLprim value llvm_write_bitcode_to_fd(value U, LLVMModuleRef M, value FD) {
int Unbuffered;
int Result;
if (U == Val_int(0)) {
Unbuffered = 0;
} else {
Unbuffered = Bool_val(Field(U, 0));
}
Result = LLVMWriteBitcodeToFD(M, Int_val(FD), 0, Unbuffered);
return Val_bool(Result == 0);
}
/* Llvm.llmodule -> Llvm.llmemorybuffer */
CAMLprim LLVMMemoryBufferRef llvm_write_bitcode_to_memory_buffer(LLVMModuleRef M) {
return LLVMWriteBitcodeToMemoryBuffer(M);
}

View File

@ -0,0 +1,27 @@
(*===-- llvm_bitwriter.ml - LLVM OCaml Interface --------------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===
*
* This interface provides an OCaml API for the LLVM intermediate
* representation, the classes in the VMCore library.
*
*===----------------------------------------------------------------------===*)
external write_bitcode_file
: Llvm.llmodule -> string -> bool
= "llvm_write_bitcode_file"
external write_bitcode_to_fd
: ?unbuffered:bool -> Llvm.llmodule -> Unix.file_descr -> bool
= "llvm_write_bitcode_to_fd"
external write_bitcode_to_memory_buffer
: Llvm.llmodule -> Llvm.llmemorybuffer
= "llvm_write_bitcode_to_memory_buffer"
let output_bitcode ?unbuffered channel m =
write_bitcode_to_fd ?unbuffered m (Unix.descr_of_out_channel channel)

View File

@ -0,0 +1,36 @@
(*===-- llvm_bitwriter.mli - LLVM OCaml Interface -------------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
(** Bitcode writer.
This interface provides an OCaml API for the LLVM bitcode writer, the
classes in the Bitwriter library. *)
(** [write_bitcode_file m path] writes the bitcode for module [m] to the file at
[path]. Returns [true] if successful, [false] otherwise. *)
external write_bitcode_file
: Llvm.llmodule -> string -> bool
= "llvm_write_bitcode_file"
(** [write_bitcode_to_fd ~unbuffered fd m] writes the bitcode for module
[m] to the channel [c]. If [unbuffered] is [true], after every write the fd
will be flushed. Returns [true] if successful, [false] otherwise. *)
external write_bitcode_to_fd
: ?unbuffered:bool -> Llvm.llmodule -> Unix.file_descr -> bool
= "llvm_write_bitcode_to_fd"
(** [write_bitcode_to_memory_buffer m] returns a memory buffer containing
the bitcode for module [m]. *)
external write_bitcode_to_memory_buffer
: Llvm.llmodule -> Llvm.llmemorybuffer
= "llvm_write_bitcode_to_memory_buffer"
(** [output_bitcode ~unbuffered c m] writes the bitcode for module [m]
to the channel [c]. If [unbuffered] is [true], after every write the fd
will be flushed. Returns [true] if successful, [false] otherwise. *)
val output_bitcode : ?unbuffered:bool -> out_channel -> Llvm.llmodule -> bool

View File

@ -0,0 +1,6 @@
add_ocaml_library(llvm_executionengine
OCAML llvm_executionengine
OCAMLDEP llvm llvm_target
C executionengine_ocaml
LLVM ExecutionEngine MCJIT native
PKG ctypes)

View File

@ -0,0 +1,127 @@
/*===-- executionengine_ocaml.c - LLVM OCaml Glue ---------------*- C++ -*-===*\
|* *|
|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *|
|* Exceptions. *|
|* See https://llvm.org/LICENSE.txt for license information. *|
|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This file glues LLVM's OCaml interface to its C interface. These functions *|
|* are by and large transparent wrappers to the corresponding C functions. *|
|* *|
|* Note that these functions intentionally take liberties with the CAMLparamX *|
|* macros, since most of the parameters are not GC heap objects. *|
|* *|
\*===----------------------------------------------------------------------===*/
#include <string.h>
#include <assert.h>
#include "llvm-c/Core.h"
#include "llvm-c/ExecutionEngine.h"
#include "llvm-c/Target.h"
#include "caml/alloc.h"
#include "caml/custom.h"
#include "caml/fail.h"
#include "caml/memory.h"
#include "caml/callback.h"
void llvm_raise(value Prototype, char *Message);
/* unit -> bool */
CAMLprim value llvm_ee_initialize(value Unit) {
LLVMLinkInMCJIT();
return Val_bool(!LLVMInitializeNativeTarget() &&
!LLVMInitializeNativeAsmParser() &&
!LLVMInitializeNativeAsmPrinter());
}
/* llmodule -> llcompileroption -> ExecutionEngine.t */
CAMLprim LLVMExecutionEngineRef llvm_ee_create(value OptRecordOpt, LLVMModuleRef M) {
value OptRecord;
LLVMExecutionEngineRef MCJIT;
char *Error;
struct LLVMMCJITCompilerOptions Options;
LLVMInitializeMCJITCompilerOptions(&Options, sizeof(Options));
if (OptRecordOpt != Val_int(0)) {
OptRecord = Field(OptRecordOpt, 0);
Options.OptLevel = Int_val(Field(OptRecord, 0));
Options.CodeModel = Int_val(Field(OptRecord, 1));
Options.NoFramePointerElim = Int_val(Field(OptRecord, 2));
Options.EnableFastISel = Int_val(Field(OptRecord, 3));
Options.MCJMM = NULL;
}
if (LLVMCreateMCJITCompilerForModule(&MCJIT, M, &Options,
sizeof(Options), &Error))
llvm_raise(*caml_named_value("Llvm_executionengine.Error"), Error);
return MCJIT;
}
/* ExecutionEngine.t -> unit */
CAMLprim value llvm_ee_dispose(LLVMExecutionEngineRef EE) {
LLVMDisposeExecutionEngine(EE);
return Val_unit;
}
/* llmodule -> ExecutionEngine.t -> unit */
CAMLprim value llvm_ee_add_module(LLVMModuleRef M, LLVMExecutionEngineRef EE) {
LLVMAddModule(EE, M);
return Val_unit;
}
/* llmodule -> ExecutionEngine.t -> llmodule */
CAMLprim value llvm_ee_remove_module(LLVMModuleRef M, LLVMExecutionEngineRef EE) {
LLVMModuleRef RemovedModule;
char *Error;
if (LLVMRemoveModule(EE, M, &RemovedModule, &Error))
llvm_raise(*caml_named_value("Llvm_executionengine.Error"), Error);
return Val_unit;
}
/* ExecutionEngine.t -> unit */
CAMLprim value llvm_ee_run_static_ctors(LLVMExecutionEngineRef EE) {
LLVMRunStaticConstructors(EE);
return Val_unit;
}
/* ExecutionEngine.t -> unit */
CAMLprim value llvm_ee_run_static_dtors(LLVMExecutionEngineRef EE) {
LLVMRunStaticDestructors(EE);
return Val_unit;
}
extern value llvm_alloc_data_layout(LLVMTargetDataRef TargetData);
/* ExecutionEngine.t -> Llvm_target.DataLayout.t */
CAMLprim value llvm_ee_get_data_layout(LLVMExecutionEngineRef EE) {
value DataLayout;
LLVMTargetDataRef OrigDataLayout;
char* TargetDataCStr;
OrigDataLayout = LLVMGetExecutionEngineTargetData(EE);
TargetDataCStr = LLVMCopyStringRepOfTargetData(OrigDataLayout);
DataLayout = llvm_alloc_data_layout(LLVMCreateTargetData(TargetDataCStr));
LLVMDisposeMessage(TargetDataCStr);
return DataLayout;
}
/* Llvm.llvalue -> int64 -> llexecutionengine -> unit */
CAMLprim value llvm_ee_add_global_mapping(LLVMValueRef Global, value Ptr,
LLVMExecutionEngineRef EE) {
LLVMAddGlobalMapping(EE, Global, (void*) (Int64_val(Ptr)));
return Val_unit;
}
CAMLprim value llvm_ee_get_global_value_address(value Name,
LLVMExecutionEngineRef EE) {
return caml_copy_int64((int64_t) LLVMGetGlobalValueAddress(EE, String_val(Name)));
}
CAMLprim value llvm_ee_get_function_address(value Name,
LLVMExecutionEngineRef EE) {
return caml_copy_int64((int64_t) LLVMGetFunctionAddress(EE, String_val(Name)));
}

View File

@ -0,0 +1,71 @@
(*===-- llvm_executionengine.ml - LLVM OCaml Interface --------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
exception Error of string
let () = Callback.register_exception "Llvm_executionengine.Error" (Error "")
external initialize : unit -> bool
= "llvm_ee_initialize"
type llexecutionengine
type llcompileroptions = {
opt_level: int;
code_model: Llvm_target.CodeModel.t;
no_framepointer_elim: bool;
enable_fast_isel: bool;
}
let default_compiler_options = {
opt_level = 0;
code_model = Llvm_target.CodeModel.JITDefault;
no_framepointer_elim = false;
enable_fast_isel = false }
external create : ?options:llcompileroptions -> Llvm.llmodule -> llexecutionengine
= "llvm_ee_create"
external dispose : llexecutionengine -> unit
= "llvm_ee_dispose"
external add_module : Llvm.llmodule -> llexecutionengine -> unit
= "llvm_ee_add_module"
external remove_module : Llvm.llmodule -> llexecutionengine -> unit
= "llvm_ee_remove_module"
external run_static_ctors : llexecutionengine -> unit
= "llvm_ee_run_static_ctors"
external run_static_dtors : llexecutionengine -> unit
= "llvm_ee_run_static_dtors"
external data_layout : llexecutionengine -> Llvm_target.DataLayout.t
= "llvm_ee_get_data_layout"
external add_global_mapping_ : Llvm.llvalue -> nativeint -> llexecutionengine -> unit
= "llvm_ee_add_global_mapping"
external get_global_value_address_ : string -> llexecutionengine -> nativeint
= "llvm_ee_get_global_value_address"
external get_function_address_ : string -> llexecutionengine -> nativeint
= "llvm_ee_get_function_address"
let add_global_mapping llval ptr ee =
add_global_mapping_ llval (Ctypes.raw_address_of_ptr (Ctypes.to_voidp ptr)) ee
let get_global_value_address name typ ee =
let vptr = get_global_value_address_ name ee in
if Nativeint.to_int vptr <> 0 then
let open Ctypes in !@ (coerce (ptr void) (ptr typ) (ptr_of_raw_address vptr))
else
raise (Error ("Value " ^ name ^ " not found"))
let get_function_address name typ ee =
let fptr = get_function_address_ name ee in
if Nativeint.to_int fptr <> 0 then
let open Ctypes in coerce (ptr void) typ (ptr_of_raw_address fptr)
else
raise (Error ("Function " ^ name ^ " not found"))
(* The following are not bound. Patches are welcome.
target_machine : llexecutionengine -> Llvm_target.TargetMachine.t
*)

View File

@ -0,0 +1,92 @@
(*===-- llvm_executionengine.mli - LLVM OCaml Interface -------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
(** JIT Interpreter.
This interface provides an OCaml API for LLVM execution engine (JIT/
interpreter), the classes in the [ExecutionEngine] library. *)
exception Error of string
(** [initialize ()] initializes the backend corresponding to the host.
Returns [true] if initialization is successful; [false] indicates
that there is no such backend or it is unable to emit object code
via MCJIT. *)
val initialize : unit -> bool
(** An execution engine is either a JIT compiler or an interpreter, capable of
directly loading an LLVM module and executing its functions without first
invoking a static compiler and generating a native executable. *)
type llexecutionengine
(** MCJIT compiler options. See [llvm::TargetOptions]. *)
type llcompileroptions = {
opt_level: int;
code_model: Llvm_target.CodeModel.t;
no_framepointer_elim: bool;
enable_fast_isel: bool;
}
(** Default MCJIT compiler options:
[{ opt_level = 0; code_model = CodeModel.JIT_default;
no_framepointer_elim = false; enable_fast_isel = false }] *)
val default_compiler_options : llcompileroptions
(** [create m optlevel] creates a new MCJIT just-in-time compiler, taking
ownership of the module [m] if successful with the desired optimization
level [optlevel]. Raises [Error msg] if an error occurrs. The execution
engine is not garbage collected and must be destroyed with [dispose ee].
Run {!initialize} before using this function.
See the function [llvm::EngineBuilder::create]. *)
val create : ?options:llcompileroptions -> Llvm.llmodule -> llexecutionengine
(** [dispose ee] releases the memory used by the execution engine and must be
invoked to avoid memory leaks. *)
val dispose : llexecutionengine -> unit
(** [add_module m ee] adds the module [m] to the execution engine [ee]. *)
val add_module : Llvm.llmodule -> llexecutionengine -> unit
(** [remove_module m ee] removes the module [m] from the execution engine
[ee]. Raises [Error msg] if an error occurs. *)
val remove_module : Llvm.llmodule -> llexecutionengine -> unit
(** [run_static_ctors ee] executes the static constructors of each module in
the execution engine [ee]. *)
val run_static_ctors : llexecutionengine -> unit
(** [run_static_dtors ee] executes the static destructors of each module in
the execution engine [ee]. *)
val run_static_dtors : llexecutionengine -> unit
(** [data_layout ee] is the data layout of the execution engine [ee]. *)
val data_layout : llexecutionengine -> Llvm_target.DataLayout.t
(** [add_global_mapping gv ptr ee] tells the execution engine [ee] that
the global [gv] is at the specified location [ptr], which must outlive
[gv] and [ee].
All uses of [gv] in the compiled code will refer to [ptr]. *)
val add_global_mapping : Llvm.llvalue -> 'a Ctypes.ptr -> llexecutionengine -> unit
(** [get_global_value_address id typ ee] returns a pointer to the
identifier [id] as type [typ], which will be a pointer type for a
value, and which will be live as long as [id] and [ee]
are. Caution: this function finalizes, i.e. forces code
generation, all loaded modules. Further modifications to the
modules will not have any effect. *)
val get_global_value_address : string -> 'a Ctypes.typ -> llexecutionengine -> 'a
(** [get_function_address fn typ ee] returns a pointer to the function
[fn] as type [typ], which will be a pointer type for a function
(e.g. [(int -> int) typ]), and which will be live as long as [fn]
and [ee] are. Caution: this function finalizes, i.e. forces code
generation, all loaded modules. Further modifications to the
modules will not have any effect. *)
val get_function_address : string -> 'a Ctypes.typ -> llexecutionengine -> 'a

View File

@ -0,0 +1,5 @@
add_ocaml_library(llvm_irreader
OCAML llvm_irreader
OCAMLDEP llvm
C irreader_ocaml
LLVM IRReader)

View File

@ -0,0 +1,35 @@
/*===-- irreader_ocaml.c - LLVM OCaml Glue ----------------------*- C++ -*-===*\
|* *|
|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *|
|* Exceptions. *|
|* See https://llvm.org/LICENSE.txt for license information. *|
|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This file glues LLVM's OCaml interface to its C interface. These functions *|
|* are by and large transparent wrappers to the corresponding C functions. *|
|* *|
\*===----------------------------------------------------------------------===*/
#include "llvm-c/IRReader.h"
#include "caml/alloc.h"
#include "caml/fail.h"
#include "caml/memory.h"
#include "caml/callback.h"
void llvm_raise(value Prototype, char *Message);
/* Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule */
CAMLprim value llvm_parse_ir(LLVMContextRef C,
LLVMMemoryBufferRef MemBuf) {
CAMLparam0();
CAMLlocal2(Variant, MessageVal);
LLVMModuleRef M;
char *Message;
if (LLVMParseIRInContext(C, MemBuf, &M, &Message))
llvm_raise(*caml_named_value("Llvm_irreader.Error"), Message);
CAMLreturn((value) M);
}

View File

@ -0,0 +1,15 @@
(*===-- llvm_irreader.ml - LLVM OCaml Interface ---------------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
exception Error of string
let _ = Callback.register_exception "Llvm_irreader.Error" (Error "")
external parse_ir : Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule
= "llvm_parse_ir"

View File

@ -0,0 +1,20 @@
(*===-- llvm_irreader.mli - LLVM OCaml Interface --------------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
(** IR reader.
This interface provides an OCaml API for the LLVM assembly reader, the
classes in the IRReader library. *)
exception Error of string
(** [parse_ir context mb] parses the IR for a new module [m] from the
memory buffer [mb] in the context [context]. Returns [m] if successful, or
raises [Error msg] otherwise, where [msg] is a description of the error
encountered. See the function [llvm::ParseIR]. *)
val parse_ir : Llvm.llcontext -> Llvm.llmemorybuffer -> Llvm.llmodule

View File

@ -0,0 +1,5 @@
add_ocaml_library(llvm_linker
OCAML llvm_linker
OCAMLDEP llvm
C linker_ocaml
LLVM Linker)

View File

@ -0,0 +1,33 @@
/*===-- linker_ocaml.c - LLVM OCaml Glue ------------------------*- C++ -*-===*\
|* *|
|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *|
|* Exceptions. *|
|* See https://llvm.org/LICENSE.txt for license information. *|
|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This file glues LLVM's OCaml interface to its C interface. These functions *|
|* are by and large transparent wrappers to the corresponding C functions. *|
|* *|
|* Note that these functions intentionally take liberties with the CAMLparamX *|
|* macros, since most of the parameters are not GC heap objects. *|
|* *|
\*===----------------------------------------------------------------------===*/
#include "llvm-c/Core.h"
#include "llvm-c/Linker.h"
#include "caml/alloc.h"
#include "caml/memory.h"
#include "caml/fail.h"
#include "caml/callback.h"
void llvm_raise(value Prototype, char *Message);
/* llmodule -> llmodule -> unit */
CAMLprim value llvm_link_modules(LLVMModuleRef Dst, LLVMModuleRef Src) {
if (LLVMLinkModules2(Dst, Src))
llvm_raise(*caml_named_value("Llvm_linker.Error"), LLVMCreateMessage("Linking failed"));
return Val_unit;
}

View File

@ -0,0 +1,14 @@
(*===-- llvm_linker.ml - LLVM OCaml Interface ------------------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
exception Error of string
let () = Callback.register_exception "Llvm_linker.Error" (Error "")
external link_modules' : Llvm.llmodule -> Llvm.llmodule -> unit
= "llvm_link_modules"

View File

@ -0,0 +1,18 @@
(*===-- llvm_linker.mli - LLVM OCaml Interface -----------------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
(** Linker.
This interface provides an OCaml API for LLVM bitcode linker,
the classes in the Linker library. *)
exception Error of string
(** [link_modules' dst src] links [src] into [dst], raising [Error]
if the linking fails. The src module is destroyed. *)
val link_modules' : Llvm.llmodule -> Llvm.llmodule -> unit

View File

@ -0,0 +1,11 @@
add_ocaml_library(llvm
OCAML llvm
C llvm_ocaml
LLVM Core Support)
configure_file(
"${CMAKE_CURRENT_SOURCE_DIR}/META.llvm.in"
"${LLVM_LIBRARY_DIR}/ocaml/META.llvm")
install(FILES "${LLVM_LIBRARY_DIR}/ocaml/META.llvm"
DESTINATION "${LLVM_OCAML_INSTALL_PATH}")

View File

@ -0,0 +1,110 @@
name = "llvm"
version = "@PACKAGE_VERSION@"
description = "LLVM OCaml bindings"
archive(byte) = "llvm.cma"
archive(native) = "llvm.cmxa"
directory = "llvm"
package "analysis" (
requires = "llvm"
version = "@PACKAGE_VERSION@"
description = "Intermediate representation analysis for LLVM"
archive(byte) = "llvm_analysis.cma"
archive(native) = "llvm_analysis.cmxa"
)
package "bitreader" (
requires = "llvm"
version = "@PACKAGE_VERSION@"
description = "Bitcode reader for LLVM"
archive(byte) = "llvm_bitreader.cma"
archive(native) = "llvm_bitreader.cmxa"
)
package "bitwriter" (
requires = "llvm,unix"
version = "@PACKAGE_VERSION@"
description = "Bitcode writer for LLVM"
archive(byte) = "llvm_bitwriter.cma"
archive(native) = "llvm_bitwriter.cmxa"
)
package "executionengine" (
requires = "llvm,llvm.target,ctypes.foreign"
version = "@PACKAGE_VERSION@"
description = "JIT and Interpreter for LLVM"
archive(byte) = "llvm_executionengine.cma"
archive(native) = "llvm_executionengine.cmxa"
)
package "ipo" (
requires = "llvm"
version = "@PACKAGE_VERSION@"
description = "IPO Transforms for LLVM"
archive(byte) = "llvm_ipo.cma"
archive(native) = "llvm_ipo.cmxa"
)
package "irreader" (
requires = "llvm"
version = "@PACKAGE_VERSION@"
description = "IR assembly reader for LLVM"
archive(byte) = "llvm_irreader.cma"
archive(native) = "llvm_irreader.cmxa"
)
package "scalar_opts" (
requires = "llvm"
version = "@PACKAGE_VERSION@"
description = "Scalar Transforms for LLVM"
archive(byte) = "llvm_scalar_opts.cma"
archive(native) = "llvm_scalar_opts.cmxa"
)
package "transform_utils" (
requires = "llvm"
version = "@PACKAGE_VERSION@"
description = "Transform utilities for LLVM"
archive(byte) = "llvm_transform_utils.cma"
archive(native) = "llvm_transform_utils.cmxa"
)
package "vectorize" (
requires = "llvm"
version = "@PACKAGE_VERSION@"
description = "Vector Transforms for LLVM"
archive(byte) = "llvm_vectorize.cma"
archive(native) = "llvm_vectorize.cmxa"
)
package "passmgr_builder" (
requires = "llvm"
version = "@PACKAGE_VERSION@"
description = "Pass Manager Builder for LLVM"
archive(byte) = "llvm_passmgr_builder.cma"
archive(native) = "llvm_passmgr_builder.cmxa"
)
package "target" (
requires = "llvm"
version = "@PACKAGE_VERSION@"
description = "Target Information for LLVM"
archive(byte) = "llvm_target.cma"
archive(native) = "llvm_target.cmxa"
)
package "linker" (
requires = "llvm"
version = "@PACKAGE_VERSION@"
description = "Intermediate Representation Linker for LLVM"
archive(byte) = "llvm_linker.cma"
archive(native) = "llvm_linker.cmxa"
)
package "all_backends" (
requires = "llvm"
version = "@PACKAGE_VERSION@"
description = "All backends for LLVM"
archive(byte) = "llvm_all_backends.cma"
archive(native) = "llvm_all_backends.cmxa"
)

1392
bindings/ocaml/llvm/llvm.ml Normal file

File diff suppressed because it is too large Load Diff

2682
bindings/ocaml/llvm/llvm.mli Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,5 @@
add_ocaml_library(llvm_target
OCAML llvm_target
OCAMLDEP llvm
C target_ocaml
LLVM Target)

View File

@ -0,0 +1,135 @@
(*===-- llvm_target.ml - LLVM OCaml Interface ------------------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
module Endian = struct
type t =
| Big
| Little
end
module CodeGenOptLevel = struct
type t =
| None
| Less
| Default
| Aggressive
end
module RelocMode = struct
type t =
| Default
| Static
| PIC
| DynamicNoPIC
end
module CodeModel = struct
type t =
| Default
| JITDefault
| Small
| Kernel
| Medium
| Large
end
module CodeGenFileType = struct
type t =
| AssemblyFile
| ObjectFile
end
exception Error of string
let () = Callback.register_exception "Llvm_target.Error" (Error "")
module DataLayout = struct
type t
external of_string : string -> t = "llvm_datalayout_of_string"
external as_string : t -> string = "llvm_datalayout_as_string"
external byte_order : t -> Endian.t = "llvm_datalayout_byte_order"
external pointer_size : t -> int = "llvm_datalayout_pointer_size"
external intptr_type : Llvm.llcontext -> t -> Llvm.lltype
= "llvm_datalayout_intptr_type"
external qualified_pointer_size : int -> t -> int
= "llvm_datalayout_qualified_pointer_size"
external qualified_intptr_type : Llvm.llcontext -> int -> t -> Llvm.lltype
= "llvm_datalayout_qualified_intptr_type"
external size_in_bits : Llvm.lltype -> t -> Int64.t
= "llvm_datalayout_size_in_bits"
external store_size : Llvm.lltype -> t -> Int64.t
= "llvm_datalayout_store_size"
external abi_size : Llvm.lltype -> t -> Int64.t
= "llvm_datalayout_abi_size"
external abi_align : Llvm.lltype -> t -> int
= "llvm_datalayout_abi_align"
external stack_align : Llvm.lltype -> t -> int
= "llvm_datalayout_stack_align"
external preferred_align : Llvm.lltype -> t -> int
= "llvm_datalayout_preferred_align"
external preferred_align_of_global : Llvm.llvalue -> t -> int
= "llvm_datalayout_preferred_align_of_global"
external element_at_offset : Llvm.lltype -> Int64.t -> t -> int
= "llvm_datalayout_element_at_offset"
external offset_of_element : Llvm.lltype -> int -> t -> Int64.t
= "llvm_datalayout_offset_of_element"
end
module Target = struct
type t
external default_triple : unit -> string = "llvm_target_default_triple"
external first : unit -> t option = "llvm_target_first"
external succ : t -> t option = "llvm_target_succ"
external by_name : string -> t option = "llvm_target_by_name"
external by_triple : string -> t = "llvm_target_by_triple"
external name : t -> string = "llvm_target_name"
external description : t -> string = "llvm_target_description"
external has_jit : t -> bool = "llvm_target_has_jit"
external has_target_machine : t -> bool = "llvm_target_has_target_machine"
external has_asm_backend : t -> bool = "llvm_target_has_asm_backend"
let all () =
let rec step elem lst =
match elem with
| Some target -> step (succ target) (target :: lst)
| None -> lst
in
step (first ()) []
end
module TargetMachine = struct
type t
external create : triple:string -> ?cpu:string -> ?features:string ->
?level:CodeGenOptLevel.t -> ?reloc_mode:RelocMode.t ->
?code_model:CodeModel.t -> Target.t -> t
= "llvm_create_targetmachine_bytecode"
"llvm_create_targetmachine_native"
external target : t -> Target.t
= "llvm_targetmachine_target"
external triple : t -> string
= "llvm_targetmachine_triple"
external cpu : t -> string
= "llvm_targetmachine_cpu"
external features : t -> string
= "llvm_targetmachine_features"
external data_layout : t -> DataLayout.t
= "llvm_targetmachine_data_layout"
external add_analysis_passes : [< Llvm.PassManager.any ] Llvm.PassManager.t -> t -> unit
= "llvm_targetmachine_add_analysis_passes"
external set_verbose_asm : bool -> t -> unit
= "llvm_targetmachine_set_verbose_asm"
external emit_to_file : Llvm.llmodule -> CodeGenFileType.t -> string ->
t -> unit
= "llvm_targetmachine_emit_to_file"
external emit_to_memory_buffer : Llvm.llmodule -> CodeGenFileType.t ->
t -> Llvm.llmemorybuffer
= "llvm_targetmachine_emit_to_memory_buffer"
end

View File

@ -0,0 +1,219 @@
(*===-- llvm_target.mli - LLVM OCaml Interface -----------------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
(** Target Information.
This interface provides an OCaml API for LLVM target information,
the classes in the Target library. *)
module Endian : sig
type t =
| Big
| Little
end
module CodeGenOptLevel : sig
type t =
| None
| Less
| Default
| Aggressive
end
module RelocMode : sig
type t =
| Default
| Static
| PIC
| DynamicNoPIC
end
module CodeModel : sig
type t =
| Default
| JITDefault
| Small
| Kernel
| Medium
| Large
end
module CodeGenFileType : sig
type t =
| AssemblyFile
| ObjectFile
end
(** {6 Exceptions} *)
exception Error of string
(** {6 Data Layout} *)
module DataLayout : sig
type t
(** [of_string rep] parses the data layout string representation [rep].
See the constructor [llvm::DataLayout::DataLayout]. *)
val of_string : string -> t
(** [as_string dl] is the string representation of the data layout [dl].
See the method [llvm::DataLayout::getStringRepresentation]. *)
val as_string : t -> string
(** Returns the byte order of a target, either [Endian.Big] or
[Endian.Little].
See the method [llvm::DataLayout::isLittleEndian]. *)
val byte_order : t -> Endian.t
(** Returns the pointer size in bytes for a target.
See the method [llvm::DataLayout::getPointerSize]. *)
val pointer_size : t -> int
(** Returns the integer type that is the same size as a pointer on a target.
See the method [llvm::DataLayout::getIntPtrType]. *)
val intptr_type : Llvm.llcontext -> t -> Llvm.lltype
(** Returns the pointer size in bytes for a target in a given address space.
See the method [llvm::DataLayout::getPointerSize]. *)
val qualified_pointer_size : int -> t -> int
(** Returns the integer type that is the same size as a pointer on a target
in a given address space.
See the method [llvm::DataLayout::getIntPtrType]. *)
val qualified_intptr_type : Llvm.llcontext -> int -> t -> Llvm.lltype
(** Computes the size of a type in bits for a target.
See the method [llvm::DataLayout::getTypeSizeInBits]. *)
val size_in_bits : Llvm.lltype -> t -> Int64.t
(** Computes the storage size of a type in bytes for a target.
See the method [llvm::DataLayout::getTypeStoreSize]. *)
val store_size : Llvm.lltype -> t -> Int64.t
(** Computes the ABI size of a type in bytes for a target.
See the method [llvm::DataLayout::getTypeAllocSize]. *)
val abi_size : Llvm.lltype -> t -> Int64.t
(** Computes the ABI alignment of a type in bytes for a target.
See the method [llvm::DataLayout::getTypeABISize]. *)
val abi_align : Llvm.lltype -> t -> int
(** Computes the call frame alignment of a type in bytes for a target.
See the method [llvm::DataLayout::getTypeABISize]. *)
val stack_align : Llvm.lltype -> t -> int
(** Computes the preferred alignment of a type in bytes for a target.
See the method [llvm::DataLayout::getTypeABISize]. *)
val preferred_align : Llvm.lltype -> t -> int
(** Computes the preferred alignment of a global variable in bytes for
a target. See the method [llvm::DataLayout::getPreferredAlignment]. *)
val preferred_align_of_global : Llvm.llvalue -> t -> int
(** Computes the structure element that contains the byte offset for a target.
See the method [llvm::StructLayout::getElementContainingOffset]. *)
val element_at_offset : Llvm.lltype -> Int64.t -> t -> int
(** Computes the byte offset of the indexed struct element for a target.
See the method [llvm::StructLayout::getElementContainingOffset]. *)
val offset_of_element : Llvm.lltype -> int -> t -> Int64.t
end
(** {6 Target} *)
module Target : sig
type t
(** [default_triple ()] returns the default target triple for current
platform. *)
val default_triple : unit -> string
(** [first ()] returns the first target in the registered targets
list, or [None]. *)
val first : unit -> t option
(** [succ t] returns the next target after [t], or [None]
if [t] was the last target. *)
val succ : t -> t option
(** [all ()] returns a list of known targets. *)
val all : unit -> t list
(** [by_name name] returns [Some t] if a target [t] named [name] is
registered, or [None] otherwise. *)
val by_name : string -> t option
(** [by_triple triple] returns a target for a triple [triple], or raises
[Error] if [triple] does not correspond to a registered target. *)
val by_triple : string -> t
(** Returns the name of a target. See [llvm::Target::getName]. *)
val name : t -> string
(** Returns the description of a target.
See [llvm::Target::getDescription]. *)
val description : t -> string
(** Returns [true] if the target has a JIT. *)
val has_jit : t -> bool
(** Returns [true] if the target has a target machine associated. *)
val has_target_machine : t -> bool
(** Returns [true] if the target has an ASM backend (required for
emitting output). *)
val has_asm_backend : t -> bool
end
(** {6 Target Machine} *)
module TargetMachine : sig
type t
(** Creates a new target machine.
See [llvm::Target::createTargetMachine]. *)
val create : triple:string -> ?cpu:string -> ?features:string ->
?level:CodeGenOptLevel.t -> ?reloc_mode:RelocMode.t ->
?code_model:CodeModel.t -> Target.t -> t
(** Returns the Target used in a TargetMachine *)
val target : t -> Target.t
(** Returns the triple used while creating this target machine. See
[llvm::TargetMachine::getTriple]. *)
val triple : t -> string
(** Returns the CPU used while creating this target machine. See
[llvm::TargetMachine::getCPU]. *)
val cpu : t -> string
(** Returns the data layout of this target machine. *)
val data_layout : t -> DataLayout.t
(** Returns the feature string used while creating this target machine. See
[llvm::TargetMachine::getFeatureString]. *)
val features : t -> string
(** Adds the target-specific analysis passes to the pass manager.
See [llvm::TargetMachine::addAnalysisPasses]. *)
val add_analysis_passes : [< Llvm.PassManager.any ] Llvm.PassManager.t -> t -> unit
(** Sets the assembly verbosity of this target machine.
See [llvm::TargetMachine::setAsmVerbosity]. *)
val set_verbose_asm : bool -> t -> unit
(** Emits assembly or object data for the given module to the given
file or raise [Error]. *)
val emit_to_file : Llvm.llmodule -> CodeGenFileType.t -> string -> t -> unit
(** Emits assembly or object data for the given module to a fresh memory
buffer or raise [Error]. *)
val emit_to_memory_buffer : Llvm.llmodule -> CodeGenFileType.t -> t ->
Llvm.llmemorybuffer
end

View File

@ -0,0 +1,347 @@
/*===-- target_ocaml.c - LLVM OCaml Glue ------------------------*- C++ -*-===*\
|* *|
|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *|
|* Exceptions. *|
|* See https://llvm.org/LICENSE.txt for license information. *|
|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This file glues LLVM's OCaml interface to its C interface. These functions *|
|* are by and large transparent wrappers to the corresponding C functions. *|
|* *|
|* Note that these functions intentionally take liberties with the CAMLparamX *|
|* macros, since most of the parameters are not GC heap objects. *|
|* *|
\*===----------------------------------------------------------------------===*/
#include "llvm-c/Core.h"
#include "llvm-c/Target.h"
#include "llvm-c/TargetMachine.h"
#include "caml/alloc.h"
#include "caml/fail.h"
#include "caml/memory.h"
#include "caml/custom.h"
#include "caml/callback.h"
void llvm_raise(value Prototype, char *Message);
value llvm_string_of_message(char* Message);
/*===---- Data Layout -----------------------------------------------------===*/
#define DataLayout_val(v) (*(LLVMTargetDataRef *)(Data_custom_val(v)))
static void llvm_finalize_data_layout(value DataLayout) {
LLVMDisposeTargetData(DataLayout_val(DataLayout));
}
static struct custom_operations llvm_data_layout_ops = {
(char *) "Llvm_target.DataLayout.t",
llvm_finalize_data_layout,
custom_compare_default,
custom_hash_default,
custom_serialize_default,
custom_deserialize_default,
custom_compare_ext_default
};
value llvm_alloc_data_layout(LLVMTargetDataRef DataLayout) {
value V = alloc_custom(&llvm_data_layout_ops, sizeof(LLVMTargetDataRef),
0, 1);
DataLayout_val(V) = DataLayout;
return V;
}
/* string -> DataLayout.t */
CAMLprim value llvm_datalayout_of_string(value StringRep) {
return llvm_alloc_data_layout(LLVMCreateTargetData(String_val(StringRep)));
}
/* DataLayout.t -> string */
CAMLprim value llvm_datalayout_as_string(value TD) {
char *StringRep = LLVMCopyStringRepOfTargetData(DataLayout_val(TD));
value Copy = copy_string(StringRep);
LLVMDisposeMessage(StringRep);
return Copy;
}
/* DataLayout.t -> Endian.t */
CAMLprim value llvm_datalayout_byte_order(value DL) {
return Val_int(LLVMByteOrder(DataLayout_val(DL)));
}
/* DataLayout.t -> int */
CAMLprim value llvm_datalayout_pointer_size(value DL) {
return Val_int(LLVMPointerSize(DataLayout_val(DL)));
}
/* Llvm.llcontext -> DataLayout.t -> Llvm.lltype */
CAMLprim LLVMTypeRef llvm_datalayout_intptr_type(LLVMContextRef C, value DL) {
return LLVMIntPtrTypeInContext(C, DataLayout_val(DL));
}
/* int -> DataLayout.t -> int */
CAMLprim value llvm_datalayout_qualified_pointer_size(value AS, value DL) {
return Val_int(LLVMPointerSizeForAS(DataLayout_val(DL), Int_val(AS)));
}
/* Llvm.llcontext -> int -> DataLayout.t -> Llvm.lltype */
CAMLprim LLVMTypeRef llvm_datalayout_qualified_intptr_type(LLVMContextRef C,
value AS,
value DL) {
return LLVMIntPtrTypeForASInContext(C, DataLayout_val(DL), Int_val(AS));
}
/* Llvm.lltype -> DataLayout.t -> Int64.t */
CAMLprim value llvm_datalayout_size_in_bits(LLVMTypeRef Ty, value DL) {
return caml_copy_int64(LLVMSizeOfTypeInBits(DataLayout_val(DL), Ty));
}
/* Llvm.lltype -> DataLayout.t -> Int64.t */
CAMLprim value llvm_datalayout_store_size(LLVMTypeRef Ty, value DL) {
return caml_copy_int64(LLVMStoreSizeOfType(DataLayout_val(DL), Ty));
}
/* Llvm.lltype -> DataLayout.t -> Int64.t */
CAMLprim value llvm_datalayout_abi_size(LLVMTypeRef Ty, value DL) {
return caml_copy_int64(LLVMABISizeOfType(DataLayout_val(DL), Ty));
}
/* Llvm.lltype -> DataLayout.t -> int */
CAMLprim value llvm_datalayout_abi_align(LLVMTypeRef Ty, value DL) {
return Val_int(LLVMABIAlignmentOfType(DataLayout_val(DL), Ty));
}
/* Llvm.lltype -> DataLayout.t -> int */
CAMLprim value llvm_datalayout_stack_align(LLVMTypeRef Ty, value DL) {
return Val_int(LLVMCallFrameAlignmentOfType(DataLayout_val(DL), Ty));
}
/* Llvm.lltype -> DataLayout.t -> int */
CAMLprim value llvm_datalayout_preferred_align(LLVMTypeRef Ty, value DL) {
return Val_int(LLVMPreferredAlignmentOfType(DataLayout_val(DL), Ty));
}
/* Llvm.llvalue -> DataLayout.t -> int */
CAMLprim value llvm_datalayout_preferred_align_of_global(LLVMValueRef GlobalVar,
value DL) {
return Val_int(LLVMPreferredAlignmentOfGlobal(DataLayout_val(DL), GlobalVar));
}
/* Llvm.lltype -> Int64.t -> DataLayout.t -> int */
CAMLprim value llvm_datalayout_element_at_offset(LLVMTypeRef Ty, value Offset,
value DL) {
return Val_int(LLVMElementAtOffset(DataLayout_val(DL), Ty,
Int64_val(Offset)));
}
/* Llvm.lltype -> int -> DataLayout.t -> Int64.t */
CAMLprim value llvm_datalayout_offset_of_element(LLVMTypeRef Ty, value Index,
value DL) {
return caml_copy_int64(LLVMOffsetOfElement(DataLayout_val(DL), Ty,
Int_val(Index)));
}
/*===---- Target ----------------------------------------------------------===*/
static value llvm_target_option(LLVMTargetRef Target) {
if(Target != NULL) {
value Result = caml_alloc_small(1, 0);
Store_field(Result, 0, (value) Target);
return Result;
}
return Val_int(0);
}
/* unit -> string */
CAMLprim value llvm_target_default_triple(value Unit) {
char *TripleCStr = LLVMGetDefaultTargetTriple();
value TripleStr = caml_copy_string(TripleCStr);
LLVMDisposeMessage(TripleCStr);
return TripleStr;
}
/* unit -> Target.t option */
CAMLprim value llvm_target_first(value Unit) {
return llvm_target_option(LLVMGetFirstTarget());
}
/* Target.t -> Target.t option */
CAMLprim value llvm_target_succ(LLVMTargetRef Target) {
return llvm_target_option(LLVMGetNextTarget(Target));
}
/* string -> Target.t option */
CAMLprim value llvm_target_by_name(value Name) {
return llvm_target_option(LLVMGetTargetFromName(String_val(Name)));
}
/* string -> Target.t */
CAMLprim LLVMTargetRef llvm_target_by_triple(value Triple) {
LLVMTargetRef T;
char *Error;
if(LLVMGetTargetFromTriple(String_val(Triple), &T, &Error))
llvm_raise(*caml_named_value("Llvm_target.Error"), Error);
return T;
}
/* Target.t -> string */
CAMLprim value llvm_target_name(LLVMTargetRef Target) {
return caml_copy_string(LLVMGetTargetName(Target));
}
/* Target.t -> string */
CAMLprim value llvm_target_description(LLVMTargetRef Target) {
return caml_copy_string(LLVMGetTargetDescription(Target));
}
/* Target.t -> bool */
CAMLprim value llvm_target_has_jit(LLVMTargetRef Target) {
return Val_bool(LLVMTargetHasJIT(Target));
}
/* Target.t -> bool */
CAMLprim value llvm_target_has_target_machine(LLVMTargetRef Target) {
return Val_bool(LLVMTargetHasTargetMachine(Target));
}
/* Target.t -> bool */
CAMLprim value llvm_target_has_asm_backend(LLVMTargetRef Target) {
return Val_bool(LLVMTargetHasAsmBackend(Target));
}
/*===---- Target Machine --------------------------------------------------===*/
#define TargetMachine_val(v) (*(LLVMTargetMachineRef *)(Data_custom_val(v)))
static void llvm_finalize_target_machine(value Machine) {
LLVMDisposeTargetMachine(TargetMachine_val(Machine));
}
static struct custom_operations llvm_target_machine_ops = {
(char *) "Llvm_target.TargetMachine.t",
llvm_finalize_target_machine,
custom_compare_default,
custom_hash_default,
custom_serialize_default,
custom_deserialize_default,
custom_compare_ext_default
};
static value llvm_alloc_targetmachine(LLVMTargetMachineRef Machine) {
value V = alloc_custom(&llvm_target_machine_ops, sizeof(LLVMTargetMachineRef),
0, 1);
TargetMachine_val(V) = Machine;
return V;
}
/* triple:string -> ?cpu:string -> ?features:string
?level:CodeGenOptLevel.t -> ?reloc_mode:RelocMode.t
?code_model:CodeModel.t -> Target.t -> TargetMachine.t */
CAMLprim value llvm_create_targetmachine_native(value Triple, value CPU,
value Features, value OptLevel, value RelocMode,
value CodeModel, LLVMTargetRef Target) {
LLVMTargetMachineRef Machine;
const char *CPUStr = "", *FeaturesStr = "";
LLVMCodeGenOptLevel OptLevelEnum = LLVMCodeGenLevelDefault;
LLVMRelocMode RelocModeEnum = LLVMRelocDefault;
LLVMCodeModel CodeModelEnum = LLVMCodeModelDefault;
if(CPU != Val_int(0))
CPUStr = String_val(Field(CPU, 0));
if(Features != Val_int(0))
FeaturesStr = String_val(Field(Features, 0));
if(OptLevel != Val_int(0))
OptLevelEnum = Int_val(Field(OptLevel, 0));
if(RelocMode != Val_int(0))
RelocModeEnum = Int_val(Field(RelocMode, 0));
if(CodeModel != Val_int(0))
CodeModelEnum = Int_val(Field(CodeModel, 0));
Machine = LLVMCreateTargetMachine(Target, String_val(Triple), CPUStr,
FeaturesStr, OptLevelEnum, RelocModeEnum, CodeModelEnum);
return llvm_alloc_targetmachine(Machine);
}
CAMLprim value llvm_create_targetmachine_bytecode(value *argv, int argn) {
return llvm_create_targetmachine_native(argv[0], argv[1], argv[2], argv[3],
argv[4], argv[5], (LLVMTargetRef) argv[6]);
}
/* TargetMachine.t -> Target.t */
CAMLprim LLVMTargetRef llvm_targetmachine_target(value Machine) {
return LLVMGetTargetMachineTarget(TargetMachine_val(Machine));
}
/* TargetMachine.t -> string */
CAMLprim value llvm_targetmachine_triple(value Machine) {
return llvm_string_of_message(LLVMGetTargetMachineTriple(
TargetMachine_val(Machine)));
}
/* TargetMachine.t -> string */
CAMLprim value llvm_targetmachine_cpu(value Machine) {
return llvm_string_of_message(LLVMGetTargetMachineCPU(
TargetMachine_val(Machine)));
}
/* TargetMachine.t -> string */
CAMLprim value llvm_targetmachine_features(value Machine) {
return llvm_string_of_message(LLVMGetTargetMachineFeatureString(
TargetMachine_val(Machine)));
}
/* TargetMachine.t -> DataLayout.t */
CAMLprim value llvm_targetmachine_data_layout(value Machine) {
return llvm_alloc_data_layout(LLVMCreateTargetDataLayout(
TargetMachine_val(Machine)));
}
/* bool -> TargetMachine.t -> unit */
CAMLprim value llvm_targetmachine_set_verbose_asm(value Verb, value Machine) {
LLVMSetTargetMachineAsmVerbosity(TargetMachine_val(Machine), Bool_val(Verb));
return Val_unit;
}
/* Llvm.llmodule -> CodeGenFileType.t -> string -> TargetMachine.t -> unit */
CAMLprim value llvm_targetmachine_emit_to_file(LLVMModuleRef Module,
value FileType, value FileName, value Machine) {
char *ErrorMessage;
if(LLVMTargetMachineEmitToFile(TargetMachine_val(Machine), Module,
String_val(FileName), Int_val(FileType),
&ErrorMessage)) {
llvm_raise(*caml_named_value("Llvm_target.Error"), ErrorMessage);
}
return Val_unit;
}
/* Llvm.llmodule -> CodeGenFileType.t -> TargetMachine.t ->
Llvm.llmemorybuffer */
CAMLprim LLVMMemoryBufferRef llvm_targetmachine_emit_to_memory_buffer(
LLVMModuleRef Module, value FileType,
value Machine) {
char *ErrorMessage;
LLVMMemoryBufferRef Buffer;
if(LLVMTargetMachineEmitToMemoryBuffer(TargetMachine_val(Machine), Module,
Int_val(FileType), &ErrorMessage,
&Buffer)) {
llvm_raise(*caml_named_value("Llvm_target.Error"), ErrorMessage);
}
return Buffer;
}
/* TargetMachine.t -> Llvm.PassManager.t -> unit */
CAMLprim value llvm_targetmachine_add_analysis_passes(LLVMPassManagerRef PM,
value Machine) {
LLVMAddAnalysisPasses(TargetMachine_val(Machine), PM);
return Val_unit;
}

View File

@ -0,0 +1,5 @@
add_subdirectory(ipo)
add_subdirectory(passmgr_builder)
add_subdirectory(scalar_opts)
add_subdirectory(utils)
add_subdirectory(vectorize)

View File

@ -0,0 +1,5 @@
add_ocaml_library(llvm_ipo
OCAML llvm_ipo
OCAMLDEP llvm
C ipo_ocaml
LLVM ipo)

View File

@ -0,0 +1,104 @@
/*===-- ipo_ocaml.c - LLVM OCaml Glue ---------------------------*- C++ -*-===*\
|* *|
|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *|
|* Exceptions. *|
|* See https://llvm.org/LICENSE.txt for license information. *|
|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This file glues LLVM's OCaml interface to its C interface. These functions *|
|* are by and large transparent wrappers to the corresponding C functions. *|
|* *|
|* Note that these functions intentionally take liberties with the CAMLparamX *|
|* macros, since most of the parameters are not GC heap objects. *|
|* *|
\*===----------------------------------------------------------------------===*/
#include "llvm-c/Transforms/IPO.h"
#include "caml/mlvalues.h"
#include "caml/misc.h"
/* [`Module] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_argument_promotion(LLVMPassManagerRef PM) {
LLVMAddArgumentPromotionPass(PM);
return Val_unit;
}
/* [`Module] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_constant_merge(LLVMPassManagerRef PM) {
LLVMAddConstantMergePass(PM);
return Val_unit;
}
/* [`Module] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_merge_functions(LLVMPassManagerRef PM) {
LLVMAddMergeFunctionsPass(PM);
return Val_unit;
}
/* [`Module] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_dead_arg_elimination(LLVMPassManagerRef PM) {
LLVMAddDeadArgEliminationPass(PM);
return Val_unit;
}
/* [`Module] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_function_attrs(LLVMPassManagerRef PM) {
LLVMAddFunctionAttrsPass(PM);
return Val_unit;
}
/* [`Module] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_function_inlining(LLVMPassManagerRef PM) {
LLVMAddFunctionInliningPass(PM);
return Val_unit;
}
/* [`Module] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_always_inliner(LLVMPassManagerRef PM) {
LLVMAddAlwaysInlinerPass(PM);
return Val_unit;
}
/* [`Module] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_global_dce(LLVMPassManagerRef PM) {
LLVMAddGlobalDCEPass(PM);
return Val_unit;
}
/* [`Module] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_global_optimizer(LLVMPassManagerRef PM) {
LLVMAddGlobalOptimizerPass(PM);
return Val_unit;
}
/* [`Module] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_prune_eh(LLVMPassManagerRef PM) {
LLVMAddPruneEHPass(PM);
return Val_unit;
}
/* [`Module] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_ipsccp(LLVMPassManagerRef PM) {
LLVMAddIPSCCPPass(PM);
return Val_unit;
}
/* [`Module] Llvm.PassManager.t -> all_but_main:bool -> unit */
CAMLprim value llvm_add_internalize(LLVMPassManagerRef PM, value AllButMain) {
LLVMAddInternalizePass(PM, Bool_val(AllButMain));
return Val_unit;
}
/* [`Module] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_strip_dead_prototypes(LLVMPassManagerRef PM) {
LLVMAddStripDeadPrototypesPass(PM);
return Val_unit;
}
/* [`Module] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_strip_symbols(LLVMPassManagerRef PM) {
LLVMAddStripSymbolsPass(PM);
return Val_unit;
}

View File

@ -0,0 +1,50 @@
(*===-- llvm_ipo.ml - LLVM OCaml Interface --------------------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
external add_argument_promotion
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_argument_promotion"
external add_constant_merge
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_constant_merge"
external add_merge_functions
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_merge_functions"
external add_dead_arg_elimination
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_dead_arg_elimination"
external add_function_attrs
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_function_attrs"
external add_function_inlining
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_function_inlining"
external add_always_inliner
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_always_inliner"
external add_global_dce
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_global_dce"
external add_global_optimizer
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_global_optimizer"
external add_prune_eh
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_prune_eh"
external add_ipsccp
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_ipsccp"
external add_internalize
: [ `Module ] Llvm.PassManager.t -> all_but_main:bool -> unit
= "llvm_add_internalize"
external add_strip_dead_prototypes
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_strip_dead_prototypes"
external add_strip_symbols
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_strip_symbols"

View File

@ -0,0 +1,82 @@
(*===-- llvm_ipo.mli - LLVM OCaml Interface -------------------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
(** IPO Transforms.
This interface provides an OCaml API for LLVM interprocedural optimizations, the
classes in the [LLVMIPO] library. *)
(** See the [llvm::createAddArgumentPromotionPass] function. *)
external add_argument_promotion
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_argument_promotion"
(** See the [llvm::createConstantMergePass] function. *)
external add_constant_merge
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_constant_merge"
(** See the [llvm::createMergeFunctionsPass] function. *)
external add_merge_functions
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_merge_functions"
(** See the [llvm::createDeadArgEliminationPass] function. *)
external add_dead_arg_elimination
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_dead_arg_elimination"
(** See the [llvm::createFunctionAttrsPass] function. *)
external add_function_attrs
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_function_attrs"
(** See the [llvm::createFunctionInliningPass] function. *)
external add_function_inlining
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_function_inlining"
(** See the [llvm::createAlwaysInlinerPass] function. *)
external add_always_inliner
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_always_inliner"
(** See the [llvm::createGlobalDCEPass] function. *)
external add_global_dce
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_global_dce"
(** See the [llvm::createGlobalOptimizerPass] function. *)
external add_global_optimizer
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_global_optimizer"
(** See the [llvm::createPruneEHPass] function. *)
external add_prune_eh
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_prune_eh"
(** See the [llvm::createIPSCCPPass] function. *)
external add_ipsccp
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_ipsccp"
(** See the [llvm::createInternalizePass] function. *)
external add_internalize
: [ `Module ] Llvm.PassManager.t -> all_but_main:bool -> unit
= "llvm_add_internalize"
(** See the [llvm::createStripDeadPrototypesPass] function. *)
external add_strip_dead_prototypes
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_strip_dead_prototypes"
(** See the [llvm::createStripSymbolsPass] function. *)
external add_strip_symbols
: [ `Module ] Llvm.PassManager.t -> unit
= "llvm_add_strip_symbols"

View File

@ -0,0 +1,5 @@
add_ocaml_library(llvm_passmgr_builder
OCAML llvm_passmgr_builder
OCAMLDEP llvm
C passmgr_builder_ocaml
LLVM ipo)

View File

@ -0,0 +1,31 @@
(*===-- llvm_passmgr_builder.ml - LLVM OCaml Interface --------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
type t
external create : unit -> t
= "llvm_pmbuilder_create"
external set_opt_level : int -> t -> unit
= "llvm_pmbuilder_set_opt_level"
external set_size_level : int -> t -> unit
= "llvm_pmbuilder_set_size_level"
external set_disable_unit_at_a_time : bool -> t -> unit
= "llvm_pmbuilder_set_disable_unit_at_a_time"
external set_disable_unroll_loops : bool -> t -> unit
= "llvm_pmbuilder_set_disable_unroll_loops"
external use_inliner_with_threshold : int -> t -> unit
= "llvm_pmbuilder_use_inliner_with_threshold"
external populate_function_pass_manager
: [ `Function ] Llvm.PassManager.t -> t -> unit
= "llvm_pmbuilder_populate_function_pass_manager"
external populate_module_pass_manager
: [ `Module ] Llvm.PassManager.t -> t -> unit
= "llvm_pmbuilder_populate_module_pass_manager"
external populate_lto_pass_manager
: [ `Module ] Llvm.PassManager.t -> internalize:bool -> run_inliner:bool -> t -> unit
= "llvm_pmbuilder_populate_lto_pass_manager"

View File

@ -0,0 +1,53 @@
(*===-- llvm_passmgr_builder.mli - LLVM OCaml Interface -------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
(** Pass Manager Builder.
This interface provides an OCaml API for LLVM pass manager builder
from the [LLVMCore] library. *)
type t
(** See the [llvm::PassManagerBuilder] function. *)
external create : unit -> t
= "llvm_pmbuilder_create"
(** See the [llvm::PassManagerBuilder::OptLevel] function. *)
external set_opt_level : int -> t -> unit
= "llvm_pmbuilder_set_opt_level"
(** See the [llvm::PassManagerBuilder::SizeLevel] function. *)
external set_size_level : int -> t -> unit
= "llvm_pmbuilder_set_size_level"
(** See the [llvm::PassManagerBuilder::DisableUnitAtATime] function. *)
external set_disable_unit_at_a_time : bool -> t -> unit
= "llvm_pmbuilder_set_disable_unit_at_a_time"
(** See the [llvm::PassManagerBuilder::DisableUnrollLoops] function. *)
external set_disable_unroll_loops : bool -> t -> unit
= "llvm_pmbuilder_set_disable_unroll_loops"
(** See the [llvm::PassManagerBuilder::Inliner] function. *)
external use_inliner_with_threshold : int -> t -> unit
= "llvm_pmbuilder_use_inliner_with_threshold"
(** See the [llvm::PassManagerBuilder::populateFunctionPassManager] function. *)
external populate_function_pass_manager
: [ `Function ] Llvm.PassManager.t -> t -> unit
= "llvm_pmbuilder_populate_function_pass_manager"
(** See the [llvm::PassManagerBuilder::populateModulePassManager] function. *)
external populate_module_pass_manager
: [ `Module ] Llvm.PassManager.t -> t -> unit
= "llvm_pmbuilder_populate_module_pass_manager"
(** See the [llvm::PassManagerBuilder::populateLTOPassManager] function. *)
external populate_lto_pass_manager
: [ `Module ] Llvm.PassManager.t -> internalize:bool -> run_inliner:bool -> t -> unit
= "llvm_pmbuilder_populate_lto_pass_manager"

View File

@ -0,0 +1,111 @@
/*===-- passmgr_builder_ocaml.c - LLVM OCaml Glue ---------------*- C++ -*-===*\
|* *|
|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *|
|* Exceptions. *|
|* See https://llvm.org/LICENSE.txt for license information. *|
|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This file glues LLVM's OCaml interface to its C interface. These functions *|
|* are by and large transparent wrappers to the corresponding C functions. *|
|* *|
|* Note that these functions intentionally take liberties with the CAMLparamX *|
|* macros, since most of the parameters are not GC heap objects. *|
|* *|
\*===----------------------------------------------------------------------===*/
#include "llvm-c/Transforms/PassManagerBuilder.h"
#include "caml/mlvalues.h"
#include "caml/custom.h"
#include "caml/misc.h"
#define PMBuilder_val(v) (*(LLVMPassManagerBuilderRef *)(Data_custom_val(v)))
static void llvm_finalize_pmbuilder(value PMB) {
LLVMPassManagerBuilderDispose(PMBuilder_val(PMB));
}
static struct custom_operations pmbuilder_ops = {
(char *) "Llvm_passmgr_builder.t",
llvm_finalize_pmbuilder,
custom_compare_default,
custom_hash_default,
custom_serialize_default,
custom_deserialize_default,
custom_compare_ext_default
};
static value alloc_pmbuilder(LLVMPassManagerBuilderRef Ref) {
value Val = alloc_custom(&pmbuilder_ops,
sizeof(LLVMPassManagerBuilderRef), 0, 1);
PMBuilder_val(Val) = Ref;
return Val;
}
/* t -> unit */
CAMLprim value llvm_pmbuilder_create(value Unit) {
return alloc_pmbuilder(LLVMPassManagerBuilderCreate());
}
/* int -> t -> unit */
CAMLprim value llvm_pmbuilder_set_opt_level(value OptLevel, value PMB) {
LLVMPassManagerBuilderSetOptLevel(PMBuilder_val(PMB), Int_val(OptLevel));
return Val_unit;
}
/* int -> t -> unit */
CAMLprim value llvm_pmbuilder_set_size_level(value SizeLevel, value PMB) {
LLVMPassManagerBuilderSetSizeLevel(PMBuilder_val(PMB), Int_val(SizeLevel));
return Val_unit;
}
/* int -> t -> unit */
CAMLprim value llvm_pmbuilder_use_inliner_with_threshold(
value Threshold, value PMB) {
LLVMPassManagerBuilderSetOptLevel(PMBuilder_val(PMB), Int_val(Threshold));
return Val_unit;
}
/* bool -> t -> unit */
CAMLprim value llvm_pmbuilder_set_disable_unit_at_a_time(
value DisableUnitAtATime, value PMB) {
LLVMPassManagerBuilderSetDisableUnitAtATime(
PMBuilder_val(PMB), Bool_val(DisableUnitAtATime));
return Val_unit;
}
/* bool -> t -> unit */
CAMLprim value llvm_pmbuilder_set_disable_unroll_loops(
value DisableUnroll, value PMB) {
LLVMPassManagerBuilderSetDisableUnrollLoops(
PMBuilder_val(PMB), Bool_val(DisableUnroll));
return Val_unit;
}
/* [ `Function ] Llvm.PassManager.t -> t -> unit */
CAMLprim value llvm_pmbuilder_populate_function_pass_manager(
LLVMPassManagerRef PM, value PMB) {
LLVMPassManagerBuilderPopulateFunctionPassManager(
PMBuilder_val(PMB), PM);
return Val_unit;
}
/* [ `Module ] Llvm.PassManager.t -> t -> unit */
CAMLprim value llvm_pmbuilder_populate_module_pass_manager(
LLVMPassManagerRef PM, value PMB) {
LLVMPassManagerBuilderPopulateModulePassManager(
PMBuilder_val(PMB), PM);
return Val_unit;
}
/* [ `Module ] Llvm.PassManager.t ->
internalize:bool -> run_inliner:bool -> t -> unit */
CAMLprim value llvm_pmbuilder_populate_lto_pass_manager(
LLVMPassManagerRef PM, value Internalize, value RunInliner,
value PMB) {
LLVMPassManagerBuilderPopulateLTOPassManager(
PMBuilder_val(PMB), PM,
Bool_val(Internalize), Bool_val(RunInliner));
return Val_unit;
}

View File

@ -0,0 +1,5 @@
add_ocaml_library(llvm_scalar_opts
OCAML llvm_scalar_opts
OCAMLDEP llvm
C scalar_opts_ocaml
LLVM Scalar)

View File

@ -0,0 +1,128 @@
(*===-- llvm_scalar_opts.ml - LLVM OCaml Interface ------------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
external add_aggressive_dce
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_aggressive_dce"
external add_dce
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_dce"
external add_alignment_from_assumptions
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_alignment_from_assumptions"
external add_cfg_simplification
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_cfg_simplification"
external add_dead_store_elimination
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_dead_store_elimination"
external add_scalarizer
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_scalarizer"
external add_merged_load_store_motion
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_merged_load_store_motion"
external add_gvn
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_gvn"
external add_ind_var_simplification
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_ind_var_simplify"
external add_instruction_combination
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_instruction_combining"
external add_jump_threading
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_jump_threading"
external add_licm
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_licm"
external add_loop_deletion
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_loop_deletion"
external add_loop_idiom
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_loop_idiom"
external add_loop_rotation
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_loop_rotate"
external add_loop_reroll
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_loop_reroll"
external add_loop_unroll
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_loop_unroll"
external add_loop_unswitch
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_loop_unswitch"
external add_memcpy_opt
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_memcpy_opt"
external add_partially_inline_lib_calls
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_partially_inline_lib_calls"
external add_lower_atomic
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_lower_atomic"
external add_lower_switch
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_lower_switch"
external add_memory_to_register_promotion
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_promote_memory_to_register"
external add_reassociation
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_reassociation"
external add_sccp
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_sccp"
external add_scalar_repl_aggregation
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_scalar_repl_aggregates"
external add_scalar_repl_aggregation_ssa
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_scalar_repl_aggregates_ssa"
external add_scalar_repl_aggregation_with_threshold
: int -> [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_scalar_repl_aggregates_with_threshold"
external add_lib_call_simplification
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_simplify_lib_calls"
external add_tail_call_elimination
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_tail_call_elimination"
external add_memory_to_register_demotion
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_demote_memory_to_register"
external add_verifier
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_verifier"
external add_correlated_value_propagation
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_correlated_value_propagation"
external add_early_cse
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_early_cse"
external add_lower_expect_intrinsic
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_lower_expect_intrinsic"
external add_lower_constant_intrinsics
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_lower_constant_intrinsics"
external add_type_based_alias_analysis
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_type_based_alias_analysis"
external add_scoped_no_alias_alias_analysis
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_scoped_no_alias_aa"
external add_basic_alias_analysis
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_basic_alias_analysis"
external add_unify_function_exit_nodes
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_unify_function_exit_nodes"

View File

@ -0,0 +1,212 @@
(*===-- llvm_scalar_opts.mli - LLVM OCaml Interface -----------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
(** Scalar Transforms.
This interface provides an OCaml API for LLVM scalar transforms, the
classes in the [LLVMScalarOpts] library. *)
(** See the [llvm::createAggressiveDCEPass] function. *)
external add_aggressive_dce
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_aggressive_dce"
(** See the [llvm::createDCEPass] function. *)
external add_dce
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_dce"
(** See the [llvm::createAlignmentFromAssumptionsPass] function. *)
external add_alignment_from_assumptions
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_alignment_from_assumptions"
(** See the [llvm::createCFGSimplificationPass] function. *)
external add_cfg_simplification
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_cfg_simplification"
(** See [llvm::createDeadStoreEliminationPass] function. *)
external add_dead_store_elimination
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_dead_store_elimination"
(** See [llvm::createScalarizerPass] function. *)
external add_scalarizer
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_scalarizer"
(** See [llvm::createMergedLoadStoreMotionPass] function. *)
external add_merged_load_store_motion
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_merged_load_store_motion"
(** See the [llvm::createGVNPass] function. *)
external add_gvn
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_gvn"
(** See the [llvm::createIndVarSimplifyPass] function. *)
external add_ind_var_simplification
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_ind_var_simplify"
(** See the [llvm::createInstructionCombiningPass] function. *)
external add_instruction_combination
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_instruction_combining"
(** See the [llvm::createJumpThreadingPass] function. *)
external add_jump_threading
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_jump_threading"
(** See the [llvm::createLICMPass] function. *)
external add_licm
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_licm"
(** See the [llvm::createLoopDeletionPass] function. *)
external add_loop_deletion
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_loop_deletion"
(** See the [llvm::createLoopIdiomPass] function. *)
external add_loop_idiom
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_loop_idiom"
(** See the [llvm::createLoopRotatePass] function. *)
external add_loop_rotation
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_loop_rotate"
(** See the [llvm::createLoopRerollPass] function. *)
external add_loop_reroll
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_loop_reroll"
(** See the [llvm::createLoopUnrollPass] function. *)
external add_loop_unroll
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_loop_unroll"
(** See the [llvm::createLoopUnswitchPass] function. *)
external add_loop_unswitch
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_loop_unswitch"
(** See the [llvm::createMemCpyOptPass] function. *)
external add_memcpy_opt
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_memcpy_opt"
(** See the [llvm::createPartiallyInlineLibCallsPass] function. *)
external add_partially_inline_lib_calls
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_partially_inline_lib_calls"
(** See the [llvm::createLowerAtomicPass] function. *)
external add_lower_atomic
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_lower_atomic"
(** See the [llvm::createLowerSwitchPass] function. *)
external add_lower_switch
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_lower_switch"
(** See the [llvm::createPromoteMemoryToRegisterPass] function. *)
external add_memory_to_register_promotion
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_promote_memory_to_register"
(** See the [llvm::createReassociatePass] function. *)
external add_reassociation
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_reassociation"
(** See the [llvm::createSCCPPass] function. *)
external add_sccp
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_sccp"
(** See the [llvm::createSROAPass] function. *)
external add_scalar_repl_aggregation
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_scalar_repl_aggregates"
(** See the [llvm::createSROAPass] function. *)
external add_scalar_repl_aggregation_ssa
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_scalar_repl_aggregates_ssa"
(** See the [llvm::createSROAPass] function. *)
external add_scalar_repl_aggregation_with_threshold
: int -> [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_scalar_repl_aggregates_with_threshold"
(** See the [llvm::createSimplifyLibCallsPass] function. *)
external add_lib_call_simplification
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_simplify_lib_calls"
(** See the [llvm::createTailCallEliminationPass] function. *)
external add_tail_call_elimination
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_tail_call_elimination"
(** See the [llvm::createDemoteMemoryToRegisterPass] function. *)
external add_memory_to_register_demotion
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_demote_memory_to_register"
(** See the [llvm::createVerifierPass] function. *)
external add_verifier
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_verifier"
(** See the [llvm::createCorrelatedValuePropagationPass] function. *)
external add_correlated_value_propagation
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_correlated_value_propagation"
(** See the [llvm::createEarlyCSE] function. *)
external add_early_cse
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_early_cse"
(** See the [llvm::createLowerExpectIntrinsicPass] function. *)
external add_lower_expect_intrinsic
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_lower_expect_intrinsic"
(** See the [llvm::createLowerConstantIntrinsicsPass] function. *)
external add_lower_constant_intrinsics
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_lower_constant_intrinsics"
(** See the [llvm::createTypeBasedAliasAnalysisPass] function. *)
external add_type_based_alias_analysis
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_type_based_alias_analysis"
(** See the [llvm::createScopedNoAliasAAPass] function. *)
external add_scoped_no_alias_alias_analysis
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_scoped_no_alias_aa"
(** See the [llvm::createBasicAliasAnalysisPass] function. *)
external add_basic_alias_analysis
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_basic_alias_analysis"
(** See the [llvm::createUnifyFunctionExitNodesPass] function. *)
external add_unify_function_exit_nodes
: [< Llvm.PassManager.any ] Llvm.PassManager.t -> unit
= "llvm_add_unify_function_exit_nodes"

View File

@ -0,0 +1,261 @@
/*===-- scalar_opts_ocaml.c - LLVM OCaml Glue -------------------*- C++ -*-===*\
|* *|
|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *|
|* Exceptions. *|
|* See https://llvm.org/LICENSE.txt for license information. *|
|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This file glues LLVM's OCaml interface to its C interface. These functions *|
|* are by and large transparent wrappers to the corresponding C functions. *|
|* *|
|* Note that these functions intentionally take liberties with the CAMLparamX *|
|* macros, since most of the parameters are not GC heap objects. *|
|* *|
\*===----------------------------------------------------------------------===*/
#include "llvm-c/Transforms/Scalar.h"
#include "llvm-c/Transforms/Utils.h"
#include "caml/mlvalues.h"
#include "caml/misc.h"
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_aggressive_dce(LLVMPassManagerRef PM) {
LLVMAddAggressiveDCEPass(PM);
return Val_unit;
}
CAMLprim value llvm_add_dce(LLVMPassManagerRef PM) {
LLVMAddDCEPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_alignment_from_assumptions(LLVMPassManagerRef PM) {
LLVMAddAlignmentFromAssumptionsPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_cfg_simplification(LLVMPassManagerRef PM) {
LLVMAddCFGSimplificationPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_dead_store_elimination(LLVMPassManagerRef PM) {
LLVMAddDeadStoreEliminationPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_scalarizer(LLVMPassManagerRef PM) {
LLVMAddScalarizerPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_merged_load_store_motion(LLVMPassManagerRef PM) {
LLVMAddMergedLoadStoreMotionPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_gvn(LLVMPassManagerRef PM) {
LLVMAddGVNPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_ind_var_simplify(LLVMPassManagerRef PM) {
LLVMAddIndVarSimplifyPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_instruction_combining(LLVMPassManagerRef PM) {
LLVMAddInstructionCombiningPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_jump_threading(LLVMPassManagerRef PM) {
LLVMAddJumpThreadingPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_licm(LLVMPassManagerRef PM) {
LLVMAddLICMPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_loop_deletion(LLVMPassManagerRef PM) {
LLVMAddLoopDeletionPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_loop_idiom(LLVMPassManagerRef PM) {
LLVMAddLoopIdiomPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_loop_rotate(LLVMPassManagerRef PM) {
LLVMAddLoopRotatePass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_loop_reroll(LLVMPassManagerRef PM) {
LLVMAddLoopRerollPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_loop_unroll(LLVMPassManagerRef PM) {
LLVMAddLoopUnrollPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_loop_unswitch(LLVMPassManagerRef PM) {
LLVMAddLoopUnswitchPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_memcpy_opt(LLVMPassManagerRef PM) {
LLVMAddMemCpyOptPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_partially_inline_lib_calls(LLVMPassManagerRef PM) {
LLVMAddPartiallyInlineLibCallsPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_lower_atomic(LLVMPassManagerRef PM) {
LLVMAddLowerAtomicPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_lower_switch(LLVMPassManagerRef PM) {
LLVMAddLowerSwitchPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_promote_memory_to_register(LLVMPassManagerRef PM) {
LLVMAddPromoteMemoryToRegisterPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_reassociation(LLVMPassManagerRef PM) {
LLVMAddReassociatePass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_sccp(LLVMPassManagerRef PM) {
LLVMAddSCCPPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_scalar_repl_aggregates(LLVMPassManagerRef PM) {
LLVMAddScalarReplAggregatesPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_scalar_repl_aggregates_ssa(LLVMPassManagerRef PM) {
LLVMAddScalarReplAggregatesPassSSA(PM);
return Val_unit;
}
/* int -> [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_scalar_repl_aggregates_with_threshold(value threshold,
LLVMPassManagerRef PM) {
LLVMAddScalarReplAggregatesPassWithThreshold(PM, Int_val(threshold));
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_simplify_lib_calls(LLVMPassManagerRef PM) {
LLVMAddSimplifyLibCallsPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_tail_call_elimination(LLVMPassManagerRef PM) {
LLVMAddTailCallEliminationPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_demote_memory_to_register(LLVMPassManagerRef PM) {
LLVMAddDemoteMemoryToRegisterPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_verifier(LLVMPassManagerRef PM) {
LLVMAddVerifierPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_correlated_value_propagation(LLVMPassManagerRef PM) {
LLVMAddCorrelatedValuePropagationPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_early_cse(LLVMPassManagerRef PM) {
LLVMAddEarlyCSEPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_lower_expect_intrinsic(LLVMPassManagerRef PM) {
LLVMAddLowerExpectIntrinsicPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_lower_constant_intrinsics(LLVMPassManagerRef PM) {
LLVMAddLowerConstantIntrinsicsPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_type_based_alias_analysis(LLVMPassManagerRef PM) {
LLVMAddTypeBasedAliasAnalysisPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_scoped_no_alias_aa(LLVMPassManagerRef PM) {
LLVMAddScopedNoAliasAAPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_basic_alias_analysis(LLVMPassManagerRef PM) {
LLVMAddBasicAliasAnalysisPass(PM);
return Val_unit;
}
/* [<Llvm.PassManager.any] Llvm.PassManager.t -> unit */
CAMLprim value llvm_add_unify_function_exit_nodes(LLVMPassManagerRef PM) {
LLVMAddUnifyFunctionExitNodesPass(PM);
return Val_unit;
}

View File

@ -0,0 +1,5 @@
add_ocaml_library(llvm_transform_utils
OCAML llvm_transform_utils
OCAMLDEP llvm
C transform_utils_ocaml
LLVM TransformUtils)

View File

@ -0,0 +1,9 @@
(*===-- llvm_transform_utils.ml - LLVM OCaml Interface --------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
external clone_module : Llvm.llmodule -> Llvm.llmodule = "llvm_clone_module"

View File

@ -0,0 +1,16 @@
(*===-- llvm_transform_utils.mli - LLVM OCaml Interface -------*- OCaml -*-===*
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*===----------------------------------------------------------------------===*)
(** Transform Utilities.
This interface provides an OCaml API for LLVM transform utilities, the
classes in the [LLVMTransformUtils] library. *)
(** [clone_module m] returns an exact copy of module [m].
See the [llvm::CloneModule] function. *)
external clone_module : Llvm.llmodule -> Llvm.llmodule = "llvm_clone_module"

View File

@ -0,0 +1,31 @@
/*===-- transform_utils_ocaml.c - LLVM OCaml Glue ---------------*- C++ -*-===*\
|* *|
|* Part of the LLVM Project, under the Apache License v2.0 with LLVM *|
|* Exceptions. *|
|* See https://llvm.org/LICENSE.txt for license information. *|
|* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This file glues LLVM's OCaml interface to its C interface. These functions *|
|* are by and large transparent wrappers to the corresponding C functions. *|
|* *|
|* Note that these functions intentionally take liberties with the CAMLparamX *|
|* macros, since most of the parameters are not GC heap objects. *|
|* *|
\*===----------------------------------------------------------------------===*/
#include "llvm-c/Core.h"
#include "caml/mlvalues.h"
#include "caml/misc.h"
/*
* Do not move directly into external. This function is here to pull in
* -lLLVMTransformUtils, which would otherwise be not linked on static builds,
* as ld can't see the reference from OCaml code.
*/
/* llmodule -> llmodule */
CAMLprim LLVMModuleRef llvm_clone_module(LLVMModuleRef M) {
return LLVMCloneModule(M);
}

Some files were not shown because too many files have changed in this diff Show More