Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos | repos/DirectXShaderCompiler/LLVMBuild.txt | ;===- ./LLVMBuild.txt ------------------------------------------*- Conf -*--===;
;
; The LLVM Compiler Infrastructure
;
; This file is distributed under the University of Illinois Open Source
; License. See LICENSE.TXT for details.
;
;===------------------------------------------------------------------------===;
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[common]
subdirectories = docs examples lib projects tools utils
[component_0]
type = Group
name = Miscellaneous
parent = $ROOT
|
0 | repos | repos/DirectXShaderCompiler/CONTRIBUTING.md | # How to contribute
One of the easiest ways to contribute is to participate in discussions and discuss issues. You can also contribute by submitting pull requests with code changes.
## General feedback and discussions?
Please start a discussion on the repo issue tracker.
## Bugs and feature requests?
For non-security related bugs please log a new issue in the GitHub repo.
## Reporting security issues and bugs
Security issues and bugs should be reported privately, via email, to the Microsoft Security Response Center (MSRC) <[email protected]>. You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Further information, including the MSRC PGP key, can be found in the [Security TechCenter](https://technet.microsoft.com/en-us/security/ff852094.aspx).
## Filing issues
When filing issues, please use our [bug filing templates](https://github.com/aspnet/Home/wiki/Functional-bug-template).
The best way to get your bug fixed is to be as detailed as you can be about the problem.
Providing a minimal project with steps to reproduce the problem is ideal.
Here are questions you can answer before you file a bug to make sure you're not missing any important information.
1. Did you read the documentation?
2. Did you include the snippet of broken code in the issue?
3. What are the *EXACT* steps to reproduce this problem?
4. What version are you using?
GitHub supports [markdown](https://help.github.com/articles/github-flavored-markdown/), so when filing bugs make sure you check the formatting before clicking submit.
## Contributing code and content
You will need to complete a Contributor License Agreement (CLA) before your pull request can be accepted. This agreement testifies that you are granting us permission to use the source code you are submitting, and that this work is being submitted under appropriate license that we can use it.
You can complete the CLA by going through the steps at the [Contribution License Agreement site](https://cla.microsoft.com). Once we have received the signed CLA, we'll review the request. You will only need to do this once.
Make sure you can build the code. Familiarize yourself with the project workflow and our coding conventions. If you don't know what a pull request is read this article: <https://help.github.com/articles/using-pull-requests>.
Before submitting a feature or substantial code contribution please discuss it with the team and ensure it follows the product roadmap. You might also read these two blogs posts on contributing code: [Open Source Contribution Etiquette](http://tirania.org/blog/archive/2010/Dec-31.html) by Miguel de Icaza and [Don't "Push" Your Pull Requests](https://www.igvita.com/2011/12/19/dont-push-your-pull-requests/) by Ilya Grigorik. Note that all code submissions will be rigorously reviewed and tested by the team, and only those that meet an extremely high bar for both quality and design/roadmap appropriateness will be merged into the source.
### Coding guidelines
The coding, style, and general engineering guidelines follow those described in the docs/CodingStandards.rst. For additional guidelines in code specific to HLSL, see the docs/HLSLChanges.rst file.
DXC has adopted a clang-format requirement for all incoming changes to C and C++ files. PRs to DXC should have the *changed code* clang formatted to the LLVM style, and leave the remaining portions of the file unchanged. This can be done using the `git-clang-format` tool or IDE driven workflows. A GitHub action will run on all PRs to validate that the change is properly formatted.
### Documenting Pull Requests
Pull request descriptions should have the following format:
```md
Title summary of the changes (Less than 80 chars)
- Description Detail 1
- Description Detail 2
Fixes #bugnumber (Where relevant. In this specific format)
```
#### Titles
The title should focus on what the change intends to do rather than how it was done.
The description can and should explain how it was done if not obvious.
Titles under 76 characters print nicely in unix terminals under `git log`.
This is not a hard requirement, but is good guidance.
Tags in titles allow for speedy categorization
Title tags are generally one word or acronym enclosed in square brackets.
Limiting to one or two tags is ideal to keep titles short.
Some examples of common tags are:
- `[NFC]` - No Functional Change
- `[RFC]` - Request For Comments (often used for drafts to get feedback)
- `[Doc]` - Documentation change
- `[SPIRV]` - Changes related to SPIR-V
- `[HLSL2021]` - Changes related to HLSL 2021 features
- Other tags in use: `[Linux]`, `[mac]`, `[Win]`, `[PIX]`, etc...
Tags aren't formalized or any specific limited set.
If you're unsure of a reasonable tag to use, just don't use any.
If you want to invent a new tag, go for it!
These are to help categorize changes at a glance.
#### Descriptions
The PR description should include a more detailed description of the change,
an explanation for the motivation of the change, and links to any relevant Issues.
This does not need to be a dissertation, but should leave breadcrumbs for the next person debugging your code (who might be you).
Using the words `Fixes`, `Fixed`, `Closes`, `Closed`, or `Close` followed by
`#<issuenumber>`, will auto close an issue after the PR is merged.
#### Release Notes
Significant changes may require release notes that highlight important
compiler behavior changes for each named release.
These include changes that are:
- Visible to the users
- Significant changes to compiler behavior
- New features: Language, Hardware support, compiler options
- Important bug fixes
- Changes in default behavior
When such a change is made, the release note should be included as part of that change.
This is done in the docs/ReleaseNotes.md file.
If the change is meant for a named release, it should be added to that named release's section of the release notes file.
As the change is merged to the appropriate release branches, the release notes will come along with it.
If a change is meant for the next upcoming release, it should be added to the "Upcoming Release" section.
When the next upcoming release is named, the title will be updated and the release note will be included in the appropriate release.
When writing release note list entries:
- Keep the description to a single sentence.
- Links to specific PRs shouldn't be included.
- Markdown links to bugs are encouraged if the issue is too complicated to completely explain in a single sentence.
- Remember to update release notes as the nature of the change alters or is removed.
### Testing Pull Requests
All changes that make functional or behavioral changes to the compiler whether by fixing bugs or adding features
must include additional testing in the implementing pull request.
Changes that do not change behavior may still be required to add testing if the change impacts areas with limited test coverage
to verify that the change doesn't alter previously untested, but important behavior.
For bug fixes, at least one added test should fail in the absence of your non-test code changes.
Tests should include reasonable permutations of the target fix/change.
Include baseline changes with your change as needed.
Submitting a pull request kicks off an automated set of regression tests that verify the change introduces no unwanted changes in behavior.
For a pull request to be mergeable in GitHub, it will have to pass this regression test suite.
Changes made to DXC for the benefit of external projects should be verified using that project's testing protocols to avoid churn.
For cases where any of the above testing requirements are not possible, please specify why in the pull request.
### Merging Pull Requests
Pull requests should be a child commit of a reasonably recent commit in the main branch.
A pull request's commits should be squashed on merging except in very special circumstances usually involving release branches.
Ensure that the title and description are fully up to date before merging.
The title and description feed the final git commit message, and we want to ensure high quality commit messages in the repository history.
|
0 | repos | repos/DirectXShaderCompiler/ThirdPartyNotices.txt | Microsoft/DirectXShaderCompiler
THIRD-PARTY SOFTWARE NOTICES AND INFORMATION
Do Not Translate or Localize
This project incorporates components from the projects listed below. The
original copyright notices and the licenses under which Microsoft received
such components are set forth below. Microsoft reserves all rights not
expressly granted herein, whether by implication, estoppel or otherwise.
* LLVM
==============================================================================
LLVM Release License
==============================================================================
University of Illinois/NCSA
Open Source License
Copyright (c) 2003-2015 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.
==============================================================================
Copyrights and Licenses for Third Party Software Distributed with LLVM:
==============================================================================
The LLVM software contains code written by third parties. Such software will
have its own individual LICENSE.TXT file in the directory in which it appears.
This file will describe the copyrights, license, and restrictions which apply
to that code.
The disclaimer of warranty in the University of Illinois Open Source License
applies to all code in the LLVM Distribution, and nothing in any of the
other licenses gives permission to use the names of the LLVM Team or the
University of Illinois to endorse or promote products derived from this
Software.
The following pieces of software have additional or alternate copyrights,
licenses, and/or restrictions:
Program Directory
------- ---------
OpenBSD regex llvm/lib/Support/{reg*, COPYRIGHT.regex}
pyyaml tests llvm/test/YAMLParser/{*.data, LICENSE.TXT}
md5 contributions llvm/lib/Support/MD5.cpp llvm/include/llvm/Support/MD5.h
* tools\clang
==============================================================================
LLVM Release License
==============================================================================
University of Illinois/NCSA
Open Source License
Copyright (c) 2007-2015 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.
==============================================================================
The LLVM software contains code written by third parties. Such software will
have its own individual LICENSE.TXT file in the directory in which it appears.
This file will describe the copyrights, license, and restrictions which apply
to that code.
The disclaimer of warranty in the University of Illinois Open Source License
applies to all code in the LLVM Distribution, and nothing in any of the
other licenses gives permission to use the names of the LLVM Team or the
University of Illinois to endorse or promote products derived from this
Software.
* test\YAMLParser
Copyright (c) 2006 Kirill Simonov
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
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:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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
AUTHORS 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 IN THE
SOFTWARE.
* include\llvm\Support
LLVM System Interface Library
-------------------------------------------------------------------------------
The LLVM System Interface Library is licensed under the Illinois Open Source
License and has the following additional copyright:
Copyright (C) 2004 eXtensible Systems, Inc.
* OpenBSD regex
$OpenBSD: COPYRIGHT,v 1.3 2003/06/02 20:18:36 millert Exp $
Copyright 1992, 1993, 1994 Henry Spencer. All rights reserved.
This software is not subject to any license of the American Telephone
and Telegraph Company or of the Regents of the University of California.
Permission is granted to anyone to use this software for any purpose on
any computer system, and to alter it and redistribute it, subject
to the following restrictions:
1. The author is not responsible for the consequences of use of this
software, no matter how awful, even if they arise from flaws in it.
2. The origin of this software must not be misrepresented, either by
explicit claim or by omission. Since few users ever read sources,
credits must appear in the documentation.
3. Altered versions must be plainly marked as such, and must not be
misrepresented as being the original software. Since few users
ever read sources, credits must appear in the documentation.
4. This notice may not be removed or altered.
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
/*-
* Copyright (c) 1994
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)COPYRIGHT 8.1 (Berkeley) 3/16/94
*/
* lib\Headers Files
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in 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:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
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
AUTHORS 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 IN
THE SOFTWARE.
|
0 | repos | repos/DirectXShaderCompiler/README.md | # DirectX Shader Compiler
The DirectX Shader Compiler project includes a compiler and related tools used to compile High-Level Shader Language (HLSL) programs into DirectX Intermediate Language (DXIL) representation. Applications that make use of DirectX for graphics, games, and computation can use it to generate shader programs.
For more information, see the [Wiki](https://github.com/microsoft/DirectXShaderCompiler/wiki).
Visit the [DirectX Landing Page](https://devblogs.microsoft.com/directx/landing-page/) for more resources for DirectX developers.
## Features and Goals
The starting point of the project is a fork of the [LLVM](http://llvm.org/) and [Clang](http://clang.llvm.org/) projects, modified to accept HLSL and emit a validated container that can be consumed by GPU drivers.
At the moment, the DirectX HLSL Compiler provides the following components:
- dxc.exe, a command-line tool that can compile HLSL programs for shader model 6.0 or higher
- dxcompiler.dll, a DLL providing a componentized compiler, assembler, disassembler, and validator
- dxilconv.dll, a DLL providing a converter from DXBC (older shader bytecode format)
- various other tools based on the above components
The Microsoft Windows SDK releases include a supported version of the compiler and validator.
The goal of the project is to allow the broader community of shader developers to contribute to the language and representation of shader programs, maintaining the principles of compatibility and supportability for the platform. It's currently in active development across two axes: language evolution (with no impact to DXIL representation), and surfacing hardware capabilities (with impact to DXIL, and thus requiring coordination with GPU implementations).
### Pre-built Releases
Development kits containing only the dxc.exe driver app, the dxcompiler.dll, and the dxil.dll signing binary are available [here](https://github.com/microsoft/DirectXShaderCompiler/wiki/Releases), or in the [releases tab](https://github.com/microsoft/DirectXShaderCompiler/releases).
### SPIR-V CodeGen
As an example of community contribution, this project can also target the [SPIR-V](https://www.khronos.org/registry/spir-v/) intermediate representation. Please see the [doc](docs/SPIR-V.rst) for how HLSL features are mapped to SPIR-V, and the [wiki](https://github.com/microsoft/DirectXShaderCompiler/wiki/SPIR%E2%80%90V-CodeGen) page for how to build, use, and contribute to the SPIR-V CodeGen.
## Building Sources
See the full documentation for [Building and testing DXC](docs/BuildingAndTestingDXC.rst) for detailed instructions.
## Running Shaders
To run shaders compiled as DXIL, you will need support from the operating system as well as from the driver for your graphics adapter. Windows 10 Creators Update is the first version to support DXIL shaders. See the [Wiki](https://github.com/microsoft/DirectXShaderCompiler/wiki/Running-Shaders) for information on using experimental support or the software adapter.
### Hardware Support
Hardware GPU support for DXIL is provided by the following vendors:
#### NVIDIA
NVIDIA's r396 drivers (r397.64 and later) provide release mode support for DXIL
1.1 and Shader Model 6.1 on Win10 1709 and later, and experimental mode support
for DXIL 1.2 and Shader Model 6.2 on Win10 1803 and later. These drivers also
support DXR in experimental mode.
Drivers can be downloaded from [geforce.com](https://www.geforce.com/drivers).
#### AMD
AMD’s driver (Radeon Software Adrenalin Edition 18.4.1 or later) provides release mode support for DXIL 1.1 and Shader Model 6.1. Drivers can be downloaded from [AMD's download site](https://support.amd.com/en-us/download).
### Intel
Intel's 15.60 drivers (15.60.0.4849 and later) support release mode for DXIL 1.0 and Shader Model 6.0 as well as
release mode for DXIL 1.1 and Shader Model 6.1 (View Instancing support only).
Drivers can be downloaded from the following link [Intel Graphics Drivers](https://downloadcenter.intel.com/product/80939/Graphics-Drivers)
Direct access to 15.60 driver (latest as of this update) is provided below:
[Installer](https://downloadmirror.intel.com/27412/a08/win64_15.60.2.4901.exe)
[Release Notes related to DXIL](https://downloadmirror.intel.com/27266/eng/ReleaseNotes_GFX_15600.4849.pdf)
## Making Changes
To make contributions, see the [CONTRIBUTING.md](CONTRIBUTING.md) file in this project.
## Documentation
You can find documentation for this project in the `docs` directory. These contain the original LLVM documentation files, as well as two new files worth nothing:
* [HLSLChanges.rst](docs/HLSLChanges.rst): this is the starting point for how this fork diverges from the original llvm/clang sources
* [DXIL.rst](docs/DXIL.rst): this file contains the specification for the DXIL format
* [tools/clang/docs/UsingDxc.rst](tools/clang/docs/UsingDxc.rst): this file contains a user guide for dxc.exe
## License
DirectX Shader Compiler is distributed under the terms of the University of Illinois Open Source License.
See [LICENSE.txt](LICENSE.TXT) and [ThirdPartyNotices.txt](ThirdPartyNotices.txt) for details.
## Code of Conduct
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [[email protected]](mailto:[email protected]) with any additional questions or comments.
|
0 | repos/DirectXShaderCompiler/include | repos/DirectXShaderCompiler/include/miniz/miniz.h | /* miniz.c 2.1.0 - public domain deflate/inflate, zlib-subset, ZIP
reading/writing/appending, PNG writing See "unlicense" statement at the end
of this file. Rich Geldreich <[email protected]>, last updated Oct. 13,
2013 Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951:
http://www.ietf.org/rfc/rfc1951.txt
Most API's defined in miniz.c are optional. For example, to disable the
archive related functions just define MINIZ_NO_ARCHIVE_APIS, or to get rid of
all stdio usage define MINIZ_NO_STDIO (see the list below for more macros).
* Low-level Deflate/Inflate implementation notes:
Compression: Use the "tdefl" API's. The compressor supports raw, static,
and dynamic blocks, lazy or greedy parsing, match length filtering, RLE-only,
and Huffman-only streams. It performs and compresses approximately as well as
zlib.
Decompression: Use the "tinfl" API's. The entire decompressor is
implemented as a single function coroutine: see tinfl_decompress(). It
supports decompression into a 32KB (or larger power of 2) wrapping buffer, or
into a memory block large enough to hold the entire file.
The low-level tdefl/tinfl API's do not make any use of dynamic memory
allocation.
* zlib-style API notes:
miniz.c implements a fairly large subset of zlib. There's enough
functionality present for it to be a drop-in zlib replacement in many apps:
The z_stream struct, optional memory allocation callbacks
deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound
inflateInit/inflateInit2/inflate/inflateReset/inflateEnd
compress, compress2, compressBound, uncompress
CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly
routines. Supports raw deflate streams or standard zlib streams with adler-32
checking.
Limitations:
The callback API's are not implemented yet. No support for gzip headers or
zlib static dictionaries. I've tried to closely emulate zlib's various
flavors of stream flushing and return status codes, but there are no
guarantees that miniz.c pulls this off perfectly.
* PNG writing: See the tdefl_write_image_to_png_file_in_memory() function,
originally written by Alex Evans. Supports 1-4 bytes/pixel images.
* ZIP archive API notes:
The ZIP archive API's where designed with simplicity and efficiency in
mind, with just enough abstraction to get the job done with minimal fuss.
There are simple API's to retrieve file information, read files from existing
archives, create new archives, append new files to existing archives, or
clone archive data from one archive to another. It supports archives located
in memory or the heap, on disk (using stdio.h), or you can specify custom
file read/write callbacks.
- Archive reading: Just call this function to read a single file from a
disk archive:
void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const
char *pArchive_name, size_t *pSize, mz_uint zip_flags);
For more complex cases, use the "mz_zip_reader" functions. Upon opening an
archive, the entire central directory is located and read as-is into memory,
and subsequent file access only occurs when reading individual files.
- Archives file scanning: The simple way is to use this function to scan a
loaded archive for a specific file:
int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
const char *pComment, mz_uint flags);
The locate operation can optionally check file comments too, which (as one
example) can be used to identify multiple versions of the same file in an
archive. This function uses a simple linear search through the central
directory, so it's not very fast.
Alternately, you can iterate through all the files in an archive (using
mz_zip_reader_get_num_files()) and retrieve detailed info on each file by
calling mz_zip_reader_file_stat().
- Archive creation: Use the "mz_zip_writer" functions. The ZIP writer
immediately writes compressed file data to disk and builds an exact image of
the central directory in memory. The central directory image is written all
at once at the end of the archive file when the archive is finalized.
The archive writer can optionally align each file's local header and file
data to any power of 2 alignment, which can be useful when the archive will
be read from optical media. Also, the writer supports placing arbitrary data
blobs at the very beginning of ZIP archives. Archives written using either
feature are still readable by any ZIP tool.
- Archive appending: The simple way to add a single file to an archive is
to call this function:
mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename,
const char *pArchive_name, const void *pBuf, size_t buf_size, const void
*pComment, mz_uint16 comment_size, mz_uint level_and_flags);
The archive will be created if it doesn't already exist, otherwise it'll be
appended to. Note the appending is done in-place and is not an atomic
operation, so if something goes wrong during the operation it's possible the
archive could be left without a central directory (although the local file
headers and file data will be fine, so the archive will be recoverable).
For more complex archive modification scenarios:
1. The safest way is to use a mz_zip_reader to read the existing archive,
cloning only those bits you want to preserve into a new archive using using
the mz_zip_writer_add_from_zip_reader() function (which compiles the
compressed file data as-is). When you're done, delete the old archive and
rename the newly written archive, and you're done. This is safe but requires
a bunch of temporary disk space or heap memory.
2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using
mz_zip_writer_init_from_reader(), append new files as needed, then finalize
the archive which will write an updated central directory to the original
archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place()
does.) There's a possibility that the archive's central directory could be
lost with this method if anything goes wrong, though.
- ZIP archive support limitations:
No zip64 or spanning support. Extraction functions can only handle
unencrypted, stored or deflated files. Requires streams capable of seeking.
* This is a header file library, like stb_image.c. To get only a header file,
either cut and paste the below header, or create miniz.h, #define
MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it.
* Important: For best perf. be sure to customize the below macros for your
target platform: #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define
MINIZ_LITTLE_ENDIAN 1 #define MINIZ_HAS_64BIT_REGISTERS 1
* On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before
including miniz.c to ensure miniz uses the 64-bit variants: fopen64(),
stat64(), etc. Otherwise you won't be able to process large files (i.e.
32-bit stat() fails for me on files > 0x7FFFFFFF bytes).
*/
#pragma once
/* Defines to completely disable specific portions of miniz.c:
If all macros here are defined the only functionality remaining will be
CRC-32, adler-32, tinfl, and tdefl. */
/* Define MINIZ_NO_STDIO to disable all usage and any functions which rely on
* stdio for file I/O. */
/*#define MINIZ_NO_STDIO */
#define MINIZ_NO_STDIO // HLSL Change
/* If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able
* to get the current time, or */
/* get/set file times, and the C run-time funcs that get/set times won't be
* called. */
/* The current downside is the times written to your archives will be from 1979.
*/
/*#define MINIZ_NO_TIME */
#define MINIZ_NO_TIME // HLSL Change
/* Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. */
/*#define MINIZ_NO_ARCHIVE_APIS */
#define MINIZ_NO_ARCHIVE_APIS // HLSL Change
/* Define MINIZ_NO_ARCHIVE_WRITING_APIS to disable all writing related ZIP
* archive API's. */
/*#define MINIZ_NO_ARCHIVE_WRITING_APIS */
/* Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression
* API's. */
/*#define MINIZ_NO_ZLIB_APIS */
/* Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent
* conflicts against stock zlib. */
/*#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES */
/* Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc.
Note if MINIZ_NO_MALLOC is defined then the user must always provide custom
user alloc/free/realloc callbacks to the zlib and archive API's, and a few
stand-alone helper API's which don't provide custom user functions (such as
tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work.
*/
/*#define MINIZ_NO_MALLOC */
#define MINIZ_NO_MALLOC // HLSL Change
#if defined(__TINYC__) && (defined(__linux) || defined(__linux__))
/* TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc
* on Linux */
#define MINIZ_NO_TIME
#endif
#include <stddef.h>
#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS)
#include <time.h>
#endif
#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \
defined(__i386) || defined(__i486__) || defined(__i486) || \
defined(i386) || defined(__ia64__) || defined(__x86_64__)
/* MINIZ_X86_OR_X64_CPU is only used to help set the below macros. */
#define MINIZ_X86_OR_X64_CPU 1
#else
#define MINIZ_X86_OR_X64_CPU 0
#endif
#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
/* Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. */
#define MINIZ_LITTLE_ENDIAN 1
#else
#define MINIZ_LITTLE_ENDIAN 0
#endif
/* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES only if not set */
#if !defined(MINIZ_USE_UNALIGNED_LOADS_AND_STORES)
#if MINIZ_X86_OR_X64_CPU
/* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient
* integer loads and stores from unaligned addresses. */
#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
#define MINIZ_UNALIGNED_USE_MEMCPY
#else
#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0
#endif
#endif
#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || \
defined(_LP64) || defined(__LP64__) || defined(__ia64__) || \
defined(__x86_64__)
/* Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are
* reasonably fast (and don't involve compiler generated calls to helper
* functions). */
#define MINIZ_HAS_64BIT_REGISTERS 1
#else
#define MINIZ_HAS_64BIT_REGISTERS 0
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* ------------------- zlib-style API Definitions. */
/* For more compatibility with zlib, miniz.c uses unsigned long for some
* parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! */
typedef unsigned long mz_ulong;
/* mz_free() internally uses the MZ_FREE() macro (which by default calls free()
* unless you've modified the MZ_MALLOC macro) to release a block allocated from
* the heap. */
void mz_free(void *p);
#define MZ_ADLER32_INIT (1)
/* mz_adler32() returns the initial adler-32 value to use when called with
* ptr==NULL. */
mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len);
#define MZ_CRC32_INIT (0)
/* mz_crc32() returns the initial CRC-32 value to use when called with
* ptr==NULL. */
mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len);
/* Compression strategies. */
enum {
MZ_DEFAULT_STRATEGY = 0,
MZ_FILTERED = 1,
MZ_HUFFMAN_ONLY = 2,
MZ_RLE = 3,
MZ_FIXED = 4
};
/* Method */
#define MZ_DEFLATED 8
/* Heap allocation callbacks.
Note that mz_alloc_func parameter types purpsosely differ from zlib's:
items/size is size_t, not unsigned long. */
typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size);
typedef void (*mz_free_func)(void *opaque, void *address);
typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items,
size_t size);
/* Compression levels: 0-9 are the standard zlib-style levels, 10 is best
* possible compression (not zlib compatible, and may be very slow),
* MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. */
enum {
MZ_NO_COMPRESSION = 0,
MZ_BEST_SPEED = 1,
MZ_BEST_COMPRESSION = 9,
MZ_UBER_COMPRESSION = 10,
MZ_DEFAULT_LEVEL = 6,
MZ_DEFAULT_COMPRESSION = -1
};
#define MZ_VERSION "10.1.0"
#define MZ_VERNUM 0xA100
#define MZ_VER_MAJOR 10
#define MZ_VER_MINOR 1
#define MZ_VER_REVISION 0
#define MZ_VER_SUBREVISION 0
#ifndef MINIZ_NO_ZLIB_APIS
/* Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The
* other values are for advanced use (refer to the zlib docs). */
enum {
MZ_NO_FLUSH = 0,
MZ_PARTIAL_FLUSH = 1,
MZ_SYNC_FLUSH = 2,
MZ_FULL_FLUSH = 3,
MZ_FINISH = 4,
MZ_BLOCK = 5
};
/* Return status codes. MZ_PARAM_ERROR is non-standard. */
enum {
MZ_OK = 0,
MZ_STREAM_END = 1,
MZ_NEED_DICT = 2,
MZ_ERRNO = -1,
MZ_STREAM_ERROR = -2,
MZ_DATA_ERROR = -3,
MZ_MEM_ERROR = -4,
MZ_BUF_ERROR = -5,
MZ_VERSION_ERROR = -6,
MZ_PARAM_ERROR = -10000
};
/* Window bits */
#define MZ_DEFAULT_WINDOW_BITS 15
struct mz_internal_state;
/* Compression/decompression stream struct. */
typedef struct mz_stream_s {
const unsigned char *next_in; /* pointer to next byte to read */
unsigned int avail_in; /* number of bytes available at next_in */
mz_ulong total_in; /* total number of bytes consumed so far */
unsigned char *next_out; /* pointer to next byte to write */
unsigned int avail_out; /* number of bytes that can be written to next_out */
mz_ulong total_out; /* total number of bytes produced so far */
char *msg; /* error msg (unused) */
struct mz_internal_state
*state; /* internal state, allocated by zalloc/zfree */
mz_alloc_func
zalloc; /* optional heap allocation function (defaults to malloc) */
mz_free_func zfree; /* optional heap free function (defaults to free) */
void *opaque; /* heap alloc function user pointer */
int data_type; /* data_type (unused) */
mz_ulong adler; /* adler32 of the source or uncompressed data */
mz_ulong reserved; /* not used */
} mz_stream;
typedef mz_stream *mz_streamp;
/* Returns the version string of miniz.c. */
const char *mz_version(void);
/* mz_deflateInit() initializes a compressor with default options: */
/* Parameters: */
/* pStream must point to an initialized mz_stream struct. */
/* level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. */
/* level 1 enables a specially optimized compression function that's been
* optimized purely for performance, not ratio. */
/* (This special func. is currently only enabled when
* MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) */
/* Return values: */
/* MZ_OK on success. */
/* MZ_STREAM_ERROR if the stream is bogus. */
/* MZ_PARAM_ERROR if the input parameters are bogus. */
/* MZ_MEM_ERROR on out of memory. */
int mz_deflateInit(mz_streamp pStream, int level);
/* mz_deflateInit2() is like mz_deflate(), except with more control: */
/* Additional parameters: */
/* method must be MZ_DEFLATED */
/* window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with
* zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no
* header or footer) */
/* mem_level must be between [1, 9] (it's checked but ignored by miniz.c) */
int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits,
int mem_level, int strategy);
/* Quickly resets a compressor without having to reallocate anything. Same as
* calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). */
int mz_deflateReset(mz_streamp pStream);
/* mz_deflate() compresses the input to output, consuming as much of the input
* and producing as much output as possible. */
/* Parameters: */
/* pStream is the stream to read from and write to. You must initialize/update
* the next_in, avail_in, next_out, and avail_out members. */
/* flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or
* MZ_FINISH. */
/* Return values: */
/* MZ_OK on success (when flushing, or if more input is needed but not
* available, and/or there's more output to be written but the output buffer is
* full). */
/* MZ_STREAM_END if all input has been consumed and all output bytes have been
* written. Don't call mz_deflate() on the stream anymore. */
/* MZ_STREAM_ERROR if the stream is bogus. */
/* MZ_PARAM_ERROR if one of the parameters is invalid. */
/* MZ_BUF_ERROR if no forward progress is possible because the input and/or
* output buffers are empty. (Fill up the input buffer or free up some output
* space and try again.) */
int mz_deflate(mz_streamp pStream, int flush);
/* mz_deflateEnd() deinitializes a compressor: */
/* Return values: */
/* MZ_OK on success. */
/* MZ_STREAM_ERROR if the stream is bogus. */
int mz_deflateEnd(mz_streamp pStream);
/* mz_deflateBound() returns a (very) conservative upper bound on the amount of
* data that could be generated by deflate(), assuming flush is set to only
* MZ_NO_FLUSH or MZ_FINISH. */
mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len);
/* Single-call compression functions mz_compress() and mz_compress2(): */
/* Returns MZ_OK on success, or one of the error codes from mz_deflate() on
* failure. */
int mz_compress(unsigned char *pDest, mz_ulong *pDest_len,
const unsigned char *pSource, mz_ulong source_len);
int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len,
const unsigned char *pSource, mz_ulong source_len, int level);
/* mz_compressBound() returns a (very) conservative upper bound on the amount of
* data that could be generated by calling mz_compress(). */
mz_ulong mz_compressBound(mz_ulong source_len);
/* Initializes a decompressor. */
int mz_inflateInit(mz_streamp pStream);
/* mz_inflateInit2() is like mz_inflateInit() with an additional option that
* controls the window size and whether or not the stream has been wrapped with
* a zlib header/footer: */
/* window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or
* -MZ_DEFAULT_WINDOW_BITS (raw deflate). */
int mz_inflateInit2(mz_streamp pStream, int window_bits);
/* Quickly resets a compressor without having to reallocate anything. Same as
* calling mz_inflateEnd() followed by mz_inflateInit()/mz_inflateInit2(). */
int mz_inflateReset(mz_streamp pStream);
/* Decompresses the input stream to the output, consuming only as much of the
* input as needed, and writing as much to the output as possible. */
/* Parameters: */
/* pStream is the stream to read from and write to. You must initialize/update
* the next_in, avail_in, next_out, and avail_out members. */
/* flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. */
/* On the first call, if flush is MZ_FINISH it's assumed the input and output
* buffers are both sized large enough to decompress the entire stream in a
* single call (this is slightly faster). */
/* MZ_FINISH implies that there are no more source bytes available beside
* what's already in the input buffer, and that the output buffer is large
* enough to hold the rest of the decompressed data. */
/* Return values: */
/* MZ_OK on success. Either more input is needed but not available, and/or
* there's more output to be written but the output buffer is full. */
/* MZ_STREAM_END if all needed input has been consumed and all output bytes
* have been written. For zlib streams, the adler-32 of the decompressed data
* has also been verified. */
/* MZ_STREAM_ERROR if the stream is bogus. */
/* MZ_DATA_ERROR if the deflate stream is invalid. */
/* MZ_PARAM_ERROR if one of the parameters is invalid. */
/* MZ_BUF_ERROR if no forward progress is possible because the input buffer is
* empty but the inflater needs more input to continue, or if the output buffer
* is not large enough. Call mz_inflate() again */
/* with more input data, or with more room in the output buffer (except when
* using single call decompression, described above). */
int mz_inflate(mz_streamp pStream, int flush);
/* Deinitializes a decompressor. */
int mz_inflateEnd(mz_streamp pStream);
/* Single-call decompression. */
/* Returns MZ_OK on success, or one of the error codes from mz_inflate() on
* failure. */
int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len,
const unsigned char *pSource, mz_ulong source_len);
/* Returns a string description of the specified error code, or NULL if the
* error code is invalid. */
const char *mz_error(int err);
/* Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used
* as a drop-in replacement for the subset of zlib that miniz.c supports. */
/* Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you
* use zlib in the same project. */
#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
typedef unsigned char Byte;
typedef unsigned int uInt;
typedef mz_ulong uLong;
typedef Byte Bytef;
typedef uInt uIntf;
typedef char charf;
typedef int intf;
typedef void *voidpf;
typedef uLong uLongf;
typedef void *voidp;
typedef void *const voidpc;
#define Z_NULL 0
#define Z_NO_FLUSH MZ_NO_FLUSH
#define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH
#define Z_SYNC_FLUSH MZ_SYNC_FLUSH
#define Z_FULL_FLUSH MZ_FULL_FLUSH
#define Z_FINISH MZ_FINISH
#define Z_BLOCK MZ_BLOCK
#define Z_OK MZ_OK
#define Z_STREAM_END MZ_STREAM_END
#define Z_NEED_DICT MZ_NEED_DICT
#define Z_ERRNO MZ_ERRNO
#define Z_STREAM_ERROR MZ_STREAM_ERROR
#define Z_DATA_ERROR MZ_DATA_ERROR
#define Z_MEM_ERROR MZ_MEM_ERROR
#define Z_BUF_ERROR MZ_BUF_ERROR
#define Z_VERSION_ERROR MZ_VERSION_ERROR
#define Z_PARAM_ERROR MZ_PARAM_ERROR
#define Z_NO_COMPRESSION MZ_NO_COMPRESSION
#define Z_BEST_SPEED MZ_BEST_SPEED
#define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION
#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION
#define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY
#define Z_FILTERED MZ_FILTERED
#define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY
#define Z_RLE MZ_RLE
#define Z_FIXED MZ_FIXED
#define Z_DEFLATED MZ_DEFLATED
#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS
#define alloc_func mz_alloc_func
#define free_func mz_free_func
#define internal_state mz_internal_state
#define z_stream mz_stream
#define deflateInit mz_deflateInit
#define deflateInit2 mz_deflateInit2
#define deflateReset mz_deflateReset
#define deflate mz_deflate
#define deflateEnd mz_deflateEnd
#define deflateBound mz_deflateBound
#define compress mz_compress
#define compress2 mz_compress2
#define compressBound mz_compressBound
#define inflateInit mz_inflateInit
#define inflateInit2 mz_inflateInit2
#define inflateReset mz_inflateReset
#define inflate mz_inflate
#define inflateEnd mz_inflateEnd
#define uncompress mz_uncompress
#define crc32 mz_crc32
#define adler32 mz_adler32
#define MAX_WBITS 15
#define MAX_MEM_LEVEL 9
#define zError mz_error
#define ZLIB_VERSION MZ_VERSION
#define ZLIB_VERNUM MZ_VERNUM
#define ZLIB_VER_MAJOR MZ_VER_MAJOR
#define ZLIB_VER_MINOR MZ_VER_MINOR
#define ZLIB_VER_REVISION MZ_VER_REVISION
#define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION
#define zlibVersion mz_version
#define zlib_version mz_version()
#endif /* #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES */
#endif /* MINIZ_NO_ZLIB_APIS */
#ifdef __cplusplus
}
#endif
#pragma once
#include <assert.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
/* ------------------- Types and macros */
typedef unsigned char mz_uint8;
typedef signed short mz_int16;
typedef unsigned short mz_uint16;
typedef unsigned int mz_uint32;
typedef unsigned int mz_uint;
typedef int64_t mz_int64;
typedef uint64_t mz_uint64;
typedef int mz_bool;
#define MZ_FALSE (0)
#define MZ_TRUE (1)
/* Works around MSVC's spammy "warning C4127: conditional expression is
* constant" message. */
#ifdef _MSC_VER
#define MZ_MACRO_END while (0, 0)
#else
#define MZ_MACRO_END while (0)
#endif
#ifdef MINIZ_NO_STDIO
#define MZ_FILE void *
#else
#include <stdio.h>
#define MZ_FILE FILE
#endif /* #ifdef MINIZ_NO_STDIO */
#ifdef MINIZ_NO_TIME
typedef struct mz_dummy_time_t_tag {
int m_dummy;
} mz_dummy_time_t;
#define MZ_TIME_T mz_dummy_time_t
#else
#define MZ_TIME_T time_t
#endif
#define MZ_ASSERT(x) assert(x)
#ifdef MINIZ_NO_MALLOC
#define MZ_MALLOC(x) NULL
#define MZ_FREE(x) (void)x, ((void)0)
#define MZ_REALLOC(p, x) NULL
#else
#define MZ_MALLOC(x) malloc(x)
#define MZ_FREE(x) free(x)
#define MZ_REALLOC(p, x) realloc(p, x)
#endif
#define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b))
#define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b))
#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj))
#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
#define MZ_READ_LE16(p) *((const mz_uint16 *)(p))
#define MZ_READ_LE32(p) *((const mz_uint32 *)(p))
#else
#define MZ_READ_LE16(p) \
((mz_uint32)(((const mz_uint8 *)(p))[0]) | \
((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U))
#define MZ_READ_LE32(p) \
((mz_uint32)(((const mz_uint8 *)(p))[0]) | \
((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | \
((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | \
((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U))
#endif
#define MZ_READ_LE64(p) \
(((mz_uint64)MZ_READ_LE32(p)) | \
(((mz_uint64)MZ_READ_LE32((const mz_uint8 *)(p) + sizeof(mz_uint32))) \
<< 32U))
#ifdef _MSC_VER
#define MZ_FORCEINLINE __forceinline
#elif defined(__GNUC__)
#define MZ_FORCEINLINE __inline__ __attribute__((__always_inline__))
#else
#define MZ_FORCEINLINE inline
#endif
#ifdef __cplusplus
extern "C" {
#endif
extern void *miniz_def_alloc_func(void *opaque, size_t items, size_t size);
extern void miniz_def_free_func(void *opaque, void *address);
extern void *miniz_def_realloc_func(void *opaque, void *address, size_t items,
size_t size);
#define MZ_UINT16_MAX (0xFFFFU)
#define MZ_UINT32_MAX (0xFFFFFFFFU)
#ifdef __cplusplus
}
#endif
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
/* ------------------- Low-level Compression API Definitions */
/* Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly
* slower, and raw/dynamic blocks will be output more frequently). */
#define TDEFL_LESS_MEMORY 0
/* tdefl_init() compression flags logically OR'd together (low 12 bits contain
* the max. number of probes per dictionary search): */
/* TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes
* per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap
* compression), 4095=Huffman+LZ (slowest/best compression). */
enum {
TDEFL_HUFFMAN_ONLY = 0,
TDEFL_DEFAULT_MAX_PROBES = 128,
TDEFL_MAX_PROBES_MASK = 0xFFF
};
/* TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before
* the deflate data, and the Adler-32 of the source data at the end. Otherwise,
* you'll get raw deflate data. */
/* TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even
* when not writing zlib headers). */
/* TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more
* efficient lazy parsing. */
/* TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's
* initialization time to the minimum, but the output may vary from run to run
* given the same input (depending on the contents of memory). */
/* TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1)
*/
/* TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. */
/* TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. */
/* TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. */
/* The low 12 bits are reserved to control the max # of hash probes per
* dictionary lookup (see TDEFL_MAX_PROBES_MASK). */
enum {
TDEFL_WRITE_ZLIB_HEADER = 0x01000,
TDEFL_COMPUTE_ADLER32 = 0x02000,
TDEFL_GREEDY_PARSING_FLAG = 0x04000,
TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000,
TDEFL_RLE_MATCHES = 0x10000,
TDEFL_FILTER_MATCHES = 0x20000,
TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000,
TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000
};
/* High level compression functions: */
/* tdefl_compress_mem_to_heap() compresses a block in memory to a heap block
* allocated via malloc(). */
/* On entry: */
/* pSrc_buf, src_buf_len: Pointer and size of source block to compress. */
/* flags: The max match finder probes (default is 128) logically OR'd against
* the above flags. Higher probes are slower but improve compression. */
/* On return: */
/* Function returns a pointer to the compressed data, or NULL on failure. */
/* *pOut_len will be set to the compressed data's size, which could be larger
* than src_buf_len on uncompressible data. */
/* The caller must free() the returned block when it's no longer needed. */
void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
size_t *pOut_len, int flags);
/* tdefl_compress_mem_to_mem() compresses a block in memory to another block in
* memory. */
/* Returns 0 on failure. */
size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
const void *pSrc_buf, size_t src_buf_len,
int flags);
/* Compresses an image to a compressed PNG file in memory. */
/* On entry: */
/* pImage, w, h, and num_chans describe the image to compress. num_chans may be
* 1, 2, 3, or 4. */
/* The image pitch in bytes per scanline will be w*num_chans. The leftmost
* pixel on the top scanline is stored first in memory. */
/* level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED,
* MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL */
/* If flip is true, the image will be flipped on the Y axis (useful for OpenGL
* apps). */
/* On return: */
/* Function returns a pointer to the compressed data, or NULL on failure. */
/* *pLen_out will be set to the size of the PNG image file. */
/* The caller must mz_free() the returned heap block (which will typically be
* larger than *pLen_out) when it's no longer needed. */
void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w,
int h, int num_chans,
size_t *pLen_out,
mz_uint level, mz_bool flip);
void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h,
int num_chans, size_t *pLen_out);
/* Output stream interface. The compressor uses this interface to write
* compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. */
typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len,
void *pUser);
/* tdefl_compress_mem_to_output() compresses a block to an output stream. The
* above helpers use this function internally. */
mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len,
tdefl_put_buf_func_ptr pPut_buf_func,
void *pPut_buf_user, int flags);
enum {
TDEFL_MAX_HUFF_TABLES = 3,
TDEFL_MAX_HUFF_SYMBOLS_0 = 288,
TDEFL_MAX_HUFF_SYMBOLS_1 = 32,
TDEFL_MAX_HUFF_SYMBOLS_2 = 19,
TDEFL_LZ_DICT_SIZE = 32768,
TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1,
TDEFL_MIN_MATCH_LEN = 3,
TDEFL_MAX_MATCH_LEN = 258
};
/* TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed
* output block (using static/fixed Huffman codes). */
#if TDEFL_LESS_MEMORY
enum {
TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024,
TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
TDEFL_MAX_HUFF_SYMBOLS = 288,
TDEFL_LZ_HASH_BITS = 12,
TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
};
#else
enum {
TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024,
TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
TDEFL_MAX_HUFF_SYMBOLS = 288,
TDEFL_LZ_HASH_BITS = 15,
TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
};
#endif
/* The low-level tdefl functions below may be used directly if the above helper
* functions aren't flexible enough. The low-level functions don't make any heap
* allocations, unlike the above helper functions. */
typedef enum {
TDEFL_STATUS_BAD_PARAM = -2,
TDEFL_STATUS_PUT_BUF_FAILED = -1,
TDEFL_STATUS_OKAY = 0,
TDEFL_STATUS_DONE = 1
} tdefl_status;
/* Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums */
typedef enum {
TDEFL_NO_FLUSH = 0,
TDEFL_SYNC_FLUSH = 2,
TDEFL_FULL_FLUSH = 3,
TDEFL_FINISH = 4
} tdefl_flush;
/* tdefl's compression state structure. */
typedef struct {
tdefl_put_buf_func_ptr m_pPut_buf_func;
void *m_pPut_buf_user;
mz_uint m_flags, m_max_probes[2];
int m_greedy_parsing;
mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;
mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end;
mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in,
m_bit_buffer;
mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit,
m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index,
m_wants_to_finish;
tdefl_status m_prev_return_status;
const void *m_pIn_buf;
void *m_pOut_buf;
size_t *m_pIn_buf_size, *m_pOut_buf_size;
tdefl_flush m_flush;
const mz_uint8 *m_pSrc;
size_t m_src_buf_left, m_out_buf_ofs;
mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1];
mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE];
mz_uint16 m_next[TDEFL_LZ_DICT_SIZE];
mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE];
mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE];
} tdefl_compressor;
/* Initializes the compressor. */
/* There is no corresponding deinit() function because the tdefl API's do not
* dynamically allocate memory. */
/* pBut_buf_func: If NULL, output data will be supplied to the specified
* callback. In this case, the user should call the tdefl_compress_buffer() API
* for compression. */
/* If pBut_buf_func is NULL the user should always call the tdefl_compress()
* API. */
/* flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER,
* etc.) */
tdefl_status tdefl_init(tdefl_compressor *d,
tdefl_put_buf_func_ptr pPut_buf_func,
void *pPut_buf_user, int flags);
/* Compresses a block of data, consuming as much of the specified input buffer
* as possible, and writing as much compressed data to the specified output
* buffer as possible. */
tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf,
size_t *pIn_buf_size, void *pOut_buf,
size_t *pOut_buf_size, tdefl_flush flush);
/* tdefl_compress_buffer() is only usable when the tdefl_init() is called with a
* non-NULL tdefl_put_buf_func_ptr. */
/* tdefl_compress_buffer() always consumes the entire input buffer. */
tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf,
size_t in_buf_size, tdefl_flush flush);
tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d);
mz_uint32 tdefl_get_adler32(tdefl_compressor *d);
/* Create tdefl_compress() flags given zlib-style compression parameters. */
/* level may range from [0,10] (where 10 is absolute max compression, but may be
* much slower on some files) */
/* window_bits may be -15 (raw deflate) or 15 (zlib) */
/* strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY,
* MZ_RLE, or MZ_FIXED */
mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits,
int strategy);
#ifndef MINIZ_NO_MALLOC
/* Allocate the tdefl_compressor structure in C so that */
/* non-C language bindings to tdefl_ API don't need to worry about */
/* structure size and allocation mechanism. */
tdefl_compressor *tdefl_compressor_alloc(void);
void tdefl_compressor_free(tdefl_compressor *pComp);
#endif
#ifdef __cplusplus
}
#endif
#pragma once
/* ------------------- Low-level Decompression API Definitions */
#ifdef __cplusplus
extern "C" {
#endif
/* Decompression flags used by tinfl_decompress(). */
/* TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and
* ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the
* input is a raw deflate stream. */
/* TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available
* beyond the end of the supplied input buffer. If clear, the input buffer
* contains all remaining input. */
/* TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large
* enough to hold the entire decompressed stream. If clear, the output buffer is
* at least the size of the dictionary (typically 32KB). */
/* TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the
* decompressed bytes. */
enum {
TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
TINFL_FLAG_HAS_MORE_INPUT = 2,
TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
TINFL_FLAG_COMPUTE_ADLER32 = 8
};
/* High level decompression functions: */
/* tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block
* allocated via malloc(). */
/* On entry: */
/* pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data
* to decompress. */
/* On return: */
/* Function returns a pointer to the decompressed data, or NULL on failure. */
/* *pOut_len will be set to the decompressed data's size, which could be larger
* than src_buf_len on uncompressible data. */
/* The caller must call mz_free() on the returned block when it's no longer
* needed. */
void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
size_t *pOut_len, int flags);
/* tinfl_decompress_mem_to_mem() decompresses a block in memory to another block
* in memory. */
/* Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes
* written on success. */
#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
const void *pSrc_buf, size_t src_buf_len,
int flags);
/* tinfl_decompress_mem_to_callback() decompresses a block in memory to an
* internal 32KB buffer, and a user provided callback function will be called to
* flush the buffer. */
/* Returns 1 on success or 0 on failure. */
typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser);
int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size,
tinfl_put_buf_func_ptr pPut_buf_func,
void *pPut_buf_user, int flags);
struct tinfl_decompressor_tag;
typedef struct tinfl_decompressor_tag tinfl_decompressor;
#ifndef MINIZ_NO_MALLOC
/* Allocate the tinfl_decompressor structure in C so that */
/* non-C language bindings to tinfl_ API don't need to worry about */
/* structure size and allocation mechanism. */
tinfl_decompressor *tinfl_decompressor_alloc(void);
void tinfl_decompressor_free(tinfl_decompressor *pDecomp);
#endif
/* Max size of LZ dictionary. */
#define TINFL_LZ_DICT_SIZE 32768
/* Return status. */
typedef enum {
/* This flags indicates the inflator needs 1 or more input bytes to make
forward progress, but the caller is indicating that no more are available.
The compressed data */
/* is probably corrupted. If you call the inflator again with more bytes it'll
try to continue processing the input but this is a BAD sign (either the
data is corrupted or you called it incorrectly). */
/* If you call it again with no input you'll just get
TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS again. */
TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS = -4,
/* This flag indicates that one or more of the input parameters was obviously
bogus. (You can try calling it again, but if you get this error the calling
code is wrong.) */
TINFL_STATUS_BAD_PARAM = -3,
/* This flags indicate the inflator is finished but the adler32 check of the
uncompressed data didn't match. If you call it again it'll return
TINFL_STATUS_DONE. */
TINFL_STATUS_ADLER32_MISMATCH = -2,
/* This flags indicate the inflator has somehow failed (bad code, corrupted
input, etc.). If you call it again without resetting via tinfl_init() it
it'll just keep on returning the same status failure code. */
TINFL_STATUS_FAILED = -1,
/* Any status code less than TINFL_STATUS_DONE must indicate a failure. */
/* This flag indicates the inflator has returned every byte of uncompressed
data that it can, has consumed every byte that it needed, has successfully
reached the end of the deflate stream, and */
/* if zlib headers and adler32 checking enabled that it has successfully
checked the uncompressed data's adler32. If you call it again you'll just
get TINFL_STATUS_DONE over and over again. */
TINFL_STATUS_DONE = 0,
/* This flag indicates the inflator MUST have more input data (even 1 byte)
before it can make any more forward progress, or you need to clear the
TINFL_FLAG_HAS_MORE_INPUT */
/* flag on the next call if you don't have any more source data. If the source
data was somehow corrupted it's also possible (but unlikely) for the
inflator to keep on demanding input to */
/* proceed, so be sure to properly set the TINFL_FLAG_HAS_MORE_INPUT flag. */
TINFL_STATUS_NEEDS_MORE_INPUT = 1,
/* This flag indicates the inflator definitely has 1 or more bytes of
uncompressed data available, but it cannot write this data into the output
buffer. */
/* Note if the source compressed data was corrupted it's possible for the
inflator to return a lot of uncompressed data to the caller. I've been
assuming you know how much uncompressed data to expect */
/* (either exact or worst case) and will stop calling the inflator and fail
after receiving too much. In pure streaming scenarios where you have no
idea how many bytes to expect this may not be possible */
/* so I may need to add some code to address this. */
TINFL_STATUS_HAS_MORE_OUTPUT = 2
} tinfl_status;
/* Initializes the decompressor to its initial state. */
#define tinfl_init(r) \
do { \
(r)->m_state = 0; \
} \
MZ_MACRO_END
#define tinfl_get_adler32(r) (r)->m_check_adler32
/* Main low-level decompressor coroutine function. This is the only function
* actually needed for decompression. All the other functions are just
* high-level helpers for improved usability. */
/* This is a universal API, i.e. it can be used as a building block to build any
* desired higher level decompression API. In the limit case, it can be called
* once per every byte input or output. */
tinfl_status tinfl_decompress(tinfl_decompressor *r,
const mz_uint8 *pIn_buf_next,
size_t *pIn_buf_size, mz_uint8 *pOut_buf_start,
mz_uint8 *pOut_buf_next, size_t *pOut_buf_size,
const mz_uint32 decomp_flags);
/* Internal/private bits follow. */
enum {
TINFL_MAX_HUFF_TABLES = 3,
TINFL_MAX_HUFF_SYMBOLS_0 = 288,
TINFL_MAX_HUFF_SYMBOLS_1 = 32,
TINFL_MAX_HUFF_SYMBOLS_2 = 19,
TINFL_FAST_LOOKUP_BITS = 10,
TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
};
typedef struct {
mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];
mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE],
m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
} tinfl_huff_table;
#if MINIZ_HAS_64BIT_REGISTERS
#define TINFL_USE_64BIT_BITBUF 1
#else
#define TINFL_USE_64BIT_BITBUF 0
#endif
#if TINFL_USE_64BIT_BITBUF
typedef mz_uint64 tinfl_bit_buf_t;
#define TINFL_BITBUF_SIZE (64)
#else
typedef mz_uint32 tinfl_bit_buf_t;
#define TINFL_BITBUF_SIZE (32)
#endif
struct tinfl_decompressor_tag {
mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type,
m_check_adler32, m_dist, m_counter, m_num_extra,
m_table_sizes[TINFL_MAX_HUFF_TABLES];
tinfl_bit_buf_t m_bit_buf;
size_t m_dist_from_out_buf_start;
tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];
mz_uint8 m_raw_header[4],
m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
};
#ifdef __cplusplus
}
#endif
#pragma once
/* ------------------- ZIP archive reading/writing */
#ifndef MINIZ_NO_ARCHIVE_APIS
#ifdef __cplusplus
extern "C" {
#endif
enum {
/* Note: These enums can be reduced as needed to save memory or stack space -
they are pretty conservative. */
MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024,
MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 512,
MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 512
};
typedef struct {
/* Central directory file index. */
mz_uint32 m_file_index;
/* Byte offset of this entry in the archive's central directory. Note we
* currently only support up to UINT_MAX or less bytes in the central dir. */
mz_uint64 m_central_dir_ofs;
/* These fields are copied directly from the zip's central dir. */
mz_uint16 m_version_made_by;
mz_uint16 m_version_needed;
mz_uint16 m_bit_flag;
mz_uint16 m_method;
#ifndef MINIZ_NO_TIME
MZ_TIME_T m_time;
#endif
/* CRC-32 of uncompressed data. */
mz_uint32 m_crc32;
/* File's compressed size. */
mz_uint64 m_comp_size;
/* File's uncompressed size. Note, I've seen some old archives where directory
* entries had 512 bytes for their uncompressed sizes, but when you try to
* unpack them you actually get 0 bytes. */
mz_uint64 m_uncomp_size;
/* Zip internal and external file attributes. */
mz_uint16 m_internal_attr;
mz_uint32 m_external_attr;
/* Entry's local header file offset in bytes. */
mz_uint64 m_local_header_ofs;
/* Size of comment in bytes. */
mz_uint32 m_comment_size;
/* MZ_TRUE if the entry appears to be a directory. */
mz_bool m_is_directory;
/* MZ_TRUE if the entry uses encryption/strong encryption (which miniz_zip
* doesn't support) */
mz_bool m_is_encrypted;
/* MZ_TRUE if the file is not encrypted, a patch file, and if it uses a
* compression method we support. */
mz_bool m_is_supported;
/* Filename. If string ends in '/' it's a subdirectory entry. */
/* Guaranteed to be zero terminated, may be truncated to fit. */
char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE];
/* Comment field. */
/* Guaranteed to be zero terminated, may be truncated to fit. */
char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE];
} mz_zip_archive_file_stat;
typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs,
void *pBuf, size_t n);
typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs,
const void *pBuf, size_t n);
typedef mz_bool (*mz_file_needs_keepalive)(void *pOpaque);
struct mz_zip_internal_state_tag;
typedef struct mz_zip_internal_state_tag mz_zip_internal_state;
typedef enum {
MZ_ZIP_MODE_INVALID = 0,
MZ_ZIP_MODE_READING = 1,
MZ_ZIP_MODE_WRITING = 2,
MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3
} mz_zip_mode;
typedef enum {
MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100,
MZ_ZIP_FLAG_IGNORE_PATH = 0x0200,
MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400,
MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800,
MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG =
0x1000, /* if enabled, mz_zip_reader_locate_file() will be called on each
file as its validated to ensure the func finds the file in the
central dir (intended for testing) */
MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY =
0x2000, /* validate the local headers, but don't decompress the entire
file and check the crc32 */
MZ_ZIP_FLAG_WRITE_ZIP64 =
0x4000, /* always use the zip64 file format, instead of the original zip
file format with automatic switch to zip64. Use as flags
parameter with mz_zip_writer_init*_v2 */
MZ_ZIP_FLAG_WRITE_ALLOW_READING = 0x8000,
MZ_ZIP_FLAG_ASCII_FILENAME = 0x10000
} mz_zip_flags;
typedef enum {
MZ_ZIP_TYPE_INVALID = 0,
MZ_ZIP_TYPE_USER,
MZ_ZIP_TYPE_MEMORY,
MZ_ZIP_TYPE_HEAP,
MZ_ZIP_TYPE_FILE,
MZ_ZIP_TYPE_CFILE,
MZ_ZIP_TOTAL_TYPES
} mz_zip_type;
/* miniz error codes. Be sure to update mz_zip_get_error_string() if you add or
* modify this enum. */
typedef enum {
MZ_ZIP_NO_ERROR = 0,
MZ_ZIP_UNDEFINED_ERROR,
MZ_ZIP_TOO_MANY_FILES,
MZ_ZIP_FILE_TOO_LARGE,
MZ_ZIP_UNSUPPORTED_METHOD,
MZ_ZIP_UNSUPPORTED_ENCRYPTION,
MZ_ZIP_UNSUPPORTED_FEATURE,
MZ_ZIP_FAILED_FINDING_CENTRAL_DIR,
MZ_ZIP_NOT_AN_ARCHIVE,
MZ_ZIP_INVALID_HEADER_OR_CORRUPTED,
MZ_ZIP_UNSUPPORTED_MULTIDISK,
MZ_ZIP_DECOMPRESSION_FAILED,
MZ_ZIP_COMPRESSION_FAILED,
MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE,
MZ_ZIP_CRC_CHECK_FAILED,
MZ_ZIP_UNSUPPORTED_CDIR_SIZE,
MZ_ZIP_ALLOC_FAILED,
MZ_ZIP_FILE_OPEN_FAILED,
MZ_ZIP_FILE_CREATE_FAILED,
MZ_ZIP_FILE_WRITE_FAILED,
MZ_ZIP_FILE_READ_FAILED,
MZ_ZIP_FILE_CLOSE_FAILED,
MZ_ZIP_FILE_SEEK_FAILED,
MZ_ZIP_FILE_STAT_FAILED,
MZ_ZIP_INVALID_PARAMETER,
MZ_ZIP_INVALID_FILENAME,
MZ_ZIP_BUF_TOO_SMALL,
MZ_ZIP_INTERNAL_ERROR,
MZ_ZIP_FILE_NOT_FOUND,
MZ_ZIP_ARCHIVE_TOO_LARGE,
MZ_ZIP_VALIDATION_FAILED,
MZ_ZIP_WRITE_CALLBACK_FAILED,
MZ_ZIP_TOTAL_ERRORS
} mz_zip_error;
typedef struct {
mz_uint64 m_archive_size;
mz_uint64 m_central_directory_file_ofs;
/* We only support up to UINT32_MAX files in zip64 mode. */
mz_uint32 m_total_files;
mz_zip_mode m_zip_mode;
mz_zip_type m_zip_type;
mz_zip_error m_last_error;
mz_uint64 m_file_offset_alignment;
mz_alloc_func m_pAlloc;
mz_free_func m_pFree;
mz_realloc_func m_pRealloc;
void *m_pAlloc_opaque;
mz_file_read_func m_pRead;
mz_file_write_func m_pWrite;
mz_file_needs_keepalive m_pNeeds_keepalive;
void *m_pIO_opaque;
mz_zip_internal_state *m_pState;
} mz_zip_archive;
typedef struct {
mz_zip_archive *pZip;
mz_uint flags;
int status;
#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS
mz_uint file_crc32;
#endif
mz_uint64 read_buf_size, read_buf_ofs, read_buf_avail, comp_remaining,
out_buf_ofs, cur_file_ofs;
mz_zip_archive_file_stat file_stat;
void *pRead_buf;
void *pWrite_buf;
size_t out_blk_remain;
tinfl_decompressor inflator;
} mz_zip_reader_extract_iter_state;
/* -------- ZIP reading */
/* Inits a ZIP archive reader. */
/* These functions read and validate the archive's central directory. */
mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags);
mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem,
size_t size, mz_uint flags);
#ifndef MINIZ_NO_STDIO
/* Read a archive from a disk file. */
/* file_start_ofs is the file offset where the archive actually begins, or 0. */
/* actual_archive_size is the true total size of the archive, which may be
* smaller than the file's actual size on disk. If zero the entire file is
* treated as the archive. */
mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename,
mz_uint32 flags);
mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename,
mz_uint flags, mz_uint64 file_start_ofs,
mz_uint64 archive_size);
/* Read an archive from an already opened FILE, beginning at the current file
* position. */
/* The archive is assumed to be archive_size bytes long. If archive_size is < 0,
* then the entire rest of the file is assumed to contain the archive. */
/* The FILE will NOT be closed when mz_zip_reader_end() is called. */
mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile,
mz_uint64 archive_size, mz_uint flags);
#endif
/* Ends archive reading, freeing all allocations, and closing the input archive
* file if mz_zip_reader_init_file() was used. */
mz_bool mz_zip_reader_end(mz_zip_archive *pZip);
/* -------- ZIP reading or writing */
/* Clears a mz_zip_archive struct to all zeros. */
/* Important: This must be done before passing the struct to any mz_zip
* functions. */
void mz_zip_zero_struct(mz_zip_archive *pZip);
mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip);
mz_zip_type mz_zip_get_type(mz_zip_archive *pZip);
/* Returns the total number of files in the archive. */
mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip);
mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip);
mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip);
MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip);
/* Reads n bytes of raw archive data, starting at file offset file_ofs, to pBuf.
*/
size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs,
void *pBuf, size_t n);
/* All mz_zip funcs set the m_last_error field in the mz_zip_archive struct.
* These functions retrieve/manipulate this field. */
/* Note that the m_last_error functionality is not thread safe. */
mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num);
mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip);
mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip);
mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip);
const char *mz_zip_get_error_string(mz_zip_error mz_err);
/* MZ_TRUE if the archive file entry is a directory entry. */
mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip,
mz_uint file_index);
/* MZ_TRUE if the file is encrypted/strong encrypted. */
mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip,
mz_uint file_index);
/* MZ_TRUE if the compression method is supported, and the file is not
* encrypted, and the file is not a compressed patch file. */
mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip,
mz_uint file_index);
/* Retrieves the filename of an archive file entry. */
/* Returns the number of bytes written to pFilename, or if filename_buf_size is
* 0 this function returns the number of bytes needed to fully store the
* filename. */
mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index,
char *pFilename, mz_uint filename_buf_size);
/* Attempts to locates a file in the archive's central directory. */
/* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */
/* Returns -1 if the file cannot be found. */
int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
const char *pComment, mz_uint flags);
int mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName,
const char *pComment, mz_uint flags,
mz_uint32 *file_index);
/* Returns detailed information about an archive file entry. */
mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index,
mz_zip_archive_file_stat *pStat);
/* MZ_TRUE if the file is in zip64 format. */
/* A file is considered zip64 if it contained a zip64 end of central directory
* marker, or if it contained any zip64 extended file information fields in the
* central directory. */
mz_bool mz_zip_is_zip64(mz_zip_archive *pZip);
/* Returns the total central directory size in bytes. */
/* The current max supported size is <= MZ_UINT32_MAX. */
size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip);
/* Extracts a archive file to a memory buffer using no memory allocation. */
/* There must be at least enough room on the stack to store the inflator's state
* (~34KB or so). */
mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip,
mz_uint file_index, void *pBuf,
size_t buf_size, mz_uint flags,
void *pUser_read_buf,
size_t user_read_buf_size);
mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(
mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size,
mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
/* Extracts a archive file to a memory buffer. */
mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index,
void *pBuf, size_t buf_size,
mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip,
const char *pFilename, void *pBuf,
size_t buf_size, mz_uint flags);
/* Extracts a archive file to a dynamically allocated heap buffer. */
/* The memory will be allocated via the mz_zip_archive's alloc/realloc
* functions. */
/* Returns NULL and sets the last error on failure. */
void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index,
size_t *pSize, mz_uint flags);
void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip,
const char *pFilename, size_t *pSize,
mz_uint flags);
/* Extracts a archive file using a callback function to output the file's data.
*/
mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip,
mz_uint file_index,
mz_file_write_func pCallback,
void *pOpaque, mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip,
const char *pFilename,
mz_file_write_func pCallback,
void *pOpaque, mz_uint flags);
/* Extract a file iteratively */
mz_zip_reader_extract_iter_state *
mz_zip_reader_extract_iter_new(mz_zip_archive *pZip, mz_uint file_index,
mz_uint flags);
mz_zip_reader_extract_iter_state *
mz_zip_reader_extract_file_iter_new(mz_zip_archive *pZip, const char *pFilename,
mz_uint flags);
size_t mz_zip_reader_extract_iter_read(mz_zip_reader_extract_iter_state *pState,
void *pvBuf, size_t buf_size);
mz_bool
mz_zip_reader_extract_iter_free(mz_zip_reader_extract_iter_state *pState);
#ifndef MINIZ_NO_STDIO
/* Extracts a archive file to a disk file and sets its last accessed and
* modified times. */
/* This function only extracts files, not archive directory records. */
mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index,
const char *pDst_filename, mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip,
const char *pArchive_filename,
const char *pDst_filename,
mz_uint flags);
/* Extracts a archive file starting at the current position in the destination
* FILE stream. */
mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index,
MZ_FILE *File, mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip,
const char *pArchive_filename,
MZ_FILE *pFile, mz_uint flags);
#endif
#if 0
/* TODO */
typedef void *mz_zip_streaming_extract_state_ptr;
mz_zip_streaming_extract_state_ptr mz_zip_streaming_extract_begin(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags);
uint64_t mz_zip_streaming_extract_get_size(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState);
uint64_t mz_zip_streaming_extract_get_cur_ofs(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState);
mz_bool mz_zip_streaming_extract_seek(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, uint64_t new_ofs);
size_t mz_zip_streaming_extract_read(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, void *pBuf, size_t buf_size);
mz_bool mz_zip_streaming_extract_end(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState);
#endif
/* This function compares the archive's local headers, the optional local zip64
* extended information block, and the optional descriptor following the
* compressed data vs. the data in the central directory. */
/* It also validates that each file can be successfully uncompressed unless the
* MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY is specified. */
mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index,
mz_uint flags);
/* Validates an entire archive by calling mz_zip_validate_file() on each file.
*/
mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags);
/* Misc utils/helpers, valid for ZIP reading or writing */
mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size,
mz_uint flags, mz_zip_error *pErr);
mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags,
mz_zip_error *pErr);
/* Universal end function - calls either mz_zip_reader_end() or
* mz_zip_writer_end(). */
mz_bool mz_zip_end(mz_zip_archive *pZip);
/* -------- ZIP writing */
#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
/* Inits a ZIP archive writer. */
/*Set pZip->m_pWrite (and pZip->m_pIO_opaque) before calling mz_zip_writer_init
* or mz_zip_writer_init_v2*/
/*The output is streamable, i.e. file_ofs in mz_file_write_func always increases
* only by n*/
mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size);
mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size,
mz_uint flags);
mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip,
size_t size_to_reserve_at_beginning,
size_t initial_allocation_size);
mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip,
size_t size_to_reserve_at_beginning,
size_t initial_allocation_size,
mz_uint flags);
#ifndef MINIZ_NO_STDIO
mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename,
mz_uint64 size_to_reserve_at_beginning);
mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename,
mz_uint64 size_to_reserve_at_beginning,
mz_uint flags);
mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile,
mz_uint flags);
#endif
/* Converts a ZIP archive reader object into a writer object, to allow efficient
* in-place file appends to occur on an existing archive. */
/* For archives opened using mz_zip_reader_init_file, pFilename must be the
* archive's filename so it can be reopened for writing. If the file can't be
* reopened, mz_zip_reader_end() will be called. */
/* For archives opened using mz_zip_reader_init_mem, the memory block must be
* growable using the realloc callback (which defaults to realloc unless you've
* overridden it). */
/* Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's
* user provided m_pWrite function cannot be NULL. */
/* Note: In-place archive modification is not recommended unless you know what
* you're doing, because if execution stops or something goes wrong before */
/* the archive is finalized the file's central directory will be hosed. */
mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip,
const char *pFilename);
mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip,
const char *pFilename, mz_uint flags);
/* Adds the contents of a memory buffer to an archive. These functions record
* the current local time into the archive. */
/* To add a directory entry, call this method with an archive name ending in a
* forwardslash with an empty buffer. */
/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
* MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
* just set to MZ_DEFAULT_COMPRESSION. */
mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name,
const void *pBuf, size_t buf_size,
mz_uint level_and_flags);
/* Like mz_zip_writer_add_mem(), except you can specify a file comment field,
* and optionally supply the function with already compressed data. */
/* uncomp_size/uncomp_crc32 are only used if the MZ_ZIP_FLAG_COMPRESSED_DATA
* flag is specified. */
mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip,
const char *pArchive_name, const void *pBuf,
size_t buf_size, const void *pComment,
mz_uint16 comment_size,
mz_uint level_and_flags, mz_uint64 uncomp_size,
mz_uint32 uncomp_crc32);
mz_bool mz_zip_writer_add_mem_ex_v2(
mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf,
size_t buf_size, const void *pComment, mz_uint16 comment_size,
mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32,
MZ_TIME_T *last_modified, const char *user_extra_data_local,
mz_uint user_extra_data_local_len, const char *user_extra_data_central,
mz_uint user_extra_data_central_len);
/* Adds the contents of a file to an archive. This function also records the
* disk file's modified time into the archive. */
/* File data is supplied via a read callback function. User
* mz_zip_writer_add_(c)file to add a file directly.*/
mz_bool mz_zip_writer_add_read_buf_callback(
mz_zip_archive *pZip, const char *pArchive_name,
mz_file_read_func read_callback, void *callback_opaque,
mz_uint64 size_to_add, const MZ_TIME_T *pFile_time, const void *pComment,
mz_uint16 comment_size, mz_uint level_and_flags,
const char *user_extra_data_local, mz_uint user_extra_data_local_len,
const char *user_extra_data_central, mz_uint user_extra_data_central_len);
#ifndef MINIZ_NO_STDIO
/* Adds the contents of a disk file to an archive. This function also records
* the disk file's modified time into the archive. */
/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
* MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
* just set to MZ_DEFAULT_COMPRESSION. */
mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name,
const char *pSrc_filename, const void *pComment,
mz_uint16 comment_size, mz_uint level_and_flags);
/* Like mz_zip_writer_add_file(), except the file data is read from the
* specified FILE stream. */
mz_bool mz_zip_writer_add_cfile(
mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file,
mz_uint64 size_to_add, const MZ_TIME_T *pFile_time, const void *pComment,
mz_uint16 comment_size, mz_uint level_and_flags,
const char *user_extra_data_local, mz_uint user_extra_data_local_len,
const char *user_extra_data_central, mz_uint user_extra_data_central_len);
#endif
/* Adds a file to an archive by fully cloning the data from another archive. */
/* This function fully clones the source file's compressed data (no
* recompression), along with its full filename, extra data (it may add or
* modify the zip64 local header extra data field), and the optional descriptor
* following the compressed data. */
mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip,
mz_zip_archive *pSource_zip,
mz_uint src_file_index);
/* Finalizes the archive by writing the central directory records followed by
* the end of central directory record. */
/* After an archive is finalized, the only valid call on the mz_zip_archive
* struct is mz_zip_writer_end(). */
/* An archive must be manually finalized by calling this function for it to be
* valid. */
mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip);
/* Finalizes a heap archive, returning a poiner to the heap block and its size.
*/
/* The heap block will be allocated using the mz_zip_archive's alloc/realloc
* callbacks. */
mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf,
size_t *pSize);
/* Ends archive writing, freeing all allocations, and closing the output file if
* mz_zip_writer_init_file() was used. */
/* Note for the archive to be valid, it *must* have been finalized before ending
* (this function will not do it for you). */
mz_bool mz_zip_writer_end(mz_zip_archive *pZip);
/* -------- Misc. high-level helper functions: */
/* mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically)
* appends a memory blob to a ZIP archive. */
/* Note this is NOT a fully safe operation. If it crashes or dies in some way
* your archive can be left in a screwed up state (without a central directory).
*/
/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
* MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
* just set to MZ_DEFAULT_COMPRESSION. */
/* TODO: Perhaps add an option to leave the existing central dir in place in
* case the add dies? We could then truncate the file (so the old central dir
* would be at the end) if something goes wrong. */
mz_bool mz_zip_add_mem_to_archive_file_in_place(
const char *pZip_filename, const char *pArchive_name, const void *pBuf,
size_t buf_size, const void *pComment, mz_uint16 comment_size,
mz_uint level_and_flags);
mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(
const char *pZip_filename, const char *pArchive_name, const void *pBuf,
size_t buf_size, const void *pComment, mz_uint16 comment_size,
mz_uint level_and_flags, mz_zip_error *pErr);
/* Reads a single file from an archive into a heap block. */
/* If pComment is not NULL, only the file with the specified comment will be
* extracted. */
/* Returns NULL on failure. */
void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename,
const char *pArchive_name,
size_t *pSize, mz_uint flags);
void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename,
const char *pArchive_name,
const char *pComment,
size_t *pSize, mz_uint flags,
mz_zip_error *pErr);
#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */
#ifdef __cplusplus
}
#endif
#endif /* MINIZ_NO_ARCHIVE_APIS */
|
0 | repos/DirectXShaderCompiler/include | repos/DirectXShaderCompiler/include/llvm/InitializePasses.h | //===- llvm/InitializePasses.h -------- Initialize All Passes ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declarations for the pass initialization routines
// for the entire LLVM project.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_INITIALIZEPASSES_H
#define LLVM_INITIALIZEPASSES_H
namespace llvm {
class PassRegistry;
/// initializeCore - Initialize all passes linked into the
/// TransformUtils library.
void initializeCore(PassRegistry&);
/// initializeTransformUtils - Initialize all passes linked into the
/// TransformUtils library.
void initializeTransformUtils(PassRegistry&);
/// initializeScalarOpts - Initialize all passes linked into the
/// ScalarOpts library.
void initializeScalarOpts(PassRegistry&);
/// initializeObjCARCOpts - Initialize all passes linked into the ObjCARCOpts
/// library.
void initializeObjCARCOpts(PassRegistry&);
/// initializeVectorization - Initialize all passes linked into the
/// Vectorize library.
void initializeVectorization(PassRegistry&);
/// initializeInstCombine - Initialize all passes linked into the
/// InstCombine library.
void initializeInstCombine(PassRegistry&);
/// initializeIPO - Initialize all passes linked into the IPO library.
void initializeIPO(PassRegistry&);
/// initializeInstrumentation - Initialize all passes linked into the
/// Instrumentation library.
void initializeInstrumentation(PassRegistry&);
/// initializeAnalysis - Initialize all passes linked into the Analysis library.
void initializeAnalysis(PassRegistry&);
/// initializeIPA - Initialize all passes linked into the IPA library.
void initializeIPA(PassRegistry&);
/// initializeCodeGen - Initialize all passes linked into the CodeGen library.
void initializeCodeGen(PassRegistry&);
/// initializeCodeGen - Initialize all passes linked into the CodeGen library.
void initializeTarget(PassRegistry&);
void initializeAAEvalPass(PassRegistry&);
void initializeAddDiscriminatorsPass(PassRegistry&);
void initializeADCEPass(PassRegistry&);
void initializeBDCEPass(PassRegistry&);
void initializeAliasAnalysisAnalysisGroup(PassRegistry&);
void initializeAliasAnalysisCounterPass(PassRegistry&);
void initializeAliasDebuggerPass(PassRegistry&);
void initializeAliasSetPrinterPass(PassRegistry&);
void initializeAlwaysInlinerPass(PassRegistry&);
void initializeArgPromotionPass(PassRegistry&);
void initializeAtomicExpandPass(PassRegistry&);
void initializeSampleProfileLoaderPass(PassRegistry&);
void initializeAlignmentFromAssumptionsPass(PassRegistry&);
void initializeBarrierNoopPass(PassRegistry&);
void initializeBasicAliasAnalysisPass(PassRegistry&);
void initializeCallGraphWrapperPassPass(PassRegistry &);
void initializeBlockExtractorPassPass(PassRegistry&);
void initializeBlockFrequencyInfoPass(PassRegistry&);
void initializeBoundsCheckingPass(PassRegistry&);
void initializeBranchFolderPassPass(PassRegistry&);
void initializeBranchProbabilityInfoPass(PassRegistry&);
void initializeBreakCriticalEdgesPass(PassRegistry&);
void initializeCallGraphPrinterPass(PassRegistry&);
void initializeCallGraphViewerPass(PassRegistry&);
void initializeCFGOnlyPrinterPass(PassRegistry&);
void initializeCFGOnlyViewerPass(PassRegistry&);
void initializeCFGPrinterPass(PassRegistry&);
void initializeCFGSimplifyPassPass(PassRegistry&);
void initializeCFLAliasAnalysisPass(PassRegistry&);
void initializeForwardControlFlowIntegrityPass(PassRegistry&);
void initializeFlattenCFGPassPass(PassRegistry&);
void initializeStructurizeCFGPass(PassRegistry&);
void initializeCFGViewerPass(PassRegistry&);
void initializeConstantHoistingPass(PassRegistry&);
void initializeCodeGenPreparePass(PassRegistry&);
void initializeConstantMergePass(PassRegistry&);
void initializeConstantPropagationPass(PassRegistry&);
void initializeMachineCopyPropagationPass(PassRegistry&);
void initializeCostModelAnalysisPass(PassRegistry&);
void initializeCorrelatedValuePropagationPass(PassRegistry&);
void initializeDAEPass(PassRegistry&);
void initializeDAHPass(PassRegistry&);
void initializeDCEPass(PassRegistry&);
void initializeDSEPass(PassRegistry&);
void initializeDeadInstEliminationPass(PassRegistry&);
void initializeDeadMachineInstructionElimPass(PassRegistry&);
void initializeDelinearizationPass(PassRegistry &);
void initializeDependenceAnalysisPass(PassRegistry&);
void initializeDivergenceAnalysisPass(PassRegistry&);
void initializeDomOnlyPrinterPass(PassRegistry&);
void initializeDomOnlyViewerPass(PassRegistry&);
void initializeDomPrinterPass(PassRegistry&);
void initializeDomViewerPass(PassRegistry&);
void initializeDominanceFrontierPass(PassRegistry&);
void initializeDominatorTreeWrapperPassPass(PassRegistry&);
void initializeEarlyIfConverterPass(PassRegistry&);
void initializeEdgeBundlesPass(PassRegistry&);
void initializeExpandPostRAPass(PassRegistry&);
void initializeGCOVProfilerPass(PassRegistry&);
void initializeInstrProfilingPass(PassRegistry&);
void initializeAddressSanitizerPass(PassRegistry&);
void initializeAddressSanitizerModulePass(PassRegistry&);
void initializeMemorySanitizerPass(PassRegistry&);
void initializeThreadSanitizerPass(PassRegistry&);
void initializeSanitizerCoverageModulePass(PassRegistry&);
void initializeDataFlowSanitizerPass(PassRegistry&);
void initializeScalarizerPass(PassRegistry&);
void initializeEarlyCSELegacyPassPass(PassRegistry &);
void initializeEliminateAvailableExternallyPass(PassRegistry&);
void initializeExpandISelPseudosPass(PassRegistry&);
void initializeFunctionAttrsPass(PassRegistry&);
void initializeGCMachineCodeAnalysisPass(PassRegistry&);
void initializeGCModuleInfoPass(PassRegistry&);
void initializeGVNPass(PassRegistry&);
void initializeGlobalDCEPass(PassRegistry&);
void initializeGlobalOptPass(PassRegistry&);
void initializeGlobalsModRefPass(PassRegistry&);
void initializeIPCPPass(PassRegistry&);
void initializeIPSCCPPass(PassRegistry&);
void initializeIVUsersPass(PassRegistry&);
void initializeIfConverterPass(PassRegistry&);
void initializeInductiveRangeCheckEliminationPass(PassRegistry&);
void initializeIndVarSimplifyPass(PassRegistry&);
void initializeInlineCostAnalysisPass(PassRegistry&);
void initializeInstructionCombiningPassPass(PassRegistry&);
void initializeInstCountPass(PassRegistry&);
void initializeInstNamerPass(PassRegistry&);
void initializeInternalizePassPass(PassRegistry&);
void initializeIntervalPartitionPass(PassRegistry&);
void initializeJumpThreadingPass(PassRegistry&);
void initializeLCSSAPass(PassRegistry&);
void initializeLICMPass(PassRegistry&);
void initializeLazyValueInfoPass(PassRegistry&);
void initializeLibCallAliasAnalysisPass(PassRegistry&);
void initializeLintPass(PassRegistry&);
void initializeLiveDebugVariablesPass(PassRegistry&);
void initializeLiveIntervalsPass(PassRegistry&);
void initializeLiveRegMatrixPass(PassRegistry&);
void initializeLiveStacksPass(PassRegistry&);
void initializeLiveVariablesPass(PassRegistry&);
void initializeLoaderPassPass(PassRegistry&);
void initializeLocalStackSlotPassPass(PassRegistry&);
void initializeLoopDeletionPass(PassRegistry&);
void initializeLoopExtractorPass(PassRegistry&);
void initializeLoopInfoWrapperPassPass(PassRegistry&);
void initializeLoopInterchangePass(PassRegistry &);
void initializeLoopInstSimplifyPass(PassRegistry&);
void initializeLoopRotatePass(PassRegistry&);
void initializeLoopSimplifyPass(PassRegistry&);
void initializeLoopStrengthReducePass(PassRegistry&);
void initializeGlobalMergePass(PassRegistry&);
void initializeLoopRerollPass(PassRegistry&);
void initializeLoopUnrollPass(PassRegistry&);
void initializeLoopUnswitchPass(PassRegistry&);
void initializeLoopIdiomRecognizePass(PassRegistry&);
void initializeLowerAtomicPass(PassRegistry&);
void initializeLowerBitSetsPass(PassRegistry&);
void initializeLowerExpectIntrinsicPass(PassRegistry&);
void initializeLowerIntrinsicsPass(PassRegistry&);
void initializeLowerInvokePass(PassRegistry&);
void initializeLowerSwitchPass(PassRegistry&);
void initializeMachineBlockFrequencyInfoPass(PassRegistry&);
void initializeMachineBlockPlacementPass(PassRegistry&);
void initializeMachineBlockPlacementStatsPass(PassRegistry&);
void initializeMachineBranchProbabilityInfoPass(PassRegistry&);
void initializeMachineCSEPass(PassRegistry&);
void initializeImplicitNullChecksPass(PassRegistry&);
void initializeMachineDominatorTreePass(PassRegistry&);
void initializeMachineDominanceFrontierPass(PassRegistry&);
void initializeMachinePostDominatorTreePass(PassRegistry&);
void initializeMachineLICMPass(PassRegistry&);
void initializeMachineLoopInfoPass(PassRegistry&);
void initializeMachineModuleInfoPass(PassRegistry&);
void initializeMachineRegionInfoPassPass(PassRegistry&);
void initializeMachineSchedulerPass(PassRegistry&);
void initializeMachineSinkingPass(PassRegistry&);
void initializeMachineTraceMetricsPass(PassRegistry&);
void initializeMachineVerifierPassPass(PassRegistry&);
void initializeMemCpyOptPass(PassRegistry&);
void initializeMemDepPrinterPass(PassRegistry&);
void initializeMemDerefPrinterPass(PassRegistry&);
void initializeMemoryDependenceAnalysisPass(PassRegistry&);
void initializeMergedLoadStoreMotionPass(PassRegistry &);
void initializeMetaRenamerPass(PassRegistry&);
void initializeMergeFunctionsPass(PassRegistry&);
void initializeModuleDebugInfoPrinterPass(PassRegistry&);
void initializeNaryReassociatePass(PassRegistry&);
void initializeNoAAPass(PassRegistry&);
void initializeObjCARCAliasAnalysisPass(PassRegistry&);
void initializeObjCARCAPElimPass(PassRegistry&);
void initializeObjCARCExpandPass(PassRegistry&);
void initializeObjCARCContractPass(PassRegistry&);
void initializeObjCARCOptPass(PassRegistry&);
void initializePAEvalPass(PassRegistry &);
void initializeOptimizePHIsPass(PassRegistry&);
void initializePartiallyInlineLibCallsPass(PassRegistry&);
void initializePEIPass(PassRegistry&);
void initializePHIEliminationPass(PassRegistry&);
void initializePartialInlinerPass(PassRegistry&);
void initializePeepholeOptimizerPass(PassRegistry&);
void initializePostDomOnlyPrinterPass(PassRegistry&);
void initializePostDomOnlyViewerPass(PassRegistry&);
void initializePostDomPrinterPass(PassRegistry&);
void initializePostDomViewerPass(PassRegistry&);
void initializePostDominatorTreePass(PassRegistry&);
void initializePostRASchedulerPass(PassRegistry&);
void initializePostMachineSchedulerPass(PassRegistry&);
void initializePrintFunctionPassWrapperPass(PassRegistry&);
void initializePrintModulePassWrapperPass(PassRegistry&);
void initializePrintBasicBlockPassPass(PassRegistry&);
void initializeProcessImplicitDefsPass(PassRegistry&);
void initializePromotePassPass(PassRegistry&);
void initializePruneEHPass(PassRegistry&);
void initializeReassociatePass(PassRegistry&);
void initializeRegToMemPass(PassRegistry&);
void initializeRegToMemHlslPass(PassRegistry&); // HLSL Change
void initializeRegionInfoPassPass(PassRegistry&);
void initializeRegionOnlyPrinterPass(PassRegistry&);
void initializeRegionOnlyViewerPass(PassRegistry&);
void initializeRegionPrinterPass(PassRegistry&);
void initializeRegionViewerPass(PassRegistry&);
void initializeRewriteStatepointsForGCPass(PassRegistry&);
void initializeSafeStackPass(PassRegistry&);
void initializeSCCPPass(PassRegistry&);
void initializeSROAPass(PassRegistry&);
void initializeSROA_DTPass(PassRegistry&);
void initializeSROA_SSAUpPass(PassRegistry&);
// HLSL Change Begins
void initializeHLExpandStoreIntrinsicsPass(PassRegistry&);
void initializeSROA_HLSLPass(PassRegistry&);
void initializeSROA_DT_HLSLPass(PassRegistry&);
void initializeSROA_Parameter_HLSLPass(PassRegistry&);
void initializeLowerStaticGlobalIntoAllocaPass(PassRegistry&);
void initializeDynamicIndexingVectorToArrayPass(PassRegistry&);
void initializeMultiDimArrayToOneDimArrayPass(PassRegistry&);
void initializeResourceToHandlePass(PassRegistry&);
void initializeLowerWaveMatTypePass(PassRegistry &);
void initializeSROA_SSAUp_HLSLPass(PassRegistry&);
void initializeHoistConstantArrayPass(PassRegistry&);
void initializeDxilLoopUnrollPass(PassRegistry&);
void initializeDxilInsertNoopsPass(PassRegistry&);
void initializeDxilFinalizeNoopsPass(PassRegistry&);
void initializeDxilEliminateVectorPass(PassRegistry&);
void initializeDxilConditionalMem2RegPass(PassRegistry&);
void initializeDxilFixConstArrayInitializerPass(PassRegistry&);
void initializeDxilInsertPreservesPass(PassRegistry&);
void initializeDxilReinsertNopsPass(PassRegistry&);
void initializeDxilFinalizePreservesPass(PassRegistry&);
void initializeDxilPreserveToSelectPass(PassRegistry&);
void initializeDxilRemoveDeadBlocksPass(PassRegistry&);
void initializeDxilRemoveUnstructuredLoopExitsPass(PassRegistry &);
void initializeDxilRewriteOutputArgDebugInfoPass(PassRegistry&);
// HLSL Change Ends
void initializeScalarEvolutionAliasAnalysisPass(PassRegistry&);
void initializeScalarEvolutionPass(PassRegistry&);
void initializeShrinkWrapPass(PassRegistry &);
void initializeSimpleInlinerPass(PassRegistry&);
void initializeShadowStackGCLoweringPass(PassRegistry&);
void initializeRegisterCoalescerPass(PassRegistry&);
void initializeSingleLoopExtractorPass(PassRegistry&);
void initializeSinkingPass(PassRegistry&);
void initializeSeparateConstOffsetFromGEPPass(PassRegistry &);
void initializeSlotIndexesPass(PassRegistry&);
void initializeSpillPlacementPass(PassRegistry&);
void initializeSpeculativeExecutionPass(PassRegistry&);
void initializeStackProtectorPass(PassRegistry&);
void initializeStackColoringPass(PassRegistry&);
void initializeStackSlotColoringPass(PassRegistry&);
void initializeStraightLineStrengthReducePass(PassRegistry &);
void initializeStripDeadDebugInfoPass(PassRegistry&);
void initializeStripDeadPrototypesPassPass(PassRegistry&);
void initializeStripDebugDeclarePass(PassRegistry&);
void initializeStripNonDebugSymbolsPass(PassRegistry&);
void initializeStripSymbolsPass(PassRegistry&);
void initializeTailCallElimPass(PassRegistry&);
void initializeTailDuplicatePassPass(PassRegistry&);
void initializeTargetPassConfigPass(PassRegistry&);
void initializeTargetTransformInfoWrapperPassPass(PassRegistry &);
void initializeTargetLibraryInfoWrapperPassPass(PassRegistry &);
void initializeAssumptionCacheTrackerPass(PassRegistry &);
void initializeTwoAddressInstructionPassPass(PassRegistry&);
void initializeTypeBasedAliasAnalysisPass(PassRegistry&);
void initializeScopedNoAliasAAPass(PassRegistry&);
void initializeUnifyFunctionExitNodesPass(PassRegistry&);
void initializeUnreachableBlockElimPass(PassRegistry&);
void initializeUnreachableMachineBlockElimPass(PassRegistry&);
void initializeVerifierLegacyPassPass(PassRegistry&);
void initializeVirtRegMapPass(PassRegistry&);
void initializeVirtRegRewriterPass(PassRegistry&);
void initializeInstSimplifierPass(PassRegistry&);
void initializeUnpackMachineBundlesPass(PassRegistry&);
void initializeFinalizeMachineBundlesPass(PassRegistry&);
void initializeLoopAccessAnalysisPass(PassRegistry&);
void initializeLoopVectorizePass(PassRegistry&);
void initializeSLPVectorizerPass(PassRegistry&);
void initializeBBVectorizePass(PassRegistry&);
void initializeMachineFunctionPrinterPassPass(PassRegistry&);
void initializeMIRPrintingPassPass(PassRegistry&);
void initializeStackMapLivenessPass(PassRegistry&);
void initializeMachineCombinerPass(PassRegistry &);
void initializeLoadCombinePass(PassRegistry&);
void initializeRewriteSymbolsPass(PassRegistry&);
void initializeWinEHPreparePass(PassRegistry&);
void initializePlaceBackedgeSafepointsImplPass(PassRegistry&);
void initializePlaceSafepointsPass(PassRegistry&);
void initializeDwarfEHPreparePass(PassRegistry&);
void initializeFloat2IntPass(PassRegistry&);
void initializeLoopDistributePass(PassRegistry&);
void initializeSjLjEHPreparePass(PassRegistry&);
}
#endif
|
0 | repos/DirectXShaderCompiler/include | repos/DirectXShaderCompiler/include/llvm/PassRegistry.h | //===- llvm/PassRegistry.h - Pass Information Registry ----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines PassRegistry, a class that is used in the initialization
// and registration of passes. At application startup, passes are registered
// with the PassRegistry, which is later provided to the PassManager for
// dependency resolution and similar tasks.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_PASSREGISTRY_H
#define LLVM_PASSREGISTRY_H
#include "llvm-c/Core.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/PassInfo.h"
#include "llvm/Support/CBindingWrapping.h"
#include "llvm/Support/RWMutex.h"
#include <vector>
namespace llvm {
class PassInfo;
struct PassRegistrationListener;
/// PassRegistry - This class manages the registration and intitialization of
/// the pass subsystem as application startup, and assists the PassManager
/// in resolving pass dependencies.
/// NOTE: PassRegistry is NOT thread-safe. If you want to use LLVM on multiple
/// threads simultaneously, you will need to use a separate PassRegistry on
/// each thread.
class PassRegistry {
#ifndef LLVM_ON_WIN32
// HLSL Change - no lock needed for Windows, as it will use its own mechanism defined in PassRegistry.cpp.
mutable sys::SmartRWMutex<true> Lock;
#endif
/// PassInfoMap - Keep track of the PassInfo object for each registered pass.
typedef DenseMap<const void *, const PassInfo *> MapType;
MapType PassInfoMap;
typedef StringMap<const PassInfo *> StringMapType;
StringMapType PassInfoStringMap;
std::vector<std::unique_ptr<const PassInfo>> ToFree;
std::vector<PassRegistrationListener *> Listeners;
public:
PassRegistry() {}
~PassRegistry();
/// getPassRegistry - Access the global registry object, which is
/// automatically initialized at application launch and destroyed by
/// llvm_shutdown.
static PassRegistry *getPassRegistry();
/// getPassInfo - Look up a pass' corresponding PassInfo, indexed by the pass'
/// type identifier (&MyPass::ID).
const PassInfo *getPassInfo(const void *TI) const;
/// getPassInfo - Look up a pass' corresponding PassInfo, indexed by the pass'
/// argument string.
const PassInfo *getPassInfo(StringRef Arg) const;
/// registerPass - Register a pass (by means of its PassInfo) with the
/// registry. Required in order to use the pass with a PassManager.
void registerPass(const PassInfo &PI, bool ShouldFree = false);
/// registerAnalysisGroup - Register an analysis group (or a pass implementing
// an analysis group) with the registry. Like registerPass, this is required
// in order for a PassManager to be able to use this group/pass.
void registerAnalysisGroup(const void *InterfaceID, const void *PassID,
PassInfo &Registeree, bool isDefault,
bool ShouldFree = false);
/// enumerateWith - Enumerate the registered passes, calling the provided
/// PassRegistrationListener's passEnumerate() callback on each of them.
void enumerateWith(PassRegistrationListener *L);
/// addRegistrationListener - Register the given PassRegistrationListener
/// to receive passRegistered() callbacks whenever a new pass is registered.
void addRegistrationListener(PassRegistrationListener *L);
/// removeRegistrationListener - Unregister a PassRegistrationListener so that
/// it no longer receives passRegistered() callbacks.
void removeRegistrationListener(PassRegistrationListener *L);
};
// Create wrappers for C Binding types (see CBindingWrapping.h).
DEFINE_STDCXX_CONVERSION_FUNCTIONS(PassRegistry, LLVMPassRegistryRef)
}
#endif
|
0 | repos/DirectXShaderCompiler/include | repos/DirectXShaderCompiler/include/llvm/PassAnalysisSupport.h | //===- llvm/PassAnalysisSupport.h - Analysis Pass Support code --*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines stuff that is used to define and "use" Analysis Passes.
// This file is automatically #included by Pass.h, so:
//
// NO .CPP FILES SHOULD INCLUDE THIS FILE DIRECTLY
//
// Instead, #include Pass.h
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_PASSANALYSISSUPPORT_H
#define LLVM_PASSANALYSISSUPPORT_H
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Pass.h"
#include <vector>
namespace llvm {
//===----------------------------------------------------------------------===//
/// Represent the analysis usage information of a pass. This tracks analyses
/// that the pass REQUIRES (must be available when the pass runs), REQUIRES
/// TRANSITIVE (must be available throughout the lifetime of the pass), and
/// analyses that the pass PRESERVES (the pass does not invalidate the results
/// of these analyses). This information is provided by a pass to the Pass
/// infrastructure through the getAnalysisUsage virtual function.
///
class AnalysisUsage {
public:
typedef SmallVector<AnalysisID, 32> VectorType;
private:
/// Sets of analyses required and preserved by a pass
VectorType Required, RequiredTransitive, Preserved;
bool PreservesAll;
public:
AnalysisUsage() : PreservesAll(false) {}
///@{
/// Add the specified ID to the required set of the usage info for a pass.
AnalysisUsage &addRequiredID(const void *ID);
AnalysisUsage &addRequiredID(char &ID);
template<class PassClass>
AnalysisUsage &addRequired() {
return addRequiredID(PassClass::ID);
}
AnalysisUsage &addRequiredTransitiveID(char &ID);
template<class PassClass>
AnalysisUsage &addRequiredTransitive() {
return addRequiredTransitiveID(PassClass::ID);
}
///@}
///@{
/// Add the specified ID to the set of analyses preserved by this pass.
AnalysisUsage &addPreservedID(const void *ID) {
Preserved.push_back(ID);
return *this;
}
AnalysisUsage &addPreservedID(char &ID) {
Preserved.push_back(&ID);
return *this;
}
///@}
/// Add the specified Pass class to the set of analyses preserved by this pass.
template<class PassClass>
AnalysisUsage &addPreserved() {
Preserved.push_back(&PassClass::ID);
return *this;
}
/// Add the Pass with the specified argument string to the set of analyses
/// preserved by this pass. If no such Pass exists, do nothing. This can be
/// useful when a pass is trivially preserved, but may not be linked in. Be
/// careful about spelling!
AnalysisUsage &addPreserved(StringRef Arg);
/// Set by analyses that do not transform their input at all
void setPreservesAll() { PreservesAll = true; }
/// Determine whether a pass said it does not transform its input at all
bool getPreservesAll() const { return PreservesAll; }
/// This function should be called by the pass, iff they do not:
///
/// 1. Add or remove basic blocks from the function
/// 2. Modify terminator instructions in any way.
///
/// This function annotates the AnalysisUsage info object to say that analyses
/// that only depend on the CFG are preserved by this pass.
///
void setPreservesCFG();
const VectorType &getRequiredSet() const { return Required; }
const VectorType &getRequiredTransitiveSet() const {
return RequiredTransitive;
}
const VectorType &getPreservedSet() const { return Preserved; }
};
// //
///////////////////////////////////////////////////////////////////////////////
/// AnalysisResolver - Simple interface used by Pass objects to pull all
/// analysis information out of pass manager that is responsible to manage
/// the pass.
///
class PMDataManager;
class AnalysisResolver {
private:
AnalysisResolver() = delete;
public:
explicit AnalysisResolver(PMDataManager &P) : PM(P) { }
inline PMDataManager &getPMDataManager() { return PM; }
/// Find pass that is implementing PI.
Pass *findImplPass(AnalysisID PI) {
Pass *ResultPass = nullptr;
for (unsigned i = 0; i < AnalysisImpls.size() ; ++i) {
if (AnalysisImpls[i].first == PI) {
ResultPass = AnalysisImpls[i].second;
break;
}
}
return ResultPass;
}
/// Find pass that is implementing PI. Initialize pass for Function F.
Pass *findImplPass(Pass *P, AnalysisID PI, Function &F);
void addAnalysisImplsPair(AnalysisID PI, Pass *P) {
if (findImplPass(PI) == P)
return;
std::pair<AnalysisID, Pass*> pir = std::make_pair(PI,P);
AnalysisImpls.push_back(pir);
}
/// Clear cache that is used to connect a pass to the the analysis (PassInfo).
void clearAnalysisImpls() {
AnalysisImpls.clear();
}
/// Return analysis result or null if it doesn't exist.
Pass *getAnalysisIfAvailable(AnalysisID ID, bool Direction) const;
private:
/// This keeps track of which passes implements the interfaces that are
/// required by the current pass (to implement getAnalysis()).
std::vector<std::pair<AnalysisID, Pass*> > AnalysisImpls;
/// PassManager that is used to resolve analysis info
PMDataManager &PM;
};
/// getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to
/// get analysis information that might be around, for example to update it.
/// This is different than getAnalysis in that it can fail (if the analysis
/// results haven't been computed), so should only be used if you can handle
/// the case when the analysis is not available. This method is often used by
/// transformation APIs to update analysis results for a pass automatically as
/// the transform is performed.
///
template<typename AnalysisType>
AnalysisType *Pass::getAnalysisIfAvailable() const {
assert(Resolver && "Pass not resident in a PassManager object!");
const void *PI = &AnalysisType::ID;
Pass *ResultPass = Resolver->getAnalysisIfAvailable(PI, true);
if (!ResultPass) return nullptr;
// Because the AnalysisType may not be a subclass of pass (for
// AnalysisGroups), we use getAdjustedAnalysisPointer here to potentially
// adjust the return pointer (because the class may multiply inherit, once
// from pass, once from AnalysisType).
return (AnalysisType*)ResultPass->getAdjustedAnalysisPointer(PI);
}
/// getAnalysis<AnalysisType>() - This function is used by subclasses to get
/// to the analysis information that they claim to use by overriding the
/// getAnalysisUsage function.
///
template<typename AnalysisType>
AnalysisType &Pass::getAnalysis() const {
assert(Resolver && "Pass has not been inserted into a PassManager object!");
return getAnalysisID<AnalysisType>(&AnalysisType::ID);
}
template<typename AnalysisType>
AnalysisType &Pass::getAnalysisID(AnalysisID PI) const {
assert(PI && "getAnalysis for unregistered pass!");
assert(Resolver&&"Pass has not been inserted into a PassManager object!");
// PI *must* appear in AnalysisImpls. Because the number of passes used
// should be a small number, we just do a linear search over a (dense)
// vector.
Pass *ResultPass = Resolver->findImplPass(PI);
assert (ResultPass &&
"getAnalysis*() called on an analysis that was not "
"'required' by pass!");
// Because the AnalysisType may not be a subclass of pass (for
// AnalysisGroups), we use getAdjustedAnalysisPointer here to potentially
// adjust the return pointer (because the class may multiply inherit, once
// from pass, once from AnalysisType).
return *(AnalysisType*)ResultPass->getAdjustedAnalysisPointer(PI);
}
/// getAnalysis<AnalysisType>() - This function is used by subclasses to get
/// to the analysis information that they claim to use by overriding the
/// getAnalysisUsage function.
///
template<typename AnalysisType>
AnalysisType &Pass::getAnalysis(Function &F) {
assert(Resolver &&"Pass has not been inserted into a PassManager object!");
return getAnalysisID<AnalysisType>(&AnalysisType::ID, F);
}
template<typename AnalysisType>
AnalysisType &Pass::getAnalysisID(AnalysisID PI, Function &F) {
assert(PI && "getAnalysis for unregistered pass!");
assert(Resolver && "Pass has not been inserted into a PassManager object!");
// PI *must* appear in AnalysisImpls. Because the number of passes used
// should be a small number, we just do a linear search over a (dense)
// vector.
Pass *ResultPass = Resolver->findImplPass(this, PI, F);
assert(ResultPass && "Unable to find requested analysis info");
// Because the AnalysisType may not be a subclass of pass (for
// AnalysisGroups), we use getAdjustedAnalysisPointer here to potentially
// adjust the return pointer (because the class may multiply inherit, once
// from pass, once from AnalysisType).
return *(AnalysisType*)ResultPass->getAdjustedAnalysisPointer(PI);
}
} // End llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/include | repos/DirectXShaderCompiler/include/llvm/CMakeLists.txt | add_subdirectory(IR)
# If we're doing an out-of-tree build, copy a module map for generated
# header files into the build area.
if (NOT "${CMAKE_SOURCE_DIR}" STREQUAL "${CMAKE_BINARY_DIR}")
configure_file(module.modulemap.build module.modulemap COPYONLY)
endif (NOT "${CMAKE_SOURCE_DIR}" STREQUAL "${CMAKE_BINARY_DIR}")
|
0 | repos/DirectXShaderCompiler/include | repos/DirectXShaderCompiler/include/llvm/module.modulemap | module LLVM_Analysis {
requires cplusplus
umbrella "Analysis"
module * { export * }
// FIXME: Why is this excluded?
exclude header "Analysis/BlockFrequencyInfoImpl.h"
// This is intended for (repeated) textual inclusion.
textual header "Analysis/TargetLibraryInfo.def"
}
module LLVM_AsmParser { requires cplusplus umbrella "AsmParser" module * { export * } }
// A module covering CodeGen/ and Target/. These are intertwined
// and codependent, and thus notionally form a single module.
module LLVM_Backend {
requires cplusplus
module CodeGen {
umbrella "CodeGen"
module * { export * }
// FIXME: Why is this excluded?
exclude header "CodeGen/MachineValueType.h"
// Exclude these; they're intended to be included into only a single
// translation unit (or none) and aren't part of this module.
exclude header "CodeGen/CommandFlags.h"
exclude header "CodeGen/LinkAllAsmWriterComponents.h"
exclude header "CodeGen/LinkAllCodegenComponents.h"
// These are intended for (repeated) textual inclusion.
textual header "CodeGen/DIEValue.def"
}
module Target {
umbrella "Target"
module * { export * }
}
// FIXME: Where should this go?
module Analysis_BlockFrequencyInfoImpl {
header "Analysis/BlockFrequencyInfoImpl.h"
export *
}
}
module LLVM_Bitcode { requires cplusplus umbrella "Bitcode" module * { export * } }
module LLVM_Config { requires cplusplus umbrella "Config" module * { export * } }
module LLVM_DebugInfo {
requires cplusplus
module DIContext { header "DebugInfo/DIContext.h" export * }
}
module LLVM_DebugInfo_DWARF {
requires cplusplus
umbrella "DebugInfo/DWARF"
module * { export * }
}
module LLVM_DebugInfo_PDB {
requires cplusplus
umbrella "DebugInfo/PDB"
module * { export * }
// Separate out this subdirectory; it's an optional component that depends on
// a separate library which might not be available.
//
// FIXME: There should be a better way to specify this.
exclude header "DebugInfo/PDB/DIA/DIADataStream.h"
exclude header "DebugInfo/PDB/DIA/DIAEnumDebugStreams.h"
exclude header "DebugInfo/PDB/DIA/DIAEnumLineNumbers.h"
exclude header "DebugInfo/PDB/DIA/DIAEnumSourceFiles.h"
exclude header "DebugInfo/PDB/DIA/DIAEnumSymbols.h"
exclude header "DebugInfo/PDB/DIA/DIALineNumber.h"
exclude header "DebugInfo/PDB/DIA/DIARawSymbol.h"
exclude header "DebugInfo/PDB/DIA/DIASession.h"
exclude header "DebugInfo/PDB/DIA/DIASourceFile.h"
exclude header "DebugInfo/PDB/DIA/DIASupport.h"
}
module LLVM_DebugInfo_PDB_DIA {
requires cplusplus
umbrella "DebugInfo/PDB/DIA"
module * { export * }
}
module LLVM_ExecutionEngine {
requires cplusplus
umbrella "ExecutionEngine"
module * { export * }
// Exclude this; it's an optional component of the ExecutionEngine.
exclude header "ExecutionEngine/OProfileWrapper.h"
// Exclude these; they're intended to be included into only a single
// translation unit (or none) and aren't part of this module.
exclude header "ExecutionEngine/JIT.h"
exclude header "ExecutionEngine/MCJIT.h"
exclude header "ExecutionEngine/Interpreter.h"
exclude header "ExecutionEngine/OrcMCJITReplacement.h"
}
module LLVM_IR {
requires cplusplus
// FIXME: Is this the right place for these?
module Pass { header "Pass.h" export * }
module PassSupport { header "PassSupport.h" export * }
module PassAnalysisSupport { header "PassAnalysisSupport.h" export * }
module PassRegistry { header "PassRegistry.h" export * }
module InitializePasses { header "InitializePasses.h" export * }
umbrella "IR"
module * { export * }
// These are intended for (repeated) textual inclusion.
textual header "IR/DebugInfoFlags.def"
textual header "IR/Instruction.def"
textual header "IR/Metadata.def"
textual header "IR/Value.def"
}
module LLVM_IRReader { requires cplusplus umbrella "IRReader" module * { export * } }
module LLVM_LineEditor { requires cplusplus umbrella "LineEditor" module * { export * } }
module LLVM_LTO { requires cplusplus umbrella "LTO" module * { export * } }
module LLVM_MC {
requires cplusplus
// FIXME: Mislayered?
module Support_TargetRegistry {
header "Support/TargetRegistry.h"
export *
}
umbrella "MC"
module * { export * }
// Exclude this; it's fundamentally non-modular.
exclude header "MC/MCTargetOptionsCommandFlags.h"
}
module LLVM_Object {
requires cplusplus
umbrella "Object"
module * { export * }
}
module LLVM_Option { requires cplusplus umbrella "Option" module * { export * } }
module LLVM_TableGen { requires cplusplus umbrella "TableGen" module * { export * } }
module LLVM_Transforms {
requires cplusplus
umbrella "Transforms"
module * { export * }
// FIXME: Excluded because it does bad things with the legacy pass manager.
exclude header "Transforms/IPO/PassManagerBuilder.h"
}
// A module covering ADT/ and Support/. These are intertwined and
// codependent, and notionally form a single module.
module LLVM_Utils {
module ADT {
requires cplusplus
umbrella "ADT"
module * { export * }
}
module Support {
requires cplusplus
umbrella "Support"
module * { export * }
// Exclude this; it's only included on Solaris.
exclude header "Support/Solaris.h"
// Exclude this; it's only included on AIX and fundamentally non-modular.
exclude header "Support/AIXDataTypesFix.h"
// Exclude this; it's fundamentally non-modular.
exclude header "Support/PluginLoader.h"
// Exclude this; it's a weirdly-factored part of llvm-gcov and conflicts
// with the Analysis module (which also defines an llvm::GCOVOptions).
exclude header "Support/GCOV.h"
// FIXME: Mislayered?
exclude header "Support/TargetRegistry.h"
// These are intended for textual inclusion.
textual header "Support/Dwarf.def"
textual header "Support/ELFRelocs/AArch64.def"
textual header "Support/ELFRelocs/ARM.def"
textual header "Support/ELFRelocs/Hexagon.def"
textual header "Support/ELFRelocs/i386.def"
textual header "Support/ELFRelocs/Mips.def"
textual header "Support/ELFRelocs/PowerPC64.def"
textual header "Support/ELFRelocs/PowerPC.def"
textual header "Support/ELFRelocs/Sparc.def"
textual header "Support/ELFRelocs/SystemZ.def"
textual header "Support/ELFRelocs/x86_64.def"
}
}
module LLVM_CodeGen_MachineValueType {
requires cplusplus
header "CodeGen/MachineValueType.h"
export *
}
// This is used for a $src == $build compilation. Otherwise we use
// LLVM_Support_DataTypes_Build, defined in a module map that is
// copied into the build area.
module LLVM_Support_DataTypes_Src {
header "llvm/Support/DataTypes.h"
export *
}
|
0 | repos/DirectXShaderCompiler/include | repos/DirectXShaderCompiler/include/llvm/LinkAllIR.h | //===----- LinkAllIR.h - Reference All VMCore Code --------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This header file pulls in all the object modules of the VMCore library so
// that tools like llc, opt, and lli can ensure they are linked with all symbols
// from libVMCore.a It should only be used from a tool's main program.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LINKALLIR_H
#define LLVM_LINKALLIR_H
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/Memory.h"
#include "llvm/Support/Mutex.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/TimeValue.h"
#include <cstdlib>
namespace {
struct ForceVMCoreLinking {
ForceVMCoreLinking() {
// We must reference VMCore in such a way that compilers will not
// delete it all as dead code, even with whole program optimization,
// yet is effectively a NO-OP. As the compiler isn't smart enough
// to know that getenv() never returns -1, this will do the job.
if (std::getenv("bar") != (char*) -1)
return;
(void)new llvm::Module("", llvm::getGlobalContext());
(void)new llvm::UnreachableInst(llvm::getGlobalContext());
(void) llvm::createVerifierPass();
}
} ForceVMCoreLinking;
}
#endif
|
0 | repos/DirectXShaderCompiler/include | repos/DirectXShaderCompiler/include/llvm/PassInfo.h | //===- llvm/PassInfo.h - Pass Info class ------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines and implements the PassInfo class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_PASSINFO_H
#define LLVM_PASSINFO_H
#include <cassert>
#include <vector>
namespace llvm {
class Pass;
class TargetMachine;
//===---------------------------------------------------------------------------
/// PassInfo class - An instance of this class exists for every pass known by
/// the system, and can be obtained from a live Pass by calling its
/// getPassInfo() method. These objects are set up by the RegisterPass<>
/// template.
///
class PassInfo {
public:
typedef Pass* (*NormalCtor_t)();
typedef Pass *(*TargetMachineCtor_t)(TargetMachine *);
private:
const char *const PassName; // Nice name for Pass
const char *const PassArgument; // Command Line argument to run this pass
const void *PassID;
const bool IsCFGOnlyPass; // Pass only looks at the CFG.
const bool IsAnalysis; // True if an analysis pass.
const bool IsAnalysisGroup; // True if an analysis group.
std::vector<const PassInfo*> ItfImpl;// Interfaces implemented by this pass
NormalCtor_t NormalCtor;
TargetMachineCtor_t TargetMachineCtor;
public:
/// PassInfo ctor - Do not call this directly, this should only be invoked
/// through RegisterPass.
PassInfo(const char *name, const char *arg, const void *pi,
NormalCtor_t normal, bool isCFGOnly, bool is_analysis,
TargetMachineCtor_t machine = nullptr)
: PassName(name), PassArgument(arg), PassID(pi),
IsCFGOnlyPass(isCFGOnly),
IsAnalysis(is_analysis), IsAnalysisGroup(false), NormalCtor(normal),
TargetMachineCtor(machine) {}
/// PassInfo ctor - Do not call this directly, this should only be invoked
/// through RegisterPass. This version is for use by analysis groups; it
/// does not auto-register the pass.
PassInfo(const char *name, const void *pi)
: PassName(name), PassArgument(""), PassID(pi),
IsCFGOnlyPass(false),
IsAnalysis(false), IsAnalysisGroup(true), NormalCtor(nullptr),
TargetMachineCtor(nullptr) {}
/// getPassName - Return the friendly name for the pass, never returns null
///
StringRef getPassName() const { return PassName; }
/// getPassArgument - Return the command line option that may be passed to
/// 'opt' that will cause this pass to be run. This will return null if there
/// is no argument.
///
const char *getPassArgument() const { return PassArgument; }
/// getTypeInfo - Return the id object for the pass...
/// TODO : Rename
const void *getTypeInfo() const { return PassID; }
/// Return true if this PassID implements the specified ID pointer.
bool isPassID(const void *IDPtr) const {
return PassID == IDPtr;
}
/// isAnalysisGroup - Return true if this is an analysis group, not a normal
/// pass.
///
bool isAnalysisGroup() const { return IsAnalysisGroup; }
bool isAnalysis() const { return IsAnalysis; }
/// isCFGOnlyPass - return true if this pass only looks at the CFG for the
/// function.
bool isCFGOnlyPass() const { return IsCFGOnlyPass; }
/// getNormalCtor - Return a pointer to a function, that when called, creates
/// an instance of the pass and returns it. This pointer may be null if there
/// is no default constructor for the pass.
///
NormalCtor_t getNormalCtor() const {
return NormalCtor;
}
void setNormalCtor(NormalCtor_t Ctor) {
NormalCtor = Ctor;
}
/// getTargetMachineCtor - Return a pointer to a function, that when called
/// with a TargetMachine, creates an instance of the pass and returns it.
/// This pointer may be null if there is no constructor with a TargetMachine
/// for the pass.
///
TargetMachineCtor_t getTargetMachineCtor() const { return TargetMachineCtor; }
void setTargetMachineCtor(TargetMachineCtor_t Ctor) {
TargetMachineCtor = Ctor;
}
/// createPass() - Use this method to create an instance of this pass.
Pass *createPass() const {
assert((!isAnalysisGroup() || NormalCtor) &&
"No default implementation found for analysis group!");
assert(NormalCtor &&
"Cannot call createPass on PassInfo without default ctor!");
return NormalCtor();
}
/// addInterfaceImplemented - This method is called when this pass is
/// registered as a member of an analysis group with the RegisterAnalysisGroup
/// template.
///
void addInterfaceImplemented(const PassInfo *ItfPI) {
ItfImpl.push_back(ItfPI);
}
/// getInterfacesImplemented - Return a list of all of the analysis group
/// interfaces implemented by this pass.
///
const std::vector<const PassInfo*> &getInterfacesImplemented() const {
return ItfImpl;
}
private:
void operator=(const PassInfo &) = delete;
PassInfo(const PassInfo &) = delete;
};
}
#endif
|
0 | repos/DirectXShaderCompiler/include | repos/DirectXShaderCompiler/include/llvm/LinkAllPasses.h | //===- llvm/LinkAllPasses.h ------------ Reference All Passes ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This header file pulls in all transformation and analysis passes for tools
// like opt and bugpoint that need this functionality.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LINKALLPASSES_H
#define LLVM_LINKALLPASSES_H
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/AliasSetTracker.h"
#include "llvm/Analysis/CallPrinter.h"
#include "llvm/Analysis/DomPrinter.h"
#include "llvm/Analysis/IntervalPartition.h"
#include "llvm/Analysis/Lint.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/PostDominators.h"
#include "llvm/Analysis/RegionPass.h"
#include "llvm/Analysis/RegionPrinter.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRPrintingPasses.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Instrumentation.h"
#include "llvm/Transforms/ObjCARC.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/SymbolRewriter.h"
#include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
#include "llvm/Transforms/Vectorize.h"
#include "llvm/Support/Valgrind.h"
#include <cstdlib>
namespace {
struct ForcePassLinking {
ForcePassLinking() {
// We must reference the passes in such a way that compilers will not
// delete it all as dead code, even with whole program optimization,
// yet is effectively a NO-OP. As the compiler isn't smart enough
// to know that getenv() never returns -1, this will do the job.
if (std::getenv("bar") != (char*) -1)
return;
(void) llvm::createAAEvalPass();
(void) llvm::createAggressiveDCEPass();
(void) llvm::createBitTrackingDCEPass();
(void) llvm::createAliasAnalysisCounterPass();
(void) llvm::createAliasDebugger();
// (void) llvm::createArgumentPromotionPass(); // HLSL Change - do not link
(void) llvm::createAlignmentFromAssumptionsPass();
(void) llvm::createBasicAliasAnalysisPass();
(void) llvm::createLibCallAliasAnalysisPass(nullptr);
(void) llvm::createScalarEvolutionAliasAnalysisPass();
(void) llvm::createTypeBasedAliasAnalysisPass();
(void) llvm::createScopedNoAliasAAPass();
// (void) llvm::createBoundsCheckingPass(); // HLSL Change - do not link
(void) llvm::createBreakCriticalEdgesPass();
(void) llvm::createCallGraphPrinterPass();
(void) llvm::createCallGraphViewerPass();
(void) llvm::createCFGSimplificationPass();
(void) llvm::createCFLAliasAnalysisPass();
(void) llvm::createStructurizeCFGPass();
(void) llvm::createConstantMergePass();
(void) llvm::createConstantPropagationPass();
(void) llvm::createCostModelAnalysisPass();
(void) llvm::createDeadArgEliminationPass();
(void) llvm::createDeadCodeEliminationPass();
(void) llvm::createDeadInstEliminationPass();
(void) llvm::createDeadStoreEliminationPass();
(void) llvm::createDependenceAnalysisPass();
(void) llvm::createDivergenceAnalysisPass();
(void) llvm::createDomOnlyPrinterPass();
(void) llvm::createDomPrinterPass();
(void) llvm::createDomOnlyViewerPass();
(void) llvm::createDomViewerPass();
// (void) llvm::createGCOVProfilerPass(); // HLSL Change - do not link
// (void) llvm::createInstrProfilingPass(); // HLSL Change - do not link
(void) llvm::createFunctionInliningPass();
(void) llvm::createAlwaysInlinerPass();
(void) llvm::createGlobalDCEPass();
(void) llvm::createGlobalOptimizerPass();
(void) llvm::createGlobalsModRefPass();
(void) llvm::createIPConstantPropagationPass();
(void) llvm::createIPSCCPPass();
(void) llvm::createInductiveRangeCheckEliminationPass();
(void) llvm::createIndVarSimplifyPass();
(void) llvm::createInstructionCombiningPass();
(void) llvm::createInternalizePass();
(void) llvm::createLCSSAPass();
(void) llvm::createLICMPass();
(void) llvm::createLazyValueInfoPass();
(void) llvm::createLoopExtractorPass();
(void) llvm::createLoopInterchangePass();
(void) llvm::createLoopSimplifyPass();
(void) llvm::createLoopStrengthReducePass();
(void) llvm::createLoopRerollPass();
(void) llvm::createLoopUnrollPass();
(void) llvm::createLoopUnswitchPass();
(void) llvm::createLoopIdiomPass();
(void) llvm::createLoopRotatePass();
(void) llvm::createLowerExpectIntrinsicPass();
(void) llvm::createLowerInvokePass();
(void) llvm::createLowerSwitchPass();
(void) llvm::createNaryReassociatePass();
(void) llvm::createNoAAPass();
// (void) llvm::createObjCARCAliasAnalysisPass(); // HLSL Change - do not link
// (void) llvm::createObjCARCAPElimPass(); // HLSL Change - do not link
// (void) llvm::createObjCARCExpandPass(); // HLSL Change - do not link
// (void) llvm::createObjCARCContractPass(); // HLSL Change - do not link
// (void) llvm::createObjCARCOptPass(); // HLSL Change - do not link
// (void) llvm::createPAEvalPass();// HLSL Change - do not link
(void) llvm::createPromoteMemoryToRegisterPass();
(void) llvm::createDemoteRegisterToMemoryPass();
// (void) llvm::createPruneEHPass(); // HLSL Change - do not link
(void) llvm::createPostDomOnlyPrinterPass();
(void) llvm::createPostDomPrinterPass();
(void) llvm::createPostDomOnlyViewerPass();
(void) llvm::createPostDomViewerPass();
(void) llvm::createReassociatePass();
(void) llvm::createRegionInfoPass();
(void) llvm::createRegionOnlyPrinterPass();
(void) llvm::createRegionOnlyViewerPass();
(void) llvm::createRegionPrinterPass();
(void) llvm::createRegionViewerPass();
(void) llvm::createSCCPPass();
// (void) llvm::createSafeStackPass(); // HLSL Change - do not link
(void) llvm::createScalarReplAggregatesPass();
(void) llvm::createSingleLoopExtractorPass();
(void) llvm::createStripSymbolsPass();
(void) llvm::createStripNonDebugSymbolsPass();
(void) llvm::createStripDeadDebugInfoPass();
(void) llvm::createStripDeadPrototypesPass();
(void) llvm::createTailCallEliminationPass();
(void) llvm::createJumpThreadingPass();
(void) llvm::createUnifyFunctionExitNodesPass();
(void) llvm::createInstCountPass();
(void) llvm::createConstantHoistingPass();
// (void) llvm::createCodeGenPreparePass(); // HLSL Change - do not link
(void) llvm::createEarlyCSEPass();
(void) llvm::createMergedLoadStoreMotionPass();
(void) llvm::createGVNPass();
(void) llvm::createMemCpyOptPass();
(void) llvm::createLoopDeletionPass();
(void) llvm::createPostDomTree();
(void) llvm::createInstructionNamerPass();
(void) llvm::createMetaRenamerPass();
(void) llvm::createFunctionAttrsPass();
(void) llvm::createMergeFunctionsPass();
// HLSL Change Begin - avoid casting nullptrs
std::string buf;
llvm::raw_string_ostream os(buf);
(void) llvm::createPrintModulePass(os);
(void) llvm::createPrintFunctionPass(os);
(void) llvm::createPrintBasicBlockPass(os);
// HLSL Change End - avoid casting nullptrs
(void) llvm::createModuleDebugInfoPrinterPass();
(void) llvm::createPartialInliningPass();
(void) llvm::createLintPass();
(void) llvm::createSinkingPass();
(void) llvm::createLowerAtomicPass();
(void) llvm::createCorrelatedValuePropagationPass();
(void) llvm::createMemDepPrinter();
(void) llvm::createInstructionSimplifierPass();
// (void) llvm::createLoopVectorizePass(); // HLSL Change - do not link
// (void) llvm::createSLPVectorizerPass(); // HLSL Change - do not link
// (void) llvm::createBBVectorizePass(); // HLSL Change - do not link
(void) llvm::createPartiallyInlineLibCallsPass();
(void) llvm::createScalarizerPass();
(void) llvm::createSeparateConstOffsetFromGEPPass();
(void) llvm::createSpeculativeExecutionPass();
(void) llvm::createRewriteSymbolsPass();
(void) llvm::createStraightLineStrengthReducePass();
(void) llvm::createMemDerefPrinter();
(void) llvm::createFloat2IntPass();
(void) llvm::createEliminateAvailableExternallyPass();
(void)new llvm::IntervalPartition();
(void)new llvm::ScalarEvolution();
// HLSL Change Begin - avoid casting nullptrs
llvm::Function::Create(nullptr, llvm::GlobalValue::ExternalLinkage)->viewCFGOnly();
llvm::AliasAnalysis AA;
llvm::AliasSetTracker X(AA);
// HLSL Change End - avoid casting nullptrs
X.add(nullptr, 0, llvm::AAMDNodes()); // for -print-alias-sets
(void) llvm::AreStatisticsEnabled();
(void) llvm::sys::RunningOnValgrind();
}
} ForcePassLinking; // Force link by creating a global definition.
}
#endif
|
0 | repos/DirectXShaderCompiler/include | repos/DirectXShaderCompiler/include/llvm/Pass.h | //===- llvm/Pass.h - Base class for Passes ----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a base class that indicates that a specified class is a
// transformation pass implementation.
//
// Passes are designed this way so that it is possible to run passes in a cache
// and organizationally optimal order without having to specify it at the front
// end. This allows arbitrary passes to be strung together and have them
// executed as efficiently as possible.
//
// Passes should extend one of the classes below, depending on the guarantees
// that it can make about what will be modified as it is run. For example, most
// global optimizations should derive from FunctionPass, because they do not add
// or delete functions, they operate on the internals of the function.
//
// Note that this file #includes PassSupport.h and PassAnalysisSupport.h (at the
// bottom), so the APIs exposed by these files are also automatically available
// to all users of this file.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_PASS_H
#define LLVM_PASS_H
#include "llvm/Support/Compiler.h"
#include <string>
#include "llvm/ADT/ArrayRef.h" // HLSL Change
#include "llvm/ADT/StringRef.h" // HLSL Change
namespace llvm {
class BasicBlock;
class Function;
class Module;
class AnalysisUsage;
class PassInfo;
class ImmutablePass;
class PMStack;
class AnalysisResolver;
class PMDataManager;
class raw_ostream;
class StringRef;
// AnalysisID - Use the PassInfo to identify a pass...
typedef const void* AnalysisID;
/// Different types of internal pass managers. External pass managers
/// (PassManager and FunctionPassManager) are not represented here.
/// Ordering of pass manager types is important here.
enum PassManagerType {
PMT_Unknown = 0,
PMT_ModulePassManager = 1, ///< MPPassManager
PMT_CallGraphPassManager, ///< CGPassManager
PMT_FunctionPassManager, ///< FPPassManager
PMT_LoopPassManager, ///< LPPassManager
PMT_RegionPassManager, ///< RGPassManager
PMT_BasicBlockPassManager, ///< BBPassManager
PMT_Last
};
// Different types of passes.
enum PassKind {
PT_BasicBlock,
PT_Region,
PT_Loop,
PT_Function,
PT_CallGraphSCC,
PT_Module,
PT_PassManager
};
// HLSL Change Starts
//
// LLVM passes typically support an empty constructor, but often they will
// have in addition to that constructors with arguments, as well as global
// options that can modify their behavior.
//
// This section allows a data-driven pipeline assembler to be built.
// The DxcOptimizer holds much of the needed information, but passes
// frequently are implemented in non-header files and as such this
// becomes a reasonable mechanism to pass flags around.
//
// Pass implementations should use the GetPassOption* functions to read
// arguments, setting fields in place of globals and updating state
// for constructor arguments.
//
typedef std::pair<llvm::StringRef, llvm::StringRef> PassOption;
typedef llvm::ArrayRef<PassOption> PassOptions;
struct PassOptionsCompare {
bool operator()(const PassOption &a, const PassOption &b) {
return a.first < b.first;
}
};
bool GetPassOption(PassOptions &O, llvm::StringRef name, llvm::StringRef *pValue);
bool GetPassOptionBool(PassOptions &O, llvm::StringRef name, bool *pValue, bool defaultValue);
bool GetPassOptionUnsigned(PassOptions &O, llvm::StringRef name, unsigned *pValue, unsigned defaultValue);
bool GetPassOptionInt(PassOptions &O, llvm::StringRef name, int *pValue, int defaultValue);
bool GetPassOptionUInt32(PassOptions &O, llvm::StringRef name, uint32_t *pValue, uint32_t defaultValue);
bool GetPassOptionUInt64(PassOptions &O, llvm::StringRef name, uint64_t *pValue, uint64_t defaultValue);
bool GetPassOptionFloat(PassOptions &O, llvm::StringRef name, float *pValue, float defaultValue);
// HLSL Change Ends
//===----------------------------------------------------------------------===//
/// Pass interface - Implemented by all 'passes'. Subclass this if you are an
/// interprocedural optimization or you do not fit into any of the more
/// constrained passes described below.
///
class Pass {
AnalysisResolver *Resolver; // Used to resolve analysis
const void *PassID;
PassKind Kind;
void operator=(const Pass&) = delete;
Pass(const Pass &) = delete;
protected: raw_ostream *OSOverride; // HLSL Change
public:
explicit Pass(PassKind K, char &pid)
: Resolver(nullptr), PassID(&pid), Kind(K), OSOverride(nullptr) { } // HLSL Change
virtual ~Pass();
void setOSOverride(raw_ostream *OS) { OSOverride = OS; } // HLSL Change
virtual void applyOptions(PassOptions O) { return; } // HLSL Change
virtual void dumpConfig(raw_ostream &OS); // HLSL Change
PassKind getPassKind() const { return Kind; }
/// getPassName - Return a nice clean name for a pass. This usually
/// implemented in terms of the name that is registered by one of the
/// Registration templates, but can be overloaded directly.
///
virtual StringRef getPassName() const;
const char *getPassArgument() const; // HLSL Change
/// getPassID - Return the PassID number that corresponds to this pass.
AnalysisID getPassID() const {
return PassID;
}
/// doInitialization - Virtual method overridden by subclasses to do
/// any necessary initialization before any pass is run.
///
virtual bool doInitialization(Module &) { return false; }
/// doFinalization - Virtual method overriden by subclasses to do any
/// necessary clean up after all passes have run.
///
virtual bool doFinalization(Module &) { return false; }
/// print - Print out the internal state of the pass. This is called by
/// Analyze to print out the contents of an analysis. Otherwise it is not
/// necessary to implement this method. Beware that the module pointer MAY be
/// null. This automatically forwards to a virtual function that does not
/// provide the Module* in case the analysis doesn't need it it can just be
/// ignored.
///
virtual void print(raw_ostream &O, const Module *M) const;
void dump() const; // dump - Print to stderr.
/// createPrinterPass - Get a Pass appropriate to print the IR this
/// pass operates on (Module, Function or MachineFunction).
virtual Pass *createPrinterPass(raw_ostream &O,
const std::string &Banner) const = 0;
/// Each pass is responsible for assigning a pass manager to itself.
/// PMS is the stack of available pass manager.
virtual void assignPassManager(PMStack &,
PassManagerType) {}
/// Check if available pass managers are suitable for this pass or not.
virtual void preparePassManager(PMStack &);
/// Return what kind of Pass Manager can manage this pass.
virtual PassManagerType getPotentialPassManagerType() const;
// Access AnalysisResolver
void setResolver(AnalysisResolver *AR);
AnalysisResolver *getResolver() const { return Resolver; }
/// getAnalysisUsage - This function should be overriden by passes that need
/// analysis information to do their job. If a pass specifies that it uses a
/// particular analysis result to this function, it can then use the
/// getAnalysis<AnalysisType>() function, below.
///
virtual void getAnalysisUsage(AnalysisUsage &) const;
/// releaseMemory() - This member can be implemented by a pass if it wants to
/// be able to release its memory when it is no longer needed. The default
/// behavior of passes is to hold onto memory for the entire duration of their
/// lifetime (which is the entire compile time). For pipelined passes, this
/// is not a big deal because that memory gets recycled every time the pass is
/// invoked on another program unit. For IP passes, it is more important to
/// free memory when it is unused.
///
/// Optionally implement this function to release pass memory when it is no
/// longer used.
///
virtual void releaseMemory();
/// getAdjustedAnalysisPointer - This method is used when a pass implements
/// an analysis interface through multiple inheritance. If needed, it should
/// override this to adjust the this pointer as needed for the specified pass
/// info.
virtual void *getAdjustedAnalysisPointer(AnalysisID ID);
virtual ImmutablePass *getAsImmutablePass();
virtual PMDataManager *getAsPMDataManager();
/// verifyAnalysis() - This member can be implemented by a analysis pass to
/// check state of analysis information.
virtual void verifyAnalysis() const;
// dumpPassStructure - Implement the -debug-passes=PassStructure option
virtual void dumpPassStructure(unsigned Offset = 0);
// lookupPassInfo - Return the pass info object for the specified pass class,
// or null if it is not known.
static const PassInfo *lookupPassInfo(const void *TI);
// lookupPassInfo - Return the pass info object for the pass with the given
// argument string, or null if it is not known.
static const PassInfo *lookupPassInfo(StringRef Arg);
// createPass - Create a object for the specified pass class,
// or null if it is not known.
static Pass *createPass(AnalysisID ID);
/// getAnalysisIfAvailable<AnalysisType>() - Subclasses use this function to
/// get analysis information that might be around, for example to update it.
/// This is different than getAnalysis in that it can fail (if the analysis
/// results haven't been computed), so should only be used if you can handle
/// the case when the analysis is not available. This method is often used by
/// transformation APIs to update analysis results for a pass automatically as
/// the transform is performed.
///
template<typename AnalysisType> AnalysisType *
getAnalysisIfAvailable() const; // Defined in PassAnalysisSupport.h
/// mustPreserveAnalysisID - This method serves the same function as
/// getAnalysisIfAvailable, but works if you just have an AnalysisID. This
/// obviously cannot give you a properly typed instance of the class if you
/// don't have the class name available (use getAnalysisIfAvailable if you
/// do), but it can tell you if you need to preserve the pass at least.
///
bool mustPreserveAnalysisID(char &AID) const;
/// getAnalysis<AnalysisType>() - This function is used by subclasses to get
/// to the analysis information that they claim to use by overriding the
/// getAnalysisUsage function.
///
template<typename AnalysisType>
AnalysisType &getAnalysis() const; // Defined in PassAnalysisSupport.h
template<typename AnalysisType>
AnalysisType &getAnalysis(Function &F); // Defined in PassAnalysisSupport.h
template<typename AnalysisType>
AnalysisType &getAnalysisID(AnalysisID PI) const;
template<typename AnalysisType>
AnalysisType &getAnalysisID(AnalysisID PI, Function &F);
};
//===----------------------------------------------------------------------===//
/// ModulePass class - This class is used to implement unstructured
/// interprocedural optimizations and analyses. ModulePasses may do anything
/// they want to the program.
///
class ModulePass : public Pass {
public:
/// createPrinterPass - Get a module printer pass.
Pass *createPrinterPass(raw_ostream &O,
const std::string &Banner) const override;
/// runOnModule - Virtual method overriden by subclasses to process the module
/// being operated on.
virtual bool runOnModule(Module &M) = 0;
void assignPassManager(PMStack &PMS, PassManagerType T) override;
/// Return what kind of Pass Manager can manage this pass.
PassManagerType getPotentialPassManagerType() const override;
explicit ModulePass(char &pid) : Pass(PT_Module, pid) {}
// Force out-of-line virtual method.
~ModulePass() override;
};
//===----------------------------------------------------------------------===//
/// ImmutablePass class - This class is used to provide information that does
/// not need to be run. This is useful for things like target information and
/// "basic" versions of AnalysisGroups.
///
class ImmutablePass : public ModulePass {
public:
/// initializePass - This method may be overriden by immutable passes to allow
/// them to perform various initialization actions they require. This is
/// primarily because an ImmutablePass can "require" another ImmutablePass,
/// and if it does, the overloaded version of initializePass may get access to
/// these passes with getAnalysis<>.
///
virtual void initializePass();
ImmutablePass *getAsImmutablePass() override { return this; }
/// ImmutablePasses are never run.
///
bool runOnModule(Module &) override { return false; }
explicit ImmutablePass(char &pid)
: ModulePass(pid) {}
// Force out-of-line virtual method.
~ImmutablePass() override;
};
//===----------------------------------------------------------------------===//
/// FunctionPass class - This class is used to implement most global
/// optimizations. Optimizations should subclass this class if they meet the
/// following constraints:
///
/// 1. Optimizations are organized globally, i.e., a function at a time
/// 2. Optimizing a function does not cause the addition or removal of any
/// functions in the module
///
class FunctionPass : public Pass {
public:
explicit FunctionPass(char &pid) : Pass(PT_Function, pid) {}
/// createPrinterPass - Get a function printer pass.
Pass *createPrinterPass(raw_ostream &O,
const std::string &Banner) const override;
/// runOnFunction - Virtual method overriden by subclasses to do the
/// per-function processing of the pass.
///
virtual bool runOnFunction(Function &F) = 0;
void assignPassManager(PMStack &PMS, PassManagerType T) override;
/// Return what kind of Pass Manager can manage this pass.
PassManagerType getPotentialPassManagerType() const override;
protected:
/// skipOptnoneFunction - This function has Attribute::OptimizeNone
/// and most transformation passes should skip it.
bool skipOptnoneFunction(const Function &F) const;
};
// //
///////////////////////////////////////////////////////////////////////////////
/// BasicBlockPass class - This class is used to implement most local
/// optimizations. Optimizations should subclass this class if they
/// meet the following constraints:
/// 1. Optimizations are local, operating on either a basic block or
/// instruction at a time.
/// 2. Optimizations do not modify the CFG of the contained function, or any
/// other basic block in the function.
/// 3. Optimizations conform to all of the constraints of FunctionPasses.
///
class BasicBlockPass : public Pass {
public:
explicit BasicBlockPass(char &pid) : Pass(PT_BasicBlock, pid) {}
/// createPrinterPass - Get a basic block printer pass.
Pass *createPrinterPass(raw_ostream &O,
const std::string &Banner) const override;
using llvm::Pass::doInitialization;
using llvm::Pass::doFinalization;
/// doInitialization - Virtual method overridden by BasicBlockPass subclasses
/// to do any necessary per-function initialization.
///
virtual bool doInitialization(Function &);
/// runOnBasicBlock - Virtual method overriden by subclasses to do the
/// per-basicblock processing of the pass.
///
virtual bool runOnBasicBlock(BasicBlock &BB) = 0;
/// doFinalization - Virtual method overriden by BasicBlockPass subclasses to
/// do any post processing needed after all passes have run.
///
virtual bool doFinalization(Function &);
void assignPassManager(PMStack &PMS, PassManagerType T) override;
/// Return what kind of Pass Manager can manage this pass.
PassManagerType getPotentialPassManagerType() const override;
protected:
/// skipOptnoneFunction - Containing function has Attribute::OptimizeNone
/// and most transformation passes should skip it.
bool skipOptnoneFunction(const BasicBlock &BB) const;
};
/// If the user specifies the -time-passes argument on an LLVM tool command line
/// then the value of this boolean will be true, otherwise false.
/// @brief This is the storage for the -time-passes option.
extern bool TimePassesIsEnabled;
} // End llvm namespace
// Include support files that contain important APIs commonly used by Passes,
// but that we want to separate out to make it easier to read the header files.
//
#include "llvm/PassSupport.h"
#include "llvm/PassAnalysisSupport.h"
#endif
|
0 | repos/DirectXShaderCompiler/include | repos/DirectXShaderCompiler/include/llvm/PassSupport.h | //===- llvm/PassSupport.h - Pass Support code -------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines stuff that is used to define and "use" Passes. This file
// is automatically #included by Pass.h, so:
//
// NO .CPP FILES SHOULD INCLUDE THIS FILE DIRECTLY
//
// Instead, #include Pass.h.
//
// This file defines Pass registration code and classes used for it.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_PASSSUPPORT_H
#define LLVM_PASSSUPPORT_H
#include "Pass.h"
#include "llvm/InitializePasses.h"
#include "llvm/PassInfo.h"
#include "llvm/PassRegistry.h"
#include "llvm/Support/Atomic.h"
#include "llvm/Support/Valgrind.h"
#include <vector>
namespace llvm {
class TargetMachine;
#define CALL_ONCE_INITIALIZATION(function) \
static volatile sys::cas_flag initialized = 0; \
sys::cas_flag old_val = sys::CompareAndSwap(&initialized, 1, 0); \
if (old_val == 0) { \
function(Registry); \
sys::MemoryFence(); \
TsanIgnoreWritesBegin(); \
TsanHappensBefore(&initialized); \
initialized = 2; \
TsanIgnoreWritesEnd(); \
} else { \
sys::cas_flag tmp = initialized; \
sys::MemoryFence(); \
while (tmp != 2) { \
tmp = initialized; \
sys::MemoryFence(); \
} \
} \
TsanHappensAfter(&initialized);
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis) \
static void* initialize##passName##PassOnce(PassRegistry &Registry) { \
PassInfo *PI = new PassInfo(name, arg, & passName ::ID, \
PassInfo::NormalCtor_t(callDefaultCtor< passName >), cfg, analysis); \
Registry.registerPass(*PI, true); \
return PI; \
} \
void llvm::initialize##passName##Pass(PassRegistry &Registry) { \
CALL_ONCE_INITIALIZATION(initialize##passName##PassOnce) \
}
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis) \
static void* initialize##passName##PassOnce(PassRegistry &Registry) {
#define INITIALIZE_PASS_DEPENDENCY(depName) \
initialize##depName##Pass(Registry);
#define INITIALIZE_AG_DEPENDENCY(depName) \
initialize##depName##AnalysisGroup(Registry);
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis) \
PassInfo *PI = new PassInfo(name, arg, & passName ::ID, \
PassInfo::NormalCtor_t(callDefaultCtor< passName >), cfg, analysis); \
Registry.registerPass(*PI, true); \
return PI; \
} \
void llvm::initialize##passName##Pass(PassRegistry &Registry) { \
CALL_ONCE_INITIALIZATION(initialize##passName##PassOnce) \
}
#define INITIALIZE_PASS_WITH_OPTIONS(PassName, Arg, Name, Cfg, Analysis) \
INITIALIZE_PASS_BEGIN(PassName, Arg, Name, Cfg, Analysis) \
PassName::registerOptions(); \
INITIALIZE_PASS_END(PassName, Arg, Name, Cfg, Analysis)
#define INITIALIZE_PASS_WITH_OPTIONS_BEGIN(PassName, Arg, Name, Cfg, Analysis) \
INITIALIZE_PASS_BEGIN(PassName, Arg, Name, Cfg, Analysis) \
PassName::registerOptions(); \
template<typename PassName>
Pass *callDefaultCtor() { return new PassName(); }
template <typename PassName> Pass *callTargetMachineCtor(TargetMachine *TM) {
return new PassName(TM);
}
//===---------------------------------------------------------------------------
/// RegisterPass<t> template - This template class is used to notify the system
/// that a Pass is available for use, and registers it into the internal
/// database maintained by the PassManager. Unless this template is used, opt,
/// for example will not be able to see the pass and attempts to create the pass
/// will fail. This template is used in the follow manner (at global scope, in
/// your .cpp file):
///
/// static RegisterPass<YourPassClassName> tmp("passopt", "My Pass Name");
///
/// This statement will cause your pass to be created by calling the default
/// constructor exposed by the pass. If you have a different constructor that
/// must be called, create a global constructor function (which takes the
/// arguments you need and returns a Pass*) and register your pass like this:
///
/// static RegisterPass<PassClassName> tmp("passopt", "My Name");
///
template<typename passName>
struct RegisterPass : public PassInfo {
// Register Pass using default constructor...
RegisterPass(const char *PassArg, const char *Name, bool CFGOnly = false,
bool is_analysis = false)
: PassInfo(Name, PassArg, &passName::ID,
PassInfo::NormalCtor_t(callDefaultCtor<passName>),
CFGOnly, is_analysis) {
PassRegistry::getPassRegistry()->registerPass(*this);
}
};
/// RegisterAnalysisGroup - Register a Pass as a member of an analysis _group_.
/// Analysis groups are used to define an interface (which need not derive from
/// Pass) that is required by passes to do their job. Analysis Groups differ
/// from normal analyses because any available implementation of the group will
/// be used if it is available.
///
/// If no analysis implementing the interface is available, a default
/// implementation is created and added. A pass registers itself as the default
/// implementation by specifying 'true' as the second template argument of this
/// class.
///
/// In addition to registering itself as an analysis group member, a pass must
/// register itself normally as well. Passes may be members of multiple groups
/// and may still be "required" specifically by name.
///
/// The actual interface may also be registered as well (by not specifying the
/// second template argument). The interface should be registered to associate
/// a nice name with the interface.
///
class RegisterAGBase : public PassInfo {
public:
RegisterAGBase(const char *Name,
const void *InterfaceID,
const void *PassID = nullptr,
bool isDefault = false);
};
template<typename Interface, bool Default = false>
struct RegisterAnalysisGroup : public RegisterAGBase {
explicit RegisterAnalysisGroup(PassInfo &RPB)
: RegisterAGBase(RPB.getPassName(),
&Interface::ID, RPB.getTypeInfo(),
Default) {
}
explicit RegisterAnalysisGroup(const char *Name)
: RegisterAGBase(Name, &Interface::ID) {
}
};
#define INITIALIZE_ANALYSIS_GROUP(agName, name, defaultPass) \
static void* initialize##agName##AnalysisGroupOnce(PassRegistry &Registry) { \
initialize##defaultPass##Pass(Registry); \
PassInfo *AI = new PassInfo(name, & agName :: ID); \
Registry.registerAnalysisGroup(& agName ::ID, 0, *AI, false, true); \
return AI; \
} \
void llvm::initialize##agName##AnalysisGroup(PassRegistry &Registry) { \
CALL_ONCE_INITIALIZATION(initialize##agName##AnalysisGroupOnce) \
}
#define INITIALIZE_AG_PASS(passName, agName, arg, name, cfg, analysis, def) \
static void* initialize##passName##PassOnce(PassRegistry &Registry) { \
if (!def) initialize##agName##AnalysisGroup(Registry); \
PassInfo *PI = new PassInfo(name, arg, & passName ::ID, \
PassInfo::NormalCtor_t(callDefaultCtor< passName >), cfg, analysis); \
Registry.registerPass(*PI, true); \
\
PassInfo *AI = new PassInfo(name, & agName :: ID); \
Registry.registerAnalysisGroup(& agName ::ID, & passName ::ID, \
*AI, def, true); \
return AI; \
} \
void llvm::initialize##passName##Pass(PassRegistry &Registry) { \
CALL_ONCE_INITIALIZATION(initialize##passName##PassOnce) \
}
#define INITIALIZE_AG_PASS_BEGIN(passName, agName, arg, n, cfg, analysis, def) \
static void* initialize##passName##PassOnce(PassRegistry &Registry) { \
if (!def) initialize##agName##AnalysisGroup(Registry);
#define INITIALIZE_AG_PASS_END(passName, agName, arg, n, cfg, analysis, def) \
PassInfo *PI = new PassInfo(n, arg, & passName ::ID, \
PassInfo::NormalCtor_t(callDefaultCtor< passName >), cfg, analysis); \
Registry.registerPass(*PI, true); \
\
PassInfo *AI = new PassInfo(n, & agName :: ID); \
Registry.registerAnalysisGroup(& agName ::ID, & passName ::ID, \
*AI, def, true); \
return AI; \
} \
void llvm::initialize##passName##Pass(PassRegistry &Registry) { \
CALL_ONCE_INITIALIZATION(initialize##passName##PassOnce) \
}
//===---------------------------------------------------------------------------
/// PassRegistrationListener class - This class is meant to be derived from by
/// clients that are interested in which passes get registered and unregistered
/// at runtime (which can be because of the RegisterPass constructors being run
/// as the program starts up, or may be because a shared object just got
/// loaded).
///
struct PassRegistrationListener {
PassRegistrationListener() {}
virtual ~PassRegistrationListener() {}
/// Callback functions - These functions are invoked whenever a pass is loaded
/// or removed from the current executable.
///
virtual void passRegistered(const PassInfo *) {}
/// enumeratePasses - Iterate over the registered passes, calling the
/// passEnumerate callback on each PassInfo object.
///
void enumeratePasses();
/// passEnumerate - Callback function invoked when someone calls
/// enumeratePasses on this PassRegistrationListener object.
///
virtual void passEnumerate(const PassInfo *) {}
};
} // End llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCAsmInfoELF.h | //===-- llvm/MC/MCAsmInfoELF.h - ELF Asm info -------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCASMINFOELF_H
#define LLVM_MC_MCASMINFOELF_H
#include "llvm/MC/MCAsmInfo.h"
namespace llvm {
class MCAsmInfoELF : public MCAsmInfo {
virtual void anchor();
MCSection *getNonexecutableStackSection(MCContext &Ctx) const final;
protected:
MCAsmInfoELF();
};
}
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCAsmInfo.h | //===-- llvm/MC/MCAsmInfo.h - Asm info --------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains a class to be used as the basis for target specific
// asm writers. This class primarily takes care of global printing constants,
// which are used in very similar ways across all targets.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCASMINFO_H
#define LLVM_MC_MCASMINFO_H
#include "llvm/MC/MCDirectives.h"
#include "llvm/MC/MCDwarf.h"
#include <cassert>
#include <vector>
namespace llvm {
class MCExpr;
class MCSection;
class MCStreamer;
class MCSymbol;
class MCContext;
namespace WinEH {
enum class EncodingType {
Invalid, /// Invalid
Alpha, /// Windows Alpha
Alpha64, /// Windows AXP64
ARM, /// Windows NT (Windows on ARM)
CE, /// Windows CE ARM, PowerPC, SH3, SH4
Itanium, /// Windows x64, Windows Itanium (IA-64)
X86, /// Windows x86, uses no CFI, just EH tables
MIPS = Alpha,
};
}
enum class ExceptionHandling {
None, /// No exception support
DwarfCFI, /// DWARF-like instruction based exceptions
SjLj, /// setjmp/longjmp based exceptions
ARM, /// ARM EHABI
WinEH, /// Windows Exception Handling
};
namespace LCOMM {
enum LCOMMType { NoAlignment, ByteAlignment, Log2Alignment };
}
/// This class is intended to be used as a base class for asm
/// properties and features specific to the target.
class MCAsmInfo {
protected:
//===------------------------------------------------------------------===//
// Properties to be set by the target writer, used to configure asm printer.
//
/// Pointer size in bytes. Default is 4.
unsigned PointerSize;
/// Size of the stack slot reserved for callee-saved registers, in bytes.
/// Default is same as pointer size.
unsigned CalleeSaveStackSlotSize;
/// True if target is little endian. Default is true.
bool IsLittleEndian;
/// True if target stack grow up. Default is false.
bool StackGrowsUp;
/// True if this target has the MachO .subsections_via_symbols directive.
/// Default is false.
bool HasSubsectionsViaSymbols;
/// True if this is a MachO target that supports the macho-specific .zerofill
/// directive for emitting BSS Symbols. Default is false.
bool HasMachoZeroFillDirective;
/// True if this is a MachO target that supports the macho-specific .tbss
/// directive for emitting thread local BSS Symbols. Default is false.
bool HasMachoTBSSDirective;
/// True if the compiler should emit a ".reference .constructors_used" or
/// ".reference .destructors_used" directive after the static ctor/dtor
/// list. This directive is only emitted in Static relocation model. Default
/// is false.
bool HasStaticCtorDtorReferenceInStaticMode;
/// This is the maximum possible length of an instruction, which is needed to
/// compute the size of an inline asm. Defaults to 4.
unsigned MaxInstLength;
/// Every possible instruction length is a multiple of this value. Factored
/// out in .debug_frame and .debug_line. Defaults to 1.
unsigned MinInstAlignment;
/// The '$' token, when not referencing an identifier or constant, refers to
/// the current PC. Defaults to false.
bool DollarIsPC;
/// This string, if specified, is used to separate instructions from each
/// other when on the same line. Defaults to ';'
const char *SeparatorString;
/// This indicates the comment character used by the assembler. Defaults to
/// "#"
const char *CommentString;
/// This is appended to emitted labels. Defaults to ":"
const char *LabelSuffix;
// Print the EH begin symbol with an assignment. Defaults to false.
bool UseAssignmentForEHBegin;
// Do we need to create a local symbol for .size?
bool NeedsLocalForSize;
/// This prefix is used for globals like constant pool entries that are
/// completely private to the .s file and should not have names in the .o
/// file. Defaults to "L"
const char *PrivateGlobalPrefix;
/// This prefix is used for labels for basic blocks. Defaults to the same as
/// PrivateGlobalPrefix.
const char *PrivateLabelPrefix;
/// This prefix is used for symbols that should be passed through the
/// assembler but be removed by the linker. This is 'l' on Darwin, currently
/// used for some ObjC metadata. The default of "" meast that for this system
/// a plain private symbol should be used. Defaults to "".
const char *LinkerPrivateGlobalPrefix;
/// If these are nonempty, they contain a directive to emit before and after
/// an inline assembly statement. Defaults to "#APP\n", "#NO_APP\n"
const char *InlineAsmStart;
const char *InlineAsmEnd;
/// These are assembly directives that tells the assembler to interpret the
/// following instructions differently. Defaults to ".code16", ".code32",
/// ".code64".
const char *Code16Directive;
const char *Code32Directive;
const char *Code64Directive;
/// Which dialect of an assembler variant to use. Defaults to 0
unsigned AssemblerDialect;
/// This is true if the assembler allows @ characters in symbol names.
/// Defaults to false.
bool AllowAtInName;
/// If this is true, symbol names with invalid characters will be printed in
/// quotes.
bool SupportsQuotedNames;
/// This is true if data region markers should be printed as
/// ".data_region/.end_data_region" directives. If false, use "$d/$a" labels
/// instead.
bool UseDataRegionDirectives;
//===--- Data Emission Directives -------------------------------------===//
/// This should be set to the directive used to get some number of zero bytes
/// emitted to the current section. Common cases are "\t.zero\t" and
/// "\t.space\t". If this is set to null, the Data*bitsDirective's will be
/// used to emit zero bytes. Defaults to "\t.zero\t"
const char *ZeroDirective;
/// This directive allows emission of an ascii string with the standard C
/// escape characters embedded into it. Defaults to "\t.ascii\t"
const char *AsciiDirective;
/// If not null, this allows for special handling of zero terminated strings
/// on this target. This is commonly supported as ".asciz". If a target
/// doesn't support this, it can be set to null. Defaults to "\t.asciz\t"
const char *AscizDirective;
/// These directives are used to output some unit of integer data to the
/// current section. If a data directive is set to null, smaller data
/// directives will be used to emit the large sizes. Defaults to "\t.byte\t",
/// "\t.short\t", "\t.long\t", "\t.quad\t"
const char *Data8bitsDirective;
const char *Data16bitsDirective;
const char *Data32bitsDirective;
const char *Data64bitsDirective;
/// If non-null, a directive that is used to emit a word which should be
/// relocated as a 64-bit GP-relative offset, e.g. .gpdword on Mips. Defaults
/// to NULL.
const char *GPRel64Directive;
/// If non-null, a directive that is used to emit a word which should be
/// relocated as a 32-bit GP-relative offset, e.g. .gpword on Mips or .gprel32
/// on Alpha. Defaults to NULL.
const char *GPRel32Directive;
/// This is true if this target uses "Sun Style" syntax for section switching
/// ("#alloc,#write" etc) instead of the normal ELF syntax (,"a,w") in
/// .section directives. Defaults to false.
bool SunStyleELFSectionSwitchSyntax;
/// This is true if this target uses ELF '.section' directive before the
/// '.bss' one. It's used for PPC/Linux which doesn't support the '.bss'
/// directive only. Defaults to false.
bool UsesELFSectionDirectiveForBSS;
bool NeedsDwarfSectionOffsetDirective;
//===--- Alignment Information ----------------------------------------===//
/// If this is true (the default) then the asmprinter emits ".align N"
/// directives, where N is the number of bytes to align to. Otherwise, it
/// emits ".align log2(N)", e.g. 3 to align to an 8 byte boundary. Defaults
/// to true.
bool AlignmentIsInBytes;
/// If non-zero, this is used to fill the executable space created as the
/// result of a alignment directive. Defaults to 0
unsigned TextAlignFillValue;
//===--- Global Variable Emission Directives --------------------------===//
/// This is the directive used to declare a global entity. Defaults to
/// ".globl".
const char *GlobalDirective;
/// True if the expression
/// .long f - g
/// uses a relocation but it can be suppressed by writing
/// a = f - g
/// .long a
bool SetDirectiveSuppressesReloc;
/// False if the assembler requires that we use
/// \code
/// Lc = a - b
/// .long Lc
/// \endcode
//
/// instead of
//
/// \code
/// .long a - b
/// \endcode
///
/// Defaults to true.
bool HasAggressiveSymbolFolding;
/// True is .comm's and .lcomms optional alignment is to be specified in bytes
/// instead of log2(n). Defaults to true.
bool COMMDirectiveAlignmentIsInBytes;
/// Describes if the .lcomm directive for the target supports an alignment
/// argument and how it is interpreted. Defaults to NoAlignment.
LCOMM::LCOMMType LCOMMDirectiveAlignmentType;
// True if the target allows .align directives on functions. This is true for
// most targets, so defaults to true.
bool HasFunctionAlignment;
/// True if the target has .type and .size directives, this is true for most
/// ELF targets. Defaults to true.
bool HasDotTypeDotSizeDirective;
/// True if the target has a single parameter .file directive, this is true
/// for ELF targets. Defaults to true.
bool HasSingleParameterDotFile;
/// True if the target has a .ident directive, this is true for ELF targets.
/// Defaults to false.
bool HasIdentDirective;
/// True if this target supports the MachO .no_dead_strip directive. Defaults
/// to false.
bool HasNoDeadStrip;
/// Used to declare a global as being a weak symbol. Defaults to ".weak".
const char *WeakDirective;
/// This directive, if non-null, is used to declare a global as being a weak
/// undefined symbol. Defaults to NULL.
const char *WeakRefDirective;
/// True if we have a directive to declare a global as being a weak defined
/// symbol. Defaults to false.
bool HasWeakDefDirective;
/// True if we have a directive to declare a global as being a weak defined
/// symbol that can be hidden (unexported). Defaults to false.
bool HasWeakDefCanBeHiddenDirective;
/// True if we have a .linkonce directive. This is used on cygwin/mingw.
/// Defaults to false.
bool HasLinkOnceDirective;
/// This attribute, if not MCSA_Invalid, is used to declare a symbol as having
/// hidden visibility. Defaults to MCSA_Hidden.
MCSymbolAttr HiddenVisibilityAttr;
/// This attribute, if not MCSA_Invalid, is used to declare an undefined
/// symbol as having hidden visibility. Defaults to MCSA_Hidden.
MCSymbolAttr HiddenDeclarationVisibilityAttr;
/// This attribute, if not MCSA_Invalid, is used to declare a symbol as having
/// protected visibility. Defaults to MCSA_Protected
MCSymbolAttr ProtectedVisibilityAttr;
//===--- Dwarf Emission Directives -----------------------------------===//
/// True if target supports emission of debugging information. Defaults to
/// false.
bool SupportsDebugInformation;
/// Exception handling format for the target. Defaults to None.
ExceptionHandling ExceptionsType;
/// Windows exception handling data (.pdata) encoding. Defaults to Invalid.
WinEH::EncodingType WinEHEncodingType;
/// True if Dwarf2 output generally uses relocations for references to other
/// .debug_* sections.
bool DwarfUsesRelocationsAcrossSections;
/// True if DWARF FDE symbol reference relocations should be replaced by an
/// absolute difference.
bool DwarfFDESymbolsUseAbsDiff;
/// True if dwarf register numbers are printed instead of symbolic register
/// names in .cfi_* directives. Defaults to false.
bool DwarfRegNumForCFI;
/// True if target uses parens to indicate the symbol variant instead of @.
/// For example, foo(plt) instead of foo@plt. Defaults to false.
bool UseParensForSymbolVariant;
//===--- Prologue State ----------------------------------------------===//
std::vector<MCCFIInstruction> InitialFrameState;
//===--- Integrated Assembler Information ----------------------------===//
/// Should we use the integrated assembler?
/// The integrated assembler should be enabled by default (by the
/// constructors) when failing to parse a valid piece of assembly (inline
/// or otherwise) is considered a bug. It may then be overridden after
/// construction (see LLVMTargetMachine::initAsmInfo()).
bool UseIntegratedAssembler;
/// Compress DWARF debug sections. Defaults to false.
bool CompressDebugSections;
/// True if the integrated assembler should interpret 'a >> b' constant
/// expressions as logical rather than arithmetic.
bool UseLogicalShr;
public:
explicit MCAsmInfo();
virtual ~MCAsmInfo();
/// Get the pointer size in bytes.
unsigned getPointerSize() const { return PointerSize; }
/// Get the callee-saved register stack slot
/// size in bytes.
unsigned getCalleeSaveStackSlotSize() const {
return CalleeSaveStackSlotSize;
}
/// True if the target is little endian.
bool isLittleEndian() const { return IsLittleEndian; }
/// True if target stack grow up.
bool isStackGrowthDirectionUp() const { return StackGrowsUp; }
bool hasSubsectionsViaSymbols() const { return HasSubsectionsViaSymbols; }
// Data directive accessors.
const char *getData8bitsDirective() const { return Data8bitsDirective; }
const char *getData16bitsDirective() const { return Data16bitsDirective; }
const char *getData32bitsDirective() const { return Data32bitsDirective; }
const char *getData64bitsDirective() const { return Data64bitsDirective; }
const char *getGPRel64Directive() const { return GPRel64Directive; }
const char *getGPRel32Directive() const { return GPRel32Directive; }
/// Targets can implement this method to specify a section to switch to if the
/// translation unit doesn't have any trampolines that require an executable
/// stack.
virtual MCSection *getNonexecutableStackSection(MCContext &Ctx) const {
return nullptr;
}
/// \brief True if the section is atomized using the symbols in it.
/// This is false if the section is not atomized at all (most ELF sections) or
/// if it is atomized based on its contents (MachO' __TEXT,__cstring for
/// example).
virtual bool isSectionAtomizableBySymbols(const MCSection &Section) const;
virtual const MCExpr *getExprForPersonalitySymbol(const MCSymbol *Sym,
unsigned Encoding,
MCStreamer &Streamer) const;
virtual const MCExpr *getExprForFDESymbol(const MCSymbol *Sym,
unsigned Encoding,
MCStreamer &Streamer) const;
/// Return true if the identifier \p Name does not need quotes to be
/// syntactically correct.
virtual bool isValidUnquotedName(StringRef Name) const;
bool usesSunStyleELFSectionSwitchSyntax() const {
return SunStyleELFSectionSwitchSyntax;
}
bool usesELFSectionDirectiveForBSS() const {
return UsesELFSectionDirectiveForBSS;
}
bool needsDwarfSectionOffsetDirective() const {
return NeedsDwarfSectionOffsetDirective;
}
// Accessors.
bool hasMachoZeroFillDirective() const { return HasMachoZeroFillDirective; }
bool hasMachoTBSSDirective() const { return HasMachoTBSSDirective; }
bool hasStaticCtorDtorReferenceInStaticMode() const {
return HasStaticCtorDtorReferenceInStaticMode;
}
unsigned getMaxInstLength() const { return MaxInstLength; }
unsigned getMinInstAlignment() const { return MinInstAlignment; }
bool getDollarIsPC() const { return DollarIsPC; }
const char *getSeparatorString() const { return SeparatorString; }
/// This indicates the column (zero-based) at which asm comments should be
/// printed.
unsigned getCommentColumn() const { return 40; }
const char *getCommentString() const { return CommentString; }
const char *getLabelSuffix() const { return LabelSuffix; }
bool useAssignmentForEHBegin() const { return UseAssignmentForEHBegin; }
bool needsLocalForSize() const { return NeedsLocalForSize; }
const char *getPrivateGlobalPrefix() const { return PrivateGlobalPrefix; }
const char *getPrivateLabelPrefix() const { return PrivateLabelPrefix; }
bool hasLinkerPrivateGlobalPrefix() const {
return LinkerPrivateGlobalPrefix[0] != '\0';
}
const char *getLinkerPrivateGlobalPrefix() const {
if (hasLinkerPrivateGlobalPrefix())
return LinkerPrivateGlobalPrefix;
return getPrivateGlobalPrefix();
}
const char *getInlineAsmStart() const { return InlineAsmStart; }
const char *getInlineAsmEnd() const { return InlineAsmEnd; }
const char *getCode16Directive() const { return Code16Directive; }
const char *getCode32Directive() const { return Code32Directive; }
const char *getCode64Directive() const { return Code64Directive; }
unsigned getAssemblerDialect() const { return AssemblerDialect; }
bool doesAllowAtInName() const { return AllowAtInName; }
bool supportsNameQuoting() const { return SupportsQuotedNames; }
bool doesSupportDataRegionDirectives() const {
return UseDataRegionDirectives;
}
const char *getZeroDirective() const { return ZeroDirective; }
const char *getAsciiDirective() const { return AsciiDirective; }
const char *getAscizDirective() const { return AscizDirective; }
bool getAlignmentIsInBytes() const { return AlignmentIsInBytes; }
unsigned getTextAlignFillValue() const { return TextAlignFillValue; }
const char *getGlobalDirective() const { return GlobalDirective; }
bool doesSetDirectiveSuppressesReloc() const {
return SetDirectiveSuppressesReloc;
}
bool hasAggressiveSymbolFolding() const { return HasAggressiveSymbolFolding; }
bool getCOMMDirectiveAlignmentIsInBytes() const {
return COMMDirectiveAlignmentIsInBytes;
}
LCOMM::LCOMMType getLCOMMDirectiveAlignmentType() const {
return LCOMMDirectiveAlignmentType;
}
bool hasFunctionAlignment() const { return HasFunctionAlignment; }
bool hasDotTypeDotSizeDirective() const { return HasDotTypeDotSizeDirective; }
bool hasSingleParameterDotFile() const { return HasSingleParameterDotFile; }
bool hasIdentDirective() const { return HasIdentDirective; }
bool hasNoDeadStrip() const { return HasNoDeadStrip; }
const char *getWeakDirective() const { return WeakDirective; }
const char *getWeakRefDirective() const { return WeakRefDirective; }
bool hasWeakDefDirective() const { return HasWeakDefDirective; }
bool hasWeakDefCanBeHiddenDirective() const {
return HasWeakDefCanBeHiddenDirective;
}
bool hasLinkOnceDirective() const { return HasLinkOnceDirective; }
MCSymbolAttr getHiddenVisibilityAttr() const { return HiddenVisibilityAttr; }
MCSymbolAttr getHiddenDeclarationVisibilityAttr() const {
return HiddenDeclarationVisibilityAttr;
}
MCSymbolAttr getProtectedVisibilityAttr() const {
return ProtectedVisibilityAttr;
}
bool doesSupportDebugInformation() const { return SupportsDebugInformation; }
bool doesSupportExceptionHandling() const {
return ExceptionsType != ExceptionHandling::None;
}
ExceptionHandling getExceptionHandlingType() const { return ExceptionsType; }
WinEH::EncodingType getWinEHEncodingType() const { return WinEHEncodingType; }
/// Returns true if the exception handling method for the platform uses call
/// frame information to unwind.
bool usesCFIForEH() const {
return (ExceptionsType == ExceptionHandling::DwarfCFI ||
ExceptionsType == ExceptionHandling::ARM || usesWindowsCFI());
}
bool usesWindowsCFI() const {
return ExceptionsType == ExceptionHandling::WinEH &&
(WinEHEncodingType != WinEH::EncodingType::Invalid &&
WinEHEncodingType != WinEH::EncodingType::X86);
}
bool doesDwarfUseRelocationsAcrossSections() const {
return DwarfUsesRelocationsAcrossSections;
}
bool doDwarfFDESymbolsUseAbsDiff() const { return DwarfFDESymbolsUseAbsDiff; }
bool useDwarfRegNumForCFI() const { return DwarfRegNumForCFI; }
bool useParensForSymbolVariant() const { return UseParensForSymbolVariant; }
void addInitialFrameState(const MCCFIInstruction &Inst) {
InitialFrameState.push_back(Inst);
}
const std::vector<MCCFIInstruction> &getInitialFrameState() const {
return InitialFrameState;
}
/// Return true if assembly (inline or otherwise) should be parsed.
bool useIntegratedAssembler() const { return UseIntegratedAssembler; }
/// Set whether assembly (inline or otherwise) should be parsed.
virtual void setUseIntegratedAssembler(bool Value) {
UseIntegratedAssembler = Value;
}
bool compressDebugSections() const { return CompressDebugSections; }
void setCompressDebugSections(bool CompressDebugSections) {
this->CompressDebugSections = CompressDebugSections;
}
bool shouldUseLogicalShr() const { return UseLogicalShr; }
};
}
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCFixedLenDisassembler.h | //===-- llvm/MC/MCFixedLenDisassembler.h - Decoder driver -------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Fixed length disassembler decoder state machine driver.
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCFIXEDLENDISASSEMBLER_H
#define LLVM_MC_MCFIXEDLENDISASSEMBLER_H
namespace llvm {
namespace MCD {
// Disassembler state machine opcodes.
enum DecoderOps {
OPC_ExtractField = 1, // OPC_ExtractField(uint8_t Start, uint8_t Len)
OPC_FilterValue, // OPC_FilterValue(uleb128 Val, uint16_t NumToSkip)
OPC_CheckField, // OPC_CheckField(uint8_t Start, uint8_t Len,
// uleb128 Val, uint16_t NumToSkip)
OPC_CheckPredicate, // OPC_CheckPredicate(uleb128 PIdx, uint16_t NumToSkip)
OPC_Decode, // OPC_Decode(uleb128 Opcode, uleb128 DIdx)
OPC_SoftFail, // OPC_SoftFail(uleb128 PMask, uleb128 NMask)
OPC_Fail // OPC_Fail()
};
} // namespace MCDecode
} // namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/SectionKind.h | //===-- llvm/Target/TargetLoweringObjectFile.h - Object Info ----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements classes used to handle lowerings specific to common
// object file formats.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_SECTIONKIND_H
#define LLVM_MC_SECTIONKIND_H
namespace llvm {
/// SectionKind - This is a simple POD value that classifies the properties of
/// a section. A section is classified into the deepest possible
/// classification, and then the target maps them onto their sections based on
/// what capabilities they have.
///
/// The comments below describe these as if they were an inheritance hierarchy
/// in order to explain the predicates below.
///
class SectionKind {
enum Kind {
/// Metadata - Debug info sections or other metadata.
Metadata,
/// Text - Text section, used for functions and other executable code.
Text,
/// ReadOnly - Data that is never written to at program runtime by the
/// program or the dynamic linker. Things in the top-level readonly
/// SectionKind are not mergeable.
ReadOnly,
/// MergableCString - Any null-terminated string which allows merging.
/// These values are known to end in a nul value of the specified size,
/// not otherwise contain a nul value, and be mergable. This allows the
/// linker to unique the strings if it so desires.
/// Mergeable1ByteCString - 1 byte mergable, null terminated, string.
Mergeable1ByteCString,
/// Mergeable2ByteCString - 2 byte mergable, null terminated, string.
Mergeable2ByteCString,
/// Mergeable4ByteCString - 4 byte mergable, null terminated, string.
Mergeable4ByteCString,
/// MergeableConst - These are sections for merging fixed-length
/// constants together. For example, this can be used to unique
/// constant pool entries etc.
/// MergeableConst4 - This is a section used by 4-byte constants,
/// for example, floats.
MergeableConst4,
/// MergeableConst8 - This is a section used by 8-byte constants,
/// for example, doubles.
MergeableConst8,
/// MergeableConst16 - This is a section used by 16-byte constants,
/// for example, vectors.
MergeableConst16,
/// Writeable - This is the base of all segments that need to be written
/// to during program runtime.
/// ThreadLocal - This is the base of all TLS segments. All TLS
/// objects must be writeable, otherwise there is no reason for them to
/// be thread local!
/// ThreadBSS - Zero-initialized TLS data objects.
ThreadBSS,
/// ThreadData - Initialized TLS data objects.
ThreadData,
/// GlobalWriteableData - Writeable data that is global (not thread
/// local).
/// BSS - Zero initialized writeable data.
BSS,
/// BSSLocal - This is BSS (zero initialized and writable) data
/// which has local linkage.
BSSLocal,
/// BSSExtern - This is BSS data with normal external linkage.
BSSExtern,
/// Common - Data with common linkage. These represent tentative
/// definitions, which always have a zero initializer and are never
/// marked 'constant'.
Common,
/// DataRel - This is the most general form of data that is written
/// to by the program, it can have random relocations to arbitrary
/// globals.
DataRel,
/// DataRelLocal - This is writeable data that has a non-zero
/// initializer and has relocations in it, but all of the
/// relocations are known to be within the final linked image
/// the global is linked into.
DataRelLocal,
/// DataNoRel - This is writeable data that has a non-zero
/// initializer, but whose initializer is known to have no
/// relocations.
DataNoRel,
/// ReadOnlyWithRel - These are global variables that are never
/// written to by the program, but that have relocations, so they
/// must be stuck in a writeable section so that the dynamic linker
/// can write to them. If it chooses to, the dynamic linker can
/// mark the pages these globals end up on as read-only after it is
/// done with its relocation phase.
ReadOnlyWithRel,
/// ReadOnlyWithRelLocal - This is data that is readonly by the
/// program, but must be writeable so that the dynamic linker
/// can perform relocations in it. This is used when we know
/// that all the relocations are to globals in this final
/// linked image.
ReadOnlyWithRelLocal
} K : 8;
public:
bool isMetadata() const { return K == Metadata; }
bool isText() const { return K == Text; }
bool isReadOnly() const {
return K == ReadOnly || isMergeableCString() ||
isMergeableConst();
}
bool isMergeableCString() const {
return K == Mergeable1ByteCString || K == Mergeable2ByteCString ||
K == Mergeable4ByteCString;
}
bool isMergeable1ByteCString() const { return K == Mergeable1ByteCString; }
bool isMergeable2ByteCString() const { return K == Mergeable2ByteCString; }
bool isMergeable4ByteCString() const { return K == Mergeable4ByteCString; }
bool isMergeableConst() const {
return K == MergeableConst4 || K == MergeableConst8 ||
K == MergeableConst16;
}
bool isMergeableConst4() const { return K == MergeableConst4; }
bool isMergeableConst8() const { return K == MergeableConst8; }
bool isMergeableConst16() const { return K == MergeableConst16; }
bool isWriteable() const {
return isThreadLocal() || isGlobalWriteableData();
}
bool isThreadLocal() const {
return K == ThreadData || K == ThreadBSS;
}
bool isThreadBSS() const { return K == ThreadBSS; }
bool isThreadData() const { return K == ThreadData; }
bool isGlobalWriteableData() const {
return isBSS() || isCommon() || isDataRel() || isReadOnlyWithRel();
}
bool isBSS() const { return K == BSS || K == BSSLocal || K == BSSExtern; }
bool isBSSLocal() const { return K == BSSLocal; }
bool isBSSExtern() const { return K == BSSExtern; }
bool isCommon() const { return K == Common; }
bool isDataRel() const {
return K == DataRel || K == DataRelLocal || K == DataNoRel;
}
bool isDataRelLocal() const {
return K == DataRelLocal || K == DataNoRel;
}
bool isDataNoRel() const { return K == DataNoRel; }
bool isReadOnlyWithRel() const {
return K == ReadOnlyWithRel || K == ReadOnlyWithRelLocal;
}
bool isReadOnlyWithRelLocal() const {
return K == ReadOnlyWithRelLocal;
}
private:
static SectionKind get(Kind K) {
SectionKind Res;
Res.K = K;
return Res;
}
public:
static SectionKind getMetadata() { return get(Metadata); }
static SectionKind getText() { return get(Text); }
static SectionKind getReadOnly() { return get(ReadOnly); }
static SectionKind getMergeable1ByteCString() {
return get(Mergeable1ByteCString);
}
static SectionKind getMergeable2ByteCString() {
return get(Mergeable2ByteCString);
}
static SectionKind getMergeable4ByteCString() {
return get(Mergeable4ByteCString);
}
static SectionKind getMergeableConst4() { return get(MergeableConst4); }
static SectionKind getMergeableConst8() { return get(MergeableConst8); }
static SectionKind getMergeableConst16() { return get(MergeableConst16); }
static SectionKind getThreadBSS() { return get(ThreadBSS); }
static SectionKind getThreadData() { return get(ThreadData); }
static SectionKind getBSS() { return get(BSS); }
static SectionKind getBSSLocal() { return get(BSSLocal); }
static SectionKind getBSSExtern() { return get(BSSExtern); }
static SectionKind getCommon() { return get(Common); }
static SectionKind getDataRel() { return get(DataRel); }
static SectionKind getDataRelLocal() { return get(DataRelLocal); }
static SectionKind getDataNoRel() { return get(DataNoRel); }
static SectionKind getReadOnlyWithRel() { return get(ReadOnlyWithRel); }
static SectionKind getReadOnlyWithRelLocal(){
return get(ReadOnlyWithRelLocal);
}
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCInstPrinter.h | //===- MCInstPrinter.h - MCInst to target assembly syntax -------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCINSTPRINTER_H
#define LLVM_MC_MCINSTPRINTER_H
#include "llvm/ADT/ArrayRef.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/Format.h"
namespace llvm {
class MCInst;
class raw_ostream;
class MCAsmInfo;
class MCInstrInfo;
class MCRegisterInfo;
class MCSubtargetInfo;
class StringRef;
/// Convert `Bytes' to a hex string and output to `OS'
void dumpBytes(ArrayRef<uint8_t> Bytes, raw_ostream &OS);
namespace HexStyle {
enum Style {
C, ///< 0xff
Asm ///< 0ffh
};
}
/// \brief This is an instance of a target assembly language printer that
/// converts an MCInst to valid target assembly syntax.
class MCInstPrinter {
protected:
/// \brief A stream that comments can be emitted to if desired. Each comment
/// must end with a newline. This will be null if verbose assembly emission
/// is disable.
raw_ostream *CommentStream;
const MCAsmInfo &MAI;
const MCInstrInfo &MII;
const MCRegisterInfo &MRI;
/// True if we are printing marked up assembly.
bool UseMarkup;
/// True if we are printing immediates as hex.
bool PrintImmHex;
/// Which style to use for printing hexadecimal values.
HexStyle::Style PrintHexStyle;
/// Utility function for printing annotations.
void printAnnotation(raw_ostream &OS, StringRef Annot);
public:
MCInstPrinter(const MCAsmInfo &mai, const MCInstrInfo &mii,
const MCRegisterInfo &mri)
: CommentStream(nullptr), MAI(mai), MII(mii), MRI(mri), UseMarkup(0),
PrintImmHex(0), PrintHexStyle(HexStyle::C) {}
virtual ~MCInstPrinter();
/// \brief Specify a stream to emit comments to.
void setCommentStream(raw_ostream &OS) { CommentStream = &OS; }
/// \brief Print the specified MCInst to the specified raw_ostream.
virtual void printInst(const MCInst *MI, raw_ostream &OS, StringRef Annot,
const MCSubtargetInfo &STI) = 0;
/// \brief Return the name of the specified opcode enum (e.g. "MOV32ri") or
/// empty if we can't resolve it.
StringRef getOpcodeName(unsigned Opcode) const;
/// \brief Print the assembler register name.
virtual void printRegName(raw_ostream &OS, unsigned RegNo) const;
bool getUseMarkup() const { return UseMarkup; }
void setUseMarkup(bool Value) { UseMarkup = Value; }
/// Utility functions to make adding mark ups simpler.
StringRef markup(StringRef s) const;
StringRef markup(StringRef a, StringRef b) const;
bool getPrintImmHex() const { return PrintImmHex; }
void setPrintImmHex(bool Value) { PrintImmHex = Value; }
HexStyle::Style getPrintHexStyle() const { return PrintHexStyle; }
void setPrintHexStyle(HexStyle::Style Value) { PrintHexStyle = Value; }
/// Utility function to print immediates in decimal or hex.
format_object<int64_t> formatImm(int64_t Value) const {
return PrintImmHex ? formatHex(Value) : formatDec(Value);
}
/// Utility functions to print decimal/hexadecimal values.
format_object<int64_t> formatDec(int64_t Value) const;
format_object<int64_t> formatHex(int64_t Value) const;
format_object<uint64_t> formatHex(uint64_t Value) const;
};
} // namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCMachObjectWriter.h | //===-- llvm/MC/MCMachObjectWriter.h - Mach Object Writer -------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCMACHOBJECTWRITER_H
#define LLVM_MC_MCMACHOBJECTWRITER_H
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCObjectWriter.h"
#include "llvm/MC/StringTableBuilder.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/MachO.h"
#include <vector>
namespace llvm {
class MachObjectWriter;
class MCMachObjectTargetWriter {
const unsigned Is64Bit : 1;
const uint32_t CPUType;
const uint32_t CPUSubtype;
unsigned LocalDifference_RIT;
protected:
MCMachObjectTargetWriter(bool Is64Bit_, uint32_t CPUType_,
uint32_t CPUSubtype_);
void setLocalDifferenceRelocationType(unsigned Type) {
LocalDifference_RIT = Type;
}
public:
virtual ~MCMachObjectTargetWriter();
/// \name Lifetime Management
/// @{
virtual void reset() {}
/// @}
/// \name Accessors
/// @{
bool is64Bit() const { return Is64Bit; }
uint32_t getCPUType() const { return CPUType; }
uint32_t getCPUSubtype() const { return CPUSubtype; }
unsigned getLocalDifferenceRelocationType() const {
return LocalDifference_RIT;
}
/// @}
/// \name API
/// @{
virtual void recordRelocation(MachObjectWriter *Writer, MCAssembler &Asm,
const MCAsmLayout &Layout,
const MCFragment *Fragment,
const MCFixup &Fixup, MCValue Target,
uint64_t &FixedValue) = 0;
/// @}
};
class MachObjectWriter : public MCObjectWriter {
/// Helper struct for containing some precomputed information on symbols.
struct MachSymbolData {
const MCSymbol *Symbol;
uint64_t StringIndex;
uint8_t SectionIndex;
// Support lexicographic sorting.
bool operator<(const MachSymbolData &RHS) const;
};
/// The target specific Mach-O writer instance.
std::unique_ptr<MCMachObjectTargetWriter> TargetObjectWriter;
/// \name Relocation Data
/// @{
struct RelAndSymbol {
const MCSymbol *Sym;
MachO::any_relocation_info MRE;
RelAndSymbol(const MCSymbol *Sym, const MachO::any_relocation_info &MRE)
: Sym(Sym), MRE(MRE) {}
};
llvm::DenseMap<const MCSection *, std::vector<RelAndSymbol>> Relocations;
llvm::DenseMap<const MCSection *, unsigned> IndirectSymBase;
SectionAddrMap SectionAddress;
/// @}
/// \name Symbol Table Data
/// @{
StringTableBuilder StringTable;
std::vector<MachSymbolData> LocalSymbolData;
std::vector<MachSymbolData> ExternalSymbolData;
std::vector<MachSymbolData> UndefinedSymbolData;
/// @}
MachSymbolData *findSymbolData(const MCSymbol &Sym);
public:
MachObjectWriter(MCMachObjectTargetWriter *MOTW, raw_pwrite_stream &OS,
bool IsLittleEndian)
: MCObjectWriter(OS, IsLittleEndian), TargetObjectWriter(MOTW) {}
const MCSymbol &findAliasedSymbol(const MCSymbol &Sym) const;
/// \name Lifetime management Methods
/// @{
void reset() override;
/// @}
/// \name Utility Methods
/// @{
bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
SectionAddrMap &getSectionAddressMap() { return SectionAddress; }
uint64_t getSectionAddress(const MCSection *Sec) const {
return SectionAddress.lookup(Sec);
}
uint64_t getSymbolAddress(const MCSymbol &S, const MCAsmLayout &Layout) const;
uint64_t getFragmentAddress(const MCFragment *Fragment,
const MCAsmLayout &Layout) const;
uint64_t getPaddingSize(const MCSection *SD, const MCAsmLayout &Layout) const;
bool doesSymbolRequireExternRelocation(const MCSymbol &S);
/// @}
/// \name Target Writer Proxy Accessors
/// @{
bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
bool isX86_64() const {
uint32_t CPUType = TargetObjectWriter->getCPUType();
return CPUType == MachO::CPU_TYPE_X86_64;
}
/// @}
void writeHeader(unsigned NumLoadCommands, unsigned LoadCommandsSize,
bool SubsectionsViaSymbols);
/// Write a segment load command.
///
/// \param NumSections The number of sections in this segment.
/// \param SectionDataSize The total size of the sections.
void writeSegmentLoadCommand(unsigned NumSections, uint64_t VMSize,
uint64_t SectionDataStartOffset,
uint64_t SectionDataSize);
void writeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
const MCSection &Sec, uint64_t FileOffset,
uint64_t RelocationsStart, unsigned NumRelocations);
void writeSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
uint32_t StringTableOffset,
uint32_t StringTableSize);
void writeDysymtabLoadCommand(
uint32_t FirstLocalSymbol, uint32_t NumLocalSymbols,
uint32_t FirstExternalSymbol, uint32_t NumExternalSymbols,
uint32_t FirstUndefinedSymbol, uint32_t NumUndefinedSymbols,
uint32_t IndirectSymbolOffset, uint32_t NumIndirectSymbols);
void writeNlist(MachSymbolData &MSD, const MCAsmLayout &Layout);
void writeLinkeditLoadCommand(uint32_t Type, uint32_t DataOffset,
uint32_t DataSize);
void writeLinkerOptionsLoadCommand(const std::vector<std::string> &Options);
// FIXME: We really need to improve the relocation validation. Basically, we
// want to implement a separate computation which evaluates the relocation
// entry as the linker would, and verifies that the resultant fixup value is
// exactly what the encoder wanted. This will catch several classes of
// problems:
//
// - Relocation entry bugs, the two algorithms are unlikely to have the same
// exact bug.
//
// - Relaxation issues, where we forget to relax something.
//
// - Input errors, where something cannot be correctly encoded. 'as' allows
// these through in many cases.
// Add a relocation to be output in the object file. At the time this is
// called, the symbol indexes are not know, so if the relocation refers
// to a symbol it should be passed as \p RelSymbol so that it can be updated
// afterwards. If the relocation doesn't refer to a symbol, nullptr should be
// used.
void addRelocation(const MCSymbol *RelSymbol, const MCSection *Sec,
MachO::any_relocation_info &MRE) {
RelAndSymbol P(RelSymbol, MRE);
Relocations[Sec].push_back(P);
}
void recordScatteredRelocation(const MCAssembler &Asm,
const MCAsmLayout &Layout,
const MCFragment *Fragment,
const MCFixup &Fixup, MCValue Target,
unsigned Log2Size, uint64_t &FixedValue);
void recordTLVPRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
const MCFragment *Fragment, const MCFixup &Fixup,
MCValue Target, uint64_t &FixedValue);
void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
const MCFragment *Fragment, const MCFixup &Fixup,
MCValue Target, bool &IsPCRel,
uint64_t &FixedValue) override;
void bindIndirectSymbols(MCAssembler &Asm);
/// Compute the symbol table data.
void computeSymbolTable(MCAssembler &Asm,
std::vector<MachSymbolData> &LocalSymbolData,
std::vector<MachSymbolData> &ExternalSymbolData,
std::vector<MachSymbolData> &UndefinedSymbolData);
void computeSectionAddresses(const MCAssembler &Asm,
const MCAsmLayout &Layout);
void executePostLayoutBinding(MCAssembler &Asm,
const MCAsmLayout &Layout) override;
bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
const MCSymbol &SymA,
const MCFragment &FB, bool InSet,
bool IsPCRel) const override;
void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
};
/// Construct a new Mach-O writer instance.
///
/// This routine takes ownership of the target writer subclass.
///
/// \param MOTW - The target specific Mach-O writer subclass.
/// \param OS - The stream to write to.
/// \returns The constructed object writer.
MCObjectWriter *createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
raw_pwrite_stream &OS,
bool IsLittleEndian);
} // End llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/ConstantPools.h | //===- ConstantPool.h - Keep track of assembler-generated ------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file declares the ConstantPool and AssemblerConstantPools classes.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_CONSTANTPOOLS_H
#define LLVM_MC_CONSTANTPOOLS_H
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/SmallVector.h"
namespace llvm {
class MCContext;
class MCExpr;
class MCSection;
class MCStreamer;
class MCSymbol;
struct ConstantPoolEntry {
ConstantPoolEntry(MCSymbol *L, const MCExpr *Val, unsigned Sz)
: Label(L), Value(Val), Size(Sz) {}
MCSymbol *Label;
const MCExpr *Value;
unsigned Size;
};
// A class to keep track of assembler-generated constant pools that are use to
// implement the ldr-pseudo.
class ConstantPool {
typedef SmallVector<ConstantPoolEntry, 4> EntryVecTy;
EntryVecTy Entries;
public:
// Initialize a new empty constant pool
ConstantPool() {}
// Add a new entry to the constant pool in the next slot.
// \param Value is the new entry to put in the constant pool.
// \param Size is the size in bytes of the entry
//
// \returns a MCExpr that references the newly inserted value
const MCExpr *addEntry(const MCExpr *Value, MCContext &Context,
unsigned Size);
// Emit the contents of the constant pool using the provided streamer.
void emitEntries(MCStreamer &Streamer);
// Return true if the constant pool is empty
bool empty();
};
class AssemblerConstantPools {
// Map type used to keep track of per-Section constant pools used by the
// ldr-pseudo opcode. The map associates a section to its constant pool. The
// constant pool is a vector of (label, value) pairs. When the ldr
// pseudo is parsed we insert a new (label, value) pair into the constant pool
// for the current section and add MCSymbolRefExpr to the new label as
// an opcode to the ldr. After we have parsed all the user input we
// output the (label, value) pairs in each constant pool at the end of the
// section.
//
// We use the MapVector for the map type to ensure stable iteration of
// the sections at the end of the parse. We need to iterate over the
// sections in a stable order to ensure that we have print the
// constant pools in a deterministic order when printing an assembly
// file.
typedef MapVector<MCSection *, ConstantPool> ConstantPoolMapTy;
ConstantPoolMapTy ConstantPools;
public:
void emitAll(MCStreamer &Streamer);
void emitForCurrentSection(MCStreamer &Streamer);
const MCExpr *addEntry(MCStreamer &Streamer, const MCExpr *Expr,
unsigned Size);
private:
ConstantPool *getConstantPool(MCSection *Section);
ConstantPool &getOrCreateConstantPool(MCSection *Section);
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCAsmBackend.h | //===-- llvm/MC/MCAsmBackend.h - MC Asm Backend -----------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCASMBACKEND_H
#define LLVM_MC_MCASMBACKEND_H
#include "llvm/ADT/ArrayRef.h"
#include "llvm/MC/MCDirectives.h"
#include "llvm/MC/MCDwarf.h"
#include "llvm/MC/MCFixup.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/ErrorHandling.h"
namespace llvm {
class MCAsmLayout;
class MCAssembler;
class MCELFObjectTargetWriter;
struct MCFixupKindInfo;
class MCFragment;
class MCInst;
class MCRelaxableFragment;
class MCObjectWriter;
class MCSection;
class MCValue;
class raw_ostream;
/// Generic interface to target specific assembler backends.
class MCAsmBackend {
MCAsmBackend(const MCAsmBackend &) = delete;
void operator=(const MCAsmBackend &) = delete;
protected: // Can only create subclasses.
MCAsmBackend();
unsigned HasDataInCodeSupport : 1;
public:
virtual ~MCAsmBackend();
/// lifetime management
virtual void reset() {}
/// Create a new MCObjectWriter instance for use by the assembler backend to
/// emit the final object file.
virtual MCObjectWriter *createObjectWriter(raw_pwrite_stream &OS) const = 0;
/// Create a new ELFObjectTargetWriter to enable non-standard
/// ELFObjectWriters.
virtual MCELFObjectTargetWriter *createELFObjectTargetWriter() const {
llvm_unreachable("createELFObjectTargetWriter is not supported by asm "
"backend");
}
/// Check whether this target implements data-in-code markers. If not, data
/// region directives will be ignored.
bool hasDataInCodeSupport() const { return HasDataInCodeSupport; }
/// \name Target Fixup Interfaces
/// @{
/// Get the number of target specific fixup kinds.
virtual unsigned getNumFixupKinds() const = 0;
/// Get information on a fixup kind.
virtual const MCFixupKindInfo &getFixupKindInfo(MCFixupKind Kind) const;
/// Target hook to adjust the literal value of a fixup if necessary.
/// IsResolved signals whether the caller believes a relocation is needed; the
/// target can modify the value. The default does nothing.
virtual void processFixupValue(const MCAssembler &Asm,
const MCAsmLayout &Layout,
const MCFixup &Fixup, const MCFragment *DF,
const MCValue &Target, uint64_t &Value,
bool &IsResolved) {}
/// Apply the \p Value for given \p Fixup into the provided data fragment, at
/// the offset specified by the fixup and following the fixup kind as
/// appropriate.
virtual void applyFixup(const MCFixup &Fixup, char *Data, unsigned DataSize,
uint64_t Value, bool IsPCRel) const = 0;
/// @}
/// \name Target Relaxation Interfaces
/// @{
/// Check whether the given instruction may need relaxation.
///
/// \param Inst - The instruction to test.
virtual bool mayNeedRelaxation(const MCInst &Inst) const = 0;
/// Target specific predicate for whether a given fixup requires the
/// associated instruction to be relaxed.
virtual bool fixupNeedsRelaxationAdvanced(const MCFixup &Fixup, bool Resolved,
uint64_t Value,
const MCRelaxableFragment *DF,
const MCAsmLayout &Layout) const;
/// Simple predicate for targets where !Resolved implies requiring relaxation
virtual bool fixupNeedsRelaxation(const MCFixup &Fixup, uint64_t Value,
const MCRelaxableFragment *DF,
const MCAsmLayout &Layout) const = 0;
/// Relax the instruction in the given fragment to the next wider instruction.
///
/// \param Inst The instruction to relax, which may be the same as the
/// output.
/// \param [out] Res On return, the relaxed instruction.
virtual void relaxInstruction(const MCInst &Inst, MCInst &Res) const = 0;
/// @}
/// Returns the minimum size of a nop in bytes on this target. The assembler
/// will use this to emit excess padding in situations where the padding
/// required for simple alignment would be less than the minimum nop size.
///
virtual unsigned getMinimumNopSize() const { return 1; }
/// Write an (optimal) nop sequence of Count bytes to the given output. If the
/// target cannot generate such a sequence, it should return an error.
///
/// \return - True on success.
virtual bool writeNopData(uint64_t Count, MCObjectWriter *OW) const = 0;
/// Handle any target-specific assembler flags. By default, do nothing.
virtual void handleAssemblerFlag(MCAssemblerFlag Flag) {}
/// \brief Generate the compact unwind encoding for the CFI instructions.
virtual uint32_t
generateCompactUnwindEncoding(ArrayRef<MCCFIInstruction>) const {
return 0;
}
};
} // End llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCSchedule.h | //===-- llvm/MC/MCSchedule.h - Scheduling -----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the classes used to describe a subtarget's machine model
// for scheduling and other instruction cost heuristics.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCSCHEDULE_H
#define LLVM_MC_MCSCHEDULE_H
#include "llvm/Support/DataTypes.h"
#include <cassert>
namespace llvm {
struct InstrItinerary;
/// Define a kind of processor resource that will be modeled by the scheduler.
struct MCProcResourceDesc {
#ifndef NDEBUG
const char *Name;
#endif
unsigned NumUnits; // Number of resource of this kind
unsigned SuperIdx; // Index of the resources kind that contains this kind.
// Number of resources that may be buffered.
//
// Buffered resources (BufferSize != 0) may be consumed at some indeterminate
// cycle after dispatch. This should be used for out-of-order cpus when
// instructions that use this resource can be buffered in a reservaton
// station.
//
// Unbuffered resources (BufferSize == 0) always consume their resource some
// fixed number of cycles after dispatch. If a resource is unbuffered, then
// the scheduler will avoid scheduling instructions with conflicting resources
// in the same cycle. This is for in-order cpus, or the in-order portion of
// an out-of-order cpus.
int BufferSize;
bool operator==(const MCProcResourceDesc &Other) const {
return NumUnits == Other.NumUnits && SuperIdx == Other.SuperIdx
&& BufferSize == Other.BufferSize;
}
};
/// Identify one of the processor resource kinds consumed by a particular
/// scheduling class for the specified number of cycles.
struct MCWriteProcResEntry {
unsigned ProcResourceIdx;
unsigned Cycles;
bool operator==(const MCWriteProcResEntry &Other) const {
return ProcResourceIdx == Other.ProcResourceIdx && Cycles == Other.Cycles;
}
};
/// Specify the latency in cpu cycles for a particular scheduling class and def
/// index. -1 indicates an invalid latency. Heuristics would typically consider
/// an instruction with invalid latency to have infinite latency. Also identify
/// the WriteResources of this def. When the operand expands to a sequence of
/// writes, this ID is the last write in the sequence.
struct MCWriteLatencyEntry {
int Cycles;
unsigned WriteResourceID;
bool operator==(const MCWriteLatencyEntry &Other) const {
return Cycles == Other.Cycles && WriteResourceID == Other.WriteResourceID;
}
};
/// Specify the number of cycles allowed after instruction issue before a
/// particular use operand reads its registers. This effectively reduces the
/// write's latency. Here we allow negative cycles for corner cases where
/// latency increases. This rule only applies when the entry's WriteResource
/// matches the write's WriteResource.
///
/// MCReadAdvanceEntries are sorted first by operand index (UseIdx), then by
/// WriteResourceIdx.
struct MCReadAdvanceEntry {
unsigned UseIdx;
unsigned WriteResourceID;
int Cycles;
bool operator==(const MCReadAdvanceEntry &Other) const {
return UseIdx == Other.UseIdx && WriteResourceID == Other.WriteResourceID
&& Cycles == Other.Cycles;
}
};
/// Summarize the scheduling resources required for an instruction of a
/// particular scheduling class.
///
/// Defined as an aggregate struct for creating tables with initializer lists.
struct MCSchedClassDesc {
static const unsigned short InvalidNumMicroOps = UINT16_MAX;
static const unsigned short VariantNumMicroOps = UINT16_MAX - 1;
#ifndef NDEBUG
const char* Name;
#endif
unsigned short NumMicroOps;
bool BeginGroup;
bool EndGroup;
unsigned WriteProcResIdx; // First index into WriteProcResTable.
unsigned NumWriteProcResEntries;
unsigned WriteLatencyIdx; // First index into WriteLatencyTable.
unsigned NumWriteLatencyEntries;
unsigned ReadAdvanceIdx; // First index into ReadAdvanceTable.
unsigned NumReadAdvanceEntries;
bool isValid() const {
return NumMicroOps != InvalidNumMicroOps;
}
bool isVariant() const {
return NumMicroOps == VariantNumMicroOps;
}
};
/// Machine model for scheduling, bundling, and heuristics.
///
/// The machine model directly provides basic information about the
/// microarchitecture to the scheduler in the form of properties. It also
/// optionally refers to scheduler resource tables and itinerary
/// tables. Scheduler resource tables model the latency and cost for each
/// instruction type. Itinerary tables are an independent mechanism that
/// provides a detailed reservation table describing each cycle of instruction
/// execution. Subtargets may define any or all of the above categories of data
/// depending on the type of CPU and selected scheduler.
struct MCSchedModel {
// IssueWidth is the maximum number of instructions that may be scheduled in
// the same per-cycle group.
unsigned IssueWidth;
static const unsigned DefaultIssueWidth = 1;
// MicroOpBufferSize is the number of micro-ops that the processor may buffer
// for out-of-order execution.
//
// "0" means operations that are not ready in this cycle are not considered
// for scheduling (they go in the pending queue). Latency is paramount. This
// may be more efficient if many instructions are pending in a schedule.
//
// "1" means all instructions are considered for scheduling regardless of
// whether they are ready in this cycle. Latency still causes issue stalls,
// but we balance those stalls against other heuristics.
//
// "> 1" means the processor is out-of-order. This is a machine independent
// estimate of highly machine specific characteristics such as the register
// renaming pool and reorder buffer.
unsigned MicroOpBufferSize;
static const unsigned DefaultMicroOpBufferSize = 0;
// LoopMicroOpBufferSize is the number of micro-ops that the processor may
// buffer for optimized loop execution. More generally, this represents the
// optimal number of micro-ops in a loop body. A loop may be partially
// unrolled to bring the count of micro-ops in the loop body closer to this
// number.
unsigned LoopMicroOpBufferSize;
static const unsigned DefaultLoopMicroOpBufferSize = 0;
// LoadLatency is the expected latency of load instructions.
//
// If MinLatency >= 0, this may be overriden for individual load opcodes by
// InstrItinerary OperandCycles.
unsigned LoadLatency;
static const unsigned DefaultLoadLatency = 4;
// HighLatency is the expected latency of "very high latency" operations.
// See TargetInstrInfo::isHighLatencyDef().
// By default, this is set to an arbitrarily high number of cycles
// likely to have some impact on scheduling heuristics.
// If MinLatency >= 0, this may be overriden by InstrItinData OperandCycles.
unsigned HighLatency;
static const unsigned DefaultHighLatency = 10;
// MispredictPenalty is the typical number of extra cycles the processor
// takes to recover from a branch misprediction.
unsigned MispredictPenalty;
static const unsigned DefaultMispredictPenalty = 10;
bool PostRAScheduler; // default value is false
bool CompleteModel;
unsigned ProcID;
const MCProcResourceDesc *ProcResourceTable;
const MCSchedClassDesc *SchedClassTable;
unsigned NumProcResourceKinds;
unsigned NumSchedClasses;
// Instruction itinerary tables used by InstrItineraryData.
friend class InstrItineraryData;
const InstrItinerary *InstrItineraries;
unsigned getProcessorID() const { return ProcID; }
/// Does this machine model include instruction-level scheduling.
bool hasInstrSchedModel() const { return SchedClassTable; }
/// Return true if this machine model data for all instructions with a
/// scheduling class (itinerary class or SchedRW list).
bool isComplete() const { return CompleteModel; }
unsigned getNumProcResourceKinds() const {
return NumProcResourceKinds;
}
const MCProcResourceDesc *getProcResource(unsigned ProcResourceIdx) const {
assert(hasInstrSchedModel() && "No scheduling machine model");
assert(ProcResourceIdx < NumProcResourceKinds && "bad proc resource idx");
return &ProcResourceTable[ProcResourceIdx];
}
const MCSchedClassDesc *getSchedClassDesc(unsigned SchedClassIdx) const {
assert(hasInstrSchedModel() && "No scheduling machine model");
assert(SchedClassIdx < NumSchedClasses && "bad scheduling class idx");
return &SchedClassTable[SchedClassIdx];
}
/// Returns the default initialized model.
static const MCSchedModel &GetDefaultSchedModel() { return Default; }
static const MCSchedModel Default;
};
} // End llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCRegisterInfo.h | //=== MC/MCRegisterInfo.h - Target Register Description ---------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file describes an abstract interface used to get information about a
// target machines register file. This information is used for a variety of
// purposed, especially register allocation.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCREGISTERINFO_H
#define LLVM_MC_MCREGISTERINFO_H
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/ErrorHandling.h"
#include <cassert>
namespace llvm {
/// An unsigned integer type large enough to represent all physical registers,
/// but not necessarily virtual registers.
typedef uint16_t MCPhysReg;
/// MCRegisterClass - Base class of TargetRegisterClass.
class MCRegisterClass {
public:
typedef const MCPhysReg* iterator;
typedef const MCPhysReg* const_iterator;
const iterator RegsBegin;
const uint8_t *const RegSet;
const uint32_t NameIdx;
const uint16_t RegsSize;
const uint16_t RegSetSize;
const uint16_t ID;
const uint16_t RegSize, Alignment; // Size & Alignment of register in bytes
const int8_t CopyCost;
const bool Allocatable;
/// getID() - Return the register class ID number.
///
unsigned getID() const { return ID; }
/// begin/end - Return all of the registers in this class.
///
iterator begin() const { return RegsBegin; }
iterator end() const { return RegsBegin + RegsSize; }
/// getNumRegs - Return the number of registers in this class.
///
unsigned getNumRegs() const { return RegsSize; }
/// getRegister - Return the specified register in the class.
///
unsigned getRegister(unsigned i) const {
assert(i < getNumRegs() && "Register number out of range!");
return RegsBegin[i];
}
/// contains - Return true if the specified register is included in this
/// register class. This does not include virtual registers.
bool contains(unsigned Reg) const {
unsigned InByte = Reg % 8;
unsigned Byte = Reg / 8;
if (Byte >= RegSetSize)
return false;
return (RegSet[Byte] & (1 << InByte)) != 0;
}
/// contains - Return true if both registers are in this class.
bool contains(unsigned Reg1, unsigned Reg2) const {
return contains(Reg1) && contains(Reg2);
}
/// getSize - Return the size of the register in bytes, which is also the size
/// of a stack slot allocated to hold a spilled copy of this register.
unsigned getSize() const { return RegSize; }
/// getAlignment - Return the minimum required alignment for a register of
/// this class.
unsigned getAlignment() const { return Alignment; }
/// getCopyCost - Return the cost of copying a value between two registers in
/// this class. A negative number means the register class is very expensive
/// to copy e.g. status flag register classes.
int getCopyCost() const { return CopyCost; }
/// isAllocatable - Return true if this register class may be used to create
/// virtual registers.
bool isAllocatable() const { return Allocatable; }
};
/// MCRegisterDesc - This record contains information about a particular
/// register. The SubRegs field is a zero terminated array of registers that
/// are sub-registers of the specific register, e.g. AL, AH are sub-registers
/// of AX. The SuperRegs field is a zero terminated array of registers that are
/// super-registers of the specific register, e.g. RAX, EAX, are
/// super-registers of AX.
///
struct MCRegisterDesc {
uint32_t Name; // Printable name for the reg (for debugging)
uint32_t SubRegs; // Sub-register set, described above
uint32_t SuperRegs; // Super-register set, described above
// Offset into MCRI::SubRegIndices of a list of sub-register indices for each
// sub-register in SubRegs.
uint32_t SubRegIndices;
// RegUnits - Points to the list of register units. The low 4 bits holds the
// Scale, the high bits hold an offset into DiffLists. See MCRegUnitIterator.
uint32_t RegUnits;
/// Index into list with lane mask sequences. The sequence contains a lanemask
/// for every register unit.
uint16_t RegUnitLaneMasks;
};
/// MCRegisterInfo base class - We assume that the target defines a static
/// array of MCRegisterDesc objects that represent all of the machine
/// registers that the target has. As such, we simply have to track a pointer
/// to this array so that we can turn register number into a register
/// descriptor.
///
/// Note this class is designed to be a base class of TargetRegisterInfo, which
/// is the interface used by codegen. However, specific targets *should never*
/// specialize this class. MCRegisterInfo should only contain getters to access
/// TableGen generated physical register data. It must not be extended with
/// virtual methods.
///
class MCRegisterInfo {
public:
typedef const MCRegisterClass *regclass_iterator;
/// DwarfLLVMRegPair - Emitted by tablegen so Dwarf<->LLVM reg mappings can be
/// performed with a binary search.
struct DwarfLLVMRegPair {
unsigned FromReg;
unsigned ToReg;
bool operator<(DwarfLLVMRegPair RHS) const { return FromReg < RHS.FromReg; }
};
/// SubRegCoveredBits - Emitted by tablegen: bit range covered by a subreg
/// index, -1 in any being invalid.
struct SubRegCoveredBits {
uint16_t Offset;
uint16_t Size;
};
private:
const MCRegisterDesc *Desc; // Pointer to the descriptor array
unsigned NumRegs; // Number of entries in the array
unsigned RAReg; // Return address register
unsigned PCReg; // Program counter register
const MCRegisterClass *Classes; // Pointer to the regclass array
unsigned NumClasses; // Number of entries in the array
unsigned NumRegUnits; // Number of regunits.
const MCPhysReg (*RegUnitRoots)[2]; // Pointer to regunit root table.
const MCPhysReg *DiffLists; // Pointer to the difflists array
const unsigned *RegUnitMaskSequences; // Pointer to lane mask sequences
// for register units.
const char *RegStrings; // Pointer to the string table.
const char *RegClassStrings; // Pointer to the class strings.
const uint16_t *SubRegIndices; // Pointer to the subreg lookup
// array.
const SubRegCoveredBits *SubRegIdxRanges; // Pointer to the subreg covered
// bit ranges array.
unsigned NumSubRegIndices; // Number of subreg indices.
const uint16_t *RegEncodingTable; // Pointer to array of register
// encodings.
unsigned L2DwarfRegsSize;
unsigned EHL2DwarfRegsSize;
unsigned Dwarf2LRegsSize;
unsigned EHDwarf2LRegsSize;
const DwarfLLVMRegPair *L2DwarfRegs; // LLVM to Dwarf regs mapping
const DwarfLLVMRegPair *EHL2DwarfRegs; // LLVM to Dwarf regs mapping EH
const DwarfLLVMRegPair *Dwarf2LRegs; // Dwarf to LLVM regs mapping
const DwarfLLVMRegPair *EHDwarf2LRegs; // Dwarf to LLVM regs mapping EH
DenseMap<unsigned, int> L2SEHRegs; // LLVM to SEH regs mapping
public:
/// DiffListIterator - Base iterator class that can traverse the
/// differentially encoded register and regunit lists in DiffLists.
/// Don't use this class directly, use one of the specialized sub-classes
/// defined below.
class DiffListIterator {
uint16_t Val;
const MCPhysReg *List;
protected:
/// Create an invalid iterator. Call init() to point to something useful.
DiffListIterator() : Val(0), List(nullptr) {}
/// init - Point the iterator to InitVal, decoding subsequent values from
/// DiffList. The iterator will initially point to InitVal, sub-classes are
/// responsible for skipping the seed value if it is not part of the list.
void init(MCPhysReg InitVal, const MCPhysReg *DiffList) {
Val = InitVal;
List = DiffList;
}
/// advance - Move to the next list position, return the applied
/// differential. This function does not detect the end of the list, that
/// is the caller's responsibility (by checking for a 0 return value).
unsigned advance() {
assert(isValid() && "Cannot move off the end of the list.");
MCPhysReg D = *List++;
Val += D;
return D;
}
public:
/// isValid - returns true if this iterator is not yet at the end.
bool isValid() const { return List; }
/// Dereference the iterator to get the value at the current position.
unsigned operator*() const { return Val; }
/// Pre-increment to move to the next position.
void operator++() {
// The end of the list is encoded as a 0 differential.
if (!advance())
List = nullptr;
}
};
// These iterators are allowed to sub-class DiffListIterator and access
// internal list pointers.
friend class MCSubRegIterator;
friend class MCSubRegIndexIterator;
friend class MCSuperRegIterator;
friend class MCRegUnitIterator;
friend class MCRegUnitMaskIterator;
friend class MCRegUnitRootIterator;
/// \brief Initialize MCRegisterInfo, called by TableGen
/// auto-generated routines. *DO NOT USE*.
void InitMCRegisterInfo(const MCRegisterDesc *D, unsigned NR, unsigned RA,
unsigned PC,
const MCRegisterClass *C, unsigned NC,
const MCPhysReg (*RURoots)[2],
unsigned NRU,
const MCPhysReg *DL,
const unsigned *RUMS,
const char *Strings,
const char *ClassStrings,
const uint16_t *SubIndices,
unsigned NumIndices,
const SubRegCoveredBits *SubIdxRanges,
const uint16_t *RET) {
Desc = D;
NumRegs = NR;
RAReg = RA;
PCReg = PC;
Classes = C;
DiffLists = DL;
RegUnitMaskSequences = RUMS;
RegStrings = Strings;
RegClassStrings = ClassStrings;
NumClasses = NC;
RegUnitRoots = RURoots;
NumRegUnits = NRU;
SubRegIndices = SubIndices;
NumSubRegIndices = NumIndices;
SubRegIdxRanges = SubIdxRanges;
RegEncodingTable = RET;
}
/// \brief Used to initialize LLVM register to Dwarf
/// register number mapping. Called by TableGen auto-generated routines.
/// *DO NOT USE*.
void mapLLVMRegsToDwarfRegs(const DwarfLLVMRegPair *Map, unsigned Size,
bool isEH) {
if (isEH) {
EHL2DwarfRegs = Map;
EHL2DwarfRegsSize = Size;
} else {
L2DwarfRegs = Map;
L2DwarfRegsSize = Size;
}
}
/// \brief Used to initialize Dwarf register to LLVM
/// register number mapping. Called by TableGen auto-generated routines.
/// *DO NOT USE*.
void mapDwarfRegsToLLVMRegs(const DwarfLLVMRegPair *Map, unsigned Size,
bool isEH) {
if (isEH) {
EHDwarf2LRegs = Map;
EHDwarf2LRegsSize = Size;
} else {
Dwarf2LRegs = Map;
Dwarf2LRegsSize = Size;
}
}
/// mapLLVMRegToSEHReg - Used to initialize LLVM register to SEH register
/// number mapping. By default the SEH register number is just the same
/// as the LLVM register number.
/// FIXME: TableGen these numbers. Currently this requires target specific
/// initialization code.
void mapLLVMRegToSEHReg(unsigned LLVMReg, int SEHReg) {
L2SEHRegs[LLVMReg] = SEHReg;
}
/// \brief This method should return the register where the return
/// address can be found.
unsigned getRARegister() const {
return RAReg;
}
/// Return the register which is the program counter.
unsigned getProgramCounter() const {
return PCReg;
}
const MCRegisterDesc &operator[](unsigned RegNo) const {
assert(RegNo < NumRegs &&
"Attempting to access record for invalid register number!");
return Desc[RegNo];
}
/// \brief Provide a get method, equivalent to [], but more useful with a
/// pointer to this object.
const MCRegisterDesc &get(unsigned RegNo) const {
return operator[](RegNo);
}
/// \brief Returns the physical register number of sub-register "Index"
/// for physical register RegNo. Return zero if the sub-register does not
/// exist.
unsigned getSubReg(unsigned Reg, unsigned Idx) const;
/// \brief Return a super-register of the specified register
/// Reg so its sub-register of index SubIdx is Reg.
unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
const MCRegisterClass *RC) const;
/// \brief For a given register pair, return the sub-register index
/// if the second register is a sub-register of the first. Return zero
/// otherwise.
unsigned getSubRegIndex(unsigned RegNo, unsigned SubRegNo) const;
/// \brief Get the size of the bit range covered by a sub-register index.
/// If the index isn't continuous, return the sum of the sizes of its parts.
/// If the index is used to access subregisters of different sizes, return -1.
unsigned getSubRegIdxSize(unsigned Idx) const;
/// \brief Get the offset of the bit range covered by a sub-register index.
/// If an Offset doesn't make sense (the index isn't continuous, or is used to
/// access sub-registers at different offsets), return -1.
unsigned getSubRegIdxOffset(unsigned Idx) const;
/// \brief Return the human-readable symbolic target-specific name for the
/// specified physical register.
const char *getName(unsigned RegNo) const {
return RegStrings + get(RegNo).Name;
}
/// \brief Return the number of registers this target has (useful for
/// sizing arrays holding per register information)
unsigned getNumRegs() const {
return NumRegs;
}
/// \brief Return the number of sub-register indices
/// understood by the target. Index 0 is reserved for the no-op sub-register,
/// while 1 to getNumSubRegIndices() - 1 represent real sub-registers.
unsigned getNumSubRegIndices() const {
return NumSubRegIndices;
}
/// \brief Return the number of (native) register units in the
/// target. Register units are numbered from 0 to getNumRegUnits() - 1. They
/// can be accessed through MCRegUnitIterator defined below.
unsigned getNumRegUnits() const {
return NumRegUnits;
}
/// \brief Map a target register to an equivalent dwarf register
/// number. Returns -1 if there is no equivalent value. The second
/// parameter allows targets to use different numberings for EH info and
/// debugging info.
int getDwarfRegNum(unsigned RegNum, bool isEH) const;
/// \brief Map a dwarf register back to a target register.
int getLLVMRegNum(unsigned RegNum, bool isEH) const;
/// \brief Map a target register to an equivalent SEH register
/// number. Returns LLVM register number if there is no equivalent value.
int getSEHRegNum(unsigned RegNum) const;
regclass_iterator regclass_begin() const { return Classes; }
regclass_iterator regclass_end() const { return Classes+NumClasses; }
unsigned getNumRegClasses() const {
return (unsigned)(regclass_end()-regclass_begin());
}
/// \brief Returns the register class associated with the enumeration
/// value. See class MCOperandInfo.
const MCRegisterClass& getRegClass(unsigned i) const {
assert(i < getNumRegClasses() && "Register Class ID out of range");
return Classes[i];
}
const char *getRegClassName(const MCRegisterClass *Class) const {
return RegClassStrings + Class->NameIdx;
}
/// \brief Returns the encoding for RegNo
uint16_t getEncodingValue(unsigned RegNo) const {
assert(RegNo < NumRegs &&
"Attempting to get encoding for invalid register number!");
return RegEncodingTable[RegNo];
}
/// \brief Returns true if RegB is a sub-register of RegA.
bool isSubRegister(unsigned RegA, unsigned RegB) const {
return isSuperRegister(RegB, RegA);
}
/// \brief Returns true if RegB is a super-register of RegA.
bool isSuperRegister(unsigned RegA, unsigned RegB) const;
/// \brief Returns true if RegB is a sub-register of RegA or if RegB == RegA.
bool isSubRegisterEq(unsigned RegA, unsigned RegB) const {
return isSuperRegisterEq(RegB, RegA);
}
/// \brief Returns true if RegB is a super-register of RegA or if
/// RegB == RegA.
bool isSuperRegisterEq(unsigned RegA, unsigned RegB) const {
return RegA == RegB || isSuperRegister(RegA, RegB);
}
};
//===----------------------------------------------------------------------===//
// Register List Iterators
//===----------------------------------------------------------------------===//
// MCRegisterInfo provides lists of super-registers, sub-registers, and
// aliasing registers. Use these iterator classes to traverse the lists.
/// MCSubRegIterator enumerates all sub-registers of Reg.
/// If IncludeSelf is set, Reg itself is included in the list.
class MCSubRegIterator : public MCRegisterInfo::DiffListIterator {
public:
MCSubRegIterator(unsigned Reg, const MCRegisterInfo *MCRI,
bool IncludeSelf = false) {
init(Reg, MCRI->DiffLists + MCRI->get(Reg).SubRegs);
// Initially, the iterator points to Reg itself.
if (!IncludeSelf)
++*this;
}
};
/// Iterator that enumerates the sub-registers of a Reg and the associated
/// sub-register indices.
class MCSubRegIndexIterator {
MCSubRegIterator SRIter;
const uint16_t *SRIndex;
public:
/// Constructs an iterator that traverses subregisters and their
/// associated subregister indices.
MCSubRegIndexIterator(unsigned Reg, const MCRegisterInfo *MCRI)
: SRIter(Reg, MCRI) {
SRIndex = MCRI->SubRegIndices + MCRI->get(Reg).SubRegIndices;
}
/// Returns current sub-register.
unsigned getSubReg() const {
return *SRIter;
}
/// Returns sub-register index of the current sub-register.
unsigned getSubRegIndex() const {
return *SRIndex;
}
/// Returns true if this iterator is not yet at the end.
bool isValid() const { return SRIter.isValid(); }
/// Moves to the next position.
void operator++() {
++SRIter;
++SRIndex;
}
};
/// MCSuperRegIterator enumerates all super-registers of Reg.
/// If IncludeSelf is set, Reg itself is included in the list.
class MCSuperRegIterator : public MCRegisterInfo::DiffListIterator {
public:
MCSuperRegIterator() {}
MCSuperRegIterator(unsigned Reg, const MCRegisterInfo *MCRI,
bool IncludeSelf = false) {
init(Reg, MCRI->DiffLists + MCRI->get(Reg).SuperRegs);
// Initially, the iterator points to Reg itself.
if (!IncludeSelf)
++*this;
}
};
// Definition for isSuperRegister. Put it down here since it needs the
// iterator defined above in addition to the MCRegisterInfo class itself.
inline bool MCRegisterInfo::isSuperRegister(unsigned RegA, unsigned RegB) const{
for (MCSuperRegIterator I(RegA, this); I.isValid(); ++I)
if (*I == RegB)
return true;
return false;
}
//===----------------------------------------------------------------------===//
// Register Units
// //
///////////////////////////////////////////////////////////////////////////////
// Register units are used to compute register aliasing. Every register has at
// least one register unit, but it can have more. Two registers overlap if and
// only if they have a common register unit.
//
// A target with a complicated sub-register structure will typically have many
// fewer register units than actual registers. MCRI::getNumRegUnits() returns
// the number of register units in the target.
// MCRegUnitIterator enumerates a list of register units for Reg. The list is
// in ascending numerical order.
class MCRegUnitIterator : public MCRegisterInfo::DiffListIterator {
public:
/// MCRegUnitIterator - Create an iterator that traverses the register units
/// in Reg.
MCRegUnitIterator() {}
MCRegUnitIterator(unsigned Reg, const MCRegisterInfo *MCRI) {
assert(Reg && "Null register has no regunits");
// Decode the RegUnits MCRegisterDesc field.
unsigned RU = MCRI->get(Reg).RegUnits;
unsigned Scale = RU & 15;
unsigned Offset = RU >> 4;
// Initialize the iterator to Reg * Scale, and the List pointer to
// DiffLists + Offset.
init(Reg * Scale, MCRI->DiffLists + Offset);
// That may not be a valid unit, we need to advance by one to get the real
// unit number. The first differential can be 0 which would normally
// terminate the list, but since we know every register has at least one
// unit, we can allow a 0 differential here.
advance();
}
};
/// MCRegUnitIterator enumerates a list of register units and their associated
/// lane masks for Reg. The register units are in ascending numerical order.
class MCRegUnitMaskIterator {
MCRegUnitIterator RUIter;
const unsigned *MaskListIter;
public:
MCRegUnitMaskIterator() {}
/// Constructs an iterator that traverses the register units and their
/// associated LaneMasks in Reg.
MCRegUnitMaskIterator(unsigned Reg, const MCRegisterInfo *MCRI)
: RUIter(Reg, MCRI) {
uint16_t Idx = MCRI->get(Reg).RegUnitLaneMasks;
MaskListIter = &MCRI->RegUnitMaskSequences[Idx];
}
/// Returns a (RegUnit, LaneMask) pair.
std::pair<unsigned,unsigned> operator*() const {
return std::make_pair(*RUIter, *MaskListIter);
}
/// Returns true if this iterator is not yet at the end.
bool isValid() const { return RUIter.isValid(); }
/// Moves to the next position.
void operator++() {
++MaskListIter;
++RUIter;
}
};
// Each register unit has one or two root registers. The complete set of
// registers containing a register unit is the union of the roots and their
// super-registers. All registers aliasing Unit can be visited like this:
//
// for (MCRegUnitRootIterator RI(Unit, MCRI); RI.isValid(); ++RI) {
// for (MCSuperRegIterator SI(*RI, MCRI, true); SI.isValid(); ++SI)
// visit(*SI);
// }
/// MCRegUnitRootIterator enumerates the root registers of a register unit.
class MCRegUnitRootIterator {
uint16_t Reg0;
uint16_t Reg1;
public:
MCRegUnitRootIterator() : Reg0(0), Reg1(0) {}
MCRegUnitRootIterator(unsigned RegUnit, const MCRegisterInfo *MCRI) {
assert(RegUnit < MCRI->getNumRegUnits() && "Invalid register unit");
Reg0 = MCRI->RegUnitRoots[RegUnit][0];
Reg1 = MCRI->RegUnitRoots[RegUnit][1];
}
/// \brief Dereference to get the current root register.
unsigned operator*() const {
return Reg0;
}
/// \brief Check if the iterator is at the end of the list.
bool isValid() const {
return Reg0;
}
/// \brief Preincrement to move to the next root register.
void operator++() {
assert(isValid() && "Cannot move off the end of the list.");
Reg0 = Reg1;
Reg1 = 0;
}
};
/// MCRegAliasIterator enumerates all registers aliasing Reg. If IncludeSelf is
/// set, Reg itself is included in the list. This iterator does not guarantee
/// any ordering or that entries are unique.
class MCRegAliasIterator {
private:
unsigned Reg;
const MCRegisterInfo *MCRI;
bool IncludeSelf;
MCRegUnitIterator RI;
MCRegUnitRootIterator RRI;
MCSuperRegIterator SI;
public:
MCRegAliasIterator(unsigned Reg, const MCRegisterInfo *MCRI,
bool IncludeSelf)
: Reg(Reg), MCRI(MCRI), IncludeSelf(IncludeSelf) {
// Initialize the iterators.
for (RI = MCRegUnitIterator(Reg, MCRI); RI.isValid(); ++RI) {
for (RRI = MCRegUnitRootIterator(*RI, MCRI); RRI.isValid(); ++RRI) {
for (SI = MCSuperRegIterator(*RRI, MCRI, true); SI.isValid(); ++SI) {
if (!(!IncludeSelf && Reg == *SI))
return;
}
}
}
}
bool isValid() const {
return RI.isValid();
}
unsigned operator*() const {
assert (SI.isValid() && "Cannot dereference an invalid iterator.");
return *SI;
}
void advance() {
// Assuming SI is valid.
++SI;
if (SI.isValid()) return;
++RRI;
if (RRI.isValid()) {
SI = MCSuperRegIterator(*RRI, MCRI, true);
return;
}
++RI;
if (RI.isValid()) {
RRI = MCRegUnitRootIterator(*RI, MCRI);
SI = MCSuperRegIterator(*RRI, MCRI, true);
}
}
void operator++() {
assert(isValid() && "Cannot move off the end of the list.");
do advance();
while (!IncludeSelf && isValid() && *SI == Reg);
}
};
} // End llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCTargetAsmParser.h | //===-- llvm/MC/MCTargetAsmParser.h - Target Assembly Parser ----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCTARGETASMPARSER_H
#define LLVM_MC_MCTARGETASMPARSER_H
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCParser/MCAsmParserExtension.h"
#include "llvm/MC/MCTargetOptions.h"
#include <memory>
namespace llvm {
class AsmToken;
class MCInst;
class MCParsedAsmOperand;
class MCStreamer;
class SMLoc;
class StringRef;
template <typename T> class SmallVectorImpl;
typedef SmallVectorImpl<std::unique_ptr<MCParsedAsmOperand>> OperandVector;
enum AsmRewriteKind {
AOK_Delete = 0, // Rewrite should be ignored.
AOK_Align, // Rewrite align as .align.
AOK_DotOperator, // Rewrite a dot operator expression as an immediate.
// E.g., [eax].foo.bar -> [eax].8
AOK_Emit, // Rewrite _emit as .byte.
AOK_Imm, // Rewrite as $$N.
AOK_ImmPrefix, // Add $$ before a parsed Imm.
AOK_Input, // Rewrite in terms of $N.
AOK_Output, // Rewrite in terms of $N.
AOK_SizeDirective, // Add a sizing directive (e.g., dword ptr).
AOK_Label, // Rewrite local labels.
AOK_Skip // Skip emission (e.g., offset/type operators).
};
const char AsmRewritePrecedence [] = {
0, // AOK_Delete
2, // AOK_Align
2, // AOK_DotOperator
2, // AOK_Emit
4, // AOK_Imm
4, // AOK_ImmPrefix
3, // AOK_Input
3, // AOK_Output
5, // AOK_SizeDirective
1, // AOK_Label
2 // AOK_Skip
};
struct AsmRewrite {
AsmRewriteKind Kind;
SMLoc Loc;
unsigned Len;
unsigned Val;
StringRef Label;
public:
AsmRewrite(AsmRewriteKind kind, SMLoc loc, unsigned len = 0, unsigned val = 0)
: Kind(kind), Loc(loc), Len(len), Val(val) {}
AsmRewrite(AsmRewriteKind kind, SMLoc loc, unsigned len, StringRef label)
: Kind(kind), Loc(loc), Len(len), Val(0), Label(label) {}
};
struct ParseInstructionInfo {
SmallVectorImpl<AsmRewrite> *AsmRewrites;
ParseInstructionInfo() : AsmRewrites(nullptr) {}
ParseInstructionInfo(SmallVectorImpl<AsmRewrite> *rewrites)
: AsmRewrites(rewrites) {}
};
/// MCTargetAsmParser - Generic interface to target specific assembly parsers.
class MCTargetAsmParser : public MCAsmParserExtension {
public:
enum MatchResultTy {
Match_InvalidOperand,
Match_MissingFeature,
Match_MnemonicFail,
Match_Success,
FIRST_TARGET_MATCH_RESULT_TY
};
private:
MCTargetAsmParser(const MCTargetAsmParser &) = delete;
void operator=(const MCTargetAsmParser &) = delete;
protected: // Can only create subclasses.
MCTargetAsmParser();
/// AvailableFeatures - The current set of available features.
uint64_t AvailableFeatures;
/// ParsingInlineAsm - Are we parsing ms-style inline assembly?
bool ParsingInlineAsm;
/// SemaCallback - The Sema callback implementation. Must be set when parsing
/// ms-style inline assembly.
MCAsmParserSemaCallback *SemaCallback;
/// Set of options which affects instrumentation of inline assembly.
MCTargetOptions MCOptions;
public:
~MCTargetAsmParser() override;
uint64_t getAvailableFeatures() const { return AvailableFeatures; }
void setAvailableFeatures(uint64_t Value) { AvailableFeatures = Value; }
bool isParsingInlineAsm () { return ParsingInlineAsm; }
void setParsingInlineAsm (bool Value) { ParsingInlineAsm = Value; }
MCTargetOptions getTargetOptions() const { return MCOptions; }
void setSemaCallback(MCAsmParserSemaCallback *Callback) {
SemaCallback = Callback;
}
virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
SMLoc &EndLoc) = 0;
/// Sets frame register corresponding to the current MachineFunction.
virtual void SetFrameRegister(unsigned RegNo) {}
/// ParseInstruction - Parse one assembly instruction.
///
/// The parser is positioned following the instruction name. The target
/// specific instruction parser should parse the entire instruction and
/// construct the appropriate MCInst, or emit an error. On success, the entire
/// line should be parsed up to and including the end-of-statement token. On
/// failure, the parser is not required to read to the end of the line.
//
/// \param Name - The instruction name.
/// \param NameLoc - The source location of the name.
/// \param Operands [out] - The list of parsed operands, this returns
/// ownership of them to the caller.
/// \return True on failure.
virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
SMLoc NameLoc, OperandVector &Operands) = 0;
/// ParseDirective - Parse a target specific assembler directive
///
/// The parser is positioned following the directive name. The target
/// specific directive parser should parse the entire directive doing or
/// recording any target specific work, or return true and do nothing if the
/// directive is not target specific. If the directive is specific for
/// the target, the entire line is parsed up to and including the
/// end-of-statement token and false is returned.
///
/// \param DirectiveID - the identifier token of the directive.
virtual bool ParseDirective(AsmToken DirectiveID) = 0;
/// mnemonicIsValid - This returns true if this is a valid mnemonic and false
/// otherwise.
virtual bool mnemonicIsValid(StringRef Mnemonic, unsigned VariantID) = 0;
/// MatchAndEmitInstruction - Recognize a series of operands of a parsed
/// instruction as an actual MCInst and emit it to the specified MCStreamer.
/// This returns false on success and returns true on failure to match.
///
/// On failure, the target parser is responsible for emitting a diagnostic
/// explaining the match failure.
virtual bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
OperandVector &Operands, MCStreamer &Out,
uint64_t &ErrorInfo,
bool MatchingInlineAsm) = 0;
/// Allows targets to let registers opt out of clobber lists.
virtual bool OmitRegisterFromClobberLists(unsigned RegNo) { return false; }
/// Allow a target to add special case operand matching for things that
/// tblgen doesn't/can't handle effectively. For example, literal
/// immediates on ARM. TableGen expects a token operand, but the parser
/// will recognize them as immediates.
virtual unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
unsigned Kind) {
return Match_InvalidOperand;
}
/// checkTargetMatchPredicate - Validate the instruction match against
/// any complex target predicates not expressible via match classes.
virtual unsigned checkTargetMatchPredicate(MCInst &Inst) {
return Match_Success;
}
virtual void convertToMapAndConstraints(unsigned Kind,
const OperandVector &Operands) = 0;
virtual const MCExpr *applyModifierToExpr(const MCExpr *E,
MCSymbolRefExpr::VariantKind,
MCContext &Ctx) {
return nullptr;
}
virtual void onLabelParsed(MCSymbol *Symbol) { };
};
} // End llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCSymbol.h | //===- MCSymbol.h - Machine Code Symbols ------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declaration of the MCSymbol class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCSYMBOL_H
#define LLVM_MC_MCSYMBOL_H
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/MC/MCAssembler.h"
#include "llvm/Support/Compiler.h"
namespace llvm {
class MCAsmInfo;
class MCExpr;
class MCSymbol;
class MCFragment;
class MCSection;
class MCContext;
class raw_ostream;
/// MCSymbol - Instances of this class represent a symbol name in the MC file,
/// and MCSymbols are created and uniqued by the MCContext class. MCSymbols
/// should only be constructed with valid names for the object file.
///
/// If the symbol is defined/emitted into the current translation unit, the
/// Section member is set to indicate what section it lives in. Otherwise, if
/// it is a reference to an external entity, it has a null section.
class MCSymbol {
protected:
/// The kind of the symbol. If it is any value other than unset then this
/// class is actually one of the appropriate subclasses of MCSymbol.
enum SymbolKind {
SymbolKindUnset,
SymbolKindCOFF,
SymbolKindELF,
SymbolKindMachO,
};
/// A symbol can contain an Offset, or Value, or be Common, but never more
/// than one of these.
enum Contents : uint8_t {
SymContentsUnset,
SymContentsOffset,
SymContentsVariable,
SymContentsCommon,
};
// Special sentinal value for the absolute pseudo section.
//
// FIXME: Use a PointerInt wrapper for this?
static MCSection *AbsolutePseudoSection;
/// If a symbol has a Fragment, the section is implied, so we only need
/// one pointer.
/// FIXME: We might be able to simplify this by having the asm streamer create
/// dummy fragments.
/// If this is a section, then it gives the symbol is defined in. This is null
/// for undefined symbols, and the special AbsolutePseudoSection value for
/// absolute symbols. If this is a variable symbol, this caches the variable
/// value's section.
///
/// If this is a fragment, then it gives the fragment this symbol's value is
/// relative to, if any.
///
/// For the 'HasName' integer, this is true if this symbol is named.
/// A named symbol will have a pointer to the name allocated in the bytes
/// immediately prior to the MCSymbol.
mutable PointerIntPair<PointerUnion<MCSection *, MCFragment *>, 1>
SectionOrFragmentAndHasName;
/// IsTemporary - True if this is an assembler temporary label, which
/// typically does not survive in the .o file's symbol table. Usually
/// "Lfoo" or ".foo".
unsigned IsTemporary : 1;
/// \brief True if this symbol can be redefined.
unsigned IsRedefinable : 1;
/// IsUsed - True if this symbol has been used.
mutable unsigned IsUsed : 1;
mutable bool IsRegistered : 1;
/// This symbol is visible outside this translation unit.
mutable unsigned IsExternal : 1;
/// This symbol is private extern.
mutable unsigned IsPrivateExtern : 1;
/// LLVM RTTI discriminator. This is actually a SymbolKind enumerator, but is
/// unsigned to avoid sign extension and achieve better bitpacking with MSVC.
unsigned Kind : 2;
/// True if we have created a relocation that uses this symbol.
mutable unsigned IsUsedInReloc : 1;
/// This is actually a Contents enumerator, but is unsigned to avoid sign
/// extension and achieve better bitpacking with MSVC.
unsigned SymbolContents : 2;
/// The alignment of the symbol, if it is 'common', or -1.
///
/// The alignment is stored as log2(align) + 1. This allows all values from
/// 0 to 2^31 to be stored which is every power of 2 representable by an
/// unsigned.
enum : unsigned { NumCommonAlignmentBits = 5 };
unsigned CommonAlignLog2 : NumCommonAlignmentBits;
/// The Flags field is used by object file implementations to store
/// additional per symbol information which is not easily classified.
enum : unsigned { NumFlagsBits = 16 };
mutable uint32_t Flags : NumFlagsBits;
/// Index field, for use by the object file implementation.
mutable uint32_t Index = 0;
union {
/// The offset to apply to the fragment address to form this symbol's value.
uint64_t Offset;
/// The size of the symbol, if it is 'common'.
uint64_t CommonSize;
/// If non-null, the value for a variable symbol.
const MCExpr *Value;
};
protected: // MCContext creates and uniques these.
friend class MCExpr;
friend class MCContext;
/// \brief The name for a symbol.
/// MCSymbol contains a uint64_t so is probably aligned to 8. On a 32-bit
/// system, the name is a pointer so isn't going to satisfy the 8 byte
/// alignment of uint64_t. Account for that here.
typedef union {
const StringMapEntry<bool> *NameEntry;
uint64_t AlignmentPadding;
} NameEntryStorageTy;
MCSymbol(SymbolKind Kind, const StringMapEntry<bool> *Name, bool isTemporary)
: IsTemporary(isTemporary), IsRedefinable(false), IsUsed(false),
IsRegistered(false), IsExternal(false), IsPrivateExtern(false),
Kind(Kind), IsUsedInReloc(false), SymbolContents(SymContentsUnset),
CommonAlignLog2(0), Flags(0) {
Offset = 0;
SectionOrFragmentAndHasName.setInt(!!Name);
if (Name)
getNameEntryPtr() = Name;
}
// Provide custom new/delete as we will only allocate space for a name
// if we need one.
void *operator new(size_t s, const StringMapEntry<bool> *Name,
MCContext &Ctx);
private:
void operator delete(void *);
/// \brief Placement delete - required by std, but never called.
void operator delete(void*, unsigned) {
llvm_unreachable("Constructor throws?");
}
/// \brief Placement delete - required by std, but never called.
void operator delete(void*, unsigned, bool) {
llvm_unreachable("Constructor throws?");
}
MCSymbol(const MCSymbol &) = delete;
void operator=(const MCSymbol &) = delete;
MCSection *getSectionPtr() const {
if (MCFragment *F = getFragment())
return F->getParent();
const auto &SectionOrFragment = SectionOrFragmentAndHasName.getPointer();
assert(!SectionOrFragment.is<MCFragment *>() && "Section or null expected");
MCSection *Section = SectionOrFragment.dyn_cast<MCSection *>();
if (Section || !isVariable())
return Section;
return Section = getVariableValue()->findAssociatedSection();
}
/// \brief Get a reference to the name field. Requires that we have a name
const StringMapEntry<bool> *&getNameEntryPtr() {
assert(SectionOrFragmentAndHasName.getInt() && "Name is required");
NameEntryStorageTy *Name = reinterpret_cast<NameEntryStorageTy *>(this);
return (*(Name - 1)).NameEntry;
}
const StringMapEntry<bool> *&getNameEntryPtr() const {
return const_cast<MCSymbol*>(this)->getNameEntryPtr();
}
public:
/// getName - Get the symbol name.
StringRef getName() const {
if (!SectionOrFragmentAndHasName.getInt())
return StringRef();
return getNameEntryPtr()->first();
}
bool isRegistered() const { return IsRegistered; }
void setIsRegistered(bool Value) const { IsRegistered = Value; }
void setUsedInReloc() const { IsUsedInReloc = true; }
bool isUsedInReloc() const { return IsUsedInReloc; }
/// \name Accessors
/// @{
/// isTemporary - Check if this is an assembler temporary symbol.
bool isTemporary() const { return IsTemporary; }
/// isUsed - Check if this is used.
bool isUsed() const { return IsUsed; }
void setUsed(bool Value) const { IsUsed = Value; }
/// \brief Check if this symbol is redefinable.
bool isRedefinable() const { return IsRedefinable; }
/// \brief Mark this symbol as redefinable.
void setRedefinable(bool Value) { IsRedefinable = Value; }
/// \brief Prepare this symbol to be redefined.
void redefineIfPossible() {
if (IsRedefinable) {
if (SymbolContents == SymContentsVariable) {
Value = nullptr;
SymbolContents = SymContentsUnset;
}
setUndefined();
IsRedefinable = false;
}
}
/// @}
/// \name Associated Sections
/// @{
/// isDefined - Check if this symbol is defined (i.e., it has an address).
///
/// Defined symbols are either absolute or in some section.
bool isDefined() const { return getSectionPtr() != nullptr; }
/// isInSection - Check if this symbol is defined in some section (i.e., it
/// is defined but not absolute).
bool isInSection() const { return isDefined() && !isAbsolute(); }
/// isUndefined - Check if this symbol undefined (i.e., implicitly defined).
bool isUndefined() const { return !isDefined(); }
/// isAbsolute - Check if this is an absolute symbol.
bool isAbsolute() const { return getSectionPtr() == AbsolutePseudoSection; }
/// Get the section associated with a defined, non-absolute symbol.
MCSection &getSection() const {
assert(isInSection() && "Invalid accessor!");
return *getSectionPtr();
}
/// Mark the symbol as defined in the section \p S.
void setSection(MCSection &S) {
assert(!isVariable() && "Cannot set section of variable");
assert(!SectionOrFragmentAndHasName.getPointer().is<MCFragment *>() &&
"Section or null expected");
SectionOrFragmentAndHasName.setPointer(&S);
}
/// Mark the symbol as undefined.
void setUndefined() {
SectionOrFragmentAndHasName.setPointer(
PointerUnion<MCSection *, MCFragment *>());
}
bool isELF() const { return Kind == SymbolKindELF; }
bool isCOFF() const { return Kind == SymbolKindCOFF; }
bool isMachO() const { return Kind == SymbolKindMachO; }
/// @}
/// \name Variable Symbols
/// @{
/// isVariable - Check if this is a variable symbol.
bool isVariable() const {
return SymbolContents == SymContentsVariable;
}
/// getVariableValue() - Get the value for variable symbols.
const MCExpr *getVariableValue() const {
assert(isVariable() && "Invalid accessor!");
IsUsed = true;
return Value;
}
void setVariableValue(const MCExpr *Value);
/// @}
/// Get the (implementation defined) index.
uint32_t getIndex() const {
return Index;
}
/// Set the (implementation defined) index.
void setIndex(uint32_t Value) const {
Index = Value;
}
uint64_t getOffset() const {
assert((SymbolContents == SymContentsUnset ||
SymbolContents == SymContentsOffset) &&
"Cannot get offset for a common/variable symbol");
return Offset;
}
void setOffset(uint64_t Value) {
assert((SymbolContents == SymContentsUnset ||
SymbolContents == SymContentsOffset) &&
"Cannot set offset for a common/variable symbol");
Offset = Value;
SymbolContents = SymContentsOffset;
}
/// Return the size of a 'common' symbol.
uint64_t getCommonSize() const {
assert(isCommon() && "Not a 'common' symbol!");
return CommonSize;
}
/// Mark this symbol as being 'common'.
///
/// \param Size - The size of the symbol.
/// \param Align - The alignment of the symbol.
void setCommon(uint64_t Size, unsigned Align) {
assert(getOffset() == 0);
CommonSize = Size;
SymbolContents = SymContentsCommon;
assert((!Align || isPowerOf2_32(Align)) &&
"Alignment must be a power of 2");
unsigned Log2Align = Log2_32(Align) + 1;
assert(Log2Align < (1U << NumCommonAlignmentBits) &&
"Out of range alignment");
CommonAlignLog2 = Log2Align;
}
/// Return the alignment of a 'common' symbol.
unsigned getCommonAlignment() const {
assert(isCommon() && "Not a 'common' symbol!");
return CommonAlignLog2 ? (1U << (CommonAlignLog2 - 1)) : 0;
}
/// Declare this symbol as being 'common'.
///
/// \param Size - The size of the symbol.
/// \param Align - The alignment of the symbol.
/// \return True if symbol was already declared as a different type
bool declareCommon(uint64_t Size, unsigned Align) {
assert(isCommon() || getOffset() == 0);
if(isCommon()) {
if(CommonSize != Size || getCommonAlignment() != Align)
return true;
} else
setCommon(Size, Align);
return false;
}
/// Is this a 'common' symbol.
bool isCommon() const {
return SymbolContents == SymContentsCommon;
}
MCFragment *getFragment() const {
return SectionOrFragmentAndHasName.getPointer().dyn_cast<MCFragment *>();
}
void setFragment(MCFragment *Value) const {
SectionOrFragmentAndHasName.setPointer(Value);
}
bool isExternal() const { return IsExternal; }
void setExternal(bool Value) const { IsExternal = Value; }
bool isPrivateExtern() const { return IsPrivateExtern; }
void setPrivateExtern(bool Value) { IsPrivateExtern = Value; }
/// print - Print the value to the stream \p OS.
void print(raw_ostream &OS, const MCAsmInfo *MAI) const;
/// dump - Print the value to stderr.
void dump() const;
protected:
/// Get the (implementation defined) symbol flags.
uint32_t getFlags() const { return Flags; }
/// Set the (implementation defined) symbol flags.
void setFlags(uint32_t Value) const {
assert(Value < (1U << NumFlagsBits) && "Out of range flags");
Flags = Value;
}
/// Modify the flags via a mask
void modifyFlags(uint32_t Value, uint32_t Mask) const {
assert(Value < (1U << NumFlagsBits) && "Out of range flags");
Flags = (Flags & ~Mask) | Value;
}
};
inline raw_ostream &operator<<(raw_ostream &OS, const MCSymbol &Sym) {
Sym.print(OS, nullptr);
return OS;
}
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCInstBuilder.h | //===-- llvm/MC/MCInstBuilder.h - Simplify creation of MCInsts --*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the MCInstBuilder class for convenient creation of
// MCInsts.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCINSTBUILDER_H
#define LLVM_MC_MCINSTBUILDER_H
#include "llvm/MC/MCInst.h"
namespace llvm {
class MCInstBuilder {
MCInst Inst;
public:
/// \brief Create a new MCInstBuilder for an MCInst with a specific opcode.
MCInstBuilder(unsigned Opcode) {
Inst.setOpcode(Opcode);
}
/// \brief Add a new register operand.
MCInstBuilder &addReg(unsigned Reg) {
Inst.addOperand(MCOperand::createReg(Reg));
return *this;
}
/// \brief Add a new integer immediate operand.
MCInstBuilder &addImm(int64_t Val) {
Inst.addOperand(MCOperand::createImm(Val));
return *this;
}
/// \brief Add a new floating point immediate operand.
MCInstBuilder &addFPImm(double Val) {
Inst.addOperand(MCOperand::createFPImm(Val));
return *this;
}
/// \brief Add a new MCExpr operand.
MCInstBuilder &addExpr(const MCExpr *Val) {
Inst.addOperand(MCOperand::createExpr(Val));
return *this;
}
/// \brief Add a new MCInst operand.
MCInstBuilder &addInst(const MCInst *Val) {
Inst.addOperand(MCOperand::createInst(Val));
return *this;
}
/// \brief Add an operand.
MCInstBuilder &addOperand(const MCOperand &Op) {
Inst.addOperand(Op);
return *this;
}
operator MCInst&() {
return Inst;
}
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCAssembler.h | //===- MCAssembler.h - Object File Generation -------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCASSEMBLER_H
#define LLVM_MC_MCASSEMBLER_H
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/ilist.h"
#include "llvm/ADT/ilist_node.h"
#include "llvm/ADT/iterator.h"
#include "llvm/MC/MCDirectives.h"
#include "llvm/MC/MCFixup.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCLinkerOptimizationHint.h"
#include "llvm/MC/MCSection.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/DataTypes.h"
#include <algorithm>
#include <vector> // FIXME: Shouldn't be needed.
namespace llvm {
class raw_ostream;
class MCAsmLayout;
class MCAssembler;
class MCContext;
class MCCodeEmitter;
class MCExpr;
class MCFragment;
class MCObjectWriter;
class MCSection;
class MCSubtargetInfo;
class MCValue;
class MCAsmBackend;
class MCFragment : public ilist_node<MCFragment> {
friend class MCAsmLayout;
MCFragment(const MCFragment &) = delete;
void operator=(const MCFragment &) = delete;
public:
enum FragmentType : uint8_t {
FT_Align,
FT_Data,
FT_CompactEncodedInst,
FT_Fill,
FT_Relaxable,
FT_Org,
FT_Dwarf,
FT_DwarfFrame,
FT_LEB,
FT_SafeSEH
};
private:
FragmentType Kind;
protected:
bool HasInstructions;
private:
/// \brief Should this fragment be aligned to the end of a bundle?
bool AlignToBundleEnd;
uint8_t BundlePadding;
/// LayoutOrder - The layout order of this fragment.
unsigned LayoutOrder;
/// The data for the section this fragment is in.
MCSection *Parent;
/// Atom - The atom this fragment is in, as represented by it's defining
/// symbol.
const MCSymbol *Atom;
/// \name Assembler Backend Data
/// @{
//
// FIXME: This could all be kept private to the assembler implementation.
/// Offset - The offset of this fragment in its section. This is ~0 until
/// initialized.
uint64_t Offset;
/// @}
protected:
MCFragment(FragmentType Kind, bool HasInstructions,
uint8_t BundlePadding, MCSection *Parent = nullptr);
~MCFragment();
private:
// This is a friend so that the sentinal can be created.
friend struct ilist_sentinel_traits<MCFragment>;
MCFragment();
public:
/// Destroys the current fragment.
///
/// This must be used instead of delete as MCFragment is non-virtual.
/// This method will dispatch to the appropriate subclass.
void destroy();
FragmentType getKind() const { return Kind; }
MCSection *getParent() const { return Parent; }
void setParent(MCSection *Value) { Parent = Value; }
const MCSymbol *getAtom() const { return Atom; }
void setAtom(const MCSymbol *Value) { Atom = Value; }
unsigned getLayoutOrder() const { return LayoutOrder; }
void setLayoutOrder(unsigned Value) { LayoutOrder = Value; }
/// \brief Does this fragment have instructions emitted into it? By default
/// this is false, but specific fragment types may set it to true.
bool hasInstructions() const { return HasInstructions; }
/// \brief Should this fragment be placed at the end of an aligned bundle?
bool alignToBundleEnd() const { return AlignToBundleEnd; }
void setAlignToBundleEnd(bool V) { AlignToBundleEnd = V; }
/// \brief Get the padding size that must be inserted before this fragment.
/// Used for bundling. By default, no padding is inserted.
/// Note that padding size is restricted to 8 bits. This is an optimization
/// to reduce the amount of space used for each fragment. In practice, larger
/// padding should never be required.
uint8_t getBundlePadding() const { return BundlePadding; }
/// \brief Set the padding size for this fragment. By default it's a no-op,
/// and only some fragments have a meaningful implementation.
void setBundlePadding(uint8_t N) { BundlePadding = N; }
void dump();
};
/// Interface implemented by fragments that contain encoded instructions and/or
/// data.
///
class MCEncodedFragment : public MCFragment {
protected:
MCEncodedFragment(MCFragment::FragmentType FType, bool HasInstructions,
MCSection *Sec)
: MCFragment(FType, HasInstructions, 0, Sec) {}
public:
static bool classof(const MCFragment *F) {
MCFragment::FragmentType Kind = F->getKind();
switch (Kind) {
default:
return false;
case MCFragment::FT_Relaxable:
case MCFragment::FT_CompactEncodedInst:
case MCFragment::FT_Data:
return true;
}
}
};
/// Interface implemented by fragments that contain encoded instructions and/or
/// data.
///
template<unsigned ContentsSize>
class MCEncodedFragmentWithContents : public MCEncodedFragment {
SmallVector<char, ContentsSize> Contents;
protected:
MCEncodedFragmentWithContents(MCFragment::FragmentType FType,
bool HasInstructions,
MCSection *Sec)
: MCEncodedFragment(FType, HasInstructions, Sec) {}
public:
SmallVectorImpl<char> &getContents() { return Contents; }
const SmallVectorImpl<char> &getContents() const { return Contents; }
};
/// Interface implemented by fragments that contain encoded instructions and/or
/// data and also have fixups registered.
///
template<unsigned ContentsSize, unsigned FixupsSize>
class MCEncodedFragmentWithFixups :
public MCEncodedFragmentWithContents<ContentsSize> {
/// Fixups - The list of fixups in this fragment.
SmallVector<MCFixup, FixupsSize> Fixups;
protected:
MCEncodedFragmentWithFixups(MCFragment::FragmentType FType,
bool HasInstructions,
MCSection *Sec)
: MCEncodedFragmentWithContents<ContentsSize>(FType, HasInstructions,
Sec) {}
public:
typedef SmallVectorImpl<MCFixup>::const_iterator const_fixup_iterator;
typedef SmallVectorImpl<MCFixup>::iterator fixup_iterator;
SmallVectorImpl<MCFixup> &getFixups() { return Fixups; }
const SmallVectorImpl<MCFixup> &getFixups() const { return Fixups; }
fixup_iterator fixup_begin() { return Fixups.begin(); }
const_fixup_iterator fixup_begin() const { return Fixups.begin(); }
fixup_iterator fixup_end() { return Fixups.end(); }
const_fixup_iterator fixup_end() const { return Fixups.end(); }
static bool classof(const MCFragment *F) {
MCFragment::FragmentType Kind = F->getKind();
return Kind == MCFragment::FT_Relaxable || Kind == MCFragment::FT_Data;
}
};
/// Fragment for data and encoded instructions.
///
class MCDataFragment : public MCEncodedFragmentWithFixups<32, 4> {
public:
MCDataFragment(MCSection *Sec = nullptr)
: MCEncodedFragmentWithFixups<32, 4>(FT_Data, false, Sec) {}
void setHasInstructions(bool V) { HasInstructions = V; }
static bool classof(const MCFragment *F) {
return F->getKind() == MCFragment::FT_Data;
}
};
/// This is a compact (memory-size-wise) fragment for holding an encoded
/// instruction (non-relaxable) that has no fixups registered. When applicable,
/// it can be used instead of MCDataFragment and lead to lower memory
/// consumption.
///
class MCCompactEncodedInstFragment : public MCEncodedFragmentWithContents<4> {
public:
MCCompactEncodedInstFragment(MCSection *Sec = nullptr)
: MCEncodedFragmentWithContents(FT_CompactEncodedInst, true, Sec) {
}
static bool classof(const MCFragment *F) {
return F->getKind() == MCFragment::FT_CompactEncodedInst;
}
};
/// A relaxable fragment holds on to its MCInst, since it may need to be
/// relaxed during the assembler layout and relaxation stage.
///
class MCRelaxableFragment : public MCEncodedFragmentWithFixups<8, 1> {
/// Inst - The instruction this is a fragment for.
MCInst Inst;
/// STI - The MCSubtargetInfo in effect when the instruction was encoded.
/// Keep a copy instead of a reference to make sure that updates to STI
/// in the assembler are not seen here.
const MCSubtargetInfo STI;
public:
MCRelaxableFragment(const MCInst &Inst, const MCSubtargetInfo &STI,
MCSection *Sec = nullptr)
: MCEncodedFragmentWithFixups(FT_Relaxable, true, Sec),
Inst(Inst), STI(STI) {}
const MCInst &getInst() const { return Inst; }
void setInst(const MCInst &Value) { Inst = Value; }
const MCSubtargetInfo &getSubtargetInfo() { return STI; }
static bool classof(const MCFragment *F) {
return F->getKind() == MCFragment::FT_Relaxable;
}
};
class MCAlignFragment : public MCFragment {
/// Alignment - The alignment to ensure, in bytes.
unsigned Alignment;
/// EmitNops - Flag to indicate that (optimal) NOPs should be emitted instead
/// of using the provided value. The exact interpretation of this flag is
/// target dependent.
bool EmitNops : 1;
/// Value - Value to use for filling padding bytes.
int64_t Value;
/// ValueSize - The size of the integer (in bytes) of \p Value.
unsigned ValueSize;
/// MaxBytesToEmit - The maximum number of bytes to emit; if the alignment
/// cannot be satisfied in this width then this fragment is ignored.
unsigned MaxBytesToEmit;
public:
MCAlignFragment(unsigned Alignment, int64_t Value, unsigned ValueSize,
unsigned MaxBytesToEmit, MCSection *Sec = nullptr)
: MCFragment(FT_Align, false, 0, Sec), Alignment(Alignment),
EmitNops(false), Value(Value),
ValueSize(ValueSize), MaxBytesToEmit(MaxBytesToEmit) {}
/// \name Accessors
/// @{
unsigned getAlignment() const { return Alignment; }
int64_t getValue() const { return Value; }
unsigned getValueSize() const { return ValueSize; }
unsigned getMaxBytesToEmit() const { return MaxBytesToEmit; }
bool hasEmitNops() const { return EmitNops; }
void setEmitNops(bool Value) { EmitNops = Value; }
/// @}
static bool classof(const MCFragment *F) {
return F->getKind() == MCFragment::FT_Align;
}
};
class MCFillFragment : public MCFragment {
/// Value - Value to use for filling bytes.
int64_t Value;
/// ValueSize - The size (in bytes) of \p Value to use when filling, or 0 if
/// this is a virtual fill fragment.
unsigned ValueSize;
/// Size - The number of bytes to insert.
uint64_t Size;
public:
MCFillFragment(int64_t Value, unsigned ValueSize, uint64_t Size,
MCSection *Sec = nullptr)
: MCFragment(FT_Fill, false, 0, Sec), Value(Value), ValueSize(ValueSize),
Size(Size) {
assert((!ValueSize || (Size % ValueSize) == 0) &&
"Fill size must be a multiple of the value size!");
}
/// \name Accessors
/// @{
int64_t getValue() const { return Value; }
unsigned getValueSize() const { return ValueSize; }
uint64_t getSize() const { return Size; }
/// @}
static bool classof(const MCFragment *F) {
return F->getKind() == MCFragment::FT_Fill;
}
};
class MCOrgFragment : public MCFragment {
/// Offset - The offset this fragment should start at.
const MCExpr *Offset;
/// Value - Value to use for filling bytes.
int8_t Value;
public:
MCOrgFragment(const MCExpr &Offset, int8_t Value, MCSection *Sec = nullptr)
: MCFragment(FT_Org, false, 0, Sec), Offset(&Offset), Value(Value) {}
/// \name Accessors
/// @{
const MCExpr &getOffset() const { return *Offset; }
uint8_t getValue() const { return Value; }
/// @}
static bool classof(const MCFragment *F) {
return F->getKind() == MCFragment::FT_Org;
}
};
class MCLEBFragment : public MCFragment {
/// Value - The value this fragment should contain.
const MCExpr *Value;
/// IsSigned - True if this is a sleb128, false if uleb128.
bool IsSigned;
SmallString<8> Contents;
public:
MCLEBFragment(const MCExpr &Value_, bool IsSigned_, MCSection *Sec = nullptr)
: MCFragment(FT_LEB, false, 0, Sec), Value(&Value_), IsSigned(IsSigned_) {
Contents.push_back(0);
}
/// \name Accessors
/// @{
const MCExpr &getValue() const { return *Value; }
bool isSigned() const { return IsSigned; }
SmallString<8> &getContents() { return Contents; }
const SmallString<8> &getContents() const { return Contents; }
/// @}
static bool classof(const MCFragment *F) {
return F->getKind() == MCFragment::FT_LEB;
}
};
class MCDwarfLineAddrFragment : public MCFragment {
/// LineDelta - the value of the difference between the two line numbers
/// between two .loc dwarf directives.
int64_t LineDelta;
/// AddrDelta - The expression for the difference of the two symbols that
/// make up the address delta between two .loc dwarf directives.
const MCExpr *AddrDelta;
SmallString<8> Contents;
public:
MCDwarfLineAddrFragment(int64_t LineDelta, const MCExpr &AddrDelta,
MCSection *Sec = nullptr)
: MCFragment(FT_Dwarf, false, 0, Sec), LineDelta(LineDelta),
AddrDelta(&AddrDelta) {
Contents.push_back(0);
}
/// \name Accessors
/// @{
int64_t getLineDelta() const { return LineDelta; }
const MCExpr &getAddrDelta() const { return *AddrDelta; }
SmallString<8> &getContents() { return Contents; }
const SmallString<8> &getContents() const { return Contents; }
/// @}
static bool classof(const MCFragment *F) {
return F->getKind() == MCFragment::FT_Dwarf;
}
};
class MCDwarfCallFrameFragment : public MCFragment {
/// AddrDelta - The expression for the difference of the two symbols that
/// make up the address delta between two .cfi_* dwarf directives.
const MCExpr *AddrDelta;
SmallString<8> Contents;
public:
MCDwarfCallFrameFragment(const MCExpr &AddrDelta, MCSection *Sec = nullptr)
: MCFragment(FT_DwarfFrame, false, 0, Sec), AddrDelta(&AddrDelta) {
Contents.push_back(0);
}
/// \name Accessors
/// @{
const MCExpr &getAddrDelta() const { return *AddrDelta; }
SmallString<8> &getContents() { return Contents; }
const SmallString<8> &getContents() const { return Contents; }
/// @}
static bool classof(const MCFragment *F) {
return F->getKind() == MCFragment::FT_DwarfFrame;
}
};
class MCSafeSEHFragment : public MCFragment {
const MCSymbol *Sym;
public:
MCSafeSEHFragment(const MCSymbol *Sym, MCSection *Sec = nullptr)
: MCFragment(FT_SafeSEH, false, 0, Sec), Sym(Sym) {}
/// \name Accessors
/// @{
const MCSymbol *getSymbol() { return Sym; }
const MCSymbol *getSymbol() const { return Sym; }
/// @}
static bool classof(const MCFragment *F) {
return F->getKind() == MCFragment::FT_SafeSEH;
}
};
// FIXME: This really doesn't belong here. See comments below.
struct IndirectSymbolData {
MCSymbol *Symbol;
MCSection *Section;
};
// FIXME: Ditto this. Purely so the Streamer and the ObjectWriter can talk
// to one another.
struct DataRegionData {
// This enum should be kept in sync w/ the mach-o definition in
// llvm/Object/MachOFormat.h.
enum KindTy { Data = 1, JumpTable8, JumpTable16, JumpTable32 } Kind;
MCSymbol *Start;
MCSymbol *End;
};
class MCAssembler {
friend class MCAsmLayout;
public:
typedef std::vector<MCSection *> SectionListType;
typedef std::vector<const MCSymbol *> SymbolDataListType;
typedef pointee_iterator<SectionListType::const_iterator> const_iterator;
typedef pointee_iterator<SectionListType::iterator> iterator;
typedef pointee_iterator<SymbolDataListType::const_iterator>
const_symbol_iterator;
typedef pointee_iterator<SymbolDataListType::iterator> symbol_iterator;
typedef iterator_range<symbol_iterator> symbol_range;
typedef iterator_range<const_symbol_iterator> const_symbol_range;
typedef std::vector<IndirectSymbolData>::const_iterator
const_indirect_symbol_iterator;
typedef std::vector<IndirectSymbolData>::iterator indirect_symbol_iterator;
typedef std::vector<DataRegionData>::const_iterator
const_data_region_iterator;
typedef std::vector<DataRegionData>::iterator data_region_iterator;
/// MachO specific deployment target version info.
// A Major version of 0 indicates that no version information was supplied
// and so the corresponding load command should not be emitted.
typedef struct {
MCVersionMinType Kind;
unsigned Major;
unsigned Minor;
unsigned Update;
} VersionMinInfoType;
private:
MCAssembler(const MCAssembler &) = delete;
void operator=(const MCAssembler &) = delete;
MCContext &Context;
MCAsmBackend &Backend;
MCCodeEmitter &Emitter;
MCObjectWriter &Writer;
raw_ostream &OS;
SectionListType Sections;
SymbolDataListType Symbols;
std::vector<IndirectSymbolData> IndirectSymbols;
std::vector<DataRegionData> DataRegions;
/// The list of linker options to propagate into the object file.
std::vector<std::vector<std::string>> LinkerOptions;
/// List of declared file names
std::vector<std::string> FileNames;
/// The set of function symbols for which a .thumb_func directive has
/// been seen.
//
// FIXME: We really would like this in target specific code rather than
// here. Maybe when the relocation stuff moves to target specific,
// this can go with it? The streamer would need some target specific
// refactoring too.
mutable SmallPtrSet<const MCSymbol *, 64> ThumbFuncs;
/// \brief The bundle alignment size currently set in the assembler.
///
/// By default it's 0, which means bundling is disabled.
unsigned BundleAlignSize;
unsigned RelaxAll : 1;
unsigned SubsectionsViaSymbols : 1;
/// ELF specific e_header flags
// It would be good if there were an MCELFAssembler class to hold this.
// ELF header flags are used both by the integrated and standalone assemblers.
// Access to the flags is necessary in cases where assembler directives affect
// which flags to be set.
unsigned ELFHeaderEFlags;
/// Used to communicate Linker Optimization Hint information between
/// the Streamer and the .o writer
MCLOHContainer LOHContainer;
VersionMinInfoType VersionMinInfo;
private:
/// Evaluate a fixup to a relocatable expression and the value which should be
/// placed into the fixup.
///
/// \param Layout The layout to use for evaluation.
/// \param Fixup The fixup to evaluate.
/// \param DF The fragment the fixup is inside.
/// \param Target [out] On return, the relocatable expression the fixup
/// evaluates to.
/// \param Value [out] On return, the value of the fixup as currently laid
/// out.
/// \return Whether the fixup value was fully resolved. This is true if the
/// \p Value result is fixed, otherwise the value may change due to
/// relocation.
bool evaluateFixup(const MCAsmLayout &Layout, const MCFixup &Fixup,
const MCFragment *DF, MCValue &Target,
uint64_t &Value) const;
/// Check whether a fixup can be satisfied, or whether it needs to be relaxed
/// (increased in size, in order to hold its value correctly).
bool fixupNeedsRelaxation(const MCFixup &Fixup, const MCRelaxableFragment *DF,
const MCAsmLayout &Layout) const;
/// Check whether the given fragment needs relaxation.
bool fragmentNeedsRelaxation(const MCRelaxableFragment *IF,
const MCAsmLayout &Layout) const;
/// \brief Perform one layout iteration and return true if any offsets
/// were adjusted.
bool layoutOnce(MCAsmLayout &Layout);
/// \brief Perform one layout iteration of the given section and return true
/// if any offsets were adjusted.
bool layoutSectionOnce(MCAsmLayout &Layout, MCSection &Sec);
bool relaxInstruction(MCAsmLayout &Layout, MCRelaxableFragment &IF);
bool relaxLEB(MCAsmLayout &Layout, MCLEBFragment &IF);
bool relaxDwarfLineAddr(MCAsmLayout &Layout, MCDwarfLineAddrFragment &DF);
bool relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
MCDwarfCallFrameFragment &DF);
/// finishLayout - Finalize a layout, including fragment lowering.
void finishLayout(MCAsmLayout &Layout);
std::pair<uint64_t, bool> handleFixup(const MCAsmLayout &Layout,
MCFragment &F, const MCFixup &Fixup);
public:
/// Compute the effective fragment size assuming it is laid out at the given
/// \p SectionAddress and \p FragmentOffset.
uint64_t computeFragmentSize(const MCAsmLayout &Layout,
const MCFragment &F) const;
/// Find the symbol which defines the atom containing the given symbol, or
/// null if there is no such symbol.
const MCSymbol *getAtom(const MCSymbol &S) const;
/// Check whether a particular symbol is visible to the linker and is required
/// in the symbol table, or whether it can be discarded by the assembler. This
/// also effects whether the assembler treats the label as potentially
/// defining a separate atom.
bool isSymbolLinkerVisible(const MCSymbol &SD) const;
/// Emit the section contents using the given object writer.
void writeSectionData(const MCSection *Section,
const MCAsmLayout &Layout) const;
/// Check whether a given symbol has been flagged with .thumb_func.
bool isThumbFunc(const MCSymbol *Func) const;
/// Flag a function symbol as the target of a .thumb_func directive.
void setIsThumbFunc(const MCSymbol *Func) { ThumbFuncs.insert(Func); }
/// ELF e_header flags
unsigned getELFHeaderEFlags() const { return ELFHeaderEFlags; }
void setELFHeaderEFlags(unsigned Flags) { ELFHeaderEFlags = Flags; }
/// MachO deployment target version information.
const VersionMinInfoType &getVersionMinInfo() const { return VersionMinInfo; }
void setVersionMinInfo(MCVersionMinType Kind, unsigned Major, unsigned Minor,
unsigned Update) {
VersionMinInfo.Kind = Kind;
VersionMinInfo.Major = Major;
VersionMinInfo.Minor = Minor;
VersionMinInfo.Update = Update;
}
public:
/// Construct a new assembler instance.
///
/// \param OS The stream to output to.
//
// FIXME: How are we going to parameterize this? Two obvious options are stay
// concrete and require clients to pass in a target like object. The other
// option is to make this abstract, and have targets provide concrete
// implementations as we do with AsmParser.
MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
raw_ostream &OS);
~MCAssembler();
/// Reuse an assembler instance
///
void reset();
MCContext &getContext() const { return Context; }
MCAsmBackend &getBackend() const { return Backend; }
MCCodeEmitter &getEmitter() const { return Emitter; }
MCObjectWriter &getWriter() const { return Writer; }
/// Finish - Do final processing and write the object to the output stream.
/// \p Writer is used for custom object writer (as the MCJIT does),
/// if not specified it is automatically created from backend.
void Finish();
// FIXME: This does not belong here.
bool getSubsectionsViaSymbols() const { return SubsectionsViaSymbols; }
void setSubsectionsViaSymbols(bool Value) { SubsectionsViaSymbols = Value; }
bool getRelaxAll() const { return RelaxAll; }
void setRelaxAll(bool Value) { RelaxAll = Value; }
bool isBundlingEnabled() const { return BundleAlignSize != 0; }
unsigned getBundleAlignSize() const { return BundleAlignSize; }
void setBundleAlignSize(unsigned Size) {
assert((Size == 0 || !(Size & (Size - 1))) &&
"Expect a power-of-two bundle align size");
BundleAlignSize = Size;
}
/// \name Section List Access
/// @{
iterator begin() { return Sections.begin(); }
const_iterator begin() const { return Sections.begin(); }
iterator end() { return Sections.end(); }
const_iterator end() const { return Sections.end(); }
size_t size() const { return Sections.size(); }
/// @}
/// \name Symbol List Access
/// @{
symbol_iterator symbol_begin() { return Symbols.begin(); }
const_symbol_iterator symbol_begin() const { return Symbols.begin(); }
symbol_iterator symbol_end() { return Symbols.end(); }
const_symbol_iterator symbol_end() const { return Symbols.end(); }
symbol_range symbols() { return make_range(symbol_begin(), symbol_end()); }
const_symbol_range symbols() const {
return make_range(symbol_begin(), symbol_end());
}
size_t symbol_size() const { return Symbols.size(); }
/// @}
/// \name Indirect Symbol List Access
/// @{
// FIXME: This is a total hack, this should not be here. Once things are
// factored so that the streamer has direct access to the .o writer, it can
// disappear.
std::vector<IndirectSymbolData> &getIndirectSymbols() {
return IndirectSymbols;
}
indirect_symbol_iterator indirect_symbol_begin() {
return IndirectSymbols.begin();
}
const_indirect_symbol_iterator indirect_symbol_begin() const {
return IndirectSymbols.begin();
}
indirect_symbol_iterator indirect_symbol_end() {
return IndirectSymbols.end();
}
const_indirect_symbol_iterator indirect_symbol_end() const {
return IndirectSymbols.end();
}
size_t indirect_symbol_size() const { return IndirectSymbols.size(); }
/// @}
/// \name Linker Option List Access
/// @{
std::vector<std::vector<std::string>> &getLinkerOptions() {
return LinkerOptions;
}
/// @}
/// \name Data Region List Access
/// @{
// FIXME: This is a total hack, this should not be here. Once things are
// factored so that the streamer has direct access to the .o writer, it can
// disappear.
std::vector<DataRegionData> &getDataRegions() { return DataRegions; }
data_region_iterator data_region_begin() { return DataRegions.begin(); }
const_data_region_iterator data_region_begin() const {
return DataRegions.begin();
}
data_region_iterator data_region_end() { return DataRegions.end(); }
const_data_region_iterator data_region_end() const {
return DataRegions.end();
}
size_t data_region_size() const { return DataRegions.size(); }
/// @}
/// \name Data Region List Access
/// @{
// FIXME: This is a total hack, this should not be here. Once things are
// factored so that the streamer has direct access to the .o writer, it can
// disappear.
MCLOHContainer &getLOHContainer() { return LOHContainer; }
const MCLOHContainer &getLOHContainer() const {
return const_cast<MCAssembler *>(this)->getLOHContainer();
}
/// @}
/// \name Backend Data Access
/// @{
bool registerSection(MCSection &Section) {
if (Section.isRegistered())
return false;
Sections.push_back(&Section);
Section.setIsRegistered(true);
return true;
}
void registerSymbol(const MCSymbol &Symbol, bool *Created = nullptr);
ArrayRef<std::string> getFileNames() { return FileNames; }
void addFileName(StringRef FileName) {
if (std::find(FileNames.begin(), FileNames.end(), FileName) ==
FileNames.end())
FileNames.push_back(FileName);
}
/// \brief Write the necessary bundle padding to the given object writer.
/// Expects a fragment \p F containing instructions and its size \p FSize.
void writeFragmentPadding(const MCFragment &F, uint64_t FSize,
MCObjectWriter *OW) const;
/// @}
void dump();
};
/// \brief Compute the amount of padding required before the fragment \p F to
/// obey bundling restrictions, where \p FOffset is the fragment's offset in
/// its section and \p FSize is the fragment's size.
uint64_t computeBundlePadding(const MCAssembler &Assembler, const MCFragment *F,
uint64_t FOffset, uint64_t FSize);
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCSectionMachO.h | //===- MCSectionMachO.h - MachO Machine Code Sections -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file declares the MCSectionMachO class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCSECTIONMACHO_H
#define LLVM_MC_MCSECTIONMACHO_H
#include "llvm/ADT/StringRef.h"
#include "llvm/MC/MCSection.h"
#include "llvm/Support/MachO.h"
namespace llvm {
/// MCSectionMachO - This represents a section on a Mach-O system (used by
/// Mac OS X). On a Mac system, these are also described in
/// /usr/include/mach-o/loader.h.
class MCSectionMachO : public MCSection {
char SegmentName[16]; // Not necessarily null terminated!
char SectionName[16]; // Not necessarily null terminated!
/// TypeAndAttributes - This is the SECTION_TYPE and SECTION_ATTRIBUTES
/// field of a section, drawn from the enums below.
unsigned TypeAndAttributes;
/// Reserved2 - The 'reserved2' field of a section, used to represent the
/// size of stubs, for example.
unsigned Reserved2;
MCSectionMachO(StringRef Segment, StringRef Section, unsigned TAA,
unsigned reserved2, SectionKind K, MCSymbol *Begin);
friend class MCContext;
public:
StringRef getSegmentName() const {
// SegmentName is not necessarily null terminated!
if (SegmentName[15])
return StringRef(SegmentName, 16);
return StringRef(SegmentName);
}
StringRef getSectionName() const {
// SectionName is not necessarily null terminated!
if (SectionName[15])
return StringRef(SectionName, 16);
return StringRef(SectionName);
}
unsigned getTypeAndAttributes() const { return TypeAndAttributes; }
unsigned getStubSize() const { return Reserved2; }
MachO::SectionType getType() const {
return static_cast<MachO::SectionType>(TypeAndAttributes &
MachO::SECTION_TYPE);
}
bool hasAttribute(unsigned Value) const {
return (TypeAndAttributes & Value) != 0;
}
/// ParseSectionSpecifier - Parse the section specifier indicated by "Spec".
/// This is a string that can appear after a .section directive in a mach-o
/// flavored .s file. If successful, this fills in the specified Out
/// parameters and returns an empty string. When an invalid section
/// specifier is present, this returns a string indicating the problem.
/// If no TAA was parsed, TAA is not altered, and TAAWasSet becomes false.
static std::string ParseSectionSpecifier(StringRef Spec, // In.
StringRef &Segment, // Out.
StringRef &Section, // Out.
unsigned &TAA, // Out.
bool &TAAParsed, // Out.
unsigned &StubSize); // Out.
void PrintSwitchToSection(const MCAsmInfo &MAI, raw_ostream &OS,
const MCExpr *Subsection) const override;
bool UseCodeAlign() const override;
bool isVirtualSection() const override;
static bool classof(const MCSection *S) {
return S->getVariant() == SV_MachO;
}
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCObjectFileInfo.h | //===-- llvm/MC/MCObjectFileInfo.h - Object File Info -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file describes common object file formats.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCOBJECTFILEINFO_H
#define LLVM_MC_MCOBJECTFILEINFO_H
#include "llvm/ADT/Triple.h"
#include "llvm/Support/CodeGen.h"
namespace llvm {
class MCContext;
class MCSection;
class MCObjectFileInfo {
protected:
/// True if .comm supports alignment. This is a hack for as long as we
/// support 10.4 Tiger, whose assembler doesn't support alignment on comm.
bool CommDirectiveSupportsAlignment;
/// True if target object file supports a weak_definition of constant 0 for an
/// omitted EH frame.
bool SupportsWeakOmittedEHFrame;
/// True if the target object file supports emitting a compact unwind section
/// without an associated EH frame section.
bool SupportsCompactUnwindWithoutEHFrame;
/// Some encoding values for EH.
unsigned PersonalityEncoding;
unsigned LSDAEncoding;
unsigned FDECFIEncoding;
unsigned TTypeEncoding;
/// Section flags for eh_frame
unsigned EHSectionType;
unsigned EHSectionFlags;
/// Compact unwind encoding indicating that we should emit only an EH frame.
unsigned CompactUnwindDwarfEHFrameOnly;
/// Section directive for standard text.
MCSection *TextSection;
/// Section directive for standard data.
MCSection *DataSection;
/// Section that is default initialized to zero.
MCSection *BSSSection;
/// Section that is readonly and can contain arbitrary initialized data.
/// Targets are not required to have a readonly section. If they don't,
/// various bits of code will fall back to using the data section for
/// constants.
MCSection *ReadOnlySection;
/// This section contains the static constructor pointer list.
MCSection *StaticCtorSection;
/// This section contains the static destructor pointer list.
MCSection *StaticDtorSection;
/// If exception handling is supported by the target, this is the section the
/// Language Specific Data Area information is emitted to.
MCSection *LSDASection;
/// If exception handling is supported by the target and the target can
/// support a compact representation of the CIE and FDE, this is the section
/// to emit them into.
MCSection *CompactUnwindSection;
// Dwarf sections for debug info. If a target supports debug info, these must
// be set.
MCSection *DwarfAbbrevSection;
MCSection *DwarfInfoSection;
MCSection *DwarfLineSection;
MCSection *DwarfFrameSection;
MCSection *DwarfPubTypesSection;
const MCSection *DwarfDebugInlineSection;
MCSection *DwarfStrSection;
MCSection *DwarfLocSection;
MCSection *DwarfARangesSection;
MCSection *DwarfRangesSection;
// The pubnames section is no longer generated by default. The generation
// can be enabled by a compiler flag.
MCSection *DwarfPubNamesSection;
/// DWARF5 Experimental Debug Info Sections
/// DwarfAccelNamesSection, DwarfAccelObjCSection,
/// DwarfAccelNamespaceSection, DwarfAccelTypesSection -
/// If we use the DWARF accelerated hash tables then we want to emit these
/// sections.
MCSection *DwarfAccelNamesSection;
MCSection *DwarfAccelObjCSection;
MCSection *DwarfAccelNamespaceSection;
MCSection *DwarfAccelTypesSection;
// These are used for the Fission separate debug information files.
MCSection *DwarfInfoDWOSection;
MCSection *DwarfTypesDWOSection;
MCSection *DwarfAbbrevDWOSection;
MCSection *DwarfStrDWOSection;
MCSection *DwarfLineDWOSection;
MCSection *DwarfLocDWOSection;
MCSection *DwarfStrOffDWOSection;
MCSection *DwarfAddrSection;
/// Section for newer gnu pubnames.
MCSection *DwarfGnuPubNamesSection;
/// Section for newer gnu pubtypes.
MCSection *DwarfGnuPubTypesSection;
MCSection *COFFDebugSymbolsSection;
/// Extra TLS Variable Data section.
///
/// If the target needs to put additional information for a TLS variable,
/// it'll go here.
MCSection *TLSExtraDataSection;
/// Section directive for Thread Local data. ELF, MachO and COFF.
MCSection *TLSDataSection; // Defaults to ".tdata".
/// Section directive for Thread Local uninitialized data.
///
/// Null if this target doesn't support a BSS section. ELF and MachO only.
MCSection *TLSBSSSection; // Defaults to ".tbss".
/// StackMap section.
MCSection *StackMapSection;
/// FaultMap section.
MCSection *FaultMapSection;
/// EH frame section.
///
/// It is initialized on demand so it can be overwritten (with uniquing).
MCSection *EHFrameSection;
// ELF specific sections.
MCSection *DataRelSection;
const MCSection *DataRelLocalSection;
MCSection *DataRelROSection;
MCSection *DataRelROLocalSection;
MCSection *MergeableConst4Section;
MCSection *MergeableConst8Section;
MCSection *MergeableConst16Section;
// MachO specific sections.
/// Section for thread local structure information.
///
/// Contains the source code name of the variable, visibility and a pointer to
/// the initial value (.tdata or .tbss).
MCSection *TLSTLVSection; // Defaults to ".tlv".
/// Section for thread local data initialization functions.
const MCSection *TLSThreadInitSection; // Defaults to ".thread_init_func".
MCSection *CStringSection;
MCSection *UStringSection;
MCSection *TextCoalSection;
MCSection *ConstTextCoalSection;
MCSection *ConstDataSection;
MCSection *DataCoalSection;
MCSection *DataCommonSection;
MCSection *DataBSSSection;
MCSection *FourByteConstantSection;
MCSection *EightByteConstantSection;
MCSection *SixteenByteConstantSection;
MCSection *LazySymbolPointerSection;
MCSection *NonLazySymbolPointerSection;
/// COFF specific sections.
MCSection *DrectveSection;
MCSection *PDataSection;
MCSection *XDataSection;
MCSection *SXDataSection;
public:
void InitMCObjectFileInfo(const Triple &TT, Reloc::Model RM,
CodeModel::Model CM, MCContext &ctx);
LLVM_ATTRIBUTE_DEPRECATED(
void InitMCObjectFileInfo(StringRef TT, Reloc::Model RM,
CodeModel::Model CM, MCContext &ctx),
"StringRef GNU Triple argument replaced by a llvm::Triple object");
bool getSupportsWeakOmittedEHFrame() const {
return SupportsWeakOmittedEHFrame;
}
bool getSupportsCompactUnwindWithoutEHFrame() const {
return SupportsCompactUnwindWithoutEHFrame;
}
bool getCommDirectiveSupportsAlignment() const {
return CommDirectiveSupportsAlignment;
}
unsigned getPersonalityEncoding() const { return PersonalityEncoding; }
unsigned getLSDAEncoding() const { return LSDAEncoding; }
unsigned getFDEEncoding() const { return FDECFIEncoding; }
unsigned getTTypeEncoding() const { return TTypeEncoding; }
unsigned getCompactUnwindDwarfEHFrameOnly() const {
return CompactUnwindDwarfEHFrameOnly;
}
MCSection *getTextSection() const { return TextSection; }
MCSection *getDataSection() const { return DataSection; }
MCSection *getBSSSection() const { return BSSSection; }
MCSection *getLSDASection() const { return LSDASection; }
MCSection *getCompactUnwindSection() const { return CompactUnwindSection; }
MCSection *getDwarfAbbrevSection() const { return DwarfAbbrevSection; }
MCSection *getDwarfInfoSection() const { return DwarfInfoSection; }
MCSection *getDwarfLineSection() const { return DwarfLineSection; }
MCSection *getDwarfFrameSection() const { return DwarfFrameSection; }
MCSection *getDwarfPubNamesSection() const { return DwarfPubNamesSection; }
MCSection *getDwarfPubTypesSection() const { return DwarfPubTypesSection; }
MCSection *getDwarfGnuPubNamesSection() const {
return DwarfGnuPubNamesSection;
}
MCSection *getDwarfGnuPubTypesSection() const {
return DwarfGnuPubTypesSection;
}
const MCSection *getDwarfDebugInlineSection() const {
return DwarfDebugInlineSection;
}
MCSection *getDwarfStrSection() const { return DwarfStrSection; }
MCSection *getDwarfLocSection() const { return DwarfLocSection; }
MCSection *getDwarfARangesSection() const { return DwarfARangesSection; }
MCSection *getDwarfRangesSection() const { return DwarfRangesSection; }
// DWARF5 Experimental Debug Info Sections
MCSection *getDwarfAccelNamesSection() const {
return DwarfAccelNamesSection;
}
MCSection *getDwarfAccelObjCSection() const { return DwarfAccelObjCSection; }
MCSection *getDwarfAccelNamespaceSection() const {
return DwarfAccelNamespaceSection;
}
MCSection *getDwarfAccelTypesSection() const {
return DwarfAccelTypesSection;
}
MCSection *getDwarfInfoDWOSection() const { return DwarfInfoDWOSection; }
MCSection *getDwarfTypesSection(uint64_t Hash) const;
MCSection *getDwarfTypesDWOSection() const { return DwarfTypesDWOSection; }
MCSection *getDwarfAbbrevDWOSection() const { return DwarfAbbrevDWOSection; }
MCSection *getDwarfStrDWOSection() const { return DwarfStrDWOSection; }
MCSection *getDwarfLineDWOSection() const { return DwarfLineDWOSection; }
MCSection *getDwarfLocDWOSection() const { return DwarfLocDWOSection; }
MCSection *getDwarfStrOffDWOSection() const { return DwarfStrOffDWOSection; }
MCSection *getDwarfAddrSection() const { return DwarfAddrSection; }
MCSection *getCOFFDebugSymbolsSection() const {
return COFFDebugSymbolsSection;
}
MCSection *getTLSExtraDataSection() const { return TLSExtraDataSection; }
const MCSection *getTLSDataSection() const { return TLSDataSection; }
MCSection *getTLSBSSSection() const { return TLSBSSSection; }
MCSection *getStackMapSection() const { return StackMapSection; }
MCSection *getFaultMapSection() const { return FaultMapSection; }
// ELF specific sections.
MCSection *getDataRelSection() const { return DataRelSection; }
const MCSection *getDataRelLocalSection() const {
return DataRelLocalSection;
}
MCSection *getDataRelROSection() const { return DataRelROSection; }
MCSection *getDataRelROLocalSection() const { return DataRelROLocalSection; }
const MCSection *getMergeableConst4Section() const {
return MergeableConst4Section;
}
const MCSection *getMergeableConst8Section() const {
return MergeableConst8Section;
}
const MCSection *getMergeableConst16Section() const {
return MergeableConst16Section;
}
// MachO specific sections.
const MCSection *getTLSTLVSection() const { return TLSTLVSection; }
const MCSection *getTLSThreadInitSection() const {
return TLSThreadInitSection;
}
const MCSection *getCStringSection() const { return CStringSection; }
const MCSection *getUStringSection() const { return UStringSection; }
MCSection *getTextCoalSection() const { return TextCoalSection; }
const MCSection *getConstTextCoalSection() const {
return ConstTextCoalSection;
}
const MCSection *getConstDataSection() const { return ConstDataSection; }
const MCSection *getDataCoalSection() const { return DataCoalSection; }
const MCSection *getDataCommonSection() const { return DataCommonSection; }
MCSection *getDataBSSSection() const { return DataBSSSection; }
const MCSection *getFourByteConstantSection() const {
return FourByteConstantSection;
}
const MCSection *getEightByteConstantSection() const {
return EightByteConstantSection;
}
const MCSection *getSixteenByteConstantSection() const {
return SixteenByteConstantSection;
}
MCSection *getLazySymbolPointerSection() const {
return LazySymbolPointerSection;
}
MCSection *getNonLazySymbolPointerSection() const {
return NonLazySymbolPointerSection;
}
// COFF specific sections.
MCSection *getDrectveSection() const { return DrectveSection; }
MCSection *getPDataSection() const { return PDataSection; }
MCSection *getXDataSection() const { return XDataSection; }
MCSection *getSXDataSection() const { return SXDataSection; }
MCSection *getEHFrameSection() {
if (!EHFrameSection)
InitEHFrameSection();
return EHFrameSection;
}
enum Environment { IsMachO, IsELF, IsCOFF };
Environment getObjectFileType() const { return Env; }
Reloc::Model getRelocM() const { return RelocM; }
private:
Environment Env;
Reloc::Model RelocM;
CodeModel::Model CMModel;
MCContext *Ctx;
Triple TT;
void initMachOMCObjectFileInfo(Triple T);
void initELFMCObjectFileInfo(Triple T);
void initCOFFMCObjectFileInfo(Triple T);
/// Initialize EHFrameSection on demand.
void InitEHFrameSection();
public:
const Triple &getTargetTriple() const { return TT; }
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCSectionCOFF.h | //===- MCSectionCOFF.h - COFF Machine Code Sections -------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file declares the MCSectionCOFF class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCSECTIONCOFF_H
#define LLVM_MC_MCSECTIONCOFF_H
#include "llvm/ADT/StringRef.h"
#include "llvm/MC/MCSection.h"
#include "llvm/Support/COFF.h"
namespace llvm {
class MCSymbol;
/// MCSectionCOFF - This represents a section on Windows
class MCSectionCOFF : public MCSection {
// The memory for this string is stored in the same MCContext as *this.
StringRef SectionName;
// FIXME: The following fields should not be mutable, but are for now so
// the asm parser can honor the .linkonce directive.
/// Characteristics - This is the Characteristics field of a section,
/// drawn from the enums below.
mutable unsigned Characteristics;
/// The COMDAT symbol of this section. Only valid if this is a COMDAT
/// section. Two COMDAT sections are merged if they have the same
/// COMDAT symbol.
MCSymbol *COMDATSymbol;
/// Selection - This is the Selection field for the section symbol, if
/// it is a COMDAT section (Characteristics & IMAGE_SCN_LNK_COMDAT) != 0
mutable int Selection;
private:
friend class MCContext;
MCSectionCOFF(StringRef Section, unsigned Characteristics,
MCSymbol *COMDATSymbol, int Selection, SectionKind K,
MCSymbol *Begin)
: MCSection(SV_COFF, K, Begin), SectionName(Section),
Characteristics(Characteristics), COMDATSymbol(COMDATSymbol),
Selection(Selection) {
assert ((Characteristics & 0x00F00000) == 0 &&
"alignment must not be set upon section creation");
}
~MCSectionCOFF() override;
public:
/// ShouldOmitSectionDirective - Decides whether a '.section' directive
/// should be printed before the section name
bool ShouldOmitSectionDirective(StringRef Name, const MCAsmInfo &MAI) const;
StringRef getSectionName() const { return SectionName; }
unsigned getCharacteristics() const { return Characteristics; }
MCSymbol *getCOMDATSymbol() const { return COMDATSymbol; }
int getSelection() const { return Selection; }
void setSelection(int Selection) const;
void PrintSwitchToSection(const MCAsmInfo &MAI, raw_ostream &OS,
const MCExpr *Subsection) const override;
bool UseCodeAlign() const override;
bool isVirtualSection() const override;
static bool classof(const MCSection *S) {
return S->getVariant() == SV_COFF;
}
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCRelocationInfo.h | //==-- llvm/MC/MCRelocationInfo.h --------------------------------*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file declares the MCRelocationInfo class, which provides methods to
// create MCExprs from relocations, either found in an object::ObjectFile
// (object::RelocationRef), or provided through the C API.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCRELOCATIONINFO_H
#define LLVM_MC_MCRELOCATIONINFO_H
#include "llvm/Support/Compiler.h"
namespace llvm {
namespace object {
class RelocationRef;
}
class MCExpr;
class MCContext;
/// \brief Create MCExprs from relocations found in an object file.
class MCRelocationInfo {
MCRelocationInfo(const MCRelocationInfo &) = delete;
void operator=(const MCRelocationInfo &) = delete;
protected:
MCContext &Ctx;
public:
MCRelocationInfo(MCContext &Ctx);
virtual ~MCRelocationInfo();
/// \brief Create an MCExpr for the relocation \p Rel.
/// \returns If possible, an MCExpr corresponding to Rel, else 0.
virtual const MCExpr *createExprForRelocation(object::RelocationRef Rel);
/// \brief Create an MCExpr for the target-specific \p VariantKind.
/// The VariantKinds are defined in llvm-c/Disassembler.h.
/// Used by MCExternalSymbolizer.
/// \returns If possible, an MCExpr corresponding to VariantKind, else 0.
virtual const MCExpr *createExprForCAPIVariantKind(const MCExpr *SubExpr,
unsigned VariantKind);
};
}
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCSymbolCOFF.h | //===- MCSymbolCOFF.h - ----------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCSYMBOLCOFF_H
#define LLVM_MC_MCSYMBOLCOFF_H
#include "llvm/MC/MCSymbol.h"
namespace llvm {
class MCSymbolCOFF : public MCSymbol {
/// This corresponds to the e_type field of the COFF symbol.
mutable uint16_t Type;
enum SymbolFlags : uint16_t {
SF_ClassMask = 0x00FF,
SF_ClassShift = 0,
SF_WeakExternal = 0x0100,
SF_SafeSEH = 0x0200,
};
public:
MCSymbolCOFF(const StringMapEntry<bool> *Name, bool isTemporary)
: MCSymbol(SymbolKindCOFF, Name, isTemporary), Type(0) {}
uint16_t getType() const {
return Type;
}
void setType(uint16_t Ty) const {
Type = Ty;
}
uint16_t getClass() const {
return (getFlags() & SF_ClassMask) >> SF_ClassShift;
}
void setClass(uint16_t StorageClass) const {
modifyFlags(StorageClass << SF_ClassShift, SF_ClassMask);
}
bool isWeakExternal() const {
return getFlags() & SF_WeakExternal;
}
void setIsWeakExternal() const {
modifyFlags(SF_WeakExternal, SF_WeakExternal);
}
bool isSafeSEH() const {
return getFlags() & SF_SafeSEH;
}
void setIsSafeSEH() const {
modifyFlags(SF_SafeSEH, SF_SafeSEH);
}
static bool classof(const MCSymbol *S) { return S->isCOFF(); }
};
}
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCSection.h | //===- MCSection.h - Machine Code Sections ----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file declares the MCSection class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCSECTION_H
#define LLVM_MC_MCSECTION_H
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/ilist.h"
#include "llvm/ADT/ilist_node.h"
#include "llvm/MC/SectionKind.h"
#include "llvm/Support/Compiler.h"
namespace llvm {
class MCAssembler;
class MCAsmInfo;
class MCContext;
class MCExpr;
class MCFragment;
class MCSection;
class MCSymbol;
class raw_ostream;
template<>
struct ilist_node_traits<MCFragment> {
MCFragment *createNode(const MCFragment &V);
static void deleteNode(MCFragment *V);
void addNodeToList(MCFragment *) {}
void removeNodeFromList(MCFragment *) {}
void transferNodesFromList(ilist_node_traits & /*SrcTraits*/,
ilist_iterator<MCFragment> /*first*/,
ilist_iterator<MCFragment> /*last*/) {}
};
/// Instances of this class represent a uniqued identifier for a section in the
/// current translation unit. The MCContext class uniques and creates these.
class MCSection {
public:
enum SectionVariant { SV_COFF = 0, SV_ELF, SV_MachO };
/// \brief Express the state of bundle locked groups while emitting code.
enum BundleLockStateType {
NotBundleLocked,
BundleLocked,
BundleLockedAlignToEnd
};
typedef iplist<MCFragment> FragmentListType;
typedef FragmentListType::const_iterator const_iterator;
typedef FragmentListType::iterator iterator;
typedef FragmentListType::const_reverse_iterator const_reverse_iterator;
typedef FragmentListType::reverse_iterator reverse_iterator;
private:
MCSection(const MCSection &) = delete;
void operator=(const MCSection &) = delete;
MCSymbol *Begin;
MCSymbol *End = nullptr;
/// The alignment requirement of this section.
unsigned Alignment = 1;
/// The section index in the assemblers section list.
unsigned Ordinal = 0;
/// The index of this section in the layout order.
unsigned LayoutOrder;
/// \brief Keeping track of bundle-locked state.
BundleLockStateType BundleLockState = NotBundleLocked;
/// \brief Current nesting depth of bundle_lock directives.
unsigned BundleLockNestingDepth = 0;
/// \brief We've seen a bundle_lock directive but not its first instruction
/// yet.
unsigned BundleGroupBeforeFirstInst : 1;
/// Whether this section has had instructions emitted into it.
unsigned HasInstructions : 1;
unsigned IsRegistered : 1;
FragmentListType Fragments;
/// Mapping from subsection number to insertion point for subsection numbers
/// below that number.
SmallVector<std::pair<unsigned, MCFragment *>, 1> SubsectionFragmentMap;
protected:
MCSection(SectionVariant V, SectionKind K, MCSymbol *Begin);
SectionVariant Variant;
SectionKind Kind;
public:
virtual ~MCSection();
SectionKind getKind() const { return Kind; }
SectionVariant getVariant() const { return Variant; }
MCSymbol *getBeginSymbol() { return Begin; }
const MCSymbol *getBeginSymbol() const {
return const_cast<MCSection *>(this)->getBeginSymbol();
}
void setBeginSymbol(MCSymbol *Sym) {
assert(!Begin);
Begin = Sym;
}
MCSymbol *getEndSymbol(MCContext &Ctx);
bool hasEnded() const;
unsigned getAlignment() const { return Alignment; }
void setAlignment(unsigned Value) { Alignment = Value; }
unsigned getOrdinal() const { return Ordinal; }
void setOrdinal(unsigned Value) { Ordinal = Value; }
unsigned getLayoutOrder() const { return LayoutOrder; }
void setLayoutOrder(unsigned Value) { LayoutOrder = Value; }
BundleLockStateType getBundleLockState() const { return BundleLockState; }
void setBundleLockState(BundleLockStateType NewState);
bool isBundleLocked() const { return BundleLockState != NotBundleLocked; }
bool isBundleGroupBeforeFirstInst() const {
return BundleGroupBeforeFirstInst;
}
void setBundleGroupBeforeFirstInst(bool IsFirst) {
BundleGroupBeforeFirstInst = IsFirst;
}
bool hasInstructions() const { return HasInstructions; }
void setHasInstructions(bool Value) { HasInstructions = Value; }
bool isRegistered() const { return IsRegistered; }
void setIsRegistered(bool Value) { IsRegistered = Value; }
MCSection::FragmentListType &getFragmentList() { return Fragments; }
const MCSection::FragmentListType &getFragmentList() const {
return const_cast<MCSection *>(this)->getFragmentList();
}
MCSection::iterator begin();
MCSection::const_iterator begin() const {
return const_cast<MCSection *>(this)->begin();
}
MCSection::iterator end();
MCSection::const_iterator end() const {
return const_cast<MCSection *>(this)->end();
}
MCSection::reverse_iterator rbegin();
MCSection::const_reverse_iterator rbegin() const {
return const_cast<MCSection *>(this)->rbegin();
}
MCSection::reverse_iterator rend();
MCSection::const_reverse_iterator rend() const {
return const_cast<MCSection *>(this)->rend();
}
MCSection::iterator getSubsectionInsertionPoint(unsigned Subsection);
void dump();
virtual void PrintSwitchToSection(const MCAsmInfo &MAI, raw_ostream &OS,
const MCExpr *Subsection) const = 0;
/// Return true if a .align directive should use "optimized nops" to fill
/// instead of 0s.
virtual bool UseCodeAlign() const = 0;
/// Check whether this section is "virtual", that is has no actual object
/// file contents.
virtual bool isVirtualSection() const = 0;
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCDisassembler.h | //===-- llvm/MC/MCDisassembler.h - Disassembler interface -------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCDISASSEMBLER_H
#define LLVM_MC_MCDISASSEMBLER_H
#include "llvm-c/Disassembler.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/MC/MCSymbolizer.h"
#include "llvm/Support/DataTypes.h"
namespace llvm {
class MCInst;
class MCSubtargetInfo;
class raw_ostream;
class MCContext;
/// Superclass for all disassemblers. Consumes a memory region and provides an
/// array of assembly instructions.
class MCDisassembler {
public:
/// Ternary decode status. Most backends will just use Fail and
/// Success, however some have a concept of an instruction with
/// understandable semantics but which is architecturally
/// incorrect. An example of this is ARM UNPREDICTABLE instructions
/// which are disassemblable but cause undefined behaviour.
///
/// Because it makes sense to disassemble these instructions, there
/// is a "soft fail" failure mode that indicates the MCInst& is
/// valid but architecturally incorrect.
///
/// The enum numbers are deliberately chosen such that reduction
/// from Success->SoftFail ->Fail can be done with a simple
/// bitwise-AND:
///
/// LEFT & TOP = | Success Unpredictable Fail
/// --------------+-----------------------------------
/// Success | Success Unpredictable Fail
/// Unpredictable | Unpredictable Unpredictable Fail
/// Fail | Fail Fail Fail
///
/// An easy way of encoding this is as 0b11, 0b01, 0b00 for
/// Success, SoftFail, Fail respectively.
enum DecodeStatus {
Fail = 0,
SoftFail = 1,
Success = 3
};
MCDisassembler(const MCSubtargetInfo &STI, MCContext &Ctx)
: Ctx(Ctx), STI(STI), Symbolizer(), CommentStream(nullptr) {}
virtual ~MCDisassembler();
/// Returns the disassembly of a single instruction.
///
/// \param Instr - An MCInst to populate with the contents of the
/// instruction.
/// \param Size - A value to populate with the size of the instruction, or
/// the number of bytes consumed while attempting to decode
/// an invalid instruction.
/// \param Address - The address, in the memory space of region, of the first
/// byte of the instruction.
/// \param VStream - The stream to print warnings and diagnostic messages on.
/// \param CStream - The stream to print comments and annotations on.
/// \return - MCDisassembler::Success if the instruction is valid,
/// MCDisassembler::SoftFail if the instruction was
/// disassemblable but invalid,
/// MCDisassembler::Fail if the instruction was invalid.
virtual DecodeStatus getInstruction(MCInst &Instr, uint64_t &Size,
ArrayRef<uint8_t> Bytes, uint64_t Address,
raw_ostream &VStream,
raw_ostream &CStream) const = 0;
private:
MCContext &Ctx;
protected:
// Subtarget information, for instruction decoding predicates if required.
const MCSubtargetInfo &STI;
std::unique_ptr<MCSymbolizer> Symbolizer;
public:
// Helpers around MCSymbolizer
bool tryAddingSymbolicOperand(MCInst &Inst,
int64_t Value,
uint64_t Address, bool IsBranch,
uint64_t Offset, uint64_t InstSize) const;
void tryAddingPcLoadReferenceComment(int64_t Value, uint64_t Address) const;
/// Set \p Symzer as the current symbolizer.
/// This takes ownership of \p Symzer, and deletes the previously set one.
void setSymbolizer(std::unique_ptr<MCSymbolizer> Symzer);
MCContext& getContext() const { return Ctx; }
const MCSubtargetInfo& getSubtargetInfo() const { return STI; }
// Marked mutable because we cache it inside the disassembler, rather than
// having to pass it around as an argument through all the autogenerated code.
mutable raw_ostream *CommentStream;
};
} // namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCSymbolELF.h | //===- MCSymbolELF.h - -----------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCSYMBOLELF_H
#define LLVM_MC_MCSYMBOLELF_H
#include "llvm/MC/MCSymbol.h"
namespace llvm {
class MCSymbolELF : public MCSymbol {
/// An expression describing how to calculate the size of a symbol. If a
/// symbol has no size this field will be NULL.
const MCExpr *SymbolSize = nullptr;
public:
MCSymbolELF(const StringMapEntry<bool> *Name, bool isTemporary)
: MCSymbol(SymbolKindELF, Name, isTemporary) {}
void setSize(const MCExpr *SS) { SymbolSize = SS; }
const MCExpr *getSize() const { return SymbolSize; }
void setVisibility(unsigned Visibility);
unsigned getVisibility() const;
void setOther(unsigned Other);
unsigned getOther() const;
void setType(unsigned Type) const;
unsigned getType() const;
void setBinding(unsigned Binding) const;
unsigned getBinding() const;
bool isBindingSet() const;
void setIsWeakrefUsedInReloc() const;
bool isWeakrefUsedInReloc() const;
void setIsSignature() const;
bool isSignature() const;
static bool classof(const MCSymbol *S) { return S->isELF(); }
private:
void setIsBindingSet() const;
};
}
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCInstrItineraries.h | //===-- llvm/MC/MCInstrItineraries.h - Scheduling ---------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file describes the structures used for instruction
// itineraries, stages, and operand reads/writes. This is used by
// schedulers to determine instruction stages and latencies.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCINSTRITINERARIES_H
#define LLVM_MC_MCINSTRITINERARIES_H
#include "llvm/MC/MCSchedule.h"
#include <algorithm>
namespace llvm {
//===----------------------------------------------------------------------===//
/// These values represent a non-pipelined step in
/// the execution of an instruction. Cycles represents the number of
/// discrete time slots needed to complete the stage. Units represent
/// the choice of functional units that can be used to complete the
/// stage. Eg. IntUnit1, IntUnit2. NextCycles indicates how many
/// cycles should elapse from the start of this stage to the start of
/// the next stage in the itinerary. A value of -1 indicates that the
/// next stage should start immediately after the current one.
/// For example:
///
/// { 1, x, -1 }
/// indicates that the stage occupies FU x for 1 cycle and that
/// the next stage starts immediately after this one.
///
/// { 2, x|y, 1 }
/// indicates that the stage occupies either FU x or FU y for 2
/// consecuative cycles and that the next stage starts one cycle
/// after this stage starts. That is, the stage requirements
/// overlap in time.
///
/// { 1, x, 0 }
/// indicates that the stage occupies FU x for 1 cycle and that
/// the next stage starts in this same cycle. This can be used to
/// indicate that the instruction requires multiple stages at the
/// same time.
///
/// FU reservation can be of two different kinds:
/// - FUs which instruction actually requires
/// - FUs which instruction just reserves. Reserved unit is not available for
/// execution of other instruction. However, several instructions can reserve
/// the same unit several times.
/// Such two types of units reservation is used to model instruction domain
/// change stalls, FUs using the same resource (e.g. same register file), etc.
struct InstrStage {
enum ReservationKinds {
Required = 0,
Reserved = 1
};
unsigned Cycles_; ///< Length of stage in machine cycles
unsigned Units_; ///< Choice of functional units
int NextCycles_; ///< Number of machine cycles to next stage
ReservationKinds Kind_; ///< Kind of the FU reservation
/// \brief Returns the number of cycles the stage is occupied.
unsigned getCycles() const {
return Cycles_;
}
/// \brief Returns the choice of FUs.
unsigned getUnits() const {
return Units_;
}
ReservationKinds getReservationKind() const {
return Kind_;
}
/// \brief Returns the number of cycles from the start of this stage to the
/// start of the next stage in the itinerary
unsigned getNextCycles() const {
return (NextCycles_ >= 0) ? (unsigned)NextCycles_ : Cycles_;
}
};
//===----------------------------------------------------------------------===//
/// An itinerary represents the scheduling information for an instruction.
/// This includes a set of stages occupied by the instruction and the pipeline
/// cycle in which operands are read and written.
///
struct InstrItinerary {
int NumMicroOps; ///< # of micro-ops, -1 means it's variable
unsigned FirstStage; ///< Index of first stage in itinerary
unsigned LastStage; ///< Index of last + 1 stage in itinerary
unsigned FirstOperandCycle; ///< Index of first operand rd/wr
unsigned LastOperandCycle; ///< Index of last + 1 operand rd/wr
};
// //
///////////////////////////////////////////////////////////////////////////////
/// Itinerary data supplied by a subtarget to be used by a target.
///
class InstrItineraryData {
public:
MCSchedModel SchedModel; ///< Basic machine properties.
const InstrStage *Stages; ///< Array of stages selected
const unsigned *OperandCycles; ///< Array of operand cycles selected
const unsigned *Forwardings; ///< Array of pipeline forwarding pathes
const InstrItinerary *Itineraries; ///< Array of itineraries selected
/// Ctors.
InstrItineraryData() : SchedModel(MCSchedModel::GetDefaultSchedModel()),
Stages(nullptr), OperandCycles(nullptr),
Forwardings(nullptr), Itineraries(nullptr) {}
InstrItineraryData(const MCSchedModel &SM, const InstrStage *S,
const unsigned *OS, const unsigned *F)
: SchedModel(SM), Stages(S), OperandCycles(OS), Forwardings(F),
Itineraries(SchedModel.InstrItineraries) {}
/// \brief Returns true if there are no itineraries.
bool isEmpty() const { return Itineraries == nullptr; }
/// \brief Returns true if the index is for the end marker itinerary.
bool isEndMarker(unsigned ItinClassIndx) const {
return ((Itineraries[ItinClassIndx].FirstStage == ~0U) &&
(Itineraries[ItinClassIndx].LastStage == ~0U));
}
/// \brief Return the first stage of the itinerary.
const InstrStage *beginStage(unsigned ItinClassIndx) const {
unsigned StageIdx = Itineraries[ItinClassIndx].FirstStage;
return Stages + StageIdx;
}
/// \brief Return the last+1 stage of the itinerary.
const InstrStage *endStage(unsigned ItinClassIndx) const {
unsigned StageIdx = Itineraries[ItinClassIndx].LastStage;
return Stages + StageIdx;
}
/// \brief Return the total stage latency of the given class. The latency is
/// the maximum completion time for any stage in the itinerary. If no stages
/// exist, it defaults to one cycle.
unsigned getStageLatency(unsigned ItinClassIndx) const {
// If the target doesn't provide itinerary information, use a simple
// non-zero default value for all instructions.
if (isEmpty())
return 1;
// Calculate the maximum completion time for any stage.
unsigned Latency = 0, StartCycle = 0;
for (const InstrStage *IS = beginStage(ItinClassIndx),
*E = endStage(ItinClassIndx); IS != E; ++IS) {
Latency = std::max(Latency, StartCycle + IS->getCycles());
StartCycle += IS->getNextCycles();
}
return Latency;
}
/// \brief Return the cycle for the given class and operand. Return -1 if no
/// cycle is specified for the operand.
int getOperandCycle(unsigned ItinClassIndx, unsigned OperandIdx) const {
if (isEmpty())
return -1;
unsigned FirstIdx = Itineraries[ItinClassIndx].FirstOperandCycle;
unsigned LastIdx = Itineraries[ItinClassIndx].LastOperandCycle;
if ((FirstIdx + OperandIdx) >= LastIdx)
return -1;
return (int)OperandCycles[FirstIdx + OperandIdx];
}
/// \brief Return true if there is a pipeline forwarding between instructions
/// of itinerary classes DefClass and UseClasses so that value produced by an
/// instruction of itinerary class DefClass, operand index DefIdx can be
/// bypassed when it's read by an instruction of itinerary class UseClass,
/// operand index UseIdx.
bool hasPipelineForwarding(unsigned DefClass, unsigned DefIdx,
unsigned UseClass, unsigned UseIdx) const {
unsigned FirstDefIdx = Itineraries[DefClass].FirstOperandCycle;
unsigned LastDefIdx = Itineraries[DefClass].LastOperandCycle;
if ((FirstDefIdx + DefIdx) >= LastDefIdx)
return false;
if (Forwardings[FirstDefIdx + DefIdx] == 0)
return false;
unsigned FirstUseIdx = Itineraries[UseClass].FirstOperandCycle;
unsigned LastUseIdx = Itineraries[UseClass].LastOperandCycle;
if ((FirstUseIdx + UseIdx) >= LastUseIdx)
return false;
return Forwardings[FirstDefIdx + DefIdx] ==
Forwardings[FirstUseIdx + UseIdx];
}
/// \brief Compute and return the use operand latency of a given itinerary
/// class and operand index if the value is produced by an instruction of the
/// specified itinerary class and def operand index.
int getOperandLatency(unsigned DefClass, unsigned DefIdx,
unsigned UseClass, unsigned UseIdx) const {
if (isEmpty())
return -1;
int DefCycle = getOperandCycle(DefClass, DefIdx);
if (DefCycle == -1)
return -1;
int UseCycle = getOperandCycle(UseClass, UseIdx);
if (UseCycle == -1)
return -1;
UseCycle = DefCycle - UseCycle + 1;
if (UseCycle > 0 &&
hasPipelineForwarding(DefClass, DefIdx, UseClass, UseIdx))
// FIXME: This assumes one cycle benefit for every pipeline forwarding.
--UseCycle;
return UseCycle;
}
/// \brief Return the number of micro-ops that the given class decodes to.
/// Return -1 for classes that require dynamic lookup via TargetInstrInfo.
int getNumMicroOps(unsigned ItinClassIndx) const {
if (isEmpty())
return 1;
return Itineraries[ItinClassIndx].NumMicroOps;
}
};
} // End llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCDirectives.h | //===- MCDirectives.h - Enums for directives on various targets -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines various enums that represent target-specific directives.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCDIRECTIVES_H
#define LLVM_MC_MCDIRECTIVES_H
namespace llvm {
enum MCSymbolAttr {
MCSA_Invalid = 0, ///< Not a valid directive.
// Various directives in alphabetical order.
MCSA_ELF_TypeFunction, ///< .type _foo, STT_FUNC # aka @function
MCSA_ELF_TypeIndFunction, ///< .type _foo, STT_GNU_IFUNC
MCSA_ELF_TypeObject, ///< .type _foo, STT_OBJECT # aka @object
MCSA_ELF_TypeTLS, ///< .type _foo, STT_TLS # aka @tls_object
MCSA_ELF_TypeCommon, ///< .type _foo, STT_COMMON # aka @common
MCSA_ELF_TypeNoType, ///< .type _foo, STT_NOTYPE # aka @notype
MCSA_ELF_TypeGnuUniqueObject, /// .type _foo, @gnu_unique_object
MCSA_Global, ///< .globl
MCSA_Hidden, ///< .hidden (ELF)
MCSA_IndirectSymbol, ///< .indirect_symbol (MachO)
MCSA_Internal, ///< .internal (ELF)
MCSA_LazyReference, ///< .lazy_reference (MachO)
MCSA_Local, ///< .local (ELF)
MCSA_NoDeadStrip, ///< .no_dead_strip (MachO)
MCSA_SymbolResolver, ///< .symbol_resolver (MachO)
MCSA_PrivateExtern, ///< .private_extern (MachO)
MCSA_Protected, ///< .protected (ELF)
MCSA_Reference, ///< .reference (MachO)
MCSA_Weak, ///< .weak
MCSA_WeakDefinition, ///< .weak_definition (MachO)
MCSA_WeakReference, ///< .weak_reference (MachO)
MCSA_WeakDefAutoPrivate ///< .weak_def_can_be_hidden (MachO)
};
enum MCAssemblerFlag {
MCAF_SyntaxUnified, ///< .syntax (ARM/ELF)
MCAF_SubsectionsViaSymbols, ///< .subsections_via_symbols (MachO)
MCAF_Code16, ///< .code16 (X86) / .code 16 (ARM)
MCAF_Code32, ///< .code32 (X86) / .code 32 (ARM)
MCAF_Code64 ///< .code64 (X86)
};
enum MCDataRegionType {
MCDR_DataRegion, ///< .data_region
MCDR_DataRegionJT8, ///< .data_region jt8
MCDR_DataRegionJT16, ///< .data_region jt16
MCDR_DataRegionJT32, ///< .data_region jt32
MCDR_DataRegionEnd ///< .end_data_region
};
enum MCVersionMinType {
MCVM_IOSVersionMin, ///< .ios_version_min
MCVM_OSXVersionMin ///< .macosx_version_min
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCDwarf.h | //===- MCDwarf.h - Machine Code Dwarf support -------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declaration of the MCDwarfFile to support the dwarf
// .file directive and the .loc directive.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCDWARF_H
#define LLVM_MC_MCDWARF_H
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/raw_ostream.h"
#include <map>
#include <string>
#include <utility>
#include <vector>
namespace llvm {
class MCAsmBackend;
class MCContext;
class MCObjectStreamer;
class MCSection;
class MCStreamer;
class MCSymbol;
class SourceMgr;
class SMLoc;
/// \brief Instances of this class represent the name of the dwarf
/// .file directive and its associated dwarf file number in the MC file,
/// and MCDwarfFile's are created and uniqued by the MCContext class where
/// the file number for each is its index into the vector of DwarfFiles (note
/// index 0 is not used and not a valid dwarf file number).
struct MCDwarfFile {
// \brief The base name of the file without its directory path.
// The StringRef references memory allocated in the MCContext.
std::string Name;
// \brief The index into the list of directory names for this file name.
unsigned DirIndex;
};
/// \brief Instances of this class represent the information from a
/// dwarf .loc directive.
class MCDwarfLoc {
uint32_t FileNum;
uint32_t Line;
uint16_t Column;
// Flags (see #define's below)
uint8_t Flags;
uint8_t Isa;
uint32_t Discriminator;
// Flag that indicates the initial value of the is_stmt_start flag.
#define DWARF2_LINE_DEFAULT_IS_STMT 1
#define DWARF2_FLAG_IS_STMT (1 << 0)
#define DWARF2_FLAG_BASIC_BLOCK (1 << 1)
#define DWARF2_FLAG_PROLOGUE_END (1 << 2)
#define DWARF2_FLAG_EPILOGUE_BEGIN (1 << 3)
private: // MCContext manages these
friend class MCContext;
friend class MCLineEntry;
MCDwarfLoc(unsigned fileNum, unsigned line, unsigned column, unsigned flags,
unsigned isa, unsigned discriminator)
: FileNum(fileNum), Line(line), Column(column), Flags(flags), Isa(isa),
Discriminator(discriminator) {}
// Allow the default copy constructor and assignment operator to be used
// for an MCDwarfLoc object.
public:
/// \brief Get the FileNum of this MCDwarfLoc.
unsigned getFileNum() const { return FileNum; }
/// \brief Get the Line of this MCDwarfLoc.
unsigned getLine() const { return Line; }
/// \brief Get the Column of this MCDwarfLoc.
unsigned getColumn() const { return Column; }
/// \brief Get the Flags of this MCDwarfLoc.
unsigned getFlags() const { return Flags; }
/// \brief Get the Isa of this MCDwarfLoc.
unsigned getIsa() const { return Isa; }
/// \brief Get the Discriminator of this MCDwarfLoc.
unsigned getDiscriminator() const { return Discriminator; }
/// \brief Set the FileNum of this MCDwarfLoc.
void setFileNum(unsigned fileNum) { FileNum = fileNum; }
/// \brief Set the Line of this MCDwarfLoc.
void setLine(unsigned line) { Line = line; }
/// \brief Set the Column of this MCDwarfLoc.
void setColumn(unsigned column) {
assert(column <= UINT16_MAX);
Column = column;
}
/// \brief Set the Flags of this MCDwarfLoc.
void setFlags(unsigned flags) {
assert(flags <= UINT8_MAX);
Flags = flags;
}
/// \brief Set the Isa of this MCDwarfLoc.
void setIsa(unsigned isa) {
assert(isa <= UINT8_MAX);
Isa = isa;
}
/// \brief Set the Discriminator of this MCDwarfLoc.
void setDiscriminator(unsigned discriminator) {
Discriminator = discriminator;
}
};
/// \brief Instances of this class represent the line information for
/// the dwarf line table entries. Which is created after a machine
/// instruction is assembled and uses an address from a temporary label
/// created at the current address in the current section and the info from
/// the last .loc directive seen as stored in the context.
class MCLineEntry : public MCDwarfLoc {
MCSymbol *Label;
private:
// Allow the default copy constructor and assignment operator to be used
// for an MCLineEntry object.
public:
// Constructor to create an MCLineEntry given a symbol and the dwarf loc.
MCLineEntry(MCSymbol *label, const MCDwarfLoc loc)
: MCDwarfLoc(loc), Label(label) {}
MCSymbol *getLabel() const { return Label; }
// This is called when an instruction is assembled into the specified
// section and if there is information from the last .loc directive that
// has yet to have a line entry made for it is made.
static void Make(MCObjectStreamer *MCOS, MCSection *Section);
};
/// \brief Instances of this class represent the line information for a compile
/// unit where machine instructions have been assembled after seeing .loc
/// directives. This is the information used to build the dwarf line
/// table for a section.
class MCLineSection {
public:
// \brief Add an entry to this MCLineSection's line entries.
void addLineEntry(const MCLineEntry &LineEntry, MCSection *Sec) {
MCLineDivisions[Sec].push_back(LineEntry);
}
typedef std::vector<MCLineEntry> MCLineEntryCollection;
typedef MCLineEntryCollection::iterator iterator;
typedef MCLineEntryCollection::const_iterator const_iterator;
typedef MapVector<MCSection *, MCLineEntryCollection> MCLineDivisionMap;
private:
// A collection of MCLineEntry for each section.
MCLineDivisionMap MCLineDivisions;
public:
// Returns the collection of MCLineEntry for a given Compile Unit ID.
const MCLineDivisionMap &getMCLineEntries() const {
return MCLineDivisions;
}
};
struct MCDwarfLineTableHeader {
MCSymbol *Label;
SmallVector<std::string, 3> MCDwarfDirs;
SmallVector<MCDwarfFile, 3> MCDwarfFiles;
StringMap<unsigned> SourceIdMap;
StringRef CompilationDir;
MCDwarfLineTableHeader() : Label(nullptr) {}
unsigned getFile(StringRef &Directory, StringRef &FileName,
unsigned FileNumber = 0);
std::pair<MCSymbol *, MCSymbol *> Emit(MCStreamer *MCOS) const;
std::pair<MCSymbol *, MCSymbol *>
Emit(MCStreamer *MCOS, ArrayRef<char> SpecialOpcodeLengths) const;
};
class MCDwarfDwoLineTable {
MCDwarfLineTableHeader Header;
public:
void setCompilationDir(StringRef CompilationDir) {
Header.CompilationDir = CompilationDir;
}
unsigned getFile(StringRef Directory, StringRef FileName) {
return Header.getFile(Directory, FileName);
}
void Emit(MCStreamer &MCOS) const;
};
class MCDwarfLineTable {
MCDwarfLineTableHeader Header;
MCLineSection MCLineSections;
public:
// This emits the Dwarf file and the line tables for all Compile Units.
static void Emit(MCObjectStreamer *MCOS);
// This emits the Dwarf file and the line tables for a given Compile Unit.
void EmitCU(MCObjectStreamer *MCOS) const;
unsigned getFile(StringRef &Directory, StringRef &FileName,
unsigned FileNumber = 0);
MCSymbol *getLabel() const {
return Header.Label;
}
void setLabel(MCSymbol *Label) {
Header.Label = Label;
}
void setCompilationDir(StringRef CompilationDir) {
Header.CompilationDir = CompilationDir;
}
const SmallVectorImpl<std::string> &getMCDwarfDirs() const {
return Header.MCDwarfDirs;
}
SmallVectorImpl<std::string> &getMCDwarfDirs() {
return Header.MCDwarfDirs;
}
const SmallVectorImpl<MCDwarfFile> &getMCDwarfFiles() const {
return Header.MCDwarfFiles;
}
SmallVectorImpl<MCDwarfFile> &getMCDwarfFiles() {
return Header.MCDwarfFiles;
}
const MCLineSection &getMCLineSections() const {
return MCLineSections;
}
MCLineSection &getMCLineSections() {
return MCLineSections;
}
};
class MCDwarfLineAddr {
public:
/// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
static void Encode(MCContext &Context, int64_t LineDelta, uint64_t AddrDelta,
raw_ostream &OS);
/// Utility function to emit the encoding to a streamer.
static void Emit(MCStreamer *MCOS, int64_t LineDelta, uint64_t AddrDelta);
};
class MCGenDwarfInfo {
public:
//
// When generating dwarf for assembly source files this emits the Dwarf
// sections.
//
static void Emit(MCStreamer *MCOS);
};
// When generating dwarf for assembly source files this is the info that is
// needed to be gathered for each symbol that will have a dwarf label.
class MCGenDwarfLabelEntry {
private:
// Name of the symbol without a leading underbar, if any.
StringRef Name;
// The dwarf file number this symbol is in.
unsigned FileNumber;
// The line number this symbol is at.
unsigned LineNumber;
// The low_pc for the dwarf label is taken from this symbol.
MCSymbol *Label;
public:
MCGenDwarfLabelEntry(StringRef name, unsigned fileNumber, unsigned lineNumber,
MCSymbol *label)
: Name(name), FileNumber(fileNumber), LineNumber(lineNumber),
Label(label) {}
StringRef getName() const { return Name; }
unsigned getFileNumber() const { return FileNumber; }
unsigned getLineNumber() const { return LineNumber; }
MCSymbol *getLabel() const { return Label; }
// This is called when label is created when we are generating dwarf for
// assembly source files.
static void Make(MCSymbol *Symbol, MCStreamer *MCOS, SourceMgr &SrcMgr,
SMLoc &Loc);
};
class MCCFIInstruction {
public:
enum OpType {
OpSameValue,
OpRememberState,
OpRestoreState,
OpOffset,
OpDefCfaRegister,
OpDefCfaOffset,
OpDefCfa,
OpRelOffset,
OpAdjustCfaOffset,
OpEscape,
OpRestore,
OpUndefined,
OpRegister,
OpWindowSave
};
private:
OpType Operation;
MCSymbol *Label;
unsigned Register;
union {
int Offset;
unsigned Register2;
};
std::vector<char> Values;
MCCFIInstruction(OpType Op, MCSymbol *L, unsigned R, int O, StringRef V)
: Operation(Op), Label(L), Register(R), Offset(O),
Values(V.begin(), V.end()) {
assert(Op != OpRegister);
}
MCCFIInstruction(OpType Op, MCSymbol *L, unsigned R1, unsigned R2)
: Operation(Op), Label(L), Register(R1), Register2(R2) {
assert(Op == OpRegister);
}
public:
/// \brief .cfi_def_cfa defines a rule for computing CFA as: take address from
/// Register and add Offset to it.
static MCCFIInstruction createDefCfa(MCSymbol *L, unsigned Register,
int Offset) {
return MCCFIInstruction(OpDefCfa, L, Register, -Offset, "");
}
/// \brief .cfi_def_cfa_register modifies a rule for computing CFA. From now
/// on Register will be used instead of the old one. Offset remains the same.
static MCCFIInstruction createDefCfaRegister(MCSymbol *L, unsigned Register) {
return MCCFIInstruction(OpDefCfaRegister, L, Register, 0, "");
}
/// \brief .cfi_def_cfa_offset modifies a rule for computing CFA. Register
/// remains the same, but offset is new. Note that it is the absolute offset
/// that will be added to a defined register to the compute CFA address.
static MCCFIInstruction createDefCfaOffset(MCSymbol *L, int Offset) {
return MCCFIInstruction(OpDefCfaOffset, L, 0, -Offset, "");
}
/// \brief .cfi_adjust_cfa_offset Same as .cfi_def_cfa_offset, but
/// Offset is a relative value that is added/subtracted from the previous
/// offset.
static MCCFIInstruction createAdjustCfaOffset(MCSymbol *L, int Adjustment) {
return MCCFIInstruction(OpAdjustCfaOffset, L, 0, Adjustment, "");
}
/// \brief .cfi_offset Previous value of Register is saved at offset Offset
/// from CFA.
static MCCFIInstruction createOffset(MCSymbol *L, unsigned Register,
int Offset) {
return MCCFIInstruction(OpOffset, L, Register, Offset, "");
}
/// \brief .cfi_rel_offset Previous value of Register is saved at offset
/// Offset from the current CFA register. This is transformed to .cfi_offset
/// using the known displacement of the CFA register from the CFA.
static MCCFIInstruction createRelOffset(MCSymbol *L, unsigned Register,
int Offset) {
return MCCFIInstruction(OpRelOffset, L, Register, Offset, "");
}
/// \brief .cfi_register Previous value of Register1 is saved in
/// register Register2.
static MCCFIInstruction createRegister(MCSymbol *L, unsigned Register1,
unsigned Register2) {
return MCCFIInstruction(OpRegister, L, Register1, Register2);
}
/// \brief .cfi_window_save SPARC register window is saved.
static MCCFIInstruction createWindowSave(MCSymbol *L) {
return MCCFIInstruction(OpWindowSave, L, 0, 0, "");
}
/// \brief .cfi_restore says that the rule for Register is now the same as it
/// was at the beginning of the function, after all initial instructions added
/// by .cfi_startproc were executed.
static MCCFIInstruction createRestore(MCSymbol *L, unsigned Register) {
return MCCFIInstruction(OpRestore, L, Register, 0, "");
}
/// \brief .cfi_undefined From now on the previous value of Register can't be
/// restored anymore.
static MCCFIInstruction createUndefined(MCSymbol *L, unsigned Register) {
return MCCFIInstruction(OpUndefined, L, Register, 0, "");
}
/// \brief .cfi_same_value Current value of Register is the same as in the
/// previous frame. I.e., no restoration is needed.
static MCCFIInstruction createSameValue(MCSymbol *L, unsigned Register) {
return MCCFIInstruction(OpSameValue, L, Register, 0, "");
}
/// \brief .cfi_remember_state Save all current rules for all registers.
static MCCFIInstruction createRememberState(MCSymbol *L) {
return MCCFIInstruction(OpRememberState, L, 0, 0, "");
}
/// \brief .cfi_restore_state Restore the previously saved state.
static MCCFIInstruction createRestoreState(MCSymbol *L) {
return MCCFIInstruction(OpRestoreState, L, 0, 0, "");
}
/// \brief .cfi_escape Allows the user to add arbitrary bytes to the unwind
/// info.
static MCCFIInstruction createEscape(MCSymbol *L, StringRef Vals) {
return MCCFIInstruction(OpEscape, L, 0, 0, Vals);
}
OpType getOperation() const { return Operation; }
MCSymbol *getLabel() const { return Label; }
unsigned getRegister() const {
assert(Operation == OpDefCfa || Operation == OpOffset ||
Operation == OpRestore || Operation == OpUndefined ||
Operation == OpSameValue || Operation == OpDefCfaRegister ||
Operation == OpRelOffset || Operation == OpRegister);
return Register;
}
unsigned getRegister2() const {
assert(Operation == OpRegister);
return Register2;
}
int getOffset() const {
assert(Operation == OpDefCfa || Operation == OpOffset ||
Operation == OpRelOffset || Operation == OpDefCfaOffset ||
Operation == OpAdjustCfaOffset);
return Offset;
}
StringRef getValues() const {
assert(Operation == OpEscape);
return StringRef(&Values[0], Values.size());
}
};
struct MCDwarfFrameInfo {
MCDwarfFrameInfo()
: Begin(nullptr), End(nullptr), Personality(nullptr), Lsda(nullptr),
Instructions(), CurrentCfaRegister(0), PersonalityEncoding(),
LsdaEncoding(0), CompactUnwindEncoding(0), IsSignalFrame(false),
IsSimple(false) {}
MCSymbol *Begin;
MCSymbol *End;
const MCSymbol *Personality;
const MCSymbol *Lsda;
std::vector<MCCFIInstruction> Instructions;
unsigned CurrentCfaRegister;
unsigned PersonalityEncoding;
unsigned LsdaEncoding;
uint32_t CompactUnwindEncoding;
bool IsSignalFrame;
bool IsSimple;
};
class MCDwarfFrameEmitter {
public:
//
// This emits the frame info section.
//
static void Emit(MCObjectStreamer &streamer, MCAsmBackend *MAB, bool isEH);
static void EmitAdvanceLoc(MCObjectStreamer &Streamer, uint64_t AddrDelta);
static void EncodeAdvanceLoc(MCContext &Context, uint64_t AddrDelta,
raw_ostream &OS);
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/SubtargetFeature.h | //===-- llvm/MC/SubtargetFeature.h - CPU characteristics --------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines and manages user or tool specified CPU characteristics.
// The intent is to be able to package specific features that should or should
// not be used on a specific target processor. A tool, such as llc, could, as
// as example, gather chip info from the command line, a long with features
// that should be used on that chip.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_SUBTARGETFEATURE_H
#define LLVM_MC_SUBTARGETFEATURE_H
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/DataTypes.h"
#include <bitset>
namespace llvm {
class raw_ostream;
class StringRef;
// A container class for subtarget features.
// This is convenient because std::bitset does not have a constructor
// with an initializer list of set bits.
const unsigned MAX_SUBTARGET_FEATURES = 64;
class FeatureBitset : public std::bitset<MAX_SUBTARGET_FEATURES> {
public:
// Cannot inherit constructors because it's not supported by VC++..
FeatureBitset() : bitset() {}
FeatureBitset(const bitset<MAX_SUBTARGET_FEATURES>& B) : bitset(B) {}
FeatureBitset(std::initializer_list<unsigned> Init) : bitset() {
for (auto I = Init.begin() , E = Init.end(); I != E; ++I)
set(*I);
}
};
//===----------------------------------------------------------------------===//
///
/// SubtargetFeatureKV - Used to provide key value pairs for feature and
/// CPU bit flags.
//
struct SubtargetFeatureKV {
const char *Key; // K-V key string
const char *Desc; // Help descriptor
FeatureBitset Value; // K-V integer value
FeatureBitset Implies; // K-V bit mask
// Compare routine for std::lower_bound
bool operator<(StringRef S) const {
return StringRef(Key) < S;
}
};
//===----------------------------------------------------------------------===//
///
/// SubtargetInfoKV - Used to provide key value pairs for CPU and arbitrary
/// pointers.
//
struct SubtargetInfoKV {
const char *Key; // K-V key string
const void *Value; // K-V pointer value
// Compare routine for std::lower_bound
bool operator<(StringRef S) const {
return StringRef(Key) < S;
}
};
// //
///////////////////////////////////////////////////////////////////////////////
///
/// SubtargetFeatures - Manages the enabling and disabling of subtarget
/// specific features. Features are encoded as a string of the form
/// "+attr1,+attr2,-attr3,...,+attrN"
/// A comma separates each feature from the next (all lowercase.)
/// Each of the remaining features is prefixed with + or - indicating whether
/// that feature should be enabled or disabled contrary to the cpu
/// specification.
///
class SubtargetFeatures {
std::vector<std::string> Features; // Subtarget features as a vector
public:
explicit SubtargetFeatures(StringRef Initial = "");
/// Features string accessors.
std::string getString() const;
/// Adding Features.
void AddFeature(StringRef String, bool Enable = true);
/// ToggleFeature - Toggle a feature and returns the newly updated feature
/// bits.
FeatureBitset ToggleFeature(FeatureBitset Bits, StringRef String,
ArrayRef<SubtargetFeatureKV> FeatureTable);
/// Apply the feature flag and return the newly updated feature bits.
FeatureBitset ApplyFeatureFlag(FeatureBitset Bits, StringRef Feature,
ArrayRef<SubtargetFeatureKV> FeatureTable);
/// Get feature bits of a CPU.
FeatureBitset getFeatureBits(StringRef CPU,
ArrayRef<SubtargetFeatureKV> CPUTable,
ArrayRef<SubtargetFeatureKV> FeatureTable);
/// Print feature string.
void print(raw_ostream &OS) const;
// Dump feature info.
void dump() const;
/// Adds the default features for the specified target triple.
void getDefaultSubtargetFeatures(const Triple& Triple);
};
} // End namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCInstrInfo.h | //===-- llvm/MC/MCInstrInfo.h - Target Instruction Info ---------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file describes the target machine instruction set.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCINSTRINFO_H
#define LLVM_MC_MCINSTRINFO_H
#include "llvm/MC/MCInstrDesc.h"
#include <cassert>
namespace llvm {
//---------------------------------------------------------------------------
/// \brief Interface to description of machine instruction set.
class MCInstrInfo {
const MCInstrDesc *Desc; // Raw array to allow static init'n
const unsigned *InstrNameIndices; // Array for name indices in InstrNameData
const char *InstrNameData; // Instruction name string pool
unsigned NumOpcodes; // Number of entries in the desc array
public:
/// \brief Initialize MCInstrInfo, called by TableGen auto-generated routines.
/// *DO NOT USE*.
void InitMCInstrInfo(const MCInstrDesc *D, const unsigned *NI, const char *ND,
unsigned NO) {
Desc = D;
InstrNameIndices = NI;
InstrNameData = ND;
NumOpcodes = NO;
}
unsigned getNumOpcodes() const { return NumOpcodes; }
/// \brief Return the machine instruction descriptor that corresponds to the
/// specified instruction opcode.
const MCInstrDesc &get(unsigned Opcode) const {
assert(Opcode < NumOpcodes && "Invalid opcode!");
return Desc[Opcode];
}
/// \brief Returns the name for the instructions with the given opcode.
const char *getName(unsigned Opcode) const {
assert(Opcode < NumOpcodes && "Invalid opcode!");
return &InstrNameData[InstrNameIndices[Opcode]];
}
};
} // End llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/StringTableBuilder.h | //===-- StringTableBuilder.h - String table building utility ------*- C++ -*-=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_STRINGTABLEBUILDER_H
#define LLVM_MC_STRINGTABLEBUILDER_H
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringMap.h"
#include <cassert>
namespace llvm {
/// \brief Utility for building string tables with deduplicated suffixes.
class StringTableBuilder {
SmallString<256> StringTable;
StringMap<size_t> StringIndexMap;
public:
/// \brief Add a string to the builder. Returns a StringRef to the internal
/// copy of s. Can only be used before the table is finalized.
StringRef add(StringRef s) {
assert(!isFinalized());
return StringIndexMap.insert(std::make_pair(s, 0)).first->first();
}
enum Kind {
ELF,
WinCOFF,
MachO
};
/// \brief Analyze the strings and build the final table. No more strings can
/// be added after this point.
void finalize(Kind kind);
/// \brief Retrieve the string table data. Can only be used after the table
/// is finalized.
StringRef data() {
assert(isFinalized());
return StringTable;
}
/// \brief Get the offest of a string in the string table. Can only be used
/// after the table is finalized.
size_t getOffset(StringRef s) {
assert(isFinalized());
assert(StringIndexMap.count(s) && "String is not in table!");
return StringIndexMap[s];
}
void clear();
private:
bool isFinalized() {
return !StringTable.empty();
}
};
} // end llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCFixupKindInfo.h | //===-- llvm/MC/MCFixupKindInfo.h - Fixup Descriptors -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCFIXUPKINDINFO_H
#define LLVM_MC_MCFIXUPKINDINFO_H
namespace llvm {
/// \brief Target independent information on a fixup kind.
struct MCFixupKindInfo {
enum FixupKindFlags {
/// Is this fixup kind PCrelative? This is used by the assembler backend to
/// evaluate fixup values in a target independent manner when possible.
FKF_IsPCRel = (1 << 0),
/// Should this fixup kind force a 4-byte aligned effective PC value?
FKF_IsAlignedDownTo32Bits = (1 << 1)
};
/// A target specific name for the fixup kind. The names will be unique for
/// distinct kinds on any given target.
const char *Name;
/// The bit offset to write the relocation into.
unsigned TargetOffset;
/// The number of bits written by this fixup. The bits are assumed to be
/// contiguous.
unsigned TargetSize;
/// Flags describing additional information on this fixup kind.
unsigned Flags;
};
} // End llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCWinEH.h | //===- MCWinEH.h - Windows Unwinding Support --------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCWINEH_H
#define LLVM_MC_MCWINEH_H
#include <vector>
namespace llvm {
class MCContext;
class MCSection;
class MCStreamer;
class MCSymbol;
class StringRef;
namespace WinEH {
struct Instruction {
const MCSymbol *Label;
const unsigned Offset;
const unsigned Register;
const unsigned Operation;
Instruction(unsigned Op, MCSymbol *L, unsigned Reg, unsigned Off)
: Label(L), Offset(Off), Register(Reg), Operation(Op) {}
};
struct FrameInfo {
const MCSymbol *Begin;
const MCSymbol *End;
const MCSymbol *ExceptionHandler;
const MCSymbol *Function;
const MCSymbol *PrologEnd;
const MCSymbol *Symbol;
bool HandlesUnwind;
bool HandlesExceptions;
int LastFrameInst;
const FrameInfo *ChainedParent;
std::vector<Instruction> Instructions;
FrameInfo()
: Begin(nullptr), End(nullptr), ExceptionHandler(nullptr),
Function(nullptr), PrologEnd(nullptr), Symbol(nullptr),
HandlesUnwind(false), HandlesExceptions(false), LastFrameInst(-1),
ChainedParent(nullptr), Instructions() {}
FrameInfo(const MCSymbol *Function, const MCSymbol *BeginFuncEHLabel)
: Begin(BeginFuncEHLabel), End(nullptr), ExceptionHandler(nullptr),
Function(Function), PrologEnd(nullptr), Symbol(nullptr),
HandlesUnwind(false), HandlesExceptions(false), LastFrameInst(-1),
ChainedParent(nullptr), Instructions() {}
FrameInfo(const MCSymbol *Function, const MCSymbol *BeginFuncEHLabel,
const FrameInfo *ChainedParent)
: Begin(BeginFuncEHLabel), End(nullptr), ExceptionHandler(nullptr),
Function(Function), PrologEnd(nullptr), Symbol(nullptr),
HandlesUnwind(false), HandlesExceptions(false), LastFrameInst(-1),
ChainedParent(ChainedParent), Instructions() {}
};
class UnwindEmitter {
public:
static MCSection *getPDataSection(const MCSymbol *Function,
MCContext &Context);
static MCSection *getXDataSection(const MCSymbol *Function,
MCContext &Context);
virtual ~UnwindEmitter() { }
//
// This emits the unwind info sections (.pdata and .xdata in PE/COFF).
//
virtual void Emit(MCStreamer &Streamer) const = 0;
virtual void EmitUnwindInfo(MCStreamer &Streamer, FrameInfo *FI) const = 0;
};
}
}
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCInst.h | //===-- llvm/MC/MCInst.h - MCInst class -------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declaration of the MCInst and MCOperand classes, which
// is the basic representation used to represent low-level machine code
// instructions.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCINST_H
#define LLVM_MC_MCINST_H
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/SMLoc.h"
namespace llvm {
class raw_ostream;
class MCAsmInfo;
class MCInstPrinter;
class MCExpr;
class MCInst;
/// \brief Instances of this class represent operands of the MCInst class.
/// This is a simple discriminated union.
class MCOperand {
enum MachineOperandType : unsigned char {
kInvalid, ///< Uninitialized.
kRegister, ///< Register operand.
kImmediate, ///< Immediate operand.
kFPImmediate, ///< Floating-point immediate operand.
kExpr, ///< Relocatable immediate operand.
kInst ///< Sub-instruction operand.
};
MachineOperandType Kind;
union {
unsigned RegVal;
int64_t ImmVal;
double FPImmVal;
const MCExpr *ExprVal;
const MCInst *InstVal;
};
public:
MCOperand() : Kind(kInvalid), FPImmVal(0.0) {}
bool isValid() const { return Kind != kInvalid; }
bool isReg() const { return Kind == kRegister; }
bool isImm() const { return Kind == kImmediate; }
bool isFPImm() const { return Kind == kFPImmediate; }
bool isExpr() const { return Kind == kExpr; }
bool isInst() const { return Kind == kInst; }
/// \brief Returns the register number.
unsigned getReg() const {
assert(isReg() && "This is not a register operand!");
return RegVal;
}
/// \brief Set the register number.
void setReg(unsigned Reg) {
assert(isReg() && "This is not a register operand!");
RegVal = Reg;
}
int64_t getImm() const {
assert(isImm() && "This is not an immediate");
return ImmVal;
}
void setImm(int64_t Val) {
assert(isImm() && "This is not an immediate");
ImmVal = Val;
}
double getFPImm() const {
assert(isFPImm() && "This is not an FP immediate");
return FPImmVal;
}
void setFPImm(double Val) {
assert(isFPImm() && "This is not an FP immediate");
FPImmVal = Val;
}
const MCExpr *getExpr() const {
assert(isExpr() && "This is not an expression");
return ExprVal;
}
void setExpr(const MCExpr *Val) {
assert(isExpr() && "This is not an expression");
ExprVal = Val;
}
const MCInst *getInst() const {
assert(isInst() && "This is not a sub-instruction");
return InstVal;
}
void setInst(const MCInst *Val) {
assert(isInst() && "This is not a sub-instruction");
InstVal = Val;
}
static MCOperand createReg(unsigned Reg) {
MCOperand Op;
Op.Kind = kRegister;
Op.RegVal = Reg;
return Op;
}
static MCOperand createImm(int64_t Val) {
MCOperand Op;
Op.Kind = kImmediate;
Op.ImmVal = Val;
return Op;
}
static MCOperand createFPImm(double Val) {
MCOperand Op;
Op.Kind = kFPImmediate;
Op.FPImmVal = Val;
return Op;
}
static MCOperand createExpr(const MCExpr *Val) {
MCOperand Op;
Op.Kind = kExpr;
Op.ExprVal = Val;
return Op;
}
static MCOperand createInst(const MCInst *Val) {
MCOperand Op;
Op.Kind = kInst;
Op.InstVal = Val;
return Op;
}
void print(raw_ostream &OS) const;
void dump() const;
};
template <> struct isPodLike<MCOperand> { static const bool value = true; };
/// \brief Instances of this class represent a single low-level machine
/// instruction.
class MCInst {
unsigned Opcode;
SMLoc Loc;
SmallVector<MCOperand, 8> Operands;
public:
MCInst() : Opcode(0) {}
void setOpcode(unsigned Op) { Opcode = Op; }
unsigned getOpcode() const { return Opcode; }
void setLoc(SMLoc loc) { Loc = loc; }
SMLoc getLoc() const { return Loc; }
const MCOperand &getOperand(unsigned i) const { return Operands[i]; }
MCOperand &getOperand(unsigned i) { return Operands[i]; }
unsigned getNumOperands() const { return Operands.size(); }
void addOperand(const MCOperand &Op) { Operands.push_back(Op); }
typedef SmallVectorImpl<MCOperand>::iterator iterator;
typedef SmallVectorImpl<MCOperand>::const_iterator const_iterator;
void clear() { Operands.clear(); }
void erase(iterator I) { Operands.erase(I); }
size_t size() const { return Operands.size(); }
iterator begin() { return Operands.begin(); }
const_iterator begin() const { return Operands.begin(); }
iterator end() { return Operands.end(); }
const_iterator end() const { return Operands.end(); }
iterator insert(iterator I, const MCOperand &Op) {
return Operands.insert(I, Op);
}
void print(raw_ostream &OS) const;
void dump() const;
/// \brief Dump the MCInst as prettily as possible using the additional MC
/// structures, if given. Operators are separated by the \p Separator
/// string.
void dump_pretty(raw_ostream &OS, const MCInstPrinter *Printer = nullptr,
StringRef Separator = " ") const;
};
inline raw_ostream& operator<<(raw_ostream &OS, const MCOperand &MO) {
MO.print(OS);
return OS;
}
inline raw_ostream& operator<<(raw_ostream &OS, const MCInst &MI) {
MI.print(OS);
return OS;
}
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCInstrDesc.h | //===-- llvm/MC/MCInstrDesc.h - Instruction Descriptors -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the MCOperandInfo and MCInstrDesc classes, which
// are used to describe target instructions and their operands.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCINSTRDESC_H
#define LLVM_MC_MCINSTRDESC_H
#include "llvm/Support/DataTypes.h"
#include <string>
namespace llvm {
class MCInst;
class MCRegisterInfo;
class MCSubtargetInfo;
class FeatureBitset;
//===----------------------------------------------------------------------===//
// Machine Operand Flags and Description
//===----------------------------------------------------------------------===//
namespace MCOI {
// Operand constraints
enum OperandConstraint {
TIED_TO = 0, // Must be allocated the same register as.
EARLY_CLOBBER // Operand is an early clobber register operand
};
/// \brief These are flags set on operands, but should be considered
/// private, all access should go through the MCOperandInfo accessors.
/// See the accessors for a description of what these are.
enum OperandFlags { LookupPtrRegClass = 0, Predicate, OptionalDef };
/// \brief Operands are tagged with one of the values of this enum.
enum OperandType {
OPERAND_UNKNOWN = 0,
OPERAND_IMMEDIATE = 1,
OPERAND_REGISTER = 2,
OPERAND_MEMORY = 3,
OPERAND_PCREL = 4,
OPERAND_FIRST_TARGET = 5
};
}
/// \brief This holds information about one operand of a machine instruction,
/// indicating the register class for register operands, etc.
class MCOperandInfo {
public:
/// \brief This specifies the register class enumeration of the operand
/// if the operand is a register. If isLookupPtrRegClass is set, then this is
/// an index that is passed to TargetRegisterInfo::getPointerRegClass(x) to
/// get a dynamic register class.
int16_t RegClass;
/// \brief These are flags from the MCOI::OperandFlags enum.
uint8_t Flags;
/// \brief Information about the type of the operand.
uint8_t OperandType;
/// \brief The lower 16 bits are used to specify which constraints are set.
/// The higher 16 bits are used to specify the value of constraints (4 bits
/// each).
uint32_t Constraints;
/// \brief Set if this operand is a pointer value and it requires a callback
/// to look up its register class.
bool isLookupPtrRegClass() const {
return Flags & (1 << MCOI::LookupPtrRegClass);
}
/// \brief Set if this is one of the operands that made up of the predicate
/// operand that controls an isPredicable() instruction.
bool isPredicate() const { return Flags & (1 << MCOI::Predicate); }
/// \brief Set if this operand is a optional def.
bool isOptionalDef() const { return Flags & (1 << MCOI::OptionalDef); }
};
//===----------------------------------------------------------------------===//
// Machine Instruction Flags and Description
// //
///////////////////////////////////////////////////////////////////////////////
namespace MCID {
/// \brief These should be considered private to the implementation of the
/// MCInstrDesc class. Clients should use the predicate methods on MCInstrDesc,
/// not use these directly. These all correspond to bitfields in the
/// MCInstrDesc::Flags field.
enum Flag {
Variadic = 0,
HasOptionalDef,
Pseudo,
Return,
Call,
Barrier,
Terminator,
Branch,
IndirectBranch,
Compare,
MoveImm,
Bitcast,
Select,
DelaySlot,
FoldableAsLoad,
MayLoad,
MayStore,
Predicable,
NotDuplicable,
UnmodeledSideEffects,
Commutable,
ConvertibleTo3Addr,
UsesCustomInserter,
HasPostISelHook,
Rematerializable,
CheapAsAMove,
ExtraSrcRegAllocReq,
ExtraDefRegAllocReq,
RegSequence,
ExtractSubreg,
InsertSubreg,
Convergent
};
}
/// \brief Describe properties that are true of each instruction in the target
/// description file. This captures information about side effects, register
/// use and many other things. There is one instance of this struct for each
/// target instruction class, and the MachineInstr class points to this struct
/// directly to describe itself.
class MCInstrDesc {
public:
unsigned short Opcode; // The opcode number
unsigned short NumOperands; // Num of args (may be more if variable_ops)
unsigned char NumDefs; // Num of args that are definitions
unsigned char Size; // Number of bytes in encoding.
unsigned short SchedClass; // enum identifying instr sched class
uint64_t Flags; // Flags identifying machine instr class
uint64_t TSFlags; // Target Specific Flag values
const uint16_t *ImplicitUses; // Registers implicitly read by this instr
const uint16_t *ImplicitDefs; // Registers implicitly defined by this instr
const MCOperandInfo *OpInfo; // 'NumOperands' entries about operands
// Subtarget feature that this is deprecated on, if any
// -1 implies this is not deprecated by any single feature. It may still be
// deprecated due to a "complex" reason, below.
int64_t DeprecatedFeature;
// A complex method to determine is a certain is deprecated or not, and return
// the reason for deprecation.
bool (*ComplexDeprecationInfo)(MCInst &, const MCSubtargetInfo &,
std::string &);
/// \brief Returns the value of the specific constraint if
/// it is set. Returns -1 if it is not set.
int getOperandConstraint(unsigned OpNum,
MCOI::OperandConstraint Constraint) const {
if (OpNum < NumOperands &&
(OpInfo[OpNum].Constraints & (1 << Constraint))) {
unsigned Pos = 16 + Constraint * 4;
return (int)(OpInfo[OpNum].Constraints >> Pos) & 0xf;
}
return -1;
}
/// \brief Returns true if a certain instruction is deprecated and if so
/// returns the reason in \p Info.
bool getDeprecatedInfo(MCInst &MI, const MCSubtargetInfo &STI,
std::string &Info) const;
/// \brief Return the opcode number for this descriptor.
unsigned getOpcode() const { return Opcode; }
/// \brief Return the number of declared MachineOperands for this
/// MachineInstruction. Note that variadic (isVariadic() returns true)
/// instructions may have additional operands at the end of the list, and note
/// that the machine instruction may include implicit register def/uses as
/// well.
unsigned getNumOperands() const { return NumOperands; }
/// \brief Return the number of MachineOperands that are register
/// definitions. Register definitions always occur at the start of the
/// machine operand list. This is the number of "outs" in the .td file,
/// and does not include implicit defs.
unsigned getNumDefs() const { return NumDefs; }
/// \brief Return flags of this instruction.
unsigned getFlags() const { return Flags; }
/// \brief Return true if this instruction can have a variable number of
/// operands. In this case, the variable operands will be after the normal
/// operands but before the implicit definitions and uses (if any are
/// present).
bool isVariadic() const { return Flags & (1 << MCID::Variadic); }
/// \brief Set if this instruction has an optional definition, e.g.
/// ARM instructions which can set condition code if 's' bit is set.
bool hasOptionalDef() const { return Flags & (1 << MCID::HasOptionalDef); }
/// \brief Return true if this is a pseudo instruction that doesn't
/// correspond to a real machine instruction.
bool isPseudo() const { return Flags & (1 << MCID::Pseudo); }
/// \brief Return true if the instruction is a return.
bool isReturn() const { return Flags & (1 << MCID::Return); }
/// \brief Return true if the instruction is a call.
bool isCall() const { return Flags & (1 << MCID::Call); }
/// \brief Returns true if the specified instruction stops control flow
/// from executing the instruction immediately following it. Examples include
/// unconditional branches and return instructions.
bool isBarrier() const { return Flags & (1 << MCID::Barrier); }
/// \brief Returns true if this instruction part of the terminator for
/// a basic block. Typically this is things like return and branch
/// instructions.
///
/// Various passes use this to insert code into the bottom of a basic block,
/// but before control flow occurs.
bool isTerminator() const { return Flags & (1 << MCID::Terminator); }
/// \brief Returns true if this is a conditional, unconditional, or
/// indirect branch. Predicates below can be used to discriminate between
/// these cases, and the TargetInstrInfo::AnalyzeBranch method can be used to
/// get more information.
bool isBranch() const { return Flags & (1 << MCID::Branch); }
/// \brief Return true if this is an indirect branch, such as a
/// branch through a register.
bool isIndirectBranch() const { return Flags & (1 << MCID::IndirectBranch); }
/// \brief Return true if this is a branch which may fall
/// through to the next instruction or may transfer control flow to some other
/// block. The TargetInstrInfo::AnalyzeBranch method can be used to get more
/// information about this branch.
bool isConditionalBranch() const {
return isBranch() && !isBarrier() && !isIndirectBranch();
}
/// \brief Return true if this is a branch which always
/// transfers control flow to some other block. The
/// TargetInstrInfo::AnalyzeBranch method can be used to get more information
/// about this branch.
bool isUnconditionalBranch() const {
return isBranch() && isBarrier() && !isIndirectBranch();
}
/// \brief Return true if this is a branch or an instruction which directly
/// writes to the program counter. Considered 'may' affect rather than
/// 'does' affect as things like predication are not taken into account.
bool mayAffectControlFlow(const MCInst &MI, const MCRegisterInfo &RI) const;
/// \brief Return true if this instruction has a predicate operand
/// that controls execution. It may be set to 'always', or may be set to other
/// values. There are various methods in TargetInstrInfo that can be used to
/// control and modify the predicate in this instruction.
bool isPredicable() const { return Flags & (1 << MCID::Predicable); }
/// \brief Return true if this instruction is a comparison.
bool isCompare() const { return Flags & (1 << MCID::Compare); }
/// \brief Return true if this instruction is a move immediate
/// (including conditional moves) instruction.
bool isMoveImmediate() const { return Flags & (1 << MCID::MoveImm); }
/// \brief Return true if this instruction is a bitcast instruction.
bool isBitcast() const { return Flags & (1 << MCID::Bitcast); }
/// \brief Return true if this is a select instruction.
bool isSelect() const { return Flags & (1 << MCID::Select); }
/// \brief Return true if this instruction cannot be safely
/// duplicated. For example, if the instruction has a unique labels attached
/// to it, duplicating it would cause multiple definition errors.
bool isNotDuplicable() const { return Flags & (1 << MCID::NotDuplicable); }
/// \brief Returns true if the specified instruction has a delay slot which
/// must be filled by the code generator.
bool hasDelaySlot() const { return Flags & (1 << MCID::DelaySlot); }
/// \brief Return true for instructions that can be folded as memory operands
/// in other instructions. The most common use for this is instructions that
/// are simple loads from memory that don't modify the loaded value in any
/// way, but it can also be used for instructions that can be expressed as
/// constant-pool loads, such as V_SETALLONES on x86, to allow them to be
/// folded when it is beneficial. This should only be set on instructions
/// that return a value in their only virtual register definition.
bool canFoldAsLoad() const { return Flags & (1 << MCID::FoldableAsLoad); }
/// \brief Return true if this instruction behaves
/// the same way as the generic REG_SEQUENCE instructions.
/// E.g., on ARM,
/// dX VMOVDRR rY, rZ
/// is equivalent to
/// dX = REG_SEQUENCE rY, ssub_0, rZ, ssub_1.
///
/// Note that for the optimizers to be able to take advantage of
/// this property, TargetInstrInfo::getRegSequenceLikeInputs has to be
/// override accordingly.
bool isRegSequenceLike() const { return Flags & (1 << MCID::RegSequence); }
/// \brief Return true if this instruction behaves
/// the same way as the generic EXTRACT_SUBREG instructions.
/// E.g., on ARM,
/// rX, rY VMOVRRD dZ
/// is equivalent to two EXTRACT_SUBREG:
/// rX = EXTRACT_SUBREG dZ, ssub_0
/// rY = EXTRACT_SUBREG dZ, ssub_1
///
/// Note that for the optimizers to be able to take advantage of
/// this property, TargetInstrInfo::getExtractSubregLikeInputs has to be
/// override accordingly.
bool isExtractSubregLike() const {
return Flags & (1 << MCID::ExtractSubreg);
}
/// \brief Return true if this instruction behaves
/// the same way as the generic INSERT_SUBREG instructions.
/// E.g., on ARM,
/// dX = VSETLNi32 dY, rZ, Imm
/// is equivalent to a INSERT_SUBREG:
/// dX = INSERT_SUBREG dY, rZ, translateImmToSubIdx(Imm)
///
/// Note that for the optimizers to be able to take advantage of
/// this property, TargetInstrInfo::getInsertSubregLikeInputs has to be
/// override accordingly.
bool isInsertSubregLike() const { return Flags & (1 << MCID::InsertSubreg); }
/// \brief Return true if this instruction is convergent.
///
/// Convergent instructions may only be moved to locations that are
/// control-equivalent to their original positions.
bool isConvergent() const { return Flags & (1 << MCID::Convergent); }
//===--------------------------------------------------------------------===//
// Side Effect Analysis
//===--------------------------------------------------------------------===//
/// \brief Return true if this instruction could possibly read memory.
/// Instructions with this flag set are not necessarily simple load
/// instructions, they may load a value and modify it, for example.
bool mayLoad() const { return Flags & (1 << MCID::MayLoad); }
/// \brief Return true if this instruction could possibly modify memory.
/// Instructions with this flag set are not necessarily simple store
/// instructions, they may store a modified value based on their operands, or
/// may not actually modify anything, for example.
bool mayStore() const { return Flags & (1 << MCID::MayStore); }
/// \brief Return true if this instruction has side
/// effects that are not modeled by other flags. This does not return true
/// for instructions whose effects are captured by:
///
/// 1. Their operand list and implicit definition/use list. Register use/def
/// info is explicit for instructions.
/// 2. Memory accesses. Use mayLoad/mayStore.
/// 3. Calling, branching, returning: use isCall/isReturn/isBranch.
///
/// Examples of side effects would be modifying 'invisible' machine state like
/// a control register, flushing a cache, modifying a register invisible to
/// LLVM, etc.
bool hasUnmodeledSideEffects() const {
return Flags & (1 << MCID::UnmodeledSideEffects);
}
//===--------------------------------------------------------------------===//
// Flags that indicate whether an instruction can be modified by a method.
//===--------------------------------------------------------------------===//
/// \brief Return true if this may be a 2- or 3-address instruction (of the
/// form "X = op Y, Z, ..."), which produces the same result if Y and Z are
/// exchanged. If this flag is set, then the
/// TargetInstrInfo::commuteInstruction method may be used to hack on the
/// instruction.
///
/// Note that this flag may be set on instructions that are only commutable
/// sometimes. In these cases, the call to commuteInstruction will fail.
/// Also note that some instructions require non-trivial modification to
/// commute them.
bool isCommutable() const { return Flags & (1 << MCID::Commutable); }
/// \brief Return true if this is a 2-address instruction which can be changed
/// into a 3-address instruction if needed. Doing this transformation can be
/// profitable in the register allocator, because it means that the
/// instruction can use a 2-address form if possible, but degrade into a less
/// efficient form if the source and dest register cannot be assigned to the
/// same register. For example, this allows the x86 backend to turn a "shl
/// reg, 3" instruction into an LEA instruction, which is the same speed as
/// the shift but has bigger code size.
///
/// If this returns true, then the target must implement the
/// TargetInstrInfo::convertToThreeAddress method for this instruction, which
/// is allowed to fail if the transformation isn't valid for this specific
/// instruction (e.g. shl reg, 4 on x86).
///
bool isConvertibleTo3Addr() const {
return Flags & (1 << MCID::ConvertibleTo3Addr);
}
/// \brief Return true if this instruction requires custom insertion support
/// when the DAG scheduler is inserting it into a machine basic block. If
/// this is true for the instruction, it basically means that it is a pseudo
/// instruction used at SelectionDAG time that is expanded out into magic code
/// by the target when MachineInstrs are formed.
///
/// If this is true, the TargetLoweringInfo::InsertAtEndOfBasicBlock method
/// is used to insert this into the MachineBasicBlock.
bool usesCustomInsertionHook() const {
return Flags & (1 << MCID::UsesCustomInserter);
}
/// \brief Return true if this instruction requires *adjustment* after
/// instruction selection by calling a target hook. For example, this can be
/// used to fill in ARM 's' optional operand depending on whether the
/// conditional flag register is used.
bool hasPostISelHook() const { return Flags & (1 << MCID::HasPostISelHook); }
/// \brief Returns true if this instruction is a candidate for remat. This
/// flag is only used in TargetInstrInfo method isTriviallyRematerializable.
///
/// If this flag is set, the isReallyTriviallyReMaterializable()
/// or isReallyTriviallyReMaterializableGeneric methods are called to verify
/// the instruction is really rematable.
bool isRematerializable() const {
return Flags & (1 << MCID::Rematerializable);
}
/// \brief Returns true if this instruction has the same cost (or less) than a
/// move instruction. This is useful during certain types of optimizations
/// (e.g., remat during two-address conversion or machine licm) where we would
/// like to remat or hoist the instruction, but not if it costs more than
/// moving the instruction into the appropriate register. Note, we are not
/// marking copies from and to the same register class with this flag.
///
/// This method could be called by interface TargetInstrInfo::isAsCheapAsAMove
/// for different subtargets.
bool isAsCheapAsAMove() const { return Flags & (1 << MCID::CheapAsAMove); }
/// \brief Returns true if this instruction source operands have special
/// register allocation requirements that are not captured by the operand
/// register classes. e.g. ARM::STRD's two source registers must be an even /
/// odd pair, ARM::STM registers have to be in ascending order. Post-register
/// allocation passes should not attempt to change allocations for sources of
/// instructions with this flag.
bool hasExtraSrcRegAllocReq() const {
return Flags & (1 << MCID::ExtraSrcRegAllocReq);
}
/// \brief Returns true if this instruction def operands have special register
/// allocation requirements that are not captured by the operand register
/// classes. e.g. ARM::LDRD's two def registers must be an even / odd pair,
/// ARM::LDM registers have to be in ascending order. Post-register
/// allocation passes should not attempt to change allocations for definitions
/// of instructions with this flag.
bool hasExtraDefRegAllocReq() const {
return Flags & (1 << MCID::ExtraDefRegAllocReq);
}
/// \brief Return a list of registers that are potentially read by any
/// instance of this machine instruction. For example, on X86, the "adc"
/// instruction adds two register operands and adds the carry bit in from the
/// flags register. In this case, the instruction is marked as implicitly
/// reading the flags. Likewise, the variable shift instruction on X86 is
/// marked as implicitly reading the 'CL' register, which it always does.
///
/// This method returns null if the instruction has no implicit uses.
const uint16_t *getImplicitUses() const { return ImplicitUses; }
/// \brief Return the number of implicit uses this instruction has.
unsigned getNumImplicitUses() const {
if (!ImplicitUses)
return 0;
unsigned i = 0;
for (; ImplicitUses[i]; ++i) /*empty*/
;
return i;
}
/// \brief Return a list of registers that are potentially written by any
/// instance of this machine instruction. For example, on X86, many
/// instructions implicitly set the flags register. In this case, they are
/// marked as setting the FLAGS. Likewise, many instructions always deposit
/// their result in a physical register. For example, the X86 divide
/// instruction always deposits the quotient and remainder in the EAX/EDX
/// registers. For that instruction, this will return a list containing the
/// EAX/EDX/EFLAGS registers.
///
/// This method returns null if the instruction has no implicit defs.
const uint16_t *getImplicitDefs() const { return ImplicitDefs; }
/// \brief Return the number of implicit defs this instruct has.
unsigned getNumImplicitDefs() const {
if (!ImplicitDefs)
return 0;
unsigned i = 0;
for (; ImplicitDefs[i]; ++i) /*empty*/
;
return i;
}
/// \brief Return true if this instruction implicitly
/// uses the specified physical register.
bool hasImplicitUseOfPhysReg(unsigned Reg) const {
if (const uint16_t *ImpUses = ImplicitUses)
for (; *ImpUses; ++ImpUses)
if (*ImpUses == Reg)
return true;
return false;
}
/// \brief Return true if this instruction implicitly
/// defines the specified physical register.
bool hasImplicitDefOfPhysReg(unsigned Reg,
const MCRegisterInfo *MRI = nullptr) const;
/// \brief Return the scheduling class for this instruction. The
/// scheduling class is an index into the InstrItineraryData table. This
/// returns zero if there is no known scheduling information for the
/// instruction.
unsigned getSchedClass() const { return SchedClass; }
/// \brief Return the number of bytes in the encoding of this instruction,
/// or zero if the encoding size cannot be known from the opcode.
unsigned getSize() const { return Size; }
/// \brief Find the index of the first operand in the
/// operand list that is used to represent the predicate. It returns -1 if
/// none is found.
int findFirstPredOperandIdx() const {
if (isPredicable()) {
for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
if (OpInfo[i].isPredicate())
return i;
}
return -1;
}
private:
/// \brief Return true if this instruction defines the specified physical
/// register, either explicitly or implicitly.
bool hasDefOfPhysReg(const MCInst &MI, unsigned Reg,
const MCRegisterInfo &RI) const;
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCSubtargetInfo.h | //==-- llvm/MC/MCSubtargetInfo.h - Subtarget Information ---------*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file describes the subtarget options of a Target machine.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCSUBTARGETINFO_H
#define LLVM_MC_MCSUBTARGETINFO_H
#include "llvm/MC/MCInstrItineraries.h"
#include "llvm/MC/SubtargetFeature.h"
#include <string>
namespace llvm {
class StringRef;
// //
///////////////////////////////////////////////////////////////////////////////
///
/// MCSubtargetInfo - Generic base class for all target subtargets.
///
class MCSubtargetInfo {
Triple TargetTriple; // Target triple
std::string CPU; // CPU being targeted.
ArrayRef<SubtargetFeatureKV> ProcFeatures; // Processor feature list
ArrayRef<SubtargetFeatureKV> ProcDesc; // Processor descriptions
// Scheduler machine model
const SubtargetInfoKV *ProcSchedModels;
const MCWriteProcResEntry *WriteProcResTable;
const MCWriteLatencyEntry *WriteLatencyTable;
const MCReadAdvanceEntry *ReadAdvanceTable;
const MCSchedModel *CPUSchedModel;
const InstrStage *Stages; // Instruction itinerary stages
const unsigned *OperandCycles; // Itinerary operand cycles
const unsigned *ForwardingPaths; // Forwarding paths
FeatureBitset FeatureBits; // Feature bits for current CPU + FS
MCSubtargetInfo() = delete;
MCSubtargetInfo &operator=(MCSubtargetInfo &&) = delete;
MCSubtargetInfo &operator=(const MCSubtargetInfo &) = delete;
public:
MCSubtargetInfo(const MCSubtargetInfo &) = default;
MCSubtargetInfo(const Triple &TT, StringRef CPU, StringRef FS,
ArrayRef<SubtargetFeatureKV> PF,
ArrayRef<SubtargetFeatureKV> PD,
const SubtargetInfoKV *ProcSched,
const MCWriteProcResEntry *WPR, const MCWriteLatencyEntry *WL,
const MCReadAdvanceEntry *RA, const InstrStage *IS,
const unsigned *OC, const unsigned *FP);
/// getTargetTriple - Return the target triple string.
const Triple &getTargetTriple() const { return TargetTriple; }
/// getCPU - Return the CPU string.
StringRef getCPU() const {
return CPU;
}
/// getFeatureBits - Return the feature bits.
///
const FeatureBitset& getFeatureBits() const {
return FeatureBits;
}
/// setFeatureBits - Set the feature bits.
///
void setFeatureBits(const FeatureBitset &FeatureBits_) {
FeatureBits = FeatureBits_;
}
protected:
/// Initialize the scheduling model and feature bits.
///
/// FIXME: Find a way to stick this in the constructor, since it should only
/// be called during initialization.
void InitMCProcessorInfo(StringRef CPU, StringRef FS);
public:
/// Set the features to the default for the given CPU.
void setDefaultFeatures(StringRef CPU);
/// ToggleFeature - Toggle a feature and returns the re-computed feature
/// bits. This version does not change the implied bits.
FeatureBitset ToggleFeature(uint64_t FB);
/// ToggleFeature - Toggle a feature and returns the re-computed feature
/// bits. This version does not change the implied bits.
FeatureBitset ToggleFeature(const FeatureBitset& FB);
/// ToggleFeature - Toggle a set of features and returns the re-computed
/// feature bits. This version will also change all implied bits.
FeatureBitset ToggleFeature(StringRef FS);
/// Apply a feature flag and return the re-computed feature bits, including
/// all feature bits implied by the flag.
FeatureBitset ApplyFeatureFlag(StringRef FS);
/// getSchedModelForCPU - Get the machine model of a CPU.
///
const MCSchedModel &getSchedModelForCPU(StringRef CPU) const;
/// Get the machine model for this subtarget's CPU.
const MCSchedModel &getSchedModel() const { return *CPUSchedModel; }
/// Return an iterator at the first process resource consumed by the given
/// scheduling class.
const MCWriteProcResEntry *getWriteProcResBegin(
const MCSchedClassDesc *SC) const {
return &WriteProcResTable[SC->WriteProcResIdx];
}
const MCWriteProcResEntry *getWriteProcResEnd(
const MCSchedClassDesc *SC) const {
return getWriteProcResBegin(SC) + SC->NumWriteProcResEntries;
}
const MCWriteLatencyEntry *getWriteLatencyEntry(const MCSchedClassDesc *SC,
unsigned DefIdx) const {
assert(DefIdx < SC->NumWriteLatencyEntries &&
"MachineModel does not specify a WriteResource for DefIdx");
return &WriteLatencyTable[SC->WriteLatencyIdx + DefIdx];
}
int getReadAdvanceCycles(const MCSchedClassDesc *SC, unsigned UseIdx,
unsigned WriteResID) const {
// TODO: The number of read advance entries in a class can be significant
// (~50). Consider compressing the WriteID into a dense ID of those that are
// used by ReadAdvance and representing them as a bitset.
for (const MCReadAdvanceEntry *I = &ReadAdvanceTable[SC->ReadAdvanceIdx],
*E = I + SC->NumReadAdvanceEntries; I != E; ++I) {
if (I->UseIdx < UseIdx)
continue;
if (I->UseIdx > UseIdx)
break;
// Find the first WriteResIdx match, which has the highest cycle count.
if (!I->WriteResourceID || I->WriteResourceID == WriteResID) {
return I->Cycles;
}
}
return 0;
}
/// getInstrItineraryForCPU - Get scheduling itinerary of a CPU.
///
InstrItineraryData getInstrItineraryForCPU(StringRef CPU) const;
/// Initialize an InstrItineraryData instance.
void initInstrItins(InstrItineraryData &InstrItins) const;
/// Check whether the CPU string is valid.
bool isCPUStringValid(StringRef CPU) const {
auto Found = std::find_if(ProcDesc.begin(), ProcDesc.end(),
[=](const SubtargetFeatureKV &KV) {
return CPU == KV.Key;
});
return Found != ProcDesc.end();
}
};
} // End llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCLabel.h | //===- MCLabel.h - Machine Code Directional Local Labels --------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declaration of the MCLabel class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCLABEL_H
#define LLVM_MC_MCLABEL_H
#include "llvm/Support/Compiler.h"
namespace llvm {
class MCContext;
class raw_ostream;
/// \brief Instances of this class represent a label name in the MC file,
/// and MCLabel are created and uniqued by the MCContext class. MCLabel
/// should only be constructed for valid instances in the object file.
class MCLabel {
// \brief The instance number of this Directional Local Label.
unsigned Instance;
private: // MCContext creates and uniques these.
friend class MCContext;
MCLabel(unsigned instance) : Instance(instance) {}
MCLabel(const MCLabel &) = delete;
void operator=(const MCLabel &) = delete;
public:
/// \brief Get the current instance of this Directional Local Label.
unsigned getInstance() const { return Instance; }
/// \brief Increment the current instance of this Directional Local Label.
unsigned incInstance() { return ++Instance; }
/// \brief Print the value to the stream \p OS.
void print(raw_ostream &OS) const;
/// \brief Print the value to stderr.
void dump() const;
};
inline raw_ostream &operator<<(raw_ostream &OS, const MCLabel &Label) {
Label.print(OS);
return OS;
}
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/YAML.h |
#ifndef LLVM_MC_YAML_H
#define LLVM_MC_YAML_H
#include "llvm/Support/YAMLTraits.h"
namespace llvm {
namespace yaml {
/// \brief Specialized YAMLIO scalar type for representing a binary blob.
///
/// A typical use case would be to represent the content of a section in a
/// binary file.
/// This class has custom YAMLIO traits for convenient reading and writing.
/// It renders as a string of hex digits in a YAML file.
/// For example, it might render as `DEADBEEFCAFEBABE` (YAML does not
/// require the quotation marks, so for simplicity when outputting they are
/// omitted).
/// When reading, any string whose content is an even number of hex digits
/// will be accepted.
/// For example, all of the following are acceptable:
/// `DEADBEEF`, `"DeADbEeF"`, `"\x44EADBEEF"` (Note: '\x44' == 'D')
///
/// A significant advantage of using this class is that it never allocates
/// temporary strings or buffers for any of its functionality.
///
/// Example:
///
/// The YAML mapping:
/// \code
/// Foo: DEADBEEFCAFEBABE
/// \endcode
///
/// Could be modeled in YAMLIO by the struct:
/// \code
/// struct FooHolder {
/// BinaryRef Foo;
/// };
/// namespace llvm {
/// namespace yaml {
/// template <>
/// struct MappingTraits<FooHolder> {
/// static void mapping(IO &IO, FooHolder &FH) {
/// IO.mapRequired("Foo", FH.Foo);
/// }
/// };
/// } // end namespace yaml
/// } // end namespace llvm
/// \endcode
class BinaryRef {
friend bool operator==(const BinaryRef &LHS, const BinaryRef &RHS);
/// \brief Either raw binary data, or a string of hex bytes (must always
/// be an even number of characters).
ArrayRef<uint8_t> Data;
/// \brief Discriminator between the two states of the `Data` member.
bool DataIsHexString;
public:
BinaryRef(ArrayRef<uint8_t> Data) : Data(Data), DataIsHexString(false) {}
BinaryRef(StringRef Data)
: Data(reinterpret_cast<const uint8_t *>(Data.data()), Data.size()),
DataIsHexString(true) {}
BinaryRef() : DataIsHexString(true) {}
/// \brief The number of bytes that are represented by this BinaryRef.
/// This is the number of bytes that writeAsBinary() will write.
ArrayRef<uint8_t>::size_type binary_size() const {
if (DataIsHexString)
return Data.size() / 2;
return Data.size();
}
/// \brief Write the contents (regardless of whether it is binary or a
/// hex string) as binary to the given raw_ostream.
void writeAsBinary(raw_ostream &OS) const;
/// \brief Write the contents (regardless of whether it is binary or a
/// hex string) as hex to the given raw_ostream.
///
/// For example, a possible output could be `DEADBEEFCAFEBABE`.
void writeAsHex(raw_ostream &OS) const;
};
inline bool operator==(const BinaryRef &LHS, const BinaryRef &RHS) {
// Special case for default constructed BinaryRef.
if (LHS.Data.empty() && RHS.Data.empty())
return true;
return LHS.DataIsHexString == RHS.DataIsHexString && LHS.Data == RHS.Data;
}
template <> struct ScalarTraits<BinaryRef> {
static void output(const BinaryRef &, void *, llvm::raw_ostream &);
static StringRef input(StringRef, void *, BinaryRef &);
static bool mustQuote(StringRef S) { return needsQuotes(S); }
};
}
}
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCELFObjectWriter.h | //===-- llvm/MC/MCELFObjectWriter.h - ELF Object Writer ---------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCELFOBJECTWRITER_H
#define LLVM_MC_MCELFOBJECTWRITER_H
#include "llvm/ADT/Triple.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/ELF.h"
#include <vector>
namespace llvm {
class MCAssembler;
class MCFixup;
class MCFragment;
class MCObjectWriter;
class MCSymbol;
class MCSymbolELF;
class MCValue;
class raw_pwrite_stream;
struct ELFRelocationEntry {
uint64_t Offset; // Where is the relocation.
const MCSymbolELF *Symbol; // The symbol to relocate with.
unsigned Type; // The type of the relocation.
uint64_t Addend; // The addend to use.
ELFRelocationEntry(uint64_t Offset, const MCSymbolELF *Symbol, unsigned Type,
uint64_t Addend)
: Offset(Offset), Symbol(Symbol), Type(Type), Addend(Addend) {}
};
class MCELFObjectTargetWriter {
const uint8_t OSABI;
const uint16_t EMachine;
const unsigned HasRelocationAddend : 1;
const unsigned Is64Bit : 1;
const unsigned IsN64 : 1;
protected:
MCELFObjectTargetWriter(bool Is64Bit_, uint8_t OSABI_,
uint16_t EMachine_, bool HasRelocationAddend,
bool IsN64=false);
public:
static uint8_t getOSABI(Triple::OSType OSType) {
switch (OSType) {
case Triple::CloudABI:
return ELF::ELFOSABI_CLOUDABI;
case Triple::PS4:
case Triple::FreeBSD:
return ELF::ELFOSABI_FREEBSD;
case Triple::Linux:
return ELF::ELFOSABI_LINUX;
default:
return ELF::ELFOSABI_NONE;
}
}
virtual ~MCELFObjectTargetWriter() {}
virtual unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
bool IsPCRel) const = 0;
virtual bool needsRelocateWithSymbol(const MCSymbol &Sym,
unsigned Type) const;
virtual void sortRelocs(const MCAssembler &Asm,
std::vector<ELFRelocationEntry> &Relocs);
/// \name Accessors
/// @{
uint8_t getOSABI() const { return OSABI; }
uint16_t getEMachine() const { return EMachine; }
bool hasRelocationAddend() const { return HasRelocationAddend; }
bool is64Bit() const { return Is64Bit; }
bool isN64() const { return IsN64; }
/// @}
// Instead of changing everyone's API we pack the N64 Type fields
// into the existing 32 bit data unsigned.
#define R_TYPE_SHIFT 0
#define R_TYPE_MASK 0xffffff00
#define R_TYPE2_SHIFT 8
#define R_TYPE2_MASK 0xffff00ff
#define R_TYPE3_SHIFT 16
#define R_TYPE3_MASK 0xff00ffff
#define R_SSYM_SHIFT 24
#define R_SSYM_MASK 0x00ffffff
// N64 relocation type accessors
uint8_t getRType(uint32_t Type) const {
return (unsigned)((Type >> R_TYPE_SHIFT) & 0xff);
}
uint8_t getRType2(uint32_t Type) const {
return (unsigned)((Type >> R_TYPE2_SHIFT) & 0xff);
}
uint8_t getRType3(uint32_t Type) const {
return (unsigned)((Type >> R_TYPE3_SHIFT) & 0xff);
}
uint8_t getRSsym(uint32_t Type) const {
return (unsigned)((Type >> R_SSYM_SHIFT) & 0xff);
}
// N64 relocation type setting
unsigned setRType(unsigned Value, unsigned Type) const {
return ((Type & R_TYPE_MASK) | ((Value & 0xff) << R_TYPE_SHIFT));
}
unsigned setRType2(unsigned Value, unsigned Type) const {
return (Type & R_TYPE2_MASK) | ((Value & 0xff) << R_TYPE2_SHIFT);
}
unsigned setRType3(unsigned Value, unsigned Type) const {
return (Type & R_TYPE3_MASK) | ((Value & 0xff) << R_TYPE3_SHIFT);
}
unsigned setRSsym(unsigned Value, unsigned Type) const {
return (Type & R_SSYM_MASK) | ((Value & 0xff) << R_SSYM_SHIFT);
}
};
/// \brief Construct a new ELF writer instance.
///
/// \param MOTW - The target specific ELF writer subclass.
/// \param OS - The stream to write to.
/// \returns The constructed object writer.
MCObjectWriter *createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
raw_pwrite_stream &OS,
bool IsLittleEndian);
} // End llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCTargetOptionsCommandFlags.h | //===-- MCTargetOptionsCommandFlags.h --------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains machine code-specific flags that are shared between
// different command line tools.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCTARGETOPTIONSCOMMANDFLAGS_H
#define LLVM_MC_MCTARGETOPTIONSCOMMANDFLAGS_H
#include "llvm/MC/MCTargetOptions.h"
#include "llvm/Support/CommandLine.h"
using namespace llvm;
cl::opt<MCTargetOptions::AsmInstrumentation> AsmInstrumentation(
"asm-instrumentation", cl::desc("Instrumentation of inline assembly and "
"assembly source files"),
cl::init(MCTargetOptions::AsmInstrumentationNone),
cl::values(clEnumValN(MCTargetOptions::AsmInstrumentationNone, "none",
"no instrumentation at all"),
clEnumValN(MCTargetOptions::AsmInstrumentationAddress, "address",
"instrument instructions with memory arguments"),
clEnumValEnd));
cl::opt<bool> RelaxAll("mc-relax-all",
cl::desc("When used with filetype=obj, "
"relax all fixups in the emitted object file"));
cl::opt<int> DwarfVersion("dwarf-version", cl::desc("Dwarf version"),
cl::init(0));
cl::opt<bool> ShowMCInst("asm-show-inst",
cl::desc("Emit internal instruction representation to "
"assembly file"));
cl::opt<std::string>
ABIName("target-abi", cl::Hidden,
cl::desc("The name of the ABI to be targeted from the backend."),
cl::init(""));
static inline MCTargetOptions InitMCTargetOptionsFromFlags() {
MCTargetOptions Options;
Options.SanitizeAddress =
(AsmInstrumentation == MCTargetOptions::AsmInstrumentationAddress);
Options.MCRelaxAll = RelaxAll;
Options.DwarfVersion = DwarfVersion;
Options.ShowMCInst = ShowMCInst;
Options.ABIName = ABIName;
return Options;
}
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCAsmLayout.h | //===- MCAsmLayout.h - Assembly Layout Object -------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCASMLAYOUT_H
#define LLVM_MC_MCASMLAYOUT_H
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
namespace llvm {
class MCAssembler;
class MCFragment;
class MCSection;
class MCSymbol;
/// Encapsulates the layout of an assembly file at a particular point in time.
///
/// Assembly may require computing multiple layouts for a particular assembly
/// file as part of the relaxation process. This class encapsulates the layout
/// at a single point in time in such a way that it is always possible to
/// efficiently compute the exact address of any symbol in the assembly file,
/// even during the relaxation process.
class MCAsmLayout {
MCAssembler &Assembler;
/// List of sections in layout order.
llvm::SmallVector<MCSection *, 16> SectionOrder;
/// The last fragment which was laid out, or 0 if nothing has been laid
/// out. Fragments are always laid out in order, so all fragments with a
/// lower ordinal will be valid.
mutable DenseMap<const MCSection *, MCFragment *> LastValidFragment;
/// \brief Make sure that the layout for the given fragment is valid, lazily
/// computing it if necessary.
void ensureValid(const MCFragment *F) const;
/// \brief Is the layout for this fragment valid?
bool isFragmentValid(const MCFragment *F) const;
public:
MCAsmLayout(MCAssembler &Assembler);
/// Get the assembler object this is a layout for.
MCAssembler &getAssembler() const { return Assembler; }
/// \brief Invalidate the fragments starting with F because it has been
/// resized. The fragment's size should have already been updated, but
/// its bundle padding will be recomputed.
void invalidateFragmentsFrom(MCFragment *F);
/// \brief Perform layout for a single fragment, assuming that the previous
/// fragment has already been laid out correctly, and the parent section has
/// been initialized.
void layoutFragment(MCFragment *Fragment);
/// \name Section Access (in layout order)
/// @{
llvm::SmallVectorImpl<MCSection *> &getSectionOrder() { return SectionOrder; }
const llvm::SmallVectorImpl<MCSection *> &getSectionOrder() const {
return SectionOrder;
}
/// @}
/// \name Fragment Layout Data
/// @{
/// \brief Get the offset of the given fragment inside its containing section.
uint64_t getFragmentOffset(const MCFragment *F) const;
/// @}
/// \name Utility Functions
/// @{
/// \brief Get the address space size of the given section, as it effects
/// layout. This may differ from the size reported by \see getSectionSize() by
/// not including section tail padding.
uint64_t getSectionAddressSize(const MCSection *Sec) const;
/// \brief Get the data size of the given section, as emitted to the object
/// file. This may include additional padding, or be 0 for virtual sections.
uint64_t getSectionFileSize(const MCSection *Sec) const;
/// \brief Get the offset of the given symbol, as computed in the current
/// layout.
/// \return True on success.
bool getSymbolOffset(const MCSymbol &S, uint64_t &Val) const;
/// \brief Variant that reports a fatal error if the offset is not computable.
uint64_t getSymbolOffset(const MCSymbol &S) const;
/// \brief If this symbol is equivalent to A + Constant, return A.
const MCSymbol *getBaseSymbol(const MCSymbol &Symbol) const;
/// @}
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCTargetOptions.h | //===- MCTargetOptions.h - MC Target Options -------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCTARGETOPTIONS_H
#define LLVM_MC_MCTARGETOPTIONS_H
#include <string>
namespace llvm {
class StringRef;
class MCTargetOptions {
public:
enum AsmInstrumentation {
AsmInstrumentationNone,
AsmInstrumentationAddress
};
/// Enables AddressSanitizer instrumentation at machine level.
bool SanitizeAddress : 1;
bool MCRelaxAll : 1;
bool MCNoExecStack : 1;
bool MCFatalWarnings : 1;
bool MCSaveTempLabels : 1;
bool MCUseDwarfDirectory : 1;
bool ShowMCEncoding : 1;
bool ShowMCInst : 1;
bool AsmVerbose : 1;
int DwarfVersion;
/// getABIName - If this returns a non-empty string this represents the
/// textual name of the ABI that we want the backend to use, e.g. o32, or
/// aapcs-linux.
StringRef getABIName() const { // HLSL Change - inline implementation
return ABIName;
}
::std::string ABIName;
MCTargetOptions() // HLSL Change - inline implementation
: SanitizeAddress(false), MCRelaxAll(false), MCNoExecStack(false),
MCFatalWarnings(false), MCSaveTempLabels(false),
MCUseDwarfDirectory(false), ShowMCEncoding(false), ShowMCInst(false),
AsmVerbose(false), DwarfVersion(0), ABIName() {}
};
inline bool operator==(const MCTargetOptions &LHS, const MCTargetOptions &RHS) {
#define ARE_EQUAL(X) LHS.X == RHS.X
return (ARE_EQUAL(SanitizeAddress) &&
ARE_EQUAL(MCRelaxAll) &&
ARE_EQUAL(MCNoExecStack) &&
ARE_EQUAL(MCFatalWarnings) &&
ARE_EQUAL(MCSaveTempLabels) &&
ARE_EQUAL(MCUseDwarfDirectory) &&
ARE_EQUAL(ShowMCEncoding) &&
ARE_EQUAL(ShowMCInst) &&
ARE_EQUAL(AsmVerbose) &&
ARE_EQUAL(DwarfVersion) &&
ARE_EQUAL(ABIName));
#undef ARE_EQUAL
}
inline bool operator!=(const MCTargetOptions &LHS, const MCTargetOptions &RHS) {
return !(LHS == RHS);
}
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCCodeEmitter.h | //===-- llvm/MC/MCCodeEmitter.h - Instruction Encoding ----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCCODEEMITTER_H
#define LLVM_MC_MCCODEEMITTER_H
#include "llvm/Support/Compiler.h"
namespace llvm {
class MCFixup;
class MCInst;
class MCSubtargetInfo;
class raw_ostream;
template<typename T> class SmallVectorImpl;
/// MCCodeEmitter - Generic instruction encoding interface.
class MCCodeEmitter {
private:
MCCodeEmitter(const MCCodeEmitter &) = delete;
void operator=(const MCCodeEmitter &) = delete;
protected: // Can only create subclasses.
MCCodeEmitter();
public:
virtual ~MCCodeEmitter();
/// Lifetime management
virtual void reset() {}
/// EncodeInstruction - Encode the given \p Inst to bytes on the output
/// stream \p OS.
virtual void encodeInstruction(const MCInst &Inst, raw_ostream &OS,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const = 0;
};
} // End llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCFixup.h | //===-- llvm/MC/MCFixup.h - Instruction Relocation and Patching -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCFIXUP_H
#define LLVM_MC_MCFIXUP_H
#include "llvm/MC/MCExpr.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/SMLoc.h"
#include <cassert>
namespace llvm {
class MCExpr;
/// \brief Extensible enumeration to represent the type of a fixup.
enum MCFixupKind {
FK_Data_1 = 0, ///< A one-byte fixup.
FK_Data_2, ///< A two-byte fixup.
FK_Data_4, ///< A four-byte fixup.
FK_Data_8, ///< A eight-byte fixup.
FK_PCRel_1, ///< A one-byte pc relative fixup.
FK_PCRel_2, ///< A two-byte pc relative fixup.
FK_PCRel_4, ///< A four-byte pc relative fixup.
FK_PCRel_8, ///< A eight-byte pc relative fixup.
FK_GPRel_1, ///< A one-byte gp relative fixup.
FK_GPRel_2, ///< A two-byte gp relative fixup.
FK_GPRel_4, ///< A four-byte gp relative fixup.
FK_GPRel_8, ///< A eight-byte gp relative fixup.
FK_SecRel_1, ///< A one-byte section relative fixup.
FK_SecRel_2, ///< A two-byte section relative fixup.
FK_SecRel_4, ///< A four-byte section relative fixup.
FK_SecRel_8, ///< A eight-byte section relative fixup.
FirstTargetFixupKind = 128,
// Limit range of target fixups, in case we want to pack more efficiently
// later.
MaxTargetFixupKind = (1 << 8)
};
/// \brief Encode information on a single operation to perform on a byte
/// sequence (e.g., an encoded instruction) which requires assemble- or run-
/// time patching.
///
/// Fixups are used any time the target instruction encoder needs to represent
/// some value in an instruction which is not yet concrete. The encoder will
/// encode the instruction assuming the value is 0, and emit a fixup which
/// communicates to the assembler backend how it should rewrite the encoded
/// value.
///
/// During the process of relaxation, the assembler will apply fixups as
/// symbolic values become concrete. When relaxation is complete, any remaining
/// fixups become relocations in the object file (or errors, if the fixup cannot
/// be encoded on the target).
class MCFixup {
/// The value to put into the fixup location. The exact interpretation of the
/// expression is target dependent, usually it will be one of the operands to
/// an instruction or an assembler directive.
const MCExpr *Value;
/// The byte index of start of the relocation inside the encoded instruction.
uint32_t Offset;
/// The target dependent kind of fixup item this is. The kind is used to
/// determine how the operand value should be encoded into the instruction.
unsigned Kind;
/// The source location which gave rise to the fixup, if any.
SMLoc Loc;
public:
static MCFixup create(uint32_t Offset, const MCExpr *Value,
MCFixupKind Kind, SMLoc Loc = SMLoc()) {
assert(unsigned(Kind) < MaxTargetFixupKind && "Kind out of range!");
MCFixup FI;
FI.Value = Value;
FI.Offset = Offset;
FI.Kind = unsigned(Kind);
FI.Loc = Loc;
return FI;
}
MCFixupKind getKind() const { return MCFixupKind(Kind); }
uint32_t getOffset() const { return Offset; }
void setOffset(uint32_t Value) { Offset = Value; }
const MCExpr *getValue() const { return Value; }
/// \brief Return the generic fixup kind for a value with the given size. It
/// is an error to pass an unsupported size.
static MCFixupKind getKindForSize(unsigned Size, bool isPCRel) {
switch (Size) {
default: llvm_unreachable("Invalid generic fixup size!");
case 1: return isPCRel ? FK_PCRel_1 : FK_Data_1;
case 2: return isPCRel ? FK_PCRel_2 : FK_Data_2;
case 4: return isPCRel ? FK_PCRel_4 : FK_Data_4;
case 8: return isPCRel ? FK_PCRel_8 : FK_Data_8;
}
}
SMLoc getLoc() const { return Loc; }
};
} // End llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCCodeGenInfo.h | //===-- llvm/MC/MCCodeGenInfo.h - Target CodeGen Info -----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file tracks information about the target which can affect codegen,
// asm parsing, and asm printing. For example, relocation model.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCCODEGENINFO_H
#define LLVM_MC_MCCODEGENINFO_H
#include "llvm/Support/CodeGen.h"
namespace llvm {
class MCCodeGenInfo {
/// RelocationModel - Relocation model: static, pic, etc.
///
Reloc::Model RelocationModel;
/// CMModel - Code model.
///
CodeModel::Model CMModel;
/// OptLevel - Optimization level.
///
CodeGenOpt::Level OptLevel;
public:
void initMCCodeGenInfo(Reloc::Model RM = Reloc::Default,
CodeModel::Model CM = CodeModel::Default,
CodeGenOpt::Level OL = CodeGenOpt::Default);
Reloc::Model getRelocationModel() const { return RelocationModel; }
CodeModel::Model getCodeModel() const { return CMModel; }
CodeGenOpt::Level getOptLevel() const { return OptLevel; }
// Allow overriding OptLevel on a per-function basis.
void setOptLevel(CodeGenOpt::Level Level) { OptLevel = Level; }
};
} // namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCWin64EH.h | //===- MCWin64EH.h - Machine Code Win64 EH support --------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains declarations to support the Win64 Exception Handling
// scheme in MC.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCWIN64EH_H
#define LLVM_MC_MCWIN64EH_H
#include "llvm/MC/MCWinEH.h"
#include "llvm/Support/Win64EH.h"
#include <vector>
namespace llvm {
class MCStreamer;
class MCSymbol;
namespace Win64EH {
struct Instruction {
static WinEH::Instruction PushNonVol(MCSymbol *L, unsigned Reg) {
return WinEH::Instruction(Win64EH::UOP_PushNonVol, L, Reg, -1);
}
static WinEH::Instruction Alloc(MCSymbol *L, unsigned Size) {
return WinEH::Instruction(Size > 128 ? UOP_AllocLarge : UOP_AllocSmall, L,
-1, Size);
}
static WinEH::Instruction PushMachFrame(MCSymbol *L, bool Code) {
return WinEH::Instruction(UOP_PushMachFrame, L, -1, Code ? 1 : 0);
}
static WinEH::Instruction SaveNonVol(MCSymbol *L, unsigned Reg,
unsigned Offset) {
return WinEH::Instruction(Offset > 512 * 1024 - 8 ? UOP_SaveNonVolBig
: UOP_SaveNonVol,
L, Reg, Offset);
}
static WinEH::Instruction SaveXMM(MCSymbol *L, unsigned Reg,
unsigned Offset) {
return WinEH::Instruction(Offset > 512 * 1024 - 8 ? UOP_SaveXMM128Big
: UOP_SaveXMM128,
L, Reg, Offset);
}
static WinEH::Instruction SetFPReg(MCSymbol *L, unsigned Reg, unsigned Off) {
return WinEH::Instruction(UOP_SetFPReg, L, Reg, Off);
}
};
class UnwindEmitter : public WinEH::UnwindEmitter {
public:
void Emit(MCStreamer &Streamer) const override;
void EmitUnwindInfo(MCStreamer &Streamer, WinEH::FrameInfo *FI) const override;
};
}
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCSectionELF.h | //===- MCSectionELF.h - ELF Machine Code Sections ---------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file declares the MCSectionELF class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCSECTIONELF_H
#define LLVM_MC_MCSECTIONELF_H
#include "llvm/ADT/Twine.h"
#include "llvm/MC/MCSection.h"
#include "llvm/MC/MCSymbolELF.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ELF.h"
#include "llvm/Support/raw_ostream.h"
namespace llvm {
class MCSymbol;
/// MCSectionELF - This represents a section on linux, lots of unix variants
/// and some bare metal systems.
class MCSectionELF : public MCSection {
/// SectionName - This is the name of the section. The referenced memory is
/// owned by TargetLoweringObjectFileELF's ELFUniqueMap.
StringRef SectionName;
/// Type - This is the sh_type field of a section, drawn from the enums below.
unsigned Type;
/// Flags - This is the sh_flags field of a section, drawn from the enums.
/// below.
unsigned Flags;
unsigned UniqueID;
/// EntrySize - The size of each entry in this section. This size only
/// makes sense for sections that contain fixed-sized entries. If a
/// section does not contain fixed-sized entries 'EntrySize' will be 0.
unsigned EntrySize;
const MCSymbolELF *Group;
/// Depending on the type of the section this is sh_link or sh_info.
const MCSectionELF *Associated;
private:
friend class MCContext;
MCSectionELF(StringRef Section, unsigned type, unsigned flags, SectionKind K,
unsigned entrySize, const MCSymbolELF *group, unsigned UniqueID,
MCSymbol *Begin, const MCSectionELF *Associated)
: MCSection(SV_ELF, K, Begin), SectionName(Section), Type(type),
Flags(flags), UniqueID(UniqueID), EntrySize(entrySize), Group(group),
Associated(Associated) {
if (Group)
Group->setIsSignature();
}
~MCSectionELF() override;
void setSectionName(StringRef Name) { SectionName = Name; }
public:
/// ShouldOmitSectionDirective - Decides whether a '.section' directive
/// should be printed before the section name
bool ShouldOmitSectionDirective(StringRef Name, const MCAsmInfo &MAI) const;
StringRef getSectionName() const { return SectionName; }
unsigned getType() const { return Type; }
unsigned getFlags() const { return Flags; }
unsigned getEntrySize() const { return EntrySize; }
const MCSymbolELF *getGroup() const { return Group; }
void PrintSwitchToSection(const MCAsmInfo &MAI, raw_ostream &OS,
const MCExpr *Subsection) const override;
bool UseCodeAlign() const override;
bool isVirtualSection() const override;
bool isUnique() const { return UniqueID != ~0U; }
unsigned getUniqueID() const { return UniqueID; }
const MCSectionELF *getAssociatedSection() const { return Associated; }
static bool classof(const MCSection *S) {
return S->getVariant() == SV_ELF;
}
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCObjectWriter.h | //===-- llvm/MC/MCObjectWriter.h - Object File Writer Interface -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCOBJECTWRITER_H
#define LLVM_MC_MCOBJECTWRITER_H
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/EndianStream.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
namespace llvm {
class MCAsmLayout;
class MCAssembler;
class MCFixup;
class MCFragment;
class MCSymbolRefExpr;
class MCValue;
/// Defines the object file and target independent interfaces used by the
/// assembler backend to write native file format object files.
///
/// The object writer contains a few callbacks used by the assembler to allow
/// the object writer to modify the assembler data structures at appropriate
/// points. Once assembly is complete, the object writer is given the
/// MCAssembler instance, which contains all the symbol and section data which
/// should be emitted as part of writeObject().
///
/// The object writer also contains a number of helper methods for writing
/// binary data to the output stream.
class MCObjectWriter {
MCObjectWriter(const MCObjectWriter &) = delete;
void operator=(const MCObjectWriter &) = delete;
protected:
raw_pwrite_stream &OS;
unsigned IsLittleEndian : 1;
protected: // Can only create subclasses.
MCObjectWriter(raw_pwrite_stream &OS, bool IsLittleEndian)
: OS(OS), IsLittleEndian(IsLittleEndian) {}
public:
virtual ~MCObjectWriter();
/// lifetime management
virtual void reset() {}
bool isLittleEndian() const { return IsLittleEndian; }
raw_ostream &getStream() { return OS; }
/// \name High-Level API
/// @{
/// Perform any late binding of symbols (for example, to assign symbol
/// indices for use when generating relocations).
///
/// This routine is called by the assembler after layout and relaxation is
/// complete.
virtual void executePostLayoutBinding(MCAssembler &Asm,
const MCAsmLayout &Layout) = 0;
/// Record a relocation entry.
///
/// This routine is called by the assembler after layout and relaxation, and
/// post layout binding. The implementation is responsible for storing
/// information about the relocation so that it can be emitted during
/// writeObject().
virtual void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
const MCFragment *Fragment,
const MCFixup &Fixup, MCValue Target,
bool &IsPCRel, uint64_t &FixedValue) = 0;
/// Check whether the difference (A - B) between two symbol references is
/// fully resolved.
///
/// Clients are not required to answer precisely and may conservatively return
/// false, even when a difference is fully resolved.
bool isSymbolRefDifferenceFullyResolved(const MCAssembler &Asm,
const MCSymbolRefExpr *A,
const MCSymbolRefExpr *B,
bool InSet) const;
virtual bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
const MCSymbol &SymA,
const MCFragment &FB,
bool InSet,
bool IsPCRel) const;
/// True if this symbol (which is a variable) is weak. This is not
/// just STB_WEAK, but more generally whether or not we can evaluate
/// past it.
virtual bool isWeak(const MCSymbol &Sym) const;
/// Write the object file.
///
/// This routine is called by the assembler after layout and relaxation is
/// complete, fixups have been evaluated and applied, and relocations
/// generated.
virtual void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) = 0;
/// @}
/// \name Binary Output
/// @{
void write8(uint8_t Value) { OS << char(Value); }
void writeLE16(uint16_t Value) {
support::endian::Writer<support::little>(OS).write(Value);
}
void writeLE32(uint32_t Value) {
support::endian::Writer<support::little>(OS).write(Value);
}
void writeLE64(uint64_t Value) {
support::endian::Writer<support::little>(OS).write(Value);
}
void writeBE16(uint16_t Value) {
support::endian::Writer<support::big>(OS).write(Value);
}
void writeBE32(uint32_t Value) {
support::endian::Writer<support::big>(OS).write(Value);
}
void writeBE64(uint64_t Value) {
support::endian::Writer<support::big>(OS).write(Value);
}
void write16(uint16_t Value) {
if (IsLittleEndian)
writeLE16(Value);
else
writeBE16(Value);
}
void write32(uint32_t Value) {
if (IsLittleEndian)
writeLE32(Value);
else
writeBE32(Value);
}
void write64(uint64_t Value) {
if (IsLittleEndian)
writeLE64(Value);
else
writeBE64(Value);
}
void WriteZeros(unsigned N) {
const char Zeros[16] = {0};
for (unsigned i = 0, e = N / 16; i != e; ++i)
OS << StringRef(Zeros, 16);
OS << StringRef(Zeros, N % 16);
}
void writeBytes(const SmallVectorImpl<char> &ByteVec,
unsigned ZeroFillSize = 0) {
writeBytes(StringRef(ByteVec.data(), ByteVec.size()), ZeroFillSize);
}
void writeBytes(StringRef Str, unsigned ZeroFillSize = 0) {
// TODO: this version may need to go away once all fragment contents are
// converted to SmallVector<char, N>
assert(
(ZeroFillSize == 0 || Str.size() <= ZeroFillSize) &&
"data size greater than fill size, unexpected large write will occur");
OS << Str;
if (ZeroFillSize)
WriteZeros(ZeroFillSize - Str.size());
}
/// @}
};
} // End llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCExpr.h | //===- MCExpr.h - Assembly Level Expressions --------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCEXPR_H
#define LLVM_MC_MCEXPR_H
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/DataTypes.h"
namespace llvm {
class MCAsmInfo;
class MCAsmLayout;
class MCAssembler;
class MCContext;
class MCFixup;
class MCSection;
class MCStreamer;
class MCSymbol;
class MCValue;
class raw_ostream;
class StringRef;
typedef DenseMap<const MCSection *, uint64_t> SectionAddrMap;
/// \brief Base class for the full range of assembler expressions which are
/// needed for parsing.
class MCExpr {
public:
enum ExprKind {
Binary, ///< Binary expressions.
Constant, ///< Constant expressions.
SymbolRef, ///< References to labels and assigned expressions.
Unary, ///< Unary expressions.
Target ///< Target specific expression.
};
private:
ExprKind Kind;
MCExpr(const MCExpr&) = delete;
void operator=(const MCExpr&) = delete;
bool evaluateAsAbsolute(int64_t &Res, const MCAssembler *Asm,
const MCAsmLayout *Layout,
const SectionAddrMap *Addrs) const;
bool evaluateAsAbsolute(int64_t &Res, const MCAssembler *Asm,
const MCAsmLayout *Layout,
const SectionAddrMap *Addrs, bool InSet) const;
protected:
explicit MCExpr(ExprKind Kind) : Kind(Kind) {}
bool evaluateAsRelocatableImpl(MCValue &Res, const MCAssembler *Asm,
const MCAsmLayout *Layout,
const MCFixup *Fixup,
const SectionAddrMap *Addrs, bool InSet) const;
public:
/// \name Accessors
/// @{
ExprKind getKind() const { return Kind; }
/// @}
/// \name Utility Methods
/// @{
void print(raw_ostream &OS, const MCAsmInfo *MAI) const;
void dump() const;
/// @}
/// \name Expression Evaluation
/// @{
/// \brief Try to evaluate the expression to an absolute value.
///
/// \param Res - The absolute value, if evaluation succeeds.
/// \param Layout - The assembler layout object to use for evaluating symbol
/// values. If not given, then only non-symbolic expressions will be
/// evaluated.
/// \return - True on success.
bool evaluateAsAbsolute(int64_t &Res, const MCAsmLayout &Layout,
const SectionAddrMap &Addrs) const;
bool evaluateAsAbsolute(int64_t &Res) const;
bool evaluateAsAbsolute(int64_t &Res, const MCAssembler &Asm) const;
bool evaluateAsAbsolute(int64_t &Res, const MCAsmLayout &Layout) const;
bool evaluateKnownAbsolute(int64_t &Res, const MCAsmLayout &Layout) const;
/// \brief Try to evaluate the expression to a relocatable value, i.e. an
/// expression of the fixed form (a - b + constant).
///
/// \param Res - The relocatable value, if evaluation succeeds.
/// \param Layout - The assembler layout object to use for evaluating values.
/// \param Fixup - The Fixup object if available.
/// \return - True on success.
bool evaluateAsRelocatable(MCValue &Res, const MCAsmLayout *Layout,
const MCFixup *Fixup) const;
/// \brief Try to evaluate the expression to the form (a - b + constant) where
/// neither a nor b are variables.
///
/// This is a more aggressive variant of evaluateAsRelocatable. The intended
/// use is for when relocations are not available, like the .size directive.
bool evaluateAsValue(MCValue &Res, const MCAsmLayout &Layout) const;
/// \brief Find the "associated section" for this expression, which is
/// currently defined as the absolute section for constants, or
/// otherwise the section associated with the first defined symbol in the
/// expression.
MCSection *findAssociatedSection() const;
/// @}
};
inline raw_ostream &operator<<(raw_ostream &OS, const MCExpr &E) {
E.print(OS, nullptr);
return OS;
}
//// \brief Represent a constant integer expression.
class MCConstantExpr : public MCExpr {
int64_t Value;
explicit MCConstantExpr(int64_t Value)
: MCExpr(MCExpr::Constant), Value(Value) {}
public:
/// \name Construction
/// @{
static const MCConstantExpr *create(int64_t Value, MCContext &Ctx);
/// @}
/// \name Accessors
/// @{
int64_t getValue() const { return Value; }
/// @}
static bool classof(const MCExpr *E) {
return E->getKind() == MCExpr::Constant;
}
};
/// \brief Represent a reference to a symbol from inside an expression.
///
/// A symbol reference in an expression may be a use of a label, a use of an
/// assembler variable (defined constant), or constitute an implicit definition
/// of the symbol as external.
class MCSymbolRefExpr : public MCExpr {
public:
enum VariantKind : uint16_t {
VK_None,
VK_Invalid,
VK_GOT,
VK_GOTOFF,
VK_GOTPCREL,
VK_GOTTPOFF,
VK_INDNTPOFF,
VK_NTPOFF,
VK_GOTNTPOFF,
VK_PLT,
VK_TLSGD,
VK_TLSLD,
VK_TLSLDM,
VK_TPOFF,
VK_DTPOFF,
VK_TLVP, // Mach-O thread local variable relocations
VK_TLVPPAGE,
VK_TLVPPAGEOFF,
VK_PAGE,
VK_PAGEOFF,
VK_GOTPAGE,
VK_GOTPAGEOFF,
VK_SECREL,
VK_SIZE, // symbol@SIZE
VK_WEAKREF, // The link between the symbols in .weakref foo, bar
VK_ARM_NONE,
VK_ARM_TARGET1,
VK_ARM_TARGET2,
VK_ARM_PREL31,
VK_ARM_SBREL, // symbol(sbrel)
VK_ARM_TLSLDO, // symbol(tlsldo)
VK_ARM_TLSCALL, // symbol(tlscall)
VK_ARM_TLSDESC, // symbol(tlsdesc)
VK_ARM_TLSDESCSEQ,
VK_PPC_LO, // symbol@l
VK_PPC_HI, // symbol@h
VK_PPC_HA, // symbol@ha
VK_PPC_HIGHER, // symbol@higher
VK_PPC_HIGHERA, // symbol@highera
VK_PPC_HIGHEST, // symbol@highest
VK_PPC_HIGHESTA, // symbol@highesta
VK_PPC_GOT_LO, // symbol@got@l
VK_PPC_GOT_HI, // symbol@got@h
VK_PPC_GOT_HA, // symbol@got@ha
VK_PPC_TOCBASE, // symbol@tocbase
VK_PPC_TOC, // symbol@toc
VK_PPC_TOC_LO, // symbol@toc@l
VK_PPC_TOC_HI, // symbol@toc@h
VK_PPC_TOC_HA, // symbol@toc@ha
VK_PPC_DTPMOD, // symbol@dtpmod
VK_PPC_TPREL, // symbol@tprel
VK_PPC_TPREL_LO, // symbol@tprel@l
VK_PPC_TPREL_HI, // symbol@tprel@h
VK_PPC_TPREL_HA, // symbol@tprel@ha
VK_PPC_TPREL_HIGHER, // symbol@tprel@higher
VK_PPC_TPREL_HIGHERA, // symbol@tprel@highera
VK_PPC_TPREL_HIGHEST, // symbol@tprel@highest
VK_PPC_TPREL_HIGHESTA, // symbol@tprel@highesta
VK_PPC_DTPREL, // symbol@dtprel
VK_PPC_DTPREL_LO, // symbol@dtprel@l
VK_PPC_DTPREL_HI, // symbol@dtprel@h
VK_PPC_DTPREL_HA, // symbol@dtprel@ha
VK_PPC_DTPREL_HIGHER, // symbol@dtprel@higher
VK_PPC_DTPREL_HIGHERA, // symbol@dtprel@highera
VK_PPC_DTPREL_HIGHEST, // symbol@dtprel@highest
VK_PPC_DTPREL_HIGHESTA,// symbol@dtprel@highesta
VK_PPC_GOT_TPREL, // symbol@got@tprel
VK_PPC_GOT_TPREL_LO, // symbol@got@tprel@l
VK_PPC_GOT_TPREL_HI, // symbol@got@tprel@h
VK_PPC_GOT_TPREL_HA, // symbol@got@tprel@ha
VK_PPC_GOT_DTPREL, // symbol@got@dtprel
VK_PPC_GOT_DTPREL_LO, // symbol@got@dtprel@l
VK_PPC_GOT_DTPREL_HI, // symbol@got@dtprel@h
VK_PPC_GOT_DTPREL_HA, // symbol@got@dtprel@ha
VK_PPC_TLS, // symbol@tls
VK_PPC_GOT_TLSGD, // symbol@got@tlsgd
VK_PPC_GOT_TLSGD_LO, // symbol@got@tlsgd@l
VK_PPC_GOT_TLSGD_HI, // symbol@got@tlsgd@h
VK_PPC_GOT_TLSGD_HA, // symbol@got@tlsgd@ha
VK_PPC_TLSGD, // symbol@tlsgd
VK_PPC_GOT_TLSLD, // symbol@got@tlsld
VK_PPC_GOT_TLSLD_LO, // symbol@got@tlsld@l
VK_PPC_GOT_TLSLD_HI, // symbol@got@tlsld@h
VK_PPC_GOT_TLSLD_HA, // symbol@got@tlsld@ha
VK_PPC_TLSLD, // symbol@tlsld
VK_PPC_LOCAL, // symbol@local
VK_Mips_GPREL,
VK_Mips_GOT_CALL,
VK_Mips_GOT16,
VK_Mips_GOT,
VK_Mips_ABS_HI,
VK_Mips_ABS_LO,
VK_Mips_TLSGD,
VK_Mips_TLSLDM,
VK_Mips_DTPREL_HI,
VK_Mips_DTPREL_LO,
VK_Mips_GOTTPREL,
VK_Mips_TPREL_HI,
VK_Mips_TPREL_LO,
VK_Mips_GPOFF_HI,
VK_Mips_GPOFF_LO,
VK_Mips_GOT_DISP,
VK_Mips_GOT_PAGE,
VK_Mips_GOT_OFST,
VK_Mips_HIGHER,
VK_Mips_HIGHEST,
VK_Mips_GOT_HI16,
VK_Mips_GOT_LO16,
VK_Mips_CALL_HI16,
VK_Mips_CALL_LO16,
VK_Mips_PCREL_HI16,
VK_Mips_PCREL_LO16,
VK_COFF_IMGREL32, // symbol@imgrel (image-relative)
VK_Hexagon_PCREL,
VK_Hexagon_LO16,
VK_Hexagon_HI16,
VK_Hexagon_GPREL,
VK_Hexagon_GD_GOT,
VK_Hexagon_LD_GOT,
VK_Hexagon_GD_PLT,
VK_Hexagon_LD_PLT,
VK_Hexagon_IE,
VK_Hexagon_IE_GOT,
VK_TPREL,
VK_DTPREL
};
private:
/// The symbol reference modifier.
const VariantKind Kind;
/// Specifies how the variant kind should be printed.
const unsigned UseParensForSymbolVariant : 1;
// FIXME: Remove this bit.
const unsigned HasSubsectionsViaSymbols : 1;
/// The symbol being referenced.
const MCSymbol *Symbol;
explicit MCSymbolRefExpr(const MCSymbol *Symbol, VariantKind Kind,
const MCAsmInfo *MAI);
public:
/// \name Construction
/// @{
static const MCSymbolRefExpr *create(const MCSymbol *Symbol, MCContext &Ctx) {
return MCSymbolRefExpr::create(Symbol, VK_None, Ctx);
}
static const MCSymbolRefExpr *create(const MCSymbol *Symbol, VariantKind Kind,
MCContext &Ctx);
static const MCSymbolRefExpr *create(StringRef Name, VariantKind Kind,
MCContext &Ctx);
/// @}
/// \name Accessors
/// @{
const MCSymbol &getSymbol() const { return *Symbol; }
VariantKind getKind() const { return Kind; }
void printVariantKind(raw_ostream &OS) const;
bool hasSubsectionsViaSymbols() const { return HasSubsectionsViaSymbols; }
/// @}
/// \name Static Utility Functions
/// @{
static StringRef getVariantKindName(VariantKind Kind);
static VariantKind getVariantKindForName(StringRef Name);
/// @}
static bool classof(const MCExpr *E) {
return E->getKind() == MCExpr::SymbolRef;
}
};
/// \brief Unary assembler expressions.
class MCUnaryExpr : public MCExpr {
public:
enum Opcode {
LNot, ///< Logical negation.
Minus, ///< Unary minus.
Not, ///< Bitwise negation.
Plus ///< Unary plus.
};
private:
Opcode Op;
const MCExpr *Expr;
MCUnaryExpr(Opcode Op, const MCExpr *Expr)
: MCExpr(MCExpr::Unary), Op(Op), Expr(Expr) {}
public:
/// \name Construction
/// @{
static const MCUnaryExpr *create(Opcode Op, const MCExpr *Expr,
MCContext &Ctx);
static const MCUnaryExpr *createLNot(const MCExpr *Expr, MCContext &Ctx) {
return create(LNot, Expr, Ctx);
}
static const MCUnaryExpr *createMinus(const MCExpr *Expr, MCContext &Ctx) {
return create(Minus, Expr, Ctx);
}
static const MCUnaryExpr *createNot(const MCExpr *Expr, MCContext &Ctx) {
return create(Not, Expr, Ctx);
}
static const MCUnaryExpr *createPlus(const MCExpr *Expr, MCContext &Ctx) {
return create(Plus, Expr, Ctx);
}
/// @}
/// \name Accessors
/// @{
/// \brief Get the kind of this unary expression.
Opcode getOpcode() const { return Op; }
/// \brief Get the child of this unary expression.
const MCExpr *getSubExpr() const { return Expr; }
/// @}
static bool classof(const MCExpr *E) {
return E->getKind() == MCExpr::Unary;
}
};
/// \brief Binary assembler expressions.
class MCBinaryExpr : public MCExpr {
public:
enum Opcode {
Add, ///< Addition.
And, ///< Bitwise and.
Div, ///< Signed division.
EQ, ///< Equality comparison.
GT, ///< Signed greater than comparison (result is either 0 or some
///< target-specific non-zero value)
GTE, ///< Signed greater than or equal comparison (result is either 0 or
///< some target-specific non-zero value).
LAnd, ///< Logical and.
LOr, ///< Logical or.
LT, ///< Signed less than comparison (result is either 0 or
///< some target-specific non-zero value).
LTE, ///< Signed less than or equal comparison (result is either 0 or
///< some target-specific non-zero value).
Mod, ///< Signed remainder.
Mul, ///< Multiplication.
NE, ///< Inequality comparison.
Or, ///< Bitwise or.
Shl, ///< Shift left.
AShr, ///< Arithmetic shift right.
LShr, ///< Logical shift right.
Sub, ///< Subtraction.
Xor ///< Bitwise exclusive or.
};
private:
Opcode Op;
const MCExpr *LHS, *RHS;
MCBinaryExpr(Opcode Op, const MCExpr *LHS, const MCExpr *RHS)
: MCExpr(MCExpr::Binary), Op(Op), LHS(LHS), RHS(RHS) {}
public:
/// \name Construction
/// @{
static const MCBinaryExpr *create(Opcode Op, const MCExpr *LHS,
const MCExpr *RHS, MCContext &Ctx);
static const MCBinaryExpr *createAdd(const MCExpr *LHS, const MCExpr *RHS,
MCContext &Ctx) {
return create(Add, LHS, RHS, Ctx);
}
static const MCBinaryExpr *createAnd(const MCExpr *LHS, const MCExpr *RHS,
MCContext &Ctx) {
return create(And, LHS, RHS, Ctx);
}
static const MCBinaryExpr *createDiv(const MCExpr *LHS, const MCExpr *RHS,
MCContext &Ctx) {
return create(Div, LHS, RHS, Ctx);
}
static const MCBinaryExpr *createEQ(const MCExpr *LHS, const MCExpr *RHS,
MCContext &Ctx) {
return create(EQ, LHS, RHS, Ctx);
}
static const MCBinaryExpr *createGT(const MCExpr *LHS, const MCExpr *RHS,
MCContext &Ctx) {
return create(GT, LHS, RHS, Ctx);
}
static const MCBinaryExpr *createGTE(const MCExpr *LHS, const MCExpr *RHS,
MCContext &Ctx) {
return create(GTE, LHS, RHS, Ctx);
}
static const MCBinaryExpr *createLAnd(const MCExpr *LHS, const MCExpr *RHS,
MCContext &Ctx) {
return create(LAnd, LHS, RHS, Ctx);
}
static const MCBinaryExpr *createLOr(const MCExpr *LHS, const MCExpr *RHS,
MCContext &Ctx) {
return create(LOr, LHS, RHS, Ctx);
}
static const MCBinaryExpr *createLT(const MCExpr *LHS, const MCExpr *RHS,
MCContext &Ctx) {
return create(LT, LHS, RHS, Ctx);
}
static const MCBinaryExpr *createLTE(const MCExpr *LHS, const MCExpr *RHS,
MCContext &Ctx) {
return create(LTE, LHS, RHS, Ctx);
}
static const MCBinaryExpr *createMod(const MCExpr *LHS, const MCExpr *RHS,
MCContext &Ctx) {
return create(Mod, LHS, RHS, Ctx);
}
static const MCBinaryExpr *createMul(const MCExpr *LHS, const MCExpr *RHS,
MCContext &Ctx) {
return create(Mul, LHS, RHS, Ctx);
}
static const MCBinaryExpr *createNE(const MCExpr *LHS, const MCExpr *RHS,
MCContext &Ctx) {
return create(NE, LHS, RHS, Ctx);
}
static const MCBinaryExpr *createOr(const MCExpr *LHS, const MCExpr *RHS,
MCContext &Ctx) {
return create(Or, LHS, RHS, Ctx);
}
static const MCBinaryExpr *createShl(const MCExpr *LHS, const MCExpr *RHS,
MCContext &Ctx) {
return create(Shl, LHS, RHS, Ctx);
}
static const MCBinaryExpr *createAShr(const MCExpr *LHS, const MCExpr *RHS,
MCContext &Ctx) {
return create(AShr, LHS, RHS, Ctx);
}
static const MCBinaryExpr *createLShr(const MCExpr *LHS, const MCExpr *RHS,
MCContext &Ctx) {
return create(LShr, LHS, RHS, Ctx);
}
static const MCBinaryExpr *createSub(const MCExpr *LHS, const MCExpr *RHS,
MCContext &Ctx) {
return create(Sub, LHS, RHS, Ctx);
}
static const MCBinaryExpr *createXor(const MCExpr *LHS, const MCExpr *RHS,
MCContext &Ctx) {
return create(Xor, LHS, RHS, Ctx);
}
/// @}
/// \name Accessors
/// @{
/// \brief Get the kind of this binary expression.
Opcode getOpcode() const { return Op; }
/// \brief Get the left-hand side expression of the binary operator.
const MCExpr *getLHS() const { return LHS; }
/// \brief Get the right-hand side expression of the binary operator.
const MCExpr *getRHS() const { return RHS; }
/// @}
static bool classof(const MCExpr *E) {
return E->getKind() == MCExpr::Binary;
}
};
/// \brief This is an extension point for target-specific MCExpr subclasses to
/// implement.
///
/// NOTE: All subclasses are required to have trivial destructors because
/// MCExprs are bump pointer allocated and not destructed.
class MCTargetExpr : public MCExpr {
virtual void anchor();
protected:
MCTargetExpr() : MCExpr(Target) {}
virtual ~MCTargetExpr() {}
public:
virtual void printImpl(raw_ostream &OS, const MCAsmInfo *MAI) const = 0;
virtual bool evaluateAsRelocatableImpl(MCValue &Res,
const MCAsmLayout *Layout,
const MCFixup *Fixup) const = 0;
virtual void visitUsedExpr(MCStreamer& Streamer) const = 0;
virtual MCSection *findAssociatedSection() const = 0;
virtual void fixELFSymbolsInTLSFixups(MCAssembler &) const = 0;
static bool classof(const MCExpr *E) {
return E->getKind() == MCExpr::Target;
}
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCContext.h | //===- MCContext.h - Machine Code Context -----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCCONTEXT_H
#define LLVM_MC_MCCONTEXT_H
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/Twine.h"
#include "llvm/MC/MCDwarf.h"
#include "llvm/MC/SectionKind.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/raw_ostream.h"
#include <map>
#include <tuple>
#include <vector> // FIXME: Shouldn't be needed.
namespace llvm {
class MCAsmInfo;
class MCExpr;
class MCSection;
class MCSymbol;
class MCSymbolELF;
class MCLabel;
struct MCDwarfFile;
class MCDwarfLoc;
class MCObjectFileInfo;
class MCRegisterInfo;
class MCLineSection;
class SMLoc;
class MCSectionMachO;
class MCSectionELF;
class MCSectionCOFF;
/// Context object for machine code objects. This class owns all of the
/// sections that it creates.
///
class MCContext {
MCContext(const MCContext &) = delete;
MCContext &operator=(const MCContext &) = delete;
public:
typedef StringMap<MCSymbol *, BumpPtrAllocator &> SymbolTable;
private:
/// The SourceMgr for this object, if any.
const SourceMgr *SrcMgr;
/// The MCAsmInfo for this target.
const MCAsmInfo *MAI;
/// The MCRegisterInfo for this target.
const MCRegisterInfo *MRI;
/// The MCObjectFileInfo for this target.
const MCObjectFileInfo *MOFI;
/// Allocator object used for creating machine code objects.
///
/// We use a bump pointer allocator to avoid the need to track all allocated
/// objects.
BumpPtrAllocator Allocator;
/// Bindings of names to symbols.
SymbolTable Symbols;
/// ELF sections can have a corresponding symbol. This maps one to the
/// other.
DenseMap<const MCSectionELF *, MCSymbolELF *> SectionSymbols;
/// A mapping from a local label number and an instance count to a symbol.
/// For example, in the assembly
/// 1:
/// 2:
/// 1:
/// We have three labels represented by the pairs (1, 0), (2, 0) and (1, 1)
DenseMap<std::pair<unsigned, unsigned>, MCSymbol *> LocalSymbols;
/// Keeps tracks of names that were used both for used declared and
/// artificial symbols.
StringMap<bool, BumpPtrAllocator &> UsedNames;
/// The next ID to dole out to an unnamed assembler temporary symbol with
/// a given prefix.
StringMap<unsigned> NextID;
/// Instances of directional local labels.
DenseMap<unsigned, MCLabel *> Instances;
/// NextInstance() creates the next instance of the directional local label
/// for the LocalLabelVal and adds it to the map if needed.
unsigned NextInstance(unsigned LocalLabelVal);
/// GetInstance() gets the current instance of the directional local label
/// for the LocalLabelVal and adds it to the map if needed.
unsigned GetInstance(unsigned LocalLabelVal);
/// The file name of the log file from the environment variable
/// AS_SECURE_LOG_FILE. Which must be set before the .secure_log_unique
/// directive is used or it is an error.
char *SecureLogFile;
/// The stream that gets written to for the .secure_log_unique directive.
raw_ostream *SecureLog;
/// Boolean toggled when .secure_log_unique / .secure_log_reset is seen to
/// catch errors if .secure_log_unique appears twice without
/// .secure_log_reset appearing between them.
bool SecureLogUsed;
/// The compilation directory to use for DW_AT_comp_dir.
SmallString<128> CompilationDir;
/// The main file name if passed in explicitly.
std::string MainFileName;
/// The dwarf file and directory tables from the dwarf .file directive.
/// We now emit a line table for each compile unit. To reduce the prologue
/// size of each line table, the files and directories used by each compile
/// unit are separated.
std::map<unsigned, MCDwarfLineTable> MCDwarfLineTablesCUMap;
/// The current dwarf line information from the last dwarf .loc directive.
MCDwarfLoc CurrentDwarfLoc;
bool DwarfLocSeen;
/// Generate dwarf debugging info for assembly source files.
bool GenDwarfForAssembly;
/// The current dwarf file number when generate dwarf debugging info for
/// assembly source files.
unsigned GenDwarfFileNumber;
/// Sections for generating the .debug_ranges and .debug_aranges sections.
SetVector<MCSection *> SectionsForRanges;
/// The information gathered from labels that will have dwarf label
/// entries when generating dwarf assembly source files.
std::vector<MCGenDwarfLabelEntry> MCGenDwarfLabelEntries;
/// The string to embed in the debug information for the compile unit, if
/// non-empty.
StringRef DwarfDebugFlags;
/// The string to embed in as the dwarf AT_producer for the compile unit, if
/// non-empty.
StringRef DwarfDebugProducer;
/// The maximum version of dwarf that we should emit.
uint16_t DwarfVersion;
/// Honor temporary labels, this is useful for debugging semantic
/// differences between temporary and non-temporary labels (primarily on
/// Darwin).
bool AllowTemporaryLabels;
bool UseNamesOnTempLabels = true;
/// The Compile Unit ID that we are currently processing.
unsigned DwarfCompileUnitID;
struct ELFSectionKey {
std::string SectionName;
StringRef GroupName;
unsigned UniqueID;
ELFSectionKey(StringRef SectionName, StringRef GroupName,
unsigned UniqueID)
: SectionName(SectionName), GroupName(GroupName), UniqueID(UniqueID) {
}
bool operator<(const ELFSectionKey &Other) const {
if (SectionName != Other.SectionName)
return SectionName < Other.SectionName;
if (GroupName != Other.GroupName)
return GroupName < Other.GroupName;
return UniqueID < Other.UniqueID;
}
};
struct COFFSectionKey {
std::string SectionName;
StringRef GroupName;
int SelectionKey;
COFFSectionKey(StringRef SectionName, StringRef GroupName,
int SelectionKey)
: SectionName(SectionName), GroupName(GroupName),
SelectionKey(SelectionKey) {}
bool operator<(const COFFSectionKey &Other) const {
if (SectionName != Other.SectionName)
return SectionName < Other.SectionName;
if (GroupName != Other.GroupName)
return GroupName < Other.GroupName;
return SelectionKey < Other.SelectionKey;
}
};
StringMap<MCSectionMachO *> MachOUniquingMap;
std::map<ELFSectionKey, MCSectionELF *> ELFUniquingMap;
std::map<COFFSectionKey, MCSectionCOFF *> COFFUniquingMap;
StringMap<bool> ELFRelSecNames;
/// Do automatic reset in destructor
bool AutoReset;
MCSymbol *createSymbolImpl(const StringMapEntry<bool> *Name,
bool CanBeUnnamed);
MCSymbol *createSymbol(StringRef Name, bool AlwaysAddSuffix,
bool IsTemporary);
MCSymbol *getOrCreateDirectionalLocalSymbol(unsigned LocalLabelVal,
unsigned Instance);
public:
explicit MCContext(const MCAsmInfo *MAI, const MCRegisterInfo *MRI,
const MCObjectFileInfo *MOFI,
const SourceMgr *Mgr = nullptr, bool DoAutoReset = true);
~MCContext();
const SourceMgr *getSourceManager() const { return SrcMgr; }
const MCAsmInfo *getAsmInfo() const { return MAI; }
const MCRegisterInfo *getRegisterInfo() const { return MRI; }
const MCObjectFileInfo *getObjectFileInfo() const { return MOFI; }
void setAllowTemporaryLabels(bool Value) { AllowTemporaryLabels = Value; }
void setUseNamesOnTempLabels(bool Value) { UseNamesOnTempLabels = Value; }
/// \name Module Lifetime Management
/// @{
/// reset - return object to right after construction state to prepare
/// to process a new module
void reset();
/// @}
/// \name Symbol Management
/// @{
/// Create and return a new linker temporary symbol with a unique but
/// unspecified name.
MCSymbol *createLinkerPrivateTempSymbol();
/// Create and return a new assembler temporary symbol with a unique but
/// unspecified name.
MCSymbol *createTempSymbol(bool CanBeUnnamed = true);
MCSymbol *createTempSymbol(const Twine &Name, bool AlwaysAddSuffix,
bool CanBeUnnamed = true);
/// Create the definition of a directional local symbol for numbered label
/// (used for "1:" definitions).
MCSymbol *createDirectionalLocalSymbol(unsigned LocalLabelVal);
/// Create and return a directional local symbol for numbered label (used
/// for "1b" or 1f" references).
MCSymbol *getDirectionalLocalSymbol(unsigned LocalLabelVal, bool Before);
/// Lookup the symbol inside with the specified \p Name. If it exists,
/// return it. If not, create a forward reference and return it.
///
/// \param Name - The symbol name, which must be unique across all symbols.
MCSymbol *getOrCreateSymbol(const Twine &Name);
MCSymbolELF *getOrCreateSectionSymbol(const MCSectionELF &Section);
/// Gets a symbol that will be defined to the final stack offset of a local
/// variable after codegen.
///
/// \param Idx - The index of a local variable passed to @llvm.localescape.
MCSymbol *getOrCreateFrameAllocSymbol(StringRef FuncName, unsigned Idx);
MCSymbol *getOrCreateParentFrameOffsetSymbol(StringRef FuncName);
MCSymbol *getOrCreateLSDASymbol(StringRef FuncName);
/// Get the symbol for \p Name, or null.
MCSymbol *lookupSymbol(const Twine &Name) const;
/// getSymbols - Get a reference for the symbol table for clients that
/// want to, for example, iterate over all symbols. 'const' because we
/// still want any modifications to the table itself to use the MCContext
/// APIs.
const SymbolTable &getSymbols() const { return Symbols; }
/// @}
/// \name Section Management
/// @{
/// Return the MCSection for the specified mach-o section. This requires
/// the operands to be valid.
MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
unsigned TypeAndAttributes,
unsigned Reserved2, SectionKind K,
const char *BeginSymName = nullptr);
MCSectionMachO *getMachOSection(StringRef Segment, StringRef Section,
unsigned TypeAndAttributes, SectionKind K,
const char *BeginSymName = nullptr) {
return getMachOSection(Segment, Section, TypeAndAttributes, 0, K,
BeginSymName);
}
MCSectionELF *getELFSection(StringRef Section, unsigned Type,
unsigned Flags) {
return getELFSection(Section, Type, Flags, nullptr);
}
MCSectionELF *getELFSection(StringRef Section, unsigned Type,
unsigned Flags, const char *BeginSymName) {
return getELFSection(Section, Type, Flags, 0, "", BeginSymName);
}
MCSectionELF *getELFSection(StringRef Section, unsigned Type,
unsigned Flags, unsigned EntrySize,
StringRef Group) {
return getELFSection(Section, Type, Flags, EntrySize, Group, nullptr);
}
MCSectionELF *getELFSection(StringRef Section, unsigned Type,
unsigned Flags, unsigned EntrySize,
StringRef Group, const char *BeginSymName) {
return getELFSection(Section, Type, Flags, EntrySize, Group, ~0,
BeginSymName);
}
MCSectionELF *getELFSection(StringRef Section, unsigned Type,
unsigned Flags, unsigned EntrySize,
StringRef Group, unsigned UniqueID) {
return getELFSection(Section, Type, Flags, EntrySize, Group, UniqueID,
nullptr);
}
MCSectionELF *getELFSection(StringRef Section, unsigned Type,
unsigned Flags, unsigned EntrySize,
StringRef Group, unsigned UniqueID,
const char *BeginSymName);
MCSectionELF *getELFSection(StringRef Section, unsigned Type,
unsigned Flags, unsigned EntrySize,
const MCSymbolELF *Group, unsigned UniqueID,
const char *BeginSymName,
const MCSectionELF *Associated);
MCSectionELF *createELFRelSection(StringRef Name, unsigned Type,
unsigned Flags, unsigned EntrySize,
const MCSymbolELF *Group,
const MCSectionELF *Associated);
void renameELFSection(MCSectionELF *Section, StringRef Name);
MCSectionELF *createELFGroupSection(const MCSymbolELF *Group);
MCSectionCOFF *getCOFFSection(StringRef Section, unsigned Characteristics,
SectionKind Kind, StringRef COMDATSymName,
int Selection,
const char *BeginSymName = nullptr);
MCSectionCOFF *getCOFFSection(StringRef Section, unsigned Characteristics,
SectionKind Kind,
const char *BeginSymName = nullptr);
MCSectionCOFF *getCOFFSection(StringRef Section);
/// Gets or creates a section equivalent to Sec that is associated with the
/// section containing KeySym. For example, to create a debug info section
/// associated with an inline function, pass the normal debug info section
/// as Sec and the function symbol as KeySym.
MCSectionCOFF *getAssociativeCOFFSection(MCSectionCOFF *Sec,
const MCSymbol *KeySym);
/// @}
/// \name Dwarf Management
/// @{
/// \brief Get the compilation directory for DW_AT_comp_dir
/// This can be overridden by clients which want to control the reported
/// compilation directory and have it be something other than the current
/// working directory.
/// Returns an empty string if the current directory cannot be determined.
StringRef getCompilationDir() const { return CompilationDir; }
/// \brief Set the compilation directory for DW_AT_comp_dir
/// Override the default (CWD) compilation directory.
void setCompilationDir(StringRef S) { CompilationDir = S.str(); }
/// \brief Get the main file name for use in error messages and debug
/// info. This can be set to ensure we've got the correct file name
/// after preprocessing or for -save-temps.
const std::string &getMainFileName() const { return MainFileName; }
/// \brief Set the main file name and override the default.
void setMainFileName(StringRef S) { MainFileName = S; }
/// Creates an entry in the dwarf file and directory tables.
unsigned getDwarfFile(StringRef Directory, StringRef FileName,
unsigned FileNumber, unsigned CUID);
bool isValidDwarfFileNumber(unsigned FileNumber, unsigned CUID = 0);
const std::map<unsigned, MCDwarfLineTable> &getMCDwarfLineTables() const {
return MCDwarfLineTablesCUMap;
}
MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) {
return MCDwarfLineTablesCUMap[CUID];
}
const MCDwarfLineTable &getMCDwarfLineTable(unsigned CUID) const {
auto I = MCDwarfLineTablesCUMap.find(CUID);
assert(I != MCDwarfLineTablesCUMap.end());
return I->second;
}
const SmallVectorImpl<MCDwarfFile> &getMCDwarfFiles(unsigned CUID = 0) {
return getMCDwarfLineTable(CUID).getMCDwarfFiles();
}
const SmallVectorImpl<std::string> &getMCDwarfDirs(unsigned CUID = 0) {
return getMCDwarfLineTable(CUID).getMCDwarfDirs();
}
bool hasMCLineSections() const {
for (const auto &Table : MCDwarfLineTablesCUMap)
if (!Table.second.getMCDwarfFiles().empty() || Table.second.getLabel())
return true;
return false;
}
unsigned getDwarfCompileUnitID() { return DwarfCompileUnitID; }
void setDwarfCompileUnitID(unsigned CUIndex) {
DwarfCompileUnitID = CUIndex;
}
void setMCLineTableCompilationDir(unsigned CUID, StringRef CompilationDir) {
getMCDwarfLineTable(CUID).setCompilationDir(CompilationDir);
}
/// Saves the information from the currently parsed dwarf .loc directive
/// and sets DwarfLocSeen. When the next instruction is assembled an entry
/// in the line number table with this information and the address of the
/// instruction will be created.
void setCurrentDwarfLoc(unsigned FileNum, unsigned Line, unsigned Column,
unsigned Flags, unsigned Isa,
unsigned Discriminator) {
CurrentDwarfLoc.setFileNum(FileNum);
CurrentDwarfLoc.setLine(Line);
CurrentDwarfLoc.setColumn(Column);
CurrentDwarfLoc.setFlags(Flags);
CurrentDwarfLoc.setIsa(Isa);
CurrentDwarfLoc.setDiscriminator(Discriminator);
DwarfLocSeen = true;
}
void clearDwarfLocSeen() { DwarfLocSeen = false; }
bool getDwarfLocSeen() { return DwarfLocSeen; }
const MCDwarfLoc &getCurrentDwarfLoc() { return CurrentDwarfLoc; }
bool getGenDwarfForAssembly() { return GenDwarfForAssembly; }
void setGenDwarfForAssembly(bool Value) { GenDwarfForAssembly = Value; }
unsigned getGenDwarfFileNumber() { return GenDwarfFileNumber; }
void setGenDwarfFileNumber(unsigned FileNumber) {
GenDwarfFileNumber = FileNumber;
}
const SetVector<MCSection *> &getGenDwarfSectionSyms() {
return SectionsForRanges;
}
bool addGenDwarfSection(MCSection *Sec) {
return SectionsForRanges.insert(Sec);
}
void finalizeDwarfSections(MCStreamer &MCOS);
const std::vector<MCGenDwarfLabelEntry> &getMCGenDwarfLabelEntries() const {
return MCGenDwarfLabelEntries;
}
void addMCGenDwarfLabelEntry(const MCGenDwarfLabelEntry &E) {
MCGenDwarfLabelEntries.push_back(E);
}
void setDwarfDebugFlags(StringRef S) { DwarfDebugFlags = S; }
StringRef getDwarfDebugFlags() { return DwarfDebugFlags; }
void setDwarfDebugProducer(StringRef S) { DwarfDebugProducer = S; }
StringRef getDwarfDebugProducer() { return DwarfDebugProducer; }
void setDwarfVersion(uint16_t v) { DwarfVersion = v; }
uint16_t getDwarfVersion() const { return DwarfVersion; }
/// @}
char *getSecureLogFile() { return SecureLogFile; }
raw_ostream *getSecureLog() { return SecureLog; }
bool getSecureLogUsed() { return SecureLogUsed; }
void setSecureLog(raw_ostream *Value) { SecureLog = Value; }
void setSecureLogUsed(bool Value) { SecureLogUsed = Value; }
void *allocate(unsigned Size, unsigned Align = 8) {
return Allocator.Allocate(Size, Align);
}
void deallocate(void *Ptr) {}
// Unrecoverable error has occurred. Display the best diagnostic we can
// and bail via exit(1). For now, most MC backend errors are unrecoverable.
// FIXME: We should really do something about that.
LLVM_ATTRIBUTE_NORETURN void reportFatalError(SMLoc L,
const Twine &Msg) const;
};
} // end namespace llvm
// operator new and delete aren't allowed inside namespaces.
// The throw specifications are mandated by the standard.
/// \brief Placement new for using the MCContext's allocator.
///
/// This placement form of operator new uses the MCContext's allocator for
/// obtaining memory. It is a non-throwing new, which means that it returns
/// null on error. (If that is what the allocator does. The current does, so if
/// this ever changes, this operator will have to be changed, too.)
/// Usage looks like this (assuming there's an MCContext 'Context' in scope):
/// \code
/// // Default alignment (8)
/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
/// // Specific alignment
/// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
/// \endcode
/// Please note that you cannot use delete on the pointer; it must be
/// deallocated using an explicit destructor call followed by
/// \c Context.Deallocate(Ptr).
///
/// \param Bytes The number of bytes to allocate. Calculated by the compiler.
/// \param C The MCContext that provides the allocator.
/// \param Alignment The alignment of the allocated memory (if the underlying
/// allocator supports it).
/// \return The allocated memory. Could be NULL.
inline void *operator new(size_t Bytes, llvm::MCContext &C,
size_t Alignment = 8) throw() {
return C.allocate(Bytes, Alignment);
}
/// \brief Placement delete companion to the new above.
///
/// This operator is just a companion to the new above. There is no way of
/// invoking it directly; see the new operator for more details. This operator
/// is called implicitly by the compiler if a placement new expression using
/// the MCContext throws in the object constructor.
inline void operator delete(void *Ptr, llvm::MCContext &C, size_t)
throw () {
C.deallocate(Ptr);
}
/// This placement form of operator new[] uses the MCContext's allocator for
/// obtaining memory. It is a non-throwing new[], which means that it returns
/// null on error.
/// Usage looks like this (assuming there's an MCContext 'Context' in scope):
/// \code
/// // Default alignment (8)
/// char *data = new (Context) char[10];
/// // Specific alignment
/// char *data = new (Context, 4) char[10];
/// \endcode
/// Please note that you cannot use delete on the pointer; it must be
/// deallocated using an explicit destructor call followed by
/// \c Context.Deallocate(Ptr).
///
/// \param Bytes The number of bytes to allocate. Calculated by the compiler.
/// \param C The MCContext that provides the allocator.
/// \param Alignment The alignment of the allocated memory (if the underlying
/// allocator supports it).
/// \return The allocated memory. Could be NULL.
inline void *operator new[](size_t Bytes, llvm::MCContext& C,
size_t Alignment = 8) throw() {
return C.allocate(Bytes, Alignment);
}
/// \brief Placement delete[] companion to the new[] above.
///
/// This operator is just a companion to the new[] above. There is no way of
/// invoking it directly; see the new[] operator for more details. This operator
/// is called implicitly by the compiler if a placement new[] expression using
/// the MCContext throws in the object constructor.
inline void operator delete[](void *Ptr, llvm::MCContext &C) throw () {
C.deallocate(Ptr);
}
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCWinCOFFObjectWriter.h | //===-- llvm/MC/MCWinCOFFObjectWriter.h - Win COFF Object Writer *- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCWINCOFFOBJECTWRITER_H
#define LLVM_MC_MCWINCOFFOBJECTWRITER_H
namespace llvm {
class MCAsmBackend;
class MCFixup;
class MCObjectWriter;
class MCValue;
class raw_ostream;
class raw_pwrite_stream;
class MCWinCOFFObjectTargetWriter {
virtual void anchor();
const unsigned Machine;
protected:
MCWinCOFFObjectTargetWriter(unsigned Machine_);
public:
virtual ~MCWinCOFFObjectTargetWriter() {}
unsigned getMachine() const { return Machine; }
virtual unsigned getRelocType(const MCValue &Target, const MCFixup &Fixup,
bool IsCrossSection,
const MCAsmBackend &MAB) const = 0;
virtual bool recordRelocation(const MCFixup &) const { return true; }
};
/// \brief Construct a new Win COFF writer instance.
///
/// \param MOTW - The target specific WinCOFF writer subclass.
/// \param OS - The stream to write to.
/// \returns The constructed object writer.
MCObjectWriter *createWinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
raw_pwrite_stream &OS);
} // End llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCELFStreamer.h | //===- MCELFStreamer.h - MCStreamer ELF Object File Interface ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCELFSTREAMER_H
#define LLVM_MC_MCELFSTREAMER_H
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/MC/MCDirectives.h"
#include "llvm/MC/MCObjectStreamer.h"
#include "llvm/MC/SectionKind.h"
#include "llvm/Support/DataTypes.h"
#include <vector>
namespace llvm {
class MCAsmBackend;
class MCAssembler;
class MCCodeEmitter;
class MCExpr;
class MCInst;
class raw_ostream;
class MCELFStreamer : public MCObjectStreamer {
public:
MCELFStreamer(MCContext &Context, MCAsmBackend &TAB, raw_pwrite_stream &OS,
MCCodeEmitter *Emitter)
: MCObjectStreamer(Context, TAB, OS, Emitter), SeenIdent(false) {}
~MCELFStreamer() override;
/// state management
void reset() override {
SeenIdent = false;
LocalCommons.clear();
BundleGroups.clear();
MCObjectStreamer::reset();
}
/// \name MCStreamer Interface
/// @{
void InitSections(bool NoExecStack) override;
void ChangeSection(MCSection *Section, const MCExpr *Subsection) override;
void EmitLabel(MCSymbol *Symbol) override;
void EmitAssemblerFlag(MCAssemblerFlag Flag) override;
void EmitThumbFunc(MCSymbol *Func) override;
void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override;
bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
unsigned ByteAlignment) override;
void BeginCOFFSymbolDef(const MCSymbol *Symbol) override;
void EmitCOFFSymbolStorageClass(int StorageClass) override;
void EmitCOFFSymbolType(int Type) override;
void EndCOFFSymbolDef() override;
void emitELFSize(MCSymbolELF *Symbol, const MCExpr *Value) override;
void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
unsigned ByteAlignment) override;
void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
uint64_t Size = 0, unsigned ByteAlignment = 0) override;
void EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size,
unsigned ByteAlignment = 0) override;
void EmitValueImpl(const MCExpr *Value, unsigned Size,
const SMLoc &Loc = SMLoc()) override;
void EmitFileDirective(StringRef Filename) override;
void EmitIdent(StringRef IdentString) override;
void EmitValueToAlignment(unsigned, int64_t, unsigned, unsigned) override;
void Flush() override;
void FinishImpl() override;
void EmitBundleAlignMode(unsigned AlignPow2) override;
void EmitBundleLock(bool AlignToEnd) override;
void EmitBundleUnlock() override;
private:
bool isBundleLocked() const;
void EmitInstToFragment(const MCInst &Inst, const MCSubtargetInfo &) override;
void EmitInstToData(const MCInst &Inst, const MCSubtargetInfo &) override;
void fixSymbolsInTLSFixups(const MCExpr *expr);
/// \brief Merge the content of the fragment \p EF into the fragment \p DF.
void mergeFragment(MCDataFragment *, MCDataFragment *);
bool SeenIdent;
struct LocalCommon {
const MCSymbol *Symbol;
uint64_t Size;
unsigned ByteAlignment;
};
std::vector<LocalCommon> LocalCommons;
/// BundleGroups - The stack of fragments holding the bundle-locked
/// instructions.
llvm::SmallVector<MCDataFragment *, 4> BundleGroups;
};
MCELFStreamer *createARMELFStreamer(MCContext &Context, MCAsmBackend &TAB,
raw_pwrite_stream &OS,
MCCodeEmitter *Emitter, bool RelaxAll,
bool IsThumb);
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCInstrAnalysis.h | //===-- llvm/MC/MCInstrAnalysis.h - InstrDesc target hooks ------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the MCInstrAnalysis class which the MCTargetDescs can
// derive from to give additional information to MC.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCINSTRANALYSIS_H
#define LLVM_MC_MCINSTRANALYSIS_H
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstrDesc.h"
#include "llvm/MC/MCInstrInfo.h"
namespace llvm {
class MCInstrAnalysis {
protected:
friend class Target;
const MCInstrInfo *Info;
public:
MCInstrAnalysis(const MCInstrInfo *Info) : Info(Info) {}
virtual ~MCInstrAnalysis() {}
virtual bool isBranch(const MCInst &Inst) const {
return Info->get(Inst.getOpcode()).isBranch();
}
virtual bool isConditionalBranch(const MCInst &Inst) const {
return Info->get(Inst.getOpcode()).isConditionalBranch();
}
virtual bool isUnconditionalBranch(const MCInst &Inst) const {
return Info->get(Inst.getOpcode()).isUnconditionalBranch();
}
virtual bool isIndirectBranch(const MCInst &Inst) const {
return Info->get(Inst.getOpcode()).isIndirectBranch();
}
virtual bool isCall(const MCInst &Inst) const {
return Info->get(Inst.getOpcode()).isCall();
}
virtual bool isReturn(const MCInst &Inst) const {
return Info->get(Inst.getOpcode()).isReturn();
}
virtual bool isTerminator(const MCInst &Inst) const {
return Info->get(Inst.getOpcode()).isTerminator();
}
/// \brief Given a branch instruction try to get the address the branch
/// targets. Return true on success, and the address in Target.
virtual bool
evaluateBranch(const MCInst &Inst, uint64_t Addr, uint64_t Size,
uint64_t &Target) const;
};
} // End llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCValue.h | //===-- llvm/MC/MCValue.h - MCValue class -----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declaration of the MCValue class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCVALUE_H
#define LLVM_MC_MCVALUE_H
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Support/DataTypes.h"
#include <cassert>
namespace llvm {
class MCAsmInfo;
class raw_ostream;
/// \brief This represents an "assembler immediate".
///
/// In its most general form, this can hold ":Kind:(SymbolA - SymbolB +
/// imm64)". Not all targets supports relocations of this general form, but we
/// need to represent this anyway.
///
/// In general both SymbolA and SymbolB will also have a modifier
/// analogous to the top-level Kind. Current targets are not expected
/// to make use of both though. The choice comes down to whether
/// relocation modifiers apply to the closest symbol or the whole
/// expression.
///
/// In the general form, SymbolB can only be defined if SymbolA is, and both
/// must be in the same (non-external) section. The latter constraint is not
/// enforced, since a symbol's section may not be known at construction.
///
/// Note that this class must remain a simple POD value class, because we need
/// it to live in unions etc.
class MCValue {
const MCSymbolRefExpr *SymA, *SymB;
int64_t Cst;
uint32_t RefKind;
public:
int64_t getConstant() const { return Cst; }
const MCSymbolRefExpr *getSymA() const { return SymA; }
const MCSymbolRefExpr *getSymB() const { return SymB; }
uint32_t getRefKind() const { return RefKind; }
/// \brief Is this an absolute (as opposed to relocatable) value.
bool isAbsolute() const { return !SymA && !SymB; }
/// \brief Print the value to the stream \p OS.
void print(raw_ostream &OS) const;
/// \brief Print the value to stderr.
void dump() const;
MCSymbolRefExpr::VariantKind getAccessVariant() const;
static MCValue get(const MCSymbolRefExpr *SymA,
const MCSymbolRefExpr *SymB = nullptr,
int64_t Val = 0, uint32_t RefKind = 0) {
MCValue R;
assert((!SymB || SymA) && "Invalid relocatable MCValue!");
R.Cst = Val;
R.SymA = SymA;
R.SymB = SymB;
R.RefKind = RefKind;
return R;
}
static MCValue get(int64_t Val) {
MCValue R;
R.Cst = Val;
R.SymA = nullptr;
R.SymB = nullptr;
R.RefKind = 0;
return R;
}
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCSymbolizer.h | //===-- llvm/MC/MCSymbolizer.h - MCSymbolizer class -------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declaration of the MCSymbolizer class, which is used
// to symbolize instructions decoded from an object, that is, transform their
// immediate operands to MCExprs.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCSYMBOLIZER_H
#define LLVM_MC_MCSYMBOLIZER_H
#include "llvm/MC/MCRelocationInfo.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/DataTypes.h"
#include <cassert>
#include <memory>
namespace llvm {
class MCContext;
class MCInst;
class raw_ostream;
/// \brief Symbolize and annotate disassembled instructions.
///
/// For now this mimics the old symbolization logic (from both ARM and x86), that
/// relied on user-provided (C API) callbacks to do the actual symbol lookup in
/// the object file. This was moved to MCExternalSymbolizer.
/// A better API would not rely on actually calling the two methods here from
/// inside each disassembler, but would use the instr info to determine what
/// operands are actually symbolizable, and in what way. I don't think this
/// information exists right now.
class MCSymbolizer {
MCSymbolizer(const MCSymbolizer &) = delete;
void operator=(const MCSymbolizer &) = delete;
protected:
MCContext &Ctx;
std::unique_ptr<MCRelocationInfo> RelInfo;
public:
/// \brief Construct an MCSymbolizer, taking ownership of \p RelInfo.
MCSymbolizer(MCContext &Ctx, std::unique_ptr<MCRelocationInfo> RelInfo)
: Ctx(Ctx), RelInfo(std::move(RelInfo)) {
}
virtual ~MCSymbolizer();
/// \brief Try to add a symbolic operand instead of \p Value to the MCInst.
///
/// Instead of having a difficult to read immediate, a symbolic operand would
/// represent this immediate in a more understandable way, for instance as a
/// symbol or an offset from a symbol. Relocations can also be used to enrich
/// the symbolic expression.
/// \param Inst - The MCInst where to insert the symbolic operand.
/// \param cStream - Stream to print comments and annotations on.
/// \param Value - Operand value, pc-adjusted by the caller if necessary.
/// \param Address - Load address of the instruction.
/// \param IsBranch - Is the instruction a branch?
/// \param Offset - Byte offset of the operand inside the inst.
/// \param InstSize - Size of the instruction in bytes.
/// \return Whether a symbolic operand was added.
virtual bool tryAddingSymbolicOperand(MCInst &Inst, raw_ostream &cStream,
int64_t Value, uint64_t Address,
bool IsBranch, uint64_t Offset,
uint64_t InstSize) = 0;
/// \brief Try to add a comment on the PC-relative load.
/// For instance, in Mach-O, this is used to add annotations to instructions
/// that use C string literals, as found in __cstring.
virtual void tryAddingPcLoadReferenceComment(raw_ostream &cStream,
int64_t Value,
uint64_t Address) = 0;
};
}
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MachineLocation.h | //===-- llvm/MC/MachineLocation.h -------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// The MachineLocation class is used to represent a simple location in a machine
// frame. Locations will be one of two forms; a register or an address formed
// from a base address plus an offset. Register indirection can be specified by
// explicitly passing an offset to the constructor.
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MACHINELOCATION_H
#define LLVM_MC_MACHINELOCATION_H
#include "llvm/Support/Compiler.h"
#include "llvm/Support/DataTypes.h"
namespace llvm {
class MCSymbol;
class MachineLocation {
private:
bool IsRegister; // True if location is a register.
unsigned Register; // gcc/gdb register number.
int Offset; // Displacement if not register.
public:
enum : uint32_t {
// The target register number for an abstract frame pointer. The value is
// an arbitrary value that doesn't collide with any real target register.
VirtualFP = ~0U
};
MachineLocation()
: IsRegister(false), Register(0), Offset(0) {}
/// Create a direct register location.
explicit MachineLocation(unsigned R)
: IsRegister(true), Register(R), Offset(0) {}
/// Create a register-indirect location with an offset.
MachineLocation(unsigned R, int O)
: IsRegister(false), Register(R), Offset(O) {}
bool operator==(const MachineLocation &Other) const {
return IsRegister == Other.IsRegister && Register == Other.Register &&
Offset == Other.Offset;
}
// Accessors.
/// \return true iff this is a register-indirect location.
bool isIndirect() const { return !IsRegister; }
bool isReg() const { return IsRegister; }
unsigned getReg() const { return Register; }
int getOffset() const { return Offset; }
void setIsRegister(bool Is) { IsRegister = Is; }
void setRegister(unsigned R) { Register = R; }
void setOffset(int O) { Offset = O; }
/// Make this location a direct register location.
void set(unsigned R) {
IsRegister = true;
Register = R;
Offset = 0;
}
/// Make this location a register-indirect+offset location.
void set(unsigned R, int O) {
IsRegister = false;
Register = R;
Offset = O;
}
#ifndef NDEBUG
void dump();
#endif
};
inline bool operator!=(const MachineLocation &LHS, const MachineLocation &RHS) {
return !(LHS == RHS);
}
} // End llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCAsmInfoDarwin.h | //===---- MCAsmInfoDarwin.h - Darwin asm properties -------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines target asm properties related what form asm statements
// should take in general on Darwin-based targets
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCASMINFODARWIN_H
#define LLVM_MC_MCASMINFODARWIN_H
#include "llvm/MC/MCAsmInfo.h"
namespace llvm {
class MCAsmInfoDarwin : public MCAsmInfo {
public:
explicit MCAsmInfoDarwin();
bool isSectionAtomizableBySymbols(const MCSection &Section) const override;
};
}
#endif // LLVM_MC_MCASMINFODARWIN_H
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCAsmInfoCOFF.h | //===-- MCAsmInfoCOFF.h - COFF asm properties -------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCASMINFOCOFF_H
#define LLVM_MC_MCASMINFOCOFF_H
#include "llvm/MC/MCAsmInfo.h"
namespace llvm {
class MCAsmInfoCOFF : public MCAsmInfo {
virtual void anchor();
protected:
explicit MCAsmInfoCOFF();
};
class MCAsmInfoMicrosoft : public MCAsmInfoCOFF {
void anchor() override;
protected:
explicit MCAsmInfoMicrosoft();
};
class MCAsmInfoGNUCOFF : public MCAsmInfoCOFF {
void anchor() override;
protected:
explicit MCAsmInfoGNUCOFF();
};
}
#endif // LLVM_MC_MCASMINFOCOFF_H
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCLinkerOptimizationHint.h | //===- MCLinkerOptimizationHint.h - LOH interface ---------------*- C++ -*-===//
//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file declares some helpers classes to handle Linker Optimization Hint
// (LOH).
//
// FIXME: LOH interface supports only MachO format at the moment.
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCLINKEROPTIMIZATIONHINT_H
#define LLVM_MC_MCLINKEROPTIMIZATIONHINT_H
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/MC/MCMachObjectWriter.h"
#include "llvm/Support/raw_ostream.h"
namespace llvm {
// Forward declarations.
class MCAsmLayout;
class MCSymbol;
/// Linker Optimization Hint Type.
enum MCLOHType {
MCLOH_AdrpAdrp = 0x1u, ///< Adrp xY, _v1@PAGE -> Adrp xY, _v2@PAGE.
MCLOH_AdrpLdr = 0x2u, ///< Adrp _v@PAGE -> Ldr _v@PAGEOFF.
MCLOH_AdrpAddLdr = 0x3u, ///< Adrp _v@PAGE -> Add _v@PAGEOFF -> Ldr.
MCLOH_AdrpLdrGotLdr = 0x4u, ///< Adrp _v@GOTPAGE -> Ldr _v@GOTPAGEOFF -> Ldr.
MCLOH_AdrpAddStr = 0x5u, ///< Adrp _v@PAGE -> Add _v@PAGEOFF -> Str.
MCLOH_AdrpLdrGotStr = 0x6u, ///< Adrp _v@GOTPAGE -> Ldr _v@GOTPAGEOFF -> Str.
MCLOH_AdrpAdd = 0x7u, ///< Adrp _v@PAGE -> Add _v@PAGEOFF.
MCLOH_AdrpLdrGot = 0x8u ///< Adrp _v@GOTPAGE -> Ldr _v@GOTPAGEOFF.
};
static inline StringRef MCLOHDirectiveName() {
return StringRef(".loh");
}
static inline bool isValidMCLOHType(unsigned Kind) {
return Kind >= MCLOH_AdrpAdrp && Kind <= MCLOH_AdrpLdrGot;
}
static inline int MCLOHNameToId(StringRef Name) {
#define MCLOHCaseNameToId(Name) .Case(#Name, MCLOH_ ## Name)
return StringSwitch<int>(Name)
MCLOHCaseNameToId(AdrpAdrp)
MCLOHCaseNameToId(AdrpLdr)
MCLOHCaseNameToId(AdrpAddLdr)
MCLOHCaseNameToId(AdrpLdrGotLdr)
MCLOHCaseNameToId(AdrpAddStr)
MCLOHCaseNameToId(AdrpLdrGotStr)
MCLOHCaseNameToId(AdrpAdd)
MCLOHCaseNameToId(AdrpLdrGot)
.Default(-1);
}
static inline StringRef MCLOHIdToName(MCLOHType Kind) {
#define MCLOHCaseIdToName(Name) case MCLOH_ ## Name: return StringRef(#Name);
switch (Kind) {
MCLOHCaseIdToName(AdrpAdrp);
MCLOHCaseIdToName(AdrpLdr);
MCLOHCaseIdToName(AdrpAddLdr);
MCLOHCaseIdToName(AdrpLdrGotLdr);
MCLOHCaseIdToName(AdrpAddStr);
MCLOHCaseIdToName(AdrpLdrGotStr);
MCLOHCaseIdToName(AdrpAdd);
MCLOHCaseIdToName(AdrpLdrGot);
}
return StringRef();
}
static inline int MCLOHIdToNbArgs(MCLOHType Kind) {
switch (Kind) {
// LOH with two arguments
case MCLOH_AdrpAdrp:
case MCLOH_AdrpLdr:
case MCLOH_AdrpAdd:
case MCLOH_AdrpLdrGot:
return 2;
// LOH with three arguments
case MCLOH_AdrpAddLdr:
case MCLOH_AdrpLdrGotLdr:
case MCLOH_AdrpAddStr:
case MCLOH_AdrpLdrGotStr:
return 3;
}
return -1;
}
/// Store Linker Optimization Hint information (LOH).
class MCLOHDirective {
MCLOHType Kind;
/// Arguments of this directive. Order matters.
SmallVector<MCSymbol *, 3> Args;
/// Emit this directive in \p OutStream using the information available
/// in the given \p ObjWriter and \p Layout to get the address of the
/// arguments within the object file.
void emit_impl(raw_ostream &OutStream, const MachObjectWriter &ObjWriter,
const MCAsmLayout &Layout) const;
public:
typedef SmallVectorImpl<MCSymbol *> LOHArgs;
MCLOHDirective(MCLOHType Kind, const LOHArgs &Args)
: Kind(Kind), Args(Args.begin(), Args.end()) {
assert(isValidMCLOHType(Kind) && "Invalid LOH directive type!");
}
MCLOHType getKind() const { return Kind; }
const LOHArgs &getArgs() const { return Args; }
/// Emit this directive as:
/// <kind, numArgs, addr1, ..., addrN>
void emit(MachObjectWriter &ObjWriter, const MCAsmLayout &Layout) const {
raw_ostream &OutStream = ObjWriter.getStream();
emit_impl(OutStream, ObjWriter, Layout);
}
/// Get the size in bytes of this directive if emitted in \p ObjWriter with
/// the given \p Layout.
uint64_t getEmitSize(const MachObjectWriter &ObjWriter,
const MCAsmLayout &Layout) const {
class raw_counting_ostream : public raw_ostream {
uint64_t Count;
void write_impl(const char *, size_t size) override { Count += size; }
uint64_t current_pos() const override { return Count; }
public:
raw_counting_ostream() : Count(0) {}
~raw_counting_ostream() override { flush(); }
};
raw_counting_ostream OutStream;
emit_impl(OutStream, ObjWriter, Layout);
return OutStream.tell();
}
};
class MCLOHContainer {
/// Keep track of the emit size of all the LOHs.
mutable uint64_t EmitSize;
/// Keep track of all LOH directives.
SmallVector<MCLOHDirective, 32> Directives;
public:
typedef SmallVectorImpl<MCLOHDirective> LOHDirectives;
MCLOHContainer() : EmitSize(0) {};
/// Const accessor to the directives.
const LOHDirectives &getDirectives() const {
return Directives;
}
/// Add the directive of the given kind \p Kind with the given arguments
/// \p Args to the container.
void addDirective(MCLOHType Kind, const MCLOHDirective::LOHArgs &Args) {
Directives.push_back(MCLOHDirective(Kind, Args));
}
/// Get the size of the directives if emitted.
uint64_t getEmitSize(const MachObjectWriter &ObjWriter,
const MCAsmLayout &Layout) const {
if (!EmitSize) {
for (const MCLOHDirective &D : Directives)
EmitSize += D.getEmitSize(ObjWriter, Layout);
}
return EmitSize;
}
/// Emit all Linker Optimization Hint in one big table.
/// Each line of the table is emitted by LOHDirective::emit.
void emit(MachObjectWriter &ObjWriter, const MCAsmLayout &Layout) const {
for (const MCLOHDirective &D : Directives)
D.emit(ObjWriter, Layout);
}
void reset() {
Directives.clear();
EmitSize = 0;
}
};
// Add types for specialized template using MCSymbol.
typedef MCLOHDirective::LOHArgs MCLOHArgs;
typedef MCLOHContainer::LOHDirectives MCLOHDirectives;
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCSymbolMachO.h | //===- MCSymbolMachO.h - ---------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCSYMBOLMACHO_H
#define LLVM_MC_MCSYMBOLMACHO_H
#include "llvm/MC/MCSymbol.h"
namespace llvm {
class MCSymbolMachO : public MCSymbol {
/// \brief We store the value for the 'desc' symbol field in the
/// lowest 16 bits of the implementation defined flags.
enum MachOSymbolFlags : uint16_t { // See <mach-o/nlist.h>.
SF_DescFlagsMask = 0xFFFF,
// Reference type flags.
SF_ReferenceTypeMask = 0x0007,
SF_ReferenceTypeUndefinedNonLazy = 0x0000,
SF_ReferenceTypeUndefinedLazy = 0x0001,
SF_ReferenceTypeDefined = 0x0002,
SF_ReferenceTypePrivateDefined = 0x0003,
SF_ReferenceTypePrivateUndefinedNonLazy = 0x0004,
SF_ReferenceTypePrivateUndefinedLazy = 0x0005,
// Other 'desc' flags.
SF_ThumbFunc = 0x0008,
SF_NoDeadStrip = 0x0020,
SF_WeakReference = 0x0040,
SF_WeakDefinition = 0x0080,
SF_SymbolResolver = 0x0100,
// Common alignment
SF_CommonAlignmentMask = 0xF0FF,
SF_CommonAlignmentShift = 8
};
public:
MCSymbolMachO(const StringMapEntry<bool> *Name, bool isTemporary)
: MCSymbol(SymbolKindMachO, Name, isTemporary) {}
// Reference type methods.
void clearReferenceType() const {
modifyFlags(0, SF_ReferenceTypeMask);
}
void setReferenceTypeUndefinedLazy(bool Value) const {
modifyFlags(Value ? SF_ReferenceTypeUndefinedLazy : 0,
SF_ReferenceTypeUndefinedLazy);
}
// Other 'desc' methods.
void setThumbFunc() const {
modifyFlags(SF_ThumbFunc, SF_ThumbFunc);
}
bool isNoDeadStrip() const {
return getFlags() & SF_NoDeadStrip;
}
void setNoDeadStrip() const {
modifyFlags(SF_NoDeadStrip, SF_NoDeadStrip);
}
bool isWeakReference() const {
return getFlags() & SF_WeakReference;
}
void setWeakReference() const {
modifyFlags(SF_WeakReference, SF_WeakReference);
}
bool isWeakDefinition() const {
return getFlags() & SF_WeakDefinition;
}
void setWeakDefinition() const {
modifyFlags(SF_WeakDefinition, SF_WeakDefinition);
}
bool isSymbolResolver() const {
return getFlags() & SF_SymbolResolver;
}
void setSymbolResolver() const {
modifyFlags(SF_SymbolResolver, SF_SymbolResolver);
}
void setDesc(unsigned Value) const {
assert(Value == (Value & SF_DescFlagsMask) &&
"Invalid .desc value!");
setFlags(Value & SF_DescFlagsMask);
}
/// \brief Get the encoded value of the flags as they will be emitted in to
/// the MachO binary
uint16_t getEncodedFlags() const {
uint16_t Flags = getFlags();
// Common alignment is packed into the 'desc' bits.
if (isCommon()) {
if (unsigned Align = getCommonAlignment()) {
unsigned Log2Size = Log2_32(Align);
assert((1U << Log2Size) == Align && "Invalid 'common' alignment!");
if (Log2Size > 15)
report_fatal_error("invalid 'common' alignment '" +
Twine(Align) + "' for '" + getName() + "'",
false);
Flags = (Flags & SF_CommonAlignmentMask) |
(Log2Size << SF_CommonAlignmentShift);
}
}
return Flags;
}
static bool classof(const MCSymbol *S) { return S->isMachO(); }
};
}
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCObjectStreamer.h | //===- MCObjectStreamer.h - MCStreamer Object File Interface ----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCOBJECTSTREAMER_H
#define LLVM_MC_MCOBJECTSTREAMER_H
#include "llvm/ADT/SmallVector.h"
#include "llvm/MC/MCAssembler.h"
#include "llvm/MC/MCSection.h"
#include "llvm/MC/MCStreamer.h"
namespace llvm {
class MCAssembler;
class MCCodeEmitter;
class MCSubtargetInfo;
class MCExpr;
class MCFragment;
class MCDataFragment;
class MCAsmBackend;
class raw_ostream;
class raw_pwrite_stream;
/// \brief Streaming object file generation interface.
///
/// This class provides an implementation of the MCStreamer interface which is
/// suitable for use with the assembler backend. Specific object file formats
/// are expected to subclass this interface to implement directives specific
/// to that file format or custom semantics expected by the object writer
/// implementation.
class MCObjectStreamer : public MCStreamer {
MCAssembler *Assembler;
MCSection::iterator CurInsertionPoint;
bool EmitEHFrame;
bool EmitDebugFrame;
SmallVector<MCSymbol *, 2> PendingLabels;
virtual void EmitInstToData(const MCInst &Inst, const MCSubtargetInfo&) = 0;
void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame) override;
void EmitCFIEndProcImpl(MCDwarfFrameInfo &Frame) override;
protected:
MCObjectStreamer(MCContext &Context, MCAsmBackend &TAB, raw_pwrite_stream &OS,
MCCodeEmitter *Emitter);
~MCObjectStreamer() override;
public:
/// state management
void reset() override;
/// Object streamers require the integrated assembler.
bool isIntegratedAssemblerRequired() const override { return true; }
void EmitFrames(MCAsmBackend *MAB);
void EmitCFISections(bool EH, bool Debug) override;
protected:
MCFragment *getCurrentFragment() const;
void insert(MCFragment *F) {
flushPendingLabels(F);
MCSection *CurSection = getCurrentSectionOnly();
CurSection->getFragmentList().insert(CurInsertionPoint, F);
F->setParent(CurSection);
}
/// Get a data fragment to write into, creating a new one if the current
/// fragment is not a data fragment.
MCDataFragment *getOrCreateDataFragment();
bool changeSectionImpl(MCSection *Section, const MCExpr *Subsection);
/// If any labels have been emitted but not assigned fragments, ensure that
/// they get assigned, either to F if possible or to a new data fragment.
/// Optionally, it is also possible to provide an offset \p FOffset, which
/// will be used as a symbol offset within the fragment.
void flushPendingLabels(MCFragment *F, uint64_t FOffset = 0);
public:
void visitUsedSymbol(const MCSymbol &Sym) override;
MCAssembler &getAssembler() { return *Assembler; }
/// \name MCStreamer Interface
/// @{
void EmitLabel(MCSymbol *Symbol) override;
void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) override;
void EmitValueImpl(const MCExpr *Value, unsigned Size,
const SMLoc &Loc = SMLoc()) override;
void EmitULEB128Value(const MCExpr *Value) override;
void EmitSLEB128Value(const MCExpr *Value) override;
void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol) override;
void ChangeSection(MCSection *Section, const MCExpr *Subsection) override;
void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo& STI) override;
/// \brief Emit an instruction to a special fragment, because this instruction
/// can change its size during relaxation.
virtual void EmitInstToFragment(const MCInst &Inst, const MCSubtargetInfo &);
void EmitBundleAlignMode(unsigned AlignPow2) override;
void EmitBundleLock(bool AlignToEnd) override;
void EmitBundleUnlock() override;
void EmitBytes(StringRef Data) override;
void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
unsigned ValueSize = 1,
unsigned MaxBytesToEmit = 0) override;
void EmitCodeAlignment(unsigned ByteAlignment,
unsigned MaxBytesToEmit = 0) override;
bool EmitValueToOffset(const MCExpr *Offset, unsigned char Value) override;
void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
unsigned Column, unsigned Flags,
unsigned Isa, unsigned Discriminator,
StringRef FileName) override;
void EmitDwarfAdvanceLineAddr(int64_t LineDelta, const MCSymbol *LastLabel,
const MCSymbol *Label,
unsigned PointerSize);
void EmitDwarfAdvanceFrameAddr(const MCSymbol *LastLabel,
const MCSymbol *Label);
void EmitGPRel32Value(const MCExpr *Value) override;
void EmitGPRel64Value(const MCExpr *Value) override;
void EmitFill(uint64_t NumBytes, uint8_t FillValue) override;
void EmitZeros(uint64_t NumBytes) override;
void FinishImpl() override;
/// Emit the absolute difference between two symbols if possible.
///
/// Emit the absolute difference between \c Hi and \c Lo, as long as we can
/// compute it. Currently, that requires that both symbols are in the same
/// data fragment. Otherwise, do nothing and return \c false.
///
/// \pre Offset of \c Hi is greater than the offset \c Lo.
void emitAbsoluteSymbolDiff(const MCSymbol *Hi, const MCSymbol *Lo,
unsigned Size) override;
bool mayHaveInstructions(MCSection &Sec) const override;
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCStreamer.h | //===- MCStreamer.h - High-level Streaming Machine Code Output --*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file declares the MCStreamer class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCSTREAMER_H
#define LLVM_MC_MCSTREAMER_H
#include "dxc/WinAdapter.h" // HLSL Change
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/MC/MCDirectives.h"
#include "llvm/MC/MCDwarf.h"
#include "llvm/MC/MCLinkerOptimizationHint.h"
#include "llvm/MC/MCWinEH.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/SMLoc.h"
#include <string>
namespace llvm {
class MCAsmBackend;
class MCCodeEmitter;
class MCContext;
class MCExpr;
class MCInst;
class MCInstPrinter;
class MCSection;
class MCStreamer;
class MCSymbol;
class MCSymbolELF;
class MCSymbolRefExpr;
class MCSubtargetInfo;
class StringRef;
class Twine;
class raw_ostream;
class formatted_raw_ostream;
class AssemblerConstantPools;
typedef std::pair<MCSection *, const MCExpr *> MCSectionSubPair;
/// Target specific streamer interface. This is used so that targets can
/// implement support for target specific assembly directives.
///
/// If target foo wants to use this, it should implement 3 classes:
/// * FooTargetStreamer : public MCTargetStreamer
/// * FooTargetAsmStreamer : public FooTargetStreamer
/// * FooTargetELFStreamer : public FooTargetStreamer
///
/// FooTargetStreamer should have a pure virtual method for each directive. For
/// example, for a ".bar symbol_name" directive, it should have
/// virtual emitBar(const MCSymbol &Symbol) = 0;
///
/// The FooTargetAsmStreamer and FooTargetELFStreamer classes implement the
/// method. The assembly streamer just prints ".bar symbol_name". The object
/// streamer does whatever is needed to implement .bar in the object file.
///
/// In the assembly printer and parser the target streamer can be used by
/// calling getTargetStreamer and casting it to FooTargetStreamer:
///
/// MCTargetStreamer &TS = OutStreamer.getTargetStreamer();
/// FooTargetStreamer &ATS = static_cast<FooTargetStreamer &>(TS);
///
/// The base classes FooTargetAsmStreamer and FooTargetELFStreamer should
/// *never* be treated differently. Callers should always talk to a
/// FooTargetStreamer.
class MCTargetStreamer {
protected:
MCStreamer &Streamer;
public:
MCTargetStreamer(MCStreamer &S);
virtual ~MCTargetStreamer();
MCStreamer &getStreamer() { return Streamer; }
// Allow a target to add behavior to the EmitLabel of MCStreamer.
virtual void emitLabel(MCSymbol *Symbol);
// Allow a target to add behavior to the emitAssignment of MCStreamer.
virtual void emitAssignment(MCSymbol *Symbol, const MCExpr *Value);
virtual void prettyPrintAsm(MCInstPrinter &InstPrinter, raw_ostream &OS,
const MCInst &Inst, const MCSubtargetInfo &STI);
virtual void finish();
};
// FIXME: declared here because it is used from
// lib/CodeGen/AsmPrinter/ARMException.cpp.
class ARMTargetStreamer : public MCTargetStreamer {
public:
ARMTargetStreamer(MCStreamer &S);
~ARMTargetStreamer() override;
virtual void emitFnStart();
virtual void emitFnEnd();
virtual void emitCantUnwind();
virtual void emitPersonality(const MCSymbol *Personality);
virtual void emitPersonalityIndex(unsigned Index);
virtual void emitHandlerData();
virtual void emitSetFP(unsigned FpReg, unsigned SpReg,
int64_t Offset = 0);
virtual void emitMovSP(unsigned Reg, int64_t Offset = 0);
virtual void emitPad(int64_t Offset);
virtual void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
bool isVector);
virtual void emitUnwindRaw(int64_t StackOffset,
const SmallVectorImpl<uint8_t> &Opcodes);
virtual void switchVendor(StringRef Vendor);
virtual void emitAttribute(unsigned Attribute, unsigned Value);
virtual void emitTextAttribute(unsigned Attribute, StringRef String);
virtual void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
StringRef StringValue = "");
virtual void emitFPU(unsigned FPU);
virtual void emitArch(unsigned Arch);
virtual void emitArchExtension(unsigned ArchExt);
virtual void emitObjectArch(unsigned Arch);
virtual void finishAttributeSection();
virtual void emitInst(uint32_t Inst, char Suffix = '\0');
virtual void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE);
virtual void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value);
void finish() override;
/// Callback used to implement the ldr= pseudo.
/// Add a new entry to the constant pool for the current section and return an
/// MCExpr that can be used to refer to the constant pool location.
const MCExpr *addConstantPoolEntry(const MCExpr *);
/// Callback used to implemnt the .ltorg directive.
/// Emit contents of constant pool for the current section.
void emitCurrentConstantPool();
private:
std::unique_ptr<AssemblerConstantPools> ConstantPools;
};
/// \brief Streaming machine code generation interface.
///
/// This interface is intended to provide a programatic interface that is very
/// similar to the level that an assembler .s file provides. It has callbacks
/// to emit bytes, handle directives, etc. The implementation of this interface
/// retains state to know what the current section is etc.
///
/// There are multiple implementations of this interface: one for writing out
/// a .s file, and implementations that write out .o files of various formats.
///
class MCStreamer {
MCContext &Context;
std::unique_ptr<MCTargetStreamer> TargetStreamer;
MCStreamer(const MCStreamer &) = delete;
MCStreamer &operator=(const MCStreamer &) = delete;
std::vector<MCDwarfFrameInfo> DwarfFrameInfos;
MCDwarfFrameInfo *getCurrentDwarfFrameInfo();
void EnsureValidDwarfFrame();
MCSymbol *EmitCFICommon();
std::vector<WinEH::FrameInfo *> WinFrameInfos;
WinEH::FrameInfo *CurrentWinFrameInfo;
void EnsureValidWinFrameInfo();
/// \brief Tracks an index to represent the order a symbol was emitted in.
/// Zero means we did not emit that symbol.
DenseMap<const MCSymbol *, unsigned> SymbolOrdering;
/// \brief This is stack of current and previous section values saved by
/// PushSection.
SmallVector<std::pair<MCSectionSubPair, MCSectionSubPair>, 4> SectionStack;
protected:
MCStreamer(MCContext &Ctx);
virtual void EmitCFIStartProcImpl(MCDwarfFrameInfo &Frame);
virtual void EmitCFIEndProcImpl(MCDwarfFrameInfo &CurFrame);
WinEH::FrameInfo *getCurrentWinFrameInfo() {
return CurrentWinFrameInfo;
}
virtual void EmitWindowsUnwindTables();
virtual void EmitRawTextImpl(StringRef String);
public:
virtual ~MCStreamer();
void visitUsedExpr(const MCExpr &Expr);
virtual void visitUsedSymbol(const MCSymbol &Sym);
void setTargetStreamer(MCTargetStreamer *TS) {
TargetStreamer.reset(TS);
}
/// State management
///
virtual void reset();
MCContext &getContext() const { return Context; }
MCTargetStreamer *getTargetStreamer() {
return TargetStreamer.get();
}
unsigned getNumFrameInfos() { return DwarfFrameInfos.size(); }
ArrayRef<MCDwarfFrameInfo> getDwarfFrameInfos() const {
return DwarfFrameInfos;
}
unsigned getNumWinFrameInfos() { return WinFrameInfos.size(); }
ArrayRef<WinEH::FrameInfo *> getWinFrameInfos() const {
return WinFrameInfos;
}
void generateCompactUnwindEncodings(MCAsmBackend *MAB);
/// \name Assembly File Formatting.
/// @{
/// \brief Return true if this streamer supports verbose assembly and if it is
/// enabled.
virtual bool isVerboseAsm() const { return false; }
/// \brief Return true if this asm streamer supports emitting unformatted text
/// to the .s file with EmitRawText.
virtual bool hasRawTextSupport() const { return false; }
/// \brief Is the integrated assembler required for this streamer to function
/// correctly?
virtual bool isIntegratedAssemblerRequired() const { return false; }
/// \brief Add a textual command.
///
/// Typically for comments that can be emitted to the generated .s
/// file if applicable as a QoI issue to make the output of the compiler
/// more readable. This only affects the MCAsmStreamer, and only when
/// verbose assembly output is enabled.
///
/// If the comment includes embedded \n's, they will each get the comment
/// prefix as appropriate. The added comment should not end with a \n.
virtual void AddComment(const Twine &T) {}
/// \brief Return a raw_ostream that comments can be written to. Unlike
/// AddComment, you are required to terminate comments with \n if you use this
/// method.
virtual raw_ostream &GetCommentOS();
/// \brief Print T and prefix it with the comment string (normally #) and
/// optionally a tab. This prints the comment immediately, not at the end of
/// the current line. It is basically a safe version of EmitRawText: since it
/// only prints comments, the object streamer ignores it instead of asserting.
virtual void emitRawComment(const Twine &T, bool TabPrefix = true);
/// AddBlankLine - Emit a blank line to a .s file to pretty it up.
virtual void AddBlankLine() {}
/// @}
/// \name Symbol & Section Management
/// @{
/// \brief Return the current section that the streamer is emitting code to.
MCSectionSubPair getCurrentSection() const {
if (!SectionStack.empty())
return SectionStack.back().first;
return MCSectionSubPair();
}
MCSection *getCurrentSectionOnly() const { return getCurrentSection().first; }
/// \brief Return the previous section that the streamer is emitting code to.
MCSectionSubPair getPreviousSection() const {
if (!SectionStack.empty())
return SectionStack.back().second;
return MCSectionSubPair();
}
/// \brief Returns an index to represent the order a symbol was emitted in.
/// (zero if we did not emit that symbol)
unsigned GetSymbolOrder(const MCSymbol *Sym) const {
return SymbolOrdering.lookup(Sym);
}
/// \brief Update streamer for a new active section.
///
/// This is called by PopSection and SwitchSection, if the current
/// section changes.
virtual void ChangeSection(MCSection *, const MCExpr *);
/// \brief Save the current and previous section on the section stack.
void PushSection() {
SectionStack.push_back(
std::make_pair(getCurrentSection(), getPreviousSection()));
}
/// \brief Restore the current and previous section from the section stack.
/// Calls ChangeSection as needed.
///
/// Returns false if the stack was empty.
bool PopSection() {
if (SectionStack.size() <= 1)
return false;
auto I = SectionStack.end();
--I;
MCSectionSubPair OldSection = I->first;
--I;
MCSectionSubPair NewSection = I->first;
if (OldSection != NewSection)
ChangeSection(NewSection.first, NewSection.second);
SectionStack.pop_back();
return true;
}
bool SubSection(const MCExpr *Subsection) {
if (SectionStack.empty())
return false;
SwitchSection(SectionStack.back().first.first, Subsection);
return true;
}
/// Set the current section where code is being emitted to \p Section. This
/// is required to update CurSection.
///
/// This corresponds to assembler directives like .section, .text, etc.
virtual void SwitchSection(MCSection *Section,
const MCExpr *Subsection = nullptr);
/// \brief Set the current section where code is being emitted to \p Section.
/// This is required to update CurSection. This version does not call
/// ChangeSection.
void SwitchSectionNoChange(MCSection *Section,
const MCExpr *Subsection = nullptr) {
assert(Section && "Cannot switch to a null section!");
MCSectionSubPair curSection = SectionStack.back().first;
SectionStack.back().second = curSection;
if (MCSectionSubPair(Section, Subsection) != curSection)
SectionStack.back().first = MCSectionSubPair(Section, Subsection);
}
/// \brief Create the default sections and set the initial one.
virtual void InitSections(bool NoExecStack);
MCSymbol *endSection(MCSection *Section);
/// \brief Sets the symbol's section.
///
/// Each emitted symbol will be tracked in the ordering table,
/// so we can sort on them later.
void AssignSection(MCSymbol *Symbol, MCSection *Section);
/// \brief Emit a label for \p Symbol into the current section.
///
/// This corresponds to an assembler statement such as:
/// foo:
///
/// \param Symbol - The symbol to emit. A given symbol should only be
/// emitted as a label once, and symbols emitted as a label should never be
/// used in an assignment.
// FIXME: These emission are non-const because we mutate the symbol to
// add the section we're emitting it to later.
virtual void EmitLabel(MCSymbol *Symbol);
virtual void EmitEHSymAttributes(const MCSymbol *Symbol, MCSymbol *EHSymbol);
/// \brief Note in the output the specified \p Flag.
virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
/// \brief Emit the given list \p Options of strings as linker
/// options into the output.
virtual void EmitLinkerOptions(ArrayRef<std::string> Kind) {}
/// \brief Note in the output the specified region \p Kind.
virtual void EmitDataRegion(MCDataRegionType Kind) {}
/// \brief Specify the MachO minimum deployment target version.
virtual void EmitVersionMin(MCVersionMinType, unsigned Major, unsigned Minor,
unsigned Update) {}
/// \brief Note in the output that the specified \p Func is a Thumb mode
/// function (ARM target only).
virtual void EmitThumbFunc(MCSymbol *Func);
/// \brief Emit an assignment of \p Value to \p Symbol.
///
/// This corresponds to an assembler statement such as:
/// symbol = value
///
/// The assignment generates no code, but has the side effect of binding the
/// value in the current context. For the assembly streamer, this prints the
/// binding into the .s file.
///
/// \param Symbol - The symbol being assigned to.
/// \param Value - The value for the symbol.
virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
/// \brief Emit an weak reference from \p Alias to \p Symbol.
///
/// This corresponds to an assembler statement such as:
/// .weakref alias, symbol
///
/// \param Alias - The alias that is being created.
/// \param Symbol - The symbol being aliased.
virtual void EmitWeakReference(MCSymbol *Alias, const MCSymbol *Symbol);
/// \brief Add the given \p Attribute to \p Symbol.
virtual bool EmitSymbolAttribute(MCSymbol *Symbol,
MCSymbolAttr Attribute) = 0;
/// \brief Set the \p DescValue for the \p Symbol.
///
/// \param Symbol - The symbol to have its n_desc field set.
/// \param DescValue - The value to set into the n_desc field.
virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
/// \brief Start emitting COFF symbol definition
///
/// \param Symbol - The symbol to have its External & Type fields set.
virtual void BeginCOFFSymbolDef(const MCSymbol *Symbol);
/// \brief Emit the storage class of the symbol.
///
/// \param StorageClass - The storage class the symbol should have.
virtual void EmitCOFFSymbolStorageClass(int StorageClass);
/// \brief Emit the type of the symbol.
///
/// \param Type - A COFF type identifier (see COFF::SymbolType in X86COFF.h)
virtual void EmitCOFFSymbolType(int Type);
/// \brief Marks the end of the symbol definition.
virtual void EndCOFFSymbolDef();
virtual void EmitCOFFSafeSEH(MCSymbol const *Symbol);
/// \brief Emits a COFF section index.
///
/// \param Symbol - Symbol the section number relocation should point to.
virtual void EmitCOFFSectionIndex(MCSymbol const *Symbol);
/// \brief Emits a COFF section relative relocation.
///
/// \param Symbol - Symbol the section relative relocation should point to.
virtual void EmitCOFFSecRel32(MCSymbol const *Symbol);
/// \brief Emit an ELF .size directive.
///
/// This corresponds to an assembler statement such as:
/// .size symbol, expression
virtual void emitELFSize(MCSymbolELF *Symbol, const MCExpr *Value);
/// \brief Emit a Linker Optimization Hint (LOH) directive.
/// \param Args - Arguments of the LOH.
virtual void EmitLOHDirective(MCLOHType Kind, const MCLOHArgs &Args) {}
/// \brief Emit a common symbol.
///
/// \param Symbol - The common symbol to emit.
/// \param Size - The size of the common symbol.
/// \param ByteAlignment - The alignment of the symbol if
/// non-zero. This must be a power of 2.
virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
unsigned ByteAlignment) = 0;
/// \brief Emit a local common (.lcomm) symbol.
///
/// \param Symbol - The common symbol to emit.
/// \param Size - The size of the common symbol.
/// \param ByteAlignment - The alignment of the common symbol in bytes.
virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
unsigned ByteAlignment);
/// \brief Emit the zerofill section and an optional symbol.
///
/// \param Section - The zerofill section to create and or to put the symbol
/// \param Symbol - The zerofill symbol to emit, if non-NULL.
/// \param Size - The size of the zerofill symbol.
/// \param ByteAlignment - The alignment of the zerofill symbol if
/// non-zero. This must be a power of 2 on some targets.
virtual void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
uint64_t Size = 0, unsigned ByteAlignment = 0) = 0;
/// \brief Emit a thread local bss (.tbss) symbol.
///
/// \param Section - The thread local common section.
/// \param Symbol - The thread local common symbol to emit.
/// \param Size - The size of the symbol.
/// \param ByteAlignment - The alignment of the thread local common symbol
/// if non-zero. This must be a power of 2 on some targets.
virtual void EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
uint64_t Size, unsigned ByteAlignment = 0);
/// @}
/// \name Generating Data
/// @{
/// \brief Emit the bytes in \p Data into the output.
///
/// This is used to implement assembler directives such as .byte, .ascii,
/// etc.
virtual void EmitBytes(StringRef Data);
/// \brief Emit the expression \p Value into the output as a native
/// integer of the given \p Size bytes.
///
/// This is used to implement assembler directives such as .word, .quad,
/// etc.
///
/// \param Value - The value to emit.
/// \param Size - The size of the integer (in bytes) to emit. This must
/// match a native machine width.
/// \param Loc - The location of the expression for error reporting.
virtual void EmitValueImpl(const MCExpr *Value, unsigned Size,
const SMLoc &Loc = SMLoc());
void EmitValue(const MCExpr *Value, unsigned Size,
const SMLoc &Loc = SMLoc());
/// \brief Special case of EmitValue that avoids the client having
/// to pass in a MCExpr for constant integers.
virtual void EmitIntValue(uint64_t Value, unsigned Size);
virtual void EmitULEB128Value(const MCExpr *Value);
virtual void EmitSLEB128Value(const MCExpr *Value);
/// \brief Special case of EmitULEB128Value that avoids the client having to
/// pass in a MCExpr for constant integers.
void EmitULEB128IntValue(uint64_t Value, unsigned Padding = 0);
/// \brief Special case of EmitSLEB128Value that avoids the client having to
/// pass in a MCExpr for constant integers.
void EmitSLEB128IntValue(int64_t Value);
/// \brief Special case of EmitValue that avoids the client having to pass in
/// a MCExpr for MCSymbols.
void EmitSymbolValue(const MCSymbol *Sym, unsigned Size,
bool IsSectionRelative = false);
/// \brief Emit the expression \p Value into the output as a gprel64 (64-bit
/// GP relative) value.
///
/// This is used to implement assembler directives such as .gpdword on
/// targets that support them.
virtual void EmitGPRel64Value(const MCExpr *Value);
/// \brief Emit the expression \p Value into the output as a gprel32 (32-bit
/// GP relative) value.
///
/// This is used to implement assembler directives such as .gprel32 on
/// targets that support them.
virtual void EmitGPRel32Value(const MCExpr *Value);
/// \brief Emit NumBytes bytes worth of the value specified by FillValue.
/// This implements directives such as '.space'.
virtual void EmitFill(uint64_t NumBytes, uint8_t FillValue);
/// \brief Emit NumBytes worth of zeros.
/// This function properly handles data in virtual sections.
virtual void EmitZeros(uint64_t NumBytes);
/// \brief Emit some number of copies of \p Value until the byte alignment \p
/// ByteAlignment is reached.
///
/// If the number of bytes need to emit for the alignment is not a multiple
/// of \p ValueSize, then the contents of the emitted fill bytes is
/// undefined.
///
/// This used to implement the .align assembler directive.
///
/// \param ByteAlignment - The alignment to reach. This must be a power of
/// two on some targets.
/// \param Value - The value to use when filling bytes.
/// \param ValueSize - The size of the integer (in bytes) to emit for
/// \p Value. This must match a native machine width.
/// \param MaxBytesToEmit - The maximum numbers of bytes to emit, or 0. If
/// the alignment cannot be reached in this many bytes, no bytes are
/// emitted.
virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
unsigned ValueSize = 1,
unsigned MaxBytesToEmit = 0);
/// \brief Emit nops until the byte alignment \p ByteAlignment is reached.
///
/// This used to align code where the alignment bytes may be executed. This
/// can emit different bytes for different sizes to optimize execution.
///
/// \param ByteAlignment - The alignment to reach. This must be a power of
/// two on some targets.
/// \param MaxBytesToEmit - The maximum numbers of bytes to emit, or 0. If
/// the alignment cannot be reached in this many bytes, no bytes are
/// emitted.
virtual void EmitCodeAlignment(unsigned ByteAlignment,
unsigned MaxBytesToEmit = 0);
/// \brief Emit some number of copies of \p Value until the byte offset \p
/// Offset is reached.
///
/// This is used to implement assembler directives such as .org.
///
/// \param Offset - The offset to reach. This may be an expression, but the
/// expression must be associated with the current section.
/// \param Value - The value to use when filling bytes.
/// \return false on success, true if the offset was invalid.
virtual bool EmitValueToOffset(const MCExpr *Offset,
unsigned char Value = 0);
/// @}
/// \brief Switch to a new logical file. This is used to implement the '.file
/// "foo.c"' assembler directive.
virtual void EmitFileDirective(StringRef Filename);
/// \brief Emit the "identifiers" directive. This implements the
/// '.ident "version foo"' assembler directive.
virtual void EmitIdent(StringRef IdentString) {}
/// \brief Associate a filename with a specified logical file number. This
/// implements the DWARF2 '.file 4 "foo.c"' assembler directive.
virtual unsigned EmitDwarfFileDirective(unsigned FileNo, StringRef Directory,
StringRef Filename,
unsigned CUID = 0);
/// \brief This implements the DWARF2 '.loc fileno lineno ...' assembler
/// directive.
virtual void EmitDwarfLocDirective(unsigned FileNo, unsigned Line,
unsigned Column, unsigned Flags,
unsigned Isa, unsigned Discriminator,
StringRef FileName);
/// Emit the absolute difference between two symbols.
///
/// \pre Offset of \c Hi is greater than the offset \c Lo.
virtual void emitAbsoluteSymbolDiff(const MCSymbol *Hi, const MCSymbol *Lo,
unsigned Size);
virtual MCSymbol *getDwarfLineTableSymbol(unsigned CUID);
virtual void EmitCFISections(bool EH, bool Debug);
void EmitCFIStartProc(bool IsSimple);
void EmitCFIEndProc();
virtual void EmitCFIDefCfa(int64_t Register, int64_t Offset);
virtual void EmitCFIDefCfaOffset(int64_t Offset);
virtual void EmitCFIDefCfaRegister(int64_t Register);
virtual void EmitCFIOffset(int64_t Register, int64_t Offset);
virtual void EmitCFIPersonality(const MCSymbol *Sym, unsigned Encoding);
virtual void EmitCFILsda(const MCSymbol *Sym, unsigned Encoding);
virtual void EmitCFIRememberState();
virtual void EmitCFIRestoreState();
virtual void EmitCFISameValue(int64_t Register);
virtual void EmitCFIRestore(int64_t Register);
virtual void EmitCFIRelOffset(int64_t Register, int64_t Offset);
virtual void EmitCFIAdjustCfaOffset(int64_t Adjustment);
virtual void EmitCFIEscape(StringRef Values);
virtual void EmitCFISignalFrame();
virtual void EmitCFIUndefined(int64_t Register);
virtual void EmitCFIRegister(int64_t Register1, int64_t Register2);
virtual void EmitCFIWindowSave();
virtual void EmitWinCFIStartProc(const MCSymbol *Symbol);
virtual void EmitWinCFIEndProc();
virtual void EmitWinCFIStartChained();
virtual void EmitWinCFIEndChained();
virtual void EmitWinCFIPushReg(unsigned Register);
virtual void EmitWinCFISetFrame(unsigned Register, unsigned Offset);
virtual void EmitWinCFIAllocStack(unsigned Size);
virtual void EmitWinCFISaveReg(unsigned Register, unsigned Offset);
virtual void EmitWinCFISaveXMM(unsigned Register, unsigned Offset);
virtual void EmitWinCFIPushFrame(bool Code);
virtual void EmitWinCFIEndProlog();
virtual void EmitWinEHHandler(const MCSymbol *Sym, bool Unwind, bool Except);
virtual void EmitWinEHHandlerData();
/// \brief Emit the given \p Instruction into the current section.
virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI);
/// \brief Set the bundle alignment mode from now on in the section.
/// The argument is the power of 2 to which the alignment is set. The
/// value 0 means turn the bundle alignment off.
virtual void EmitBundleAlignMode(unsigned AlignPow2);
/// \brief The following instructions are a bundle-locked group.
///
/// \param AlignToEnd - If true, the bundle-locked group will be aligned to
/// the end of a bundle.
virtual void EmitBundleLock(bool AlignToEnd);
/// \brief Ends a bundle-locked group.
virtual void EmitBundleUnlock();
/// \brief If this file is backed by a assembly streamer, this dumps the
/// specified string in the output .s file. This capability is indicated by
/// the hasRawTextSupport() predicate. By default this aborts.
void EmitRawText(const Twine &String);
/// \brief Causes any cached state to be written out.
virtual void Flush() {}
/// \brief Streamer specific finalization.
virtual void FinishImpl();
/// \brief Finish emission of machine code.
void Finish();
virtual bool mayHaveInstructions(MCSection &Sec) const { return true; }
};
/// Create a dummy machine code streamer, which does nothing. This is useful for
/// timing the assembler front end.
MCStreamer *createNullStreamer(MCContext &Ctx);
/// Create a machine code streamer which will print out assembly for the native
/// target, suitable for compiling with a native assembler.
///
/// \param InstPrint - If given, the instruction printer to use. If not given
/// the MCInst representation will be printed. This method takes ownership of
/// InstPrint.
///
/// \param CE - If given, a code emitter to use to show the instruction
/// encoding inline with the assembly. This method takes ownership of \p CE.
///
/// \param TAB - If given, a target asm backend to use to show the fixup
/// information in conjunction with encoding information. This method takes
/// ownership of \p TAB.
///
/// \param ShowInst - Whether to show the MCInst representation inline with
/// the assembly.
MCStreamer *createAsmStreamer(MCContext &Ctx,
std::unique_ptr<formatted_raw_ostream> OS,
bool isVerboseAsm, bool useDwarfDirectory,
MCInstPrinter *InstPrint, MCCodeEmitter *CE,
MCAsmBackend *TAB, bool ShowInst);
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCExternalSymbolizer.h | //===-- llvm/MC/MCExternalSymbolizer.h - ------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declaration of the MCExternalSymbolizer class, which
// enables library users to provide callbacks (through the C API) to do the
// symbolization externally.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCEXTERNALSYMBOLIZER_H
#define LLVM_MC_MCEXTERNALSYMBOLIZER_H
#include "llvm-c/Disassembler.h"
#include "llvm/MC/MCSymbolizer.h"
#include <memory>
namespace llvm {
/// \brief Symbolize using user-provided, C API, callbacks.
///
/// See llvm-c/Disassembler.h.
class MCExternalSymbolizer : public MCSymbolizer {
protected:
/// \name Hooks for symbolic disassembly via the public 'C' interface.
/// @{
/// The function to get the symbolic information for operands.
LLVMOpInfoCallback GetOpInfo;
/// The function to lookup a symbol name.
LLVMSymbolLookupCallback SymbolLookUp;
/// The pointer to the block of symbolic information for above call back.
void *DisInfo;
/// @}
public:
MCExternalSymbolizer(MCContext &Ctx,
std::unique_ptr<MCRelocationInfo> RelInfo,
LLVMOpInfoCallback getOpInfo,
LLVMSymbolLookupCallback symbolLookUp, void *disInfo)
: MCSymbolizer(Ctx, std::move(RelInfo)), GetOpInfo(getOpInfo),
SymbolLookUp(symbolLookUp), DisInfo(disInfo) {}
bool tryAddingSymbolicOperand(MCInst &MI, raw_ostream &CommentStream,
int64_t Value, uint64_t Address, bool IsBranch,
uint64_t Offset, uint64_t InstSize) override;
void tryAddingPcLoadReferenceComment(raw_ostream &CommentStream,
int64_t Value,
uint64_t Address) override;
};
}
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/MC/MCWinCOFFStreamer.h | //===- MCWinCOFFStreamer.h - COFF Object File Interface ---------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCWINCOFFSTREAMER_H
#define LLVM_MC_MCWINCOFFSTREAMER_H
#include "llvm/MC/MCDirectives.h"
#include "llvm/MC/MCObjectStreamer.h"
namespace llvm {
class MCAsmBackend;
class MCContext;
class MCCodeEmitter;
class MCExpr;
class MCInst;
class MCSection;
class MCSubtargetInfo;
class MCSymbol;
class StringRef;
class raw_ostream;
class raw_pwrite_stream;
class MCWinCOFFStreamer : public MCObjectStreamer {
public:
MCWinCOFFStreamer(MCContext &Context, MCAsmBackend &MAB, MCCodeEmitter &CE,
raw_pwrite_stream &OS);
/// state management
void reset() override {
CurSymbol = nullptr;
MCObjectStreamer::reset();
}
/// \name MCStreamer interface
/// \{
void InitSections(bool NoExecStack) override;
void EmitLabel(MCSymbol *Symbol) override;
void EmitAssemblerFlag(MCAssemblerFlag Flag) override;
void EmitThumbFunc(MCSymbol *Func) override;
bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override;
void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) override;
void BeginCOFFSymbolDef(MCSymbol const *Symbol) override;
void EmitCOFFSymbolStorageClass(int StorageClass) override;
void EmitCOFFSymbolType(int Type) override;
void EndCOFFSymbolDef() override;
void EmitCOFFSafeSEH(MCSymbol const *Symbol) override;
void EmitCOFFSectionIndex(MCSymbol const *Symbol) override;
void EmitCOFFSecRel32(MCSymbol const *Symbol) override;
void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
unsigned ByteAlignment) override;
void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size,
unsigned ByteAlignment) override;
void EmitZerofill(MCSection *Section, MCSymbol *Symbol, uint64_t Size,
unsigned ByteAlignment) override;
void EmitTBSSSymbol(MCSection *Section, MCSymbol *Symbol, uint64_t Size,
unsigned ByteAlignment) override;
void EmitFileDirective(StringRef Filename) override;
void EmitIdent(StringRef IdentString) override;
void EmitWinEHHandlerData() override;
void FinishImpl() override;
/// \}
protected:
const MCSymbol *CurSymbol;
void EmitInstToData(const MCInst &Inst, const MCSubtargetInfo &STI) override;
private:
LLVM_ATTRIBUTE_NORETURN void FatalError(const Twine &Msg) const;
};
}
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm/MC | repos/DirectXShaderCompiler/include/llvm/MC/MCParser/AsmLexer.h | //===- AsmLexer.h - Lexer for Assembly Files --------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class declares the lexer for assembly files.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCPARSER_ASMLEXER_H
#define LLVM_MC_MCPARSER_ASMLEXER_H
#include "llvm/ADT/StringRef.h"
#include "llvm/MC/MCParser/MCAsmLexer.h"
#include "llvm/Support/DataTypes.h"
#include <string>
namespace llvm {
class MemoryBuffer;
class MCAsmInfo;
/// AsmLexer - Lexer class for assembly files.
class AsmLexer : public MCAsmLexer {
const MCAsmInfo &MAI;
const char *CurPtr;
StringRef CurBuf;
bool isAtStartOfLine;
void operator=(const AsmLexer&) = delete;
AsmLexer(const AsmLexer&) = delete;
protected:
/// LexToken - Read the next token and return its code.
AsmToken LexToken() override;
public:
AsmLexer(const MCAsmInfo &MAI);
~AsmLexer() override;
void setBuffer(StringRef Buf, const char *ptr = nullptr);
StringRef LexUntilEndOfStatement() override;
StringRef LexUntilEndOfLine();
const AsmToken peekTok(bool ShouldSkipSpace = true) override;
bool isAtStartOfComment(const char *Ptr);
bool isAtStatementSeparator(const char *Ptr);
const MCAsmInfo &getMAI() const { return MAI; }
private:
int getNextChar();
AsmToken ReturnError(const char *Loc, const std::string &Msg);
AsmToken LexIdentifier();
AsmToken LexSlash();
AsmToken LexLineComment();
AsmToken LexDigit();
AsmToken LexSingleQuote();
AsmToken LexQuote();
AsmToken LexFloatLiteral();
AsmToken LexHexFloatLiteral(bool NoIntDigits);
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm/MC | repos/DirectXShaderCompiler/include/llvm/MC/MCParser/MCAsmParser.h | //===-- llvm/MC/MCAsmParser.h - Abstract Asm Parser Interface ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCPARSER_MCASMPARSER_H
#define LLVM_MC_MCPARSER_MCASMPARSER_H
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/MC/MCParser/AsmLexer.h"
#include "llvm/Support/DataTypes.h"
namespace llvm {
class MCAsmInfo;
class MCAsmLexer;
class MCAsmParserExtension;
class MCContext;
class MCExpr;
class MCInstPrinter;
class MCInstrInfo;
class MCStreamer;
class MCTargetAsmParser;
class SMLoc;
class SMRange;
class SourceMgr;
class Twine;
class InlineAsmIdentifierInfo {
public:
void *OpDecl;
bool IsVarDecl;
unsigned Length, Size, Type;
void clear() {
OpDecl = nullptr;
IsVarDecl = false;
Length = 1;
Size = 0;
Type = 0;
}
};
/// \brief Generic Sema callback for assembly parser.
class MCAsmParserSemaCallback {
public:
virtual ~MCAsmParserSemaCallback();
virtual void *LookupInlineAsmIdentifier(StringRef &LineBuf,
InlineAsmIdentifierInfo &Info,
bool IsUnevaluatedContext) = 0;
virtual StringRef LookupInlineAsmLabel(StringRef Identifier, SourceMgr &SM,
SMLoc Location, bool Create) = 0;
virtual bool LookupInlineAsmField(StringRef Base, StringRef Member,
unsigned &Offset) = 0;
};
/// \brief Generic assembler parser interface, for use by target specific
/// assembly parsers.
class MCAsmParser {
public:
typedef bool (*DirectiveHandler)(MCAsmParserExtension*, StringRef, SMLoc);
typedef std::pair<MCAsmParserExtension*, DirectiveHandler>
ExtensionDirectiveHandler;
private:
MCAsmParser(const MCAsmParser &) = delete;
void operator=(const MCAsmParser &) = delete;
MCTargetAsmParser *TargetParser;
unsigned ShowParsedOperands : 1;
protected: // Can only create subclasses.
MCAsmParser();
public:
virtual ~MCAsmParser();
virtual void addDirectiveHandler(StringRef Directive,
ExtensionDirectiveHandler Handler) = 0;
virtual void addAliasForDirective(StringRef Directive, StringRef Alias) = 0;
virtual SourceMgr &getSourceManager() = 0;
virtual MCAsmLexer &getLexer() = 0;
const MCAsmLexer &getLexer() const {
return const_cast<MCAsmParser*>(this)->getLexer();
}
virtual MCContext &getContext() = 0;
/// \brief Return the output streamer for the assembler.
virtual MCStreamer &getStreamer() = 0;
MCTargetAsmParser &getTargetParser() const { return *TargetParser; }
void setTargetParser(MCTargetAsmParser &P);
virtual unsigned getAssemblerDialect() { return 0;}
virtual void setAssemblerDialect(unsigned i) { }
bool getShowParsedOperands() const { return ShowParsedOperands; }
void setShowParsedOperands(bool Value) { ShowParsedOperands = Value; }
/// \brief Run the parser on the input source buffer.
virtual bool Run(bool NoInitialTextSection, bool NoFinalize = false) = 0;
virtual void setParsingInlineAsm(bool V) = 0;
virtual bool isParsingInlineAsm() = 0;
/// \brief Parse MS-style inline assembly.
virtual bool parseMSInlineAsm(
void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
SmallVectorImpl<std::string> &Constraints,
SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) = 0;
/// \brief Emit a note at the location \p L, with the message \p Msg.
virtual void Note(SMLoc L, const Twine &Msg,
ArrayRef<SMRange> Ranges = None) = 0;
/// \brief Emit a warning at the location \p L, with the message \p Msg.
///
/// \return The return value is true, if warnings are fatal.
virtual bool Warning(SMLoc L, const Twine &Msg,
ArrayRef<SMRange> Ranges = None) = 0;
/// \brief Emit an error at the location \p L, with the message \p Msg.
///
/// \return The return value is always true, as an idiomatic convenience to
/// clients.
virtual bool Error(SMLoc L, const Twine &Msg,
ArrayRef<SMRange> Ranges = None) = 0;
/// \brief Get the next AsmToken in the stream, possibly handling file
/// inclusion first.
virtual const AsmToken &Lex() = 0;
/// \brief Get the current AsmToken from the stream.
const AsmToken &getTok() const;
/// \brief Report an error at the current lexer location.
bool TokError(const Twine &Msg, ArrayRef<SMRange> Ranges = None);
/// \brief Parse an identifier or string (as a quoted identifier) and set \p
/// Res to the identifier contents.
virtual bool parseIdentifier(StringRef &Res) = 0;
/// \brief Parse up to the end of statement and return the contents from the
/// current token until the end of the statement; the current token on exit
/// will be either the EndOfStatement or EOF.
virtual StringRef parseStringToEndOfStatement() = 0;
/// \brief Parse the current token as a string which may include escaped
/// characters and return the string contents.
virtual bool parseEscapedString(std::string &Data) = 0;
/// \brief Skip to the end of the current statement, for error recovery.
virtual void eatToEndOfStatement() = 0;
/// \brief Parse an arbitrary expression.
///
/// \param Res - The value of the expression. The result is undefined
/// on error.
/// \return - False on success.
virtual bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) = 0;
bool parseExpression(const MCExpr *&Res);
/// \brief Parse a primary expression.
///
/// \param Res - The value of the expression. The result is undefined
/// on error.
/// \return - False on success.
virtual bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) = 0;
/// \brief Parse an arbitrary expression, assuming that an initial '(' has
/// already been consumed.
///
/// \param Res - The value of the expression. The result is undefined
/// on error.
/// \return - False on success.
virtual bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) = 0;
/// \brief Parse an expression which must evaluate to an absolute value.
///
/// \param Res - The value of the absolute expression. The result is undefined
/// on error.
/// \return - False on success.
virtual bool parseAbsoluteExpression(int64_t &Res) = 0;
/// \brief Ensure that we have a valid section set in the streamer. Otherwise,
/// report an error and switch to .text.
virtual void checkForValidSection() = 0;
/// \brief Parse an arbitrary expression of a specified parenthesis depth,
/// assuming that the initial '(' characters have already been consumed.
///
/// \param ParenDepth - Specifies how many trailing expressions outside the
/// current parentheses we have to parse.
/// \param Res - The value of the expression. The result is undefined
/// on error.
/// \return - False on success.
virtual bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
SMLoc &EndLoc) = 0;
};
/// \brief Create an MCAsmParser instance.
MCAsmParser *createMCAsmParser(SourceMgr &, MCContext &, MCStreamer &,
const MCAsmInfo &);
} // End llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm/MC | repos/DirectXShaderCompiler/include/llvm/MC/MCParser/MCAsmLexer.h | //===-- llvm/MC/MCAsmLexer.h - Abstract Asm Lexer Interface -----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCPARSER_MCASMLEXER_H
#define LLVM_MC_MCPARSER_MCASMLEXER_H
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/SMLoc.h"
namespace llvm {
/// Target independent representation for an assembler token.
class AsmToken {
public:
enum TokenKind {
// Markers
Eof, Error,
// String values.
Identifier,
String,
// Integer values.
Integer,
BigNum, // larger than 64 bits
// Real values.
Real,
// No-value.
EndOfStatement,
Colon,
Space,
Plus, Minus, Tilde,
Slash, // '/'
BackSlash, // '\'
LParen, RParen, LBrac, RBrac, LCurly, RCurly,
Star, Dot, Comma, Dollar, Equal, EqualEqual,
Pipe, PipePipe, Caret,
Amp, AmpAmp, Exclaim, ExclaimEqual, Percent, Hash,
Less, LessEqual, LessLess, LessGreater,
Greater, GreaterEqual, GreaterGreater, At
};
private:
TokenKind Kind;
/// A reference to the entire token contents; this is always a pointer into
/// a memory buffer owned by the source manager.
StringRef Str;
APInt IntVal;
public:
AsmToken() {}
AsmToken(TokenKind Kind, StringRef Str, APInt IntVal)
: Kind(Kind), Str(Str), IntVal(IntVal) {}
AsmToken(TokenKind Kind, StringRef Str, int64_t IntVal = 0)
: Kind(Kind), Str(Str), IntVal(64, IntVal, true) {}
TokenKind getKind() const { return Kind; }
bool is(TokenKind K) const { return Kind == K; }
bool isNot(TokenKind K) const { return Kind != K; }
SMLoc getLoc() const;
SMLoc getEndLoc() const;
SMRange getLocRange() const;
/// Get the contents of a string token (without quotes).
StringRef getStringContents() const {
assert(Kind == String && "This token isn't a string!");
return Str.slice(1, Str.size() - 1);
}
/// Get the identifier string for the current token, which should be an
/// identifier or a string. This gets the portion of the string which should
/// be used as the identifier, e.g., it does not include the quotes on
/// strings.
StringRef getIdentifier() const {
if (Kind == Identifier)
return getString();
return getStringContents();
}
/// Get the string for the current token, this includes all characters (for
/// example, the quotes on strings) in the token.
///
/// The returned StringRef points into the source manager's memory buffer, and
/// is safe to store across calls to Lex().
StringRef getString() const { return Str; }
// FIXME: Don't compute this in advance, it makes every token larger, and is
// also not generally what we want (it is nicer for recovery etc. to lex 123br
// as a single token, then diagnose as an invalid number).
int64_t getIntVal() const {
assert(Kind == Integer && "This token isn't an integer!");
return IntVal.getZExtValue();
}
APInt getAPIntVal() const {
assert((Kind == Integer || Kind == BigNum) &&
"This token isn't an integer!");
return IntVal;
}
};
/// Generic assembler lexer interface, for use by target specific assembly
/// lexers.
class MCAsmLexer {
/// The current token, stored in the base class for faster access.
AsmToken CurTok;
/// The location and description of the current error
SMLoc ErrLoc;
std::string Err;
MCAsmLexer(const MCAsmLexer &) = delete;
void operator=(const MCAsmLexer &) = delete;
protected: // Can only create subclasses.
const char *TokStart;
bool SkipSpace;
bool AllowAtInIdentifier;
MCAsmLexer();
virtual AsmToken LexToken() = 0;
void SetError(const SMLoc &errLoc, const std::string &err) {
ErrLoc = errLoc;
Err = err;
}
public:
virtual ~MCAsmLexer();
/// Consume the next token from the input stream and return it.
///
/// The lexer will continuosly return the end-of-file token once the end of
/// the main input file has been reached.
const AsmToken &Lex() {
return CurTok = LexToken();
}
virtual StringRef LexUntilEndOfStatement() = 0;
/// Get the current source location.
SMLoc getLoc() const;
/// Get the current (last) lexed token.
const AsmToken &getTok() const {
return CurTok;
}
/// Look ahead at the next token to be lexed.
virtual const AsmToken peekTok(bool ShouldSkipSpace = true) = 0;
/// Get the current error location
const SMLoc &getErrLoc() {
return ErrLoc;
}
/// Get the current error string
const std::string &getErr() {
return Err;
}
/// Get the kind of current token.
AsmToken::TokenKind getKind() const { return CurTok.getKind(); }
/// Check if the current token has kind \p K.
bool is(AsmToken::TokenKind K) const { return CurTok.is(K); }
/// Check if the current token has kind \p K.
bool isNot(AsmToken::TokenKind K) const { return CurTok.isNot(K); }
/// Set whether spaces should be ignored by the lexer
void setSkipSpace(bool val) { SkipSpace = val; }
bool getAllowAtInIdentifier() { return AllowAtInIdentifier; }
void setAllowAtInIdentifier(bool v) { AllowAtInIdentifier = v; }
};
} // End llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm/MC | repos/DirectXShaderCompiler/include/llvm/MC/MCParser/MCAsmParserUtils.h | //===------ llvm/MC/MCAsmParserUtils.h - Asm Parser Utilities ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCPARSER_MCASMPARSERUTILS_H
#define LLVM_MC_MCPARSER_MCASMPARSERUTILS_H
namespace llvm {
class MCAsmParser;
class MCExpr;
class MCSymbol;
class StringRef;
namespace MCParserUtils {
/// Parse a value expression and return whether it can be assigned to a symbol
/// with the given name.
///
/// On success, returns false and sets the Symbol and Value output parameters.
bool parseAssignmentExpression(StringRef Name, bool allow_redef,
MCAsmParser &Parser, MCSymbol *&Symbol,
const MCExpr *&Value);
} // namespace MCParserUtils
} // namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm/MC | repos/DirectXShaderCompiler/include/llvm/MC/MCParser/MCParsedAsmOperand.h | //===-- llvm/MC/MCParsedAsmOperand.h - Asm Parser Operand -------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCPARSER_MCPARSEDASMOPERAND_H
#define LLVM_MC_MCPARSER_MCPARSEDASMOPERAND_H
#include <string>
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/SMLoc.h"
namespace llvm {
class raw_ostream;
/// MCParsedAsmOperand - This abstract class represents a source-level assembly
/// instruction operand. It should be subclassed by target-specific code. This
/// base class is used by target-independent clients and is the interface
/// between parsing an asm instruction and recognizing it.
class MCParsedAsmOperand {
/// MCOperandNum - The corresponding MCInst operand number. Only valid when
/// parsing MS-style inline assembly.
unsigned MCOperandNum;
/// Constraint - The constraint on this operand. Only valid when parsing
/// MS-style inline assembly.
std::string Constraint;
public:
MCParsedAsmOperand() {}
virtual ~MCParsedAsmOperand() {}
void setConstraint(StringRef C) { Constraint = C.str(); }
StringRef getConstraint() { return Constraint; }
void setMCOperandNum (unsigned OpNum) { MCOperandNum = OpNum; }
unsigned getMCOperandNum() { return MCOperandNum; }
virtual StringRef getSymName() { return StringRef(); }
virtual void *getOpDecl() { return nullptr; }
/// isToken - Is this a token operand?
virtual bool isToken() const = 0;
/// isImm - Is this an immediate operand?
virtual bool isImm() const = 0;
/// isReg - Is this a register operand?
virtual bool isReg() const = 0;
virtual unsigned getReg() const = 0;
/// isMem - Is this a memory operand?
virtual bool isMem() const = 0;
/// getStartLoc - Get the location of the first token of this operand.
virtual SMLoc getStartLoc() const = 0;
/// getEndLoc - Get the location of the last token of this operand.
virtual SMLoc getEndLoc() const = 0;
/// needAddressOf - Do we need to emit code to get the address of the
/// variable/label? Only valid when parsing MS-style inline assembly.
virtual bool needAddressOf() const { return false; }
/// isOffsetOf - Do we need to emit code to get the offset of the variable,
/// rather then the value of the variable? Only valid when parsing MS-style
/// inline assembly.
virtual bool isOffsetOf() const { return false; }
/// getOffsetOfLoc - Get the location of the offset operator.
virtual SMLoc getOffsetOfLoc() const { return SMLoc(); }
/// print - Print a debug representation of the operand to the given stream.
virtual void print(raw_ostream &OS) const = 0;
/// dump - Print to the debug stream.
virtual void dump() const;
};
// //
///////////////////////////////////////////////////////////////////////////////
// Debugging Support
inline raw_ostream& operator<<(raw_ostream &OS, const MCParsedAsmOperand &MO) {
MO.print(OS);
return OS;
}
} // end namespace llvm.
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm/MC | repos/DirectXShaderCompiler/include/llvm/MC/MCParser/AsmCond.h | //===- AsmCond.h - Assembly file conditional assembly ----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCPARSER_ASMCOND_H
#define LLVM_MC_MCPARSER_ASMCOND_H
namespace llvm {
/// AsmCond - Class to support conditional assembly
///
/// The conditional assembly feature (.if, .else, .elseif and .endif) is
/// implemented with AsmCond that tells us what we are in the middle of
/// processing. Ignore can be either true or false. When true we are ignoring
/// the block of code in the middle of a conditional.
class AsmCond {
public:
enum ConditionalAssemblyType {
NoCond, // no conditional is being processed
IfCond, // inside if conditional
ElseIfCond, // inside elseif conditional
ElseCond // inside else conditional
};
ConditionalAssemblyType TheCond;
bool CondMet;
bool Ignore;
AsmCond() : TheCond(NoCond), CondMet(false), Ignore(false) {}
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm/MC | repos/DirectXShaderCompiler/include/llvm/MC/MCParser/MCAsmParserExtension.h | //===-- llvm/MC/MCAsmParserExtension.h - Asm Parser Hooks -------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_MC_MCPARSER_MCASMPARSEREXTENSION_H
#define LLVM_MC_MCPARSER_MCASMPARSEREXTENSION_H
#include "llvm/ADT/StringRef.h"
#include "llvm/MC/MCParser/MCAsmParser.h"
#include "llvm/Support/SMLoc.h"
namespace llvm {
class Twine;
/// \brief Generic interface for extending the MCAsmParser,
/// which is implemented by target and object file assembly parser
/// implementations.
class MCAsmParserExtension {
MCAsmParserExtension(const MCAsmParserExtension &) = delete;
void operator=(const MCAsmParserExtension &) = delete;
MCAsmParser *Parser;
protected:
MCAsmParserExtension();
// Helper template for implementing static dispatch functions.
template<typename T, bool (T::*Handler)(StringRef, SMLoc)>
static bool HandleDirective(MCAsmParserExtension *Target,
StringRef Directive,
SMLoc DirectiveLoc) {
T *Obj = static_cast<T*>(Target);
return (Obj->*Handler)(Directive, DirectiveLoc);
}
bool BracketExpressionsSupported;
public:
virtual ~MCAsmParserExtension();
/// \brief Initialize the extension for parsing using the given \p Parser.
/// The extension should use the AsmParser interfaces to register its
/// parsing routines.
virtual void Initialize(MCAsmParser &Parser);
/// \name MCAsmParser Proxy Interfaces
/// @{
MCContext &getContext() { return getParser().getContext(); }
MCAsmLexer &getLexer() { return getParser().getLexer(); }
const MCAsmLexer &getLexer() const {
return const_cast<MCAsmParserExtension *>(this)->getLexer();
}
MCAsmParser &getParser() { return *Parser; }
const MCAsmParser &getParser() const {
return const_cast<MCAsmParserExtension*>(this)->getParser();
}
SourceMgr &getSourceManager() { return getParser().getSourceManager(); }
MCStreamer &getStreamer() { return getParser().getStreamer(); }
bool Warning(SMLoc L, const Twine &Msg) {
return getParser().Warning(L, Msg);
}
bool Error(SMLoc L, const Twine &Msg) {
return getParser().Error(L, Msg);
}
bool TokError(const Twine &Msg) {
return getParser().TokError(Msg);
}
const AsmToken &Lex() { return getParser().Lex(); }
const AsmToken &getTok() { return getParser().getTok(); }
bool HasBracketExpressions() const { return BracketExpressionsSupported; }
/// @}
};
} // End llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/Config/AsmParsers.def.in | /*===- llvm/Config/AsmParsers.def - LLVM Assembly Parsers -------*- C++ -*-===*\
|* *|
|* The LLVM Compiler Infrastructure *|
|* *|
|* This file is distributed under the University of Illinois Open Source *|
|* License. See LICENSE.TXT for details. *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This file enumerates all of the assembly-language parsers *|
|* supported by this build of LLVM. Clients of this file should define *|
|* the LLVM_ASM_PARSER macro to be a function-like macro with a *|
|* single parameter (the name of the target whose assembly can be *|
|* generated); including this file will then enumerate all of the *|
|* targets with assembly parsers. *|
|* *|
|* The set of targets supported by LLVM is generated at configuration *|
|* time, at which point this header is generated. Do not modify this *|
|* header directly. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_ASM_PARSER
# error Please define the macro LLVM_ASM_PARSER(TargetName)
#endif
@LLVM_ENUM_ASM_PARSERS@
#undef LLVM_ASM_PARSER
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/Config/llvm-config.h.in | /*===------- llvm/Config/llvm-config.h - llvm configuration -------*- C -*-===*/
/* */
/* The LLVM Compiler Infrastructure */
/* */
/* This file is distributed under the University of Illinois Open Source */
/* License. See LICENSE.TXT for details. */
/* */
/*===----------------------------------------------------------------------===*/
/* This file enumerates variables from the LLVM configuration so that they
can be in exported headers and won't override package specific directives.
This is a C header that can be included in the llvm-c headers. */
#ifndef LLVM_CONFIG_H
#define LLVM_CONFIG_H
/* Installation directory for binary executables */
#undef LLVM_BINDIR
/* Time at which LLVM was configured */
#undef LLVM_CONFIGTIME
/* Installation directory for data files */
#undef LLVM_DATADIR
/* Target triple LLVM will generate code for by default */
#undef LLVM_DEFAULT_TARGET_TRIPLE
/* Installation directory for documentation */
#undef LLVM_DOCSDIR
/* Define to enable checks that alter the LLVM C++ ABI */
#undef LLVM_ENABLE_ABI_BREAKING_CHECKS
/* Define if threads enabled */
#undef LLVM_ENABLE_THREADS
/* Installation directory for config files */
#undef LLVM_ETCDIR
/* Has gcc/MSVC atomic intrinsics */
#undef LLVM_HAS_ATOMICS
/* Host triple LLVM will be executed on */
#undef LLVM_HOST_TRIPLE
/* Installation directory for include files */
#undef LLVM_INCLUDEDIR
/* Installation directory for .info files */
#undef LLVM_INFODIR
/* Installation directory for man pages */
#undef LLVM_MANDIR
/* LLVM architecture name for the native architecture, if available */
#undef LLVM_NATIVE_ARCH
/* LLVM name for the native AsmParser init function, if available */
#undef LLVM_NATIVE_ASMPARSER
/* LLVM name for the native AsmPrinter init function, if available */
#undef LLVM_NATIVE_ASMPRINTER
/* LLVM name for the native Disassembler init function, if available */
#undef LLVM_NATIVE_DISASSEMBLER
/* LLVM name for the native Target init function, if available */
#undef LLVM_NATIVE_TARGET
/* LLVM name for the native TargetInfo init function, if available */
#undef LLVM_NATIVE_TARGETINFO
/* LLVM name for the native target MC init function, if available */
#undef LLVM_NATIVE_TARGETMC
/* Define if this is Unixish platform */
#undef LLVM_ON_UNIX
/* Define if this is Win32ish platform */
#undef LLVM_ON_WIN32
/* Installation prefix directory */
#undef LLVM_PREFIX
/* Define if we have the Intel JIT API runtime support library */
#undef LLVM_USE_INTEL_JITEVENTS
/* Define if we have the oprofile JIT-support library */
#undef LLVM_USE_OPROFILE
/* Major version of the LLVM API */
#undef LLVM_VERSION_MAJOR
/* Minor version of the LLVM API */
#undef LLVM_VERSION_MINOR
/* Patch version of the LLVM API */
#undef LLVM_VERSION_PATCH
/* LLVM version string */
#undef LLVM_VERSION_STRING
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/Config/config.h.cmake | /* include/llvm/Config/config.h.cmake corresponding to config.h.in. */
#ifndef CONFIG_H
#define CONFIG_H
/* Exported configuration */
#include "llvm/Config/llvm-config.h"
/* Bug report URL. */
#define BUG_REPORT_URL "${BUG_REPORT_URL}"
/* Define if you want backtraces on crash */
#cmakedefine ENABLE_BACKTRACES
/* Define to enable crash overrides */
#cmakedefine ENABLE_CRASH_OVERRIDES
/* Define to disable C++ atexit */
#cmakedefine DISABLE_LLVM_DYLIB_ATEXIT
/* Define if position independent code is enabled */
#cmakedefine ENABLE_PIC
/* Define if timestamp information (e.g., __DATE__) is allowed */
#cmakedefine ENABLE_TIMESTAMPS ${ENABLE_TIMESTAMPS}
/* Define to 1 if you have the `arc4random' function. */
#cmakedefine HAVE_DECL_ARC4RANDOM ${HAVE_DECL_ARC4RANDOM}
/* Define to 1 if you have the `backtrace' function. */
#cmakedefine HAVE_BACKTRACE ${HAVE_BACKTRACE}
/* Define to 1 if you have the `bcopy' function. */
#undef HAVE_BCOPY
/* Define to 1 if you have the `closedir' function. */
#cmakedefine HAVE_CLOSEDIR ${HAVE_CLOSEDIR}
/* Define to 1 if you have the <cxxabi.h> header file. */
#cmakedefine HAVE_CXXABI_H ${HAVE_CXXABI_H}
/* Define to 1 if you have the <CrashReporterClient.h> header file. */
#undef HAVE_CRASHREPORTERCLIENT_H
/* can use __crashreporter_info__ */
#undef HAVE_CRASHREPORTER_INFO
/* Define to 1 if you have the declaration of `strerror_s', and to 0 if you
don't. */
#cmakedefine01 HAVE_DECL_STRERROR_S
/* Define to 1 if you have the DIA SDK installed, and to 0 if you don't. */
#cmakedefine HAVE_DIA_SDK ${HAVE_DIA_SDK}
/* Define to 1 if you have the <dirent.h> header file, and it defines `DIR'.
*/
#cmakedefine HAVE_DIRENT_H ${HAVE_DIRENT_H}
/* Define if you have the GNU dld library. */
#undef HAVE_DLD
/* Define to 1 if you have the `dlerror' function. */
#cmakedefine HAVE_DLERROR ${HAVE_DLERROR}
/* Define to 1 if you have the <dlfcn.h> header file. */
#cmakedefine HAVE_DLFCN_H ${HAVE_DLFCN_H}
/* Define if dlopen() is available on this platform. */
#cmakedefine HAVE_DLOPEN ${HAVE_DLOPEN}
/* Define if you have the _dyld_func_lookup function. */
#undef HAVE_DYLD
/* Define to 1 if you have the <errno.h> header file. */
#cmakedefine HAVE_ERRNO_H ${HAVE_ERRNO_H}
/* Define to 1 if you have the <execinfo.h> header file. */
#cmakedefine HAVE_EXECINFO_H ${HAVE_EXECINFO_H}
/* Define to 1 if you have the <fcntl.h> header file. */
#cmakedefine HAVE_FCNTL_H ${HAVE_FCNTL_H}
/* Define to 1 if you have the <fenv.h> header file. */
#cmakedefine HAVE_FENV_H ${HAVE_FENV_H}
/* Define if libffi is available on this platform. */
#cmakedefine HAVE_FFI_CALL ${HAVE_FFI_CALL}
/* Define to 1 if you have the <ffi/ffi.h> header file. */
#cmakedefine HAVE_FFI_FFI_H ${HAVE_FFI_FFI_H}
/* Define to 1 if you have the <ffi.h> header file. */
#cmakedefine HAVE_FFI_H ${HAVE_FFI_H}
/* Define to 1 if you have the `futimes' function. */
#cmakedefine HAVE_FUTIMES ${HAVE_FUTIMES}
/* Define to 1 if you have the `futimens' function */
#cmakedefine HAVE_FUTIMENS ${HAVE_FUTIMENS}
/* Define to 1 if you have the `getcwd' function. */
#cmakedefine HAVE_GETCWD ${HAVE_GETCWD}
/* Define to 1 if you have the `getpagesize' function. */
#cmakedefine HAVE_GETPAGESIZE ${HAVE_GETPAGESIZE}
/* Define to 1 if you have the `getrlimit' function. */
#cmakedefine HAVE_GETRLIMIT ${HAVE_GETRLIMIT}
/* Define to 1 if you have the `getrusage' function. */
#cmakedefine HAVE_GETRUSAGE ${HAVE_GETRUSAGE}
/* Define to 1 if you have the `gettimeofday' function. */
#cmakedefine HAVE_GETTIMEOFDAY ${HAVE_GETTIMEOFDAY}
/* Define to 1 if the system has the type `int64_t'. */
#cmakedefine HAVE_INT64_T ${HAVE_INT64_T}
/* Define to 1 if you have the <inttypes.h> header file. */
#cmakedefine HAVE_INTTYPES_H ${HAVE_INTTYPES_H}
/* Define to 1 if you have the `isatty' function. */
#cmakedefine HAVE_ISATTY 1
/* Define if you have the libdl library or equivalent. */
#cmakedefine HAVE_LIBDL ${HAVE_LIBDL}
/* Define to 1 if you have the `m' library (-lm). */
#undef HAVE_LIBM
/* Define to 1 if you have the `ole32' library (-lole32). */
#undef HAVE_LIBOLE32
/* Define to 1 if you have the `psapi' library (-lpsapi). */
#cmakedefine HAVE_LIBPSAPI ${HAVE_LIBPSAPI}
/* Define to 1 if you have the `pthread' library (-lpthread). */
#cmakedefine HAVE_LIBPTHREAD ${HAVE_LIBPTHREAD}
/* Define to 1 if you have the `shell32' library (-lshell32). */
#cmakedefine HAVE_LIBSHELL32 ${HAVE_LIBSHELL32}
/* Define to 1 if you have the 'z' library (-lz). */
#cmakedefine HAVE_LIBZ ${HAVE_LIBZ}
/* Define to 1 if you have the 'edit' library (-ledit). */
#cmakedefine HAVE_LIBEDIT ${HAVE_LIBEDIT}
/* Define to 1 if you have the <limits.h> header file. */
#cmakedefine HAVE_LIMITS_H ${HAVE_LIMITS_H}
/* Define to 1 if you have the <link.h> header file. */
#cmakedefine HAVE_LINK_H ${HAVE_LINK_H}
/* Define if you can use -rdynamic. */
#define HAVE_LINK_EXPORT_DYNAMIC 1
/* Define if you can use -Wl,-R. to pass -R. to the linker, in order to add
the current directory to the dynamic linker search path. */
#undef HAVE_LINK_R
/* Define to 1 if you have the `longjmp' function. */
#cmakedefine HAVE_LONGJMP ${HAVE_LONGJMP}
/* Define to 1 if you have the <mach/mach.h> header file. */
#cmakedefine HAVE_MACH_MACH_H ${HAVE_MACH_MACH_H}
/* Define to 1 if you have the <mach-o/dyld.h> header file. */
#cmakedefine HAVE_MACH_O_DYLD_H ${HAVE_MACH_O_DYLD_H}
/* Define if mallinfo() is available on this platform. */
#cmakedefine HAVE_MALLINFO ${HAVE_MALLINFO}
/* Define if mallinfo2() is available on this platform. */
#cmakedefine HAVE_MALLINFO2 ${HAVE_MALLINFO2}
/* Define to 1 if you have the <malloc.h> header file. */
#cmakedefine HAVE_MALLOC_H ${HAVE_MALLOC_H}
/* Define to 1 if you have the <malloc/malloc.h> header file. */
#cmakedefine HAVE_MALLOC_MALLOC_H ${HAVE_MALLOC_MALLOC_H}
/* Define to 1 if you have the `malloc_zone_statistics' function. */
#cmakedefine HAVE_MALLOC_ZONE_STATISTICS ${HAVE_MALLOC_ZONE_STATISTICS}
/* Define to 1 if you have the `mallctl` function. */
#cmakedefine HAVE_MALLCTL ${HAVE_MALLCTL}
/* Define to 1 if you have the `mkdtemp' function. */
#cmakedefine HAVE_MKDTEMP ${HAVE_MKDTEMP}
/* Define to 1 if you have the `mkstemp' function. */
#cmakedefine HAVE_MKSTEMP ${HAVE_MKSTEMP}
/* Define to 1 if you have the `mktemp' function. */
#cmakedefine HAVE_MKTEMP ${HAVE_MKTEMP}
/* Define to 1 if you have a working `mmap' system call. */
#undef HAVE_MMAP
/* Define if mmap() uses MAP_ANONYMOUS to map anonymous pages, or undefine if
it uses MAP_ANON */
#undef HAVE_MMAP_ANONYMOUS
/* Define if mmap() can map files into memory */
#undef HAVE_MMAP_FILE
/* Define to 1 if you have the <ndir.h> header file, and it defines `DIR'. */
#cmakedefine HAVE_NDIR_H ${HAVE_NDIR_H}
/* Define to 1 if you have the `opendir' function. */
#cmakedefine HAVE_OPENDIR ${HAVE_OPENDIR}
/* Define to 1 if you have the `posix_spawn' function. */
#cmakedefine HAVE_POSIX_SPAWN ${HAVE_POSIX_SPAWN}
/* Define to 1 if you have the `pread' function. */
#cmakedefine HAVE_PREAD ${HAVE_PREAD}
/* Define if libtool can extract symbol lists from object files. */
#undef HAVE_PRELOADED_SYMBOLS
/* Define to have the %a format string */
#undef HAVE_PRINTF_A
/* Have pthread_getspecific */
#cmakedefine HAVE_PTHREAD_GETSPECIFIC ${HAVE_PTHREAD_GETSPECIFIC}
/* Define to 1 if you have the <pthread.h> header file. */
#cmakedefine HAVE_PTHREAD_H ${HAVE_PTHREAD_H}
/* Have pthread_mutex_lock */
#cmakedefine HAVE_PTHREAD_MUTEX_LOCK ${HAVE_PTHREAD_MUTEX_LOCK}
/* Have pthread_rwlock_init */
#cmakedefine HAVE_PTHREAD_RWLOCK_INIT ${HAVE_PTHREAD_RWLOCK_INIT}
/* Define to 1 if srand48/lrand48/drand48 exist in <stdlib.h> */
#cmakedefine HAVE_RAND48 ${HAVE_RAND48}
/* Define to 1 if you have the `readdir' function. */
#cmakedefine HAVE_READDIR ${HAVE_READDIR}
/* Define to 1 if you have the `realpath' function. */
#cmakedefine HAVE_REALPATH ${HAVE_REALPATH}
/* Define to 1 if you have the `sbrk' function. */
#cmakedefine HAVE_SBRK ${HAVE_SBRK}
/* Define to 1 if you have the `setenv' function. */
#cmakedefine HAVE_SETENV ${HAVE_SETENV}
/* Define to 1 if you have the `setjmp' function. */
#cmakedefine HAVE_SETJMP ${HAVE_SETJMP}
/* Define to 1 if you have the `setrlimit' function. */
#cmakedefine HAVE_SETRLIMIT ${HAVE_SETRLIMIT}
/* Define if you have the shl_load function. */
#undef HAVE_SHL_LOAD
/* Define to 1 if you have the `siglongjmp' function. */
#cmakedefine HAVE_SIGLONGJMP ${HAVE_SIGLONGJMP}
/* Define to 1 if you have the <signal.h> header file. */
#cmakedefine HAVE_SIGNAL_H ${HAVE_SIGNAL_H}
/* Define to 1 if you have the `sigsetjmp' function. */
#cmakedefine HAVE_SIGSETJMP ${HAVE_SIGSETJMP}
/* Define to 1 if you have the <stdint.h> header file. */
#cmakedefine HAVE_STDINT_H ${HAVE_STDINT_H}
/* Set to 1 if the std::isinf function is found in <cmath> */
#undef HAVE_STD_ISINF_IN_CMATH
/* Set to 1 if the std::isnan function is found in <cmath> */
#undef HAVE_STD_ISNAN_IN_CMATH
/* Define to 1 if you have the `strdup' function. */
#cmakedefine HAVE_STRDUP ${HAVE_STRDUP}
/* Define to 1 if you have the `strerror' function. */
#cmakedefine HAVE_STRERROR ${HAVE_STRERROR}
/* Define to 1 if you have the `strerror_r' function. */
#cmakedefine HAVE_STRERROR_R ${HAVE_STRERROR_R}
/* Define to 1 if you have the `strtoll' function. */
#cmakedefine HAVE_STRTOLL ${HAVE_STRTOLL}
/* Define to 1 if you have the `strtoq' function. */
#cmakedefine HAVE_STRTOQ ${HAVE_STRTOQ}
/* Define to 1 if you have the `sysconf' function. */
#undef HAVE_SYSCONF
/* Define to 1 if you have the <sys/dir.h> header file, and it defines `DIR'.
*/
#cmakedefine HAVE_SYS_DIR_H ${HAVE_SYS_DIR_H}
/* Define to 1 if you have the <sys/ioctl.h> header file. */
#cmakedefine HAVE_SYS_IOCTL_H ${HAVE_SYS_IOCTL_H}
/* Define to 1 if you have the <sys/mman.h> header file. */
#cmakedefine HAVE_SYS_MMAN_H ${HAVE_SYS_MMAN_H}
/* Define to 1 if you have the <sys/ndir.h> header file, and it defines `DIR'.
*/
#cmakedefine HAVE_SYS_NDIR_H ${HAVE_SYS_NDIR_H}
/* Define to 1 if you have the <sys/param.h> header file. */
#cmakedefine HAVE_SYS_PARAM_H ${HAVE_SYS_PARAM_H}
/* Define to 1 if you have the <sys/resource.h> header file. */
#cmakedefine HAVE_SYS_RESOURCE_H ${HAVE_SYS_RESOURCE_H}
/* Define to 1 if you have the <sys/stat.h> header file. */
#cmakedefine HAVE_SYS_STAT_H ${HAVE_SYS_STAT_H}
/* Define to 1 if you have the <sys/time.h> header file. */
#cmakedefine HAVE_SYS_TIME_H ${HAVE_SYS_TIME_H}
/* Define to 1 if you have the <sys/types.h> header file. */
#cmakedefine HAVE_SYS_TYPES_H ${HAVE_SYS_TYPES_H}
/* Define to 1 if you have the <sys/uio.h> header file. */
#cmakedefine HAVE_SYS_UIO_H ${HAVE_SYS_UIO_H}
/* Define to 1 if you have <sys/wait.h> that is POSIX.1 compatible. */
#cmakedefine HAVE_SYS_WAIT_H ${HAVE_SYS_WAIT_H}
/* Define if the setupterm() function is supported this platform. */
#cmakedefine HAVE_TERMINFO ${HAVE_TERMINFO}
/* Define to 1 if you have the <termios.h> header file. */
#cmakedefine HAVE_TERMIOS_H ${HAVE_TERMIOS_H}
/* Define to 1 if the system has the type `uint64_t'. */
#cmakedefine HAVE_UINT64_T ${HAVE_UINT64_T}
/* Define to 1 if you have the <unistd.h> header file. */
#cmakedefine HAVE_UNISTD_H ${HAVE_UNISTD_H}
/* Define to 1 if you have the <utime.h> header file. */
#cmakedefine HAVE_UTIME_H ${HAVE_UTIME_H}
/* Define to 1 if the system has the type `u_int64_t'. */
#cmakedefine HAVE_U_INT64_T ${HAVE_U_INT64_T}
/* Define to 1 if you have the <valgrind/valgrind.h> header file. */
#cmakedefine HAVE_VALGRIND_VALGRIND_H ${HAVE_VALGRIND_VALGRIND_H}
/* Define to 1 if you have the `writev' function. */
#cmakedefine HAVE_WRITEV ${HAVE_WRITEV}
/* Define to 1 if you have the <zlib.h> header file. */
#cmakedefine HAVE_ZLIB_H ${HAVE_ZLIB_H}
/* Have host's _alloca */
#cmakedefine HAVE__ALLOCA ${HAVE__ALLOCA}
/* Have host's __alloca */
#cmakedefine HAVE___ALLOCA ${HAVE___ALLOCA}
/* Have host's __ashldi3 */
#cmakedefine HAVE___ASHLDI3 ${HAVE___ASHLDI3}
/* Have host's __ashrdi3 */
#cmakedefine HAVE___ASHRDI3 ${HAVE___ASHRDI3}
/* Have host's __chkstk */
#cmakedefine HAVE___CHKSTK ${HAVE___CHKSTK}
/* Have host's __chkstk_ms */
#cmakedefine HAVE___CHKSTK_MS ${HAVE___CHKSTK_MS}
/* Have host's __cmpdi2 */
#cmakedefine HAVE___CMPDI2 ${HAVE___CMPDI2}
/* Have host's __divdi3 */
#cmakedefine HAVE___DIVDI3 ${HAVE___DIVDI3}
/* Define to 1 if you have the `__dso_handle' function. */
#undef HAVE___DSO_HANDLE
/* Have host's __fixdfdi */
#cmakedefine HAVE___FIXDFDI ${HAVE___FIXDFDI}
/* Have host's __fixsfdi */
#cmakedefine HAVE___FIXSFDI ${HAVE___FIXSFDI}
/* Have host's __floatdidf */
#cmakedefine HAVE___FLOATDIDF ${HAVE___FLOATDIDF}
/* Have host's __lshrdi3 */
#cmakedefine HAVE___LSHRDI3 ${HAVE___LSHRDI3}
/* Have host's __main */
#cmakedefine HAVE___MAIN ${HAVE___MAIN}
/* Have host's __moddi3 */
#cmakedefine HAVE___MODDI3 ${HAVE___MODDI3}
/* Have host's __udivdi3 */
#cmakedefine HAVE___UDIVDI3 ${HAVE___UDIVDI3}
/* Have host's __umoddi3 */
#cmakedefine HAVE___UMODDI3 ${HAVE___UMODDI3}
/* Have host's ___chkstk */
#cmakedefine HAVE____CHKSTK ${HAVE____CHKSTK}
/* Have host's ___chkstk_ms */
#cmakedefine HAVE____CHKSTK_MS ${HAVE____CHKSTK_MS}
/* Linker version detected at compile time. */
#undef HOST_LINK_VERSION
/* Installation directory for binary executables */
#cmakedefine LLVM_BINDIR "${LLVM_BINDIR}"
/* Time at which LLVM was configured */
#cmakedefine LLVM_CONFIGTIME "${LLVM_CONFIGTIME}"
/* Installation directory for data files */
#cmakedefine LLVM_DATADIR "${LLVM_DATADIR}"
/* Target triple LLVM will generate code for by default */
#cmakedefine LLVM_DEFAULT_TARGET_TRIPLE "${LLVM_DEFAULT_TARGET_TRIPLE}"
/* Installation directory for documentation */
#cmakedefine LLVM_DOCSDIR "${LLVM_DOCSDIR}"
/* Define if threads enabled */
#cmakedefine01 LLVM_ENABLE_THREADS
/* Define if zlib compression is available */
#cmakedefine01 LLVM_ENABLE_ZLIB
/* Installation directory for config files */
#cmakedefine LLVM_ETCDIR "${LLVM_ETCDIR}"
/* Has gcc/MSVC atomic intrinsics */
#cmakedefine01 LLVM_HAS_ATOMICS
/* Host triple LLVM will be executed on */
#cmakedefine LLVM_HOST_TRIPLE "${LLVM_HOST_TRIPLE}"
/* Installation directory for include files */
#cmakedefine LLVM_INCLUDEDIR "${LLVM_INCLUDEDIR}"
/* Installation directory for .info files */
#cmakedefine LLVM_INFODIR "${LLVM_INFODIR}"
/* Installation directory for man pages */
#cmakedefine LLVM_MANDIR "${LLVM_MANDIR}"
/* LLVM architecture name for the native architecture, if available */
#cmakedefine LLVM_NATIVE_ARCH ${LLVM_NATIVE_ARCH}
/* LLVM name for the native AsmParser init function, if available */
#cmakedefine LLVM_NATIVE_ASMPARSER LLVMInitialize${LLVM_NATIVE_ARCH}AsmParser
/* LLVM name for the native AsmPrinter init function, if available */
#cmakedefine LLVM_NATIVE_ASMPRINTER LLVMInitialize${LLVM_NATIVE_ARCH}AsmPrinter
/* LLVM name for the native Disassembler init function, if available */
#cmakedefine LLVM_NATIVE_DISASSEMBLER LLVMInitialize${LLVM_NATIVE_ARCH}Disassembler
/* LLVM name for the native Target init function, if available */
#cmakedefine LLVM_NATIVE_TARGET LLVMInitialize${LLVM_NATIVE_ARCH}Target
/* LLVM name for the native TargetInfo init function, if available */
#cmakedefine LLVM_NATIVE_TARGETINFO LLVMInitialize${LLVM_NATIVE_ARCH}TargetInfo
/* LLVM name for the native target MC init function, if available */
#cmakedefine LLVM_NATIVE_TARGETMC LLVMInitialize${LLVM_NATIVE_ARCH}TargetMC
/* Define if this is Unixish platform */
#cmakedefine LLVM_ON_UNIX ${LLVM_ON_UNIX}
/* Define if this is Win32ish platform */
#cmakedefine LLVM_ON_WIN32 ${LLVM_ON_WIN32}
/* Installation prefix directory */
#cmakedefine LLVM_PREFIX "${LLVM_PREFIX}"
/* Define if we have the Intel JIT API runtime support library */
#cmakedefine LLVM_USE_INTEL_JITEVENTS 1
/* Define if we have the oprofile JIT-support library */
#cmakedefine LLVM_USE_OPROFILE 1
/* Major version of the LLVM API */
#define LLVM_VERSION_MAJOR ${LLVM_VERSION_MAJOR}
/* Minor version of the LLVM API */
#define LLVM_VERSION_MINOR ${LLVM_VERSION_MINOR}
/* Patch version of the LLVM API */
#define LLVM_VERSION_PATCH ${LLVM_VERSION_PATCH}
/* LLVM version string */
#define LLVM_VERSION_STRING "${PACKAGE_VERSION}"
/* Define if we link Polly to the tools */
#cmakedefine LINK_POLLY_INTO_TOOLS
/* Define if the OS needs help to load dependent libraries for dlopen(). */
#cmakedefine LTDL_DLOPEN_DEPLIBS ${LTDL_DLOPEN_DEPLIBS}
/* Define to the sub-directory in which libtool stores uninstalled libraries.
*/
#undef LTDL_OBJDIR
/* Define to the extension used for shared libraries, say, ".so". */
#cmakedefine LTDL_SHLIB_EXT "${LTDL_SHLIB_EXT}"
/* Define to the system default library search path. */
#cmakedefine LTDL_SYSSEARCHPATH "${LTDL_SYSSEARCHPATH}"
/* Define if /dev/zero should be used when mapping RWX memory, or undefine if
its not necessary */
#undef NEED_DEV_ZERO_FOR_MMAP
/* Define if dlsym() requires a leading underscore in symbol names. */
#undef NEED_USCORE
/* Define to the address where bug reports for this package should be sent. */
#cmakedefine PACKAGE_BUGREPORT "${PACKAGE_BUGREPORT}"
/* Define to the full name of this package. */
#cmakedefine PACKAGE_NAME "${PACKAGE_NAME}"
/* Define to the full name and version of this package. */
#cmakedefine PACKAGE_STRING "${PACKAGE_STRING}"
/* Define to the one symbol short name of this package. */
#undef PACKAGE_TARNAME
/* Define to the version of this package. */
#cmakedefine PACKAGE_VERSION "${PACKAGE_VERSION}"
/* Define as the return type of signal handlers (`int' or `void'). */
#cmakedefine RETSIGTYPE ${RETSIGTYPE}
/* Define to 1 if the `S_IS*' macros in <sys/stat.h> do not work properly. */
#undef STAT_MACROS_BROKEN
/* Define to 1 if you have the ANSI C header files. */
#undef STDC_HEADERS
/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
#undef TIME_WITH_SYS_TIME
/* Define to 1 if your <sys/time.h> declares `struct tm'. */
#undef TM_IN_SYS_TIME
/* Type of 1st arg on ELM Callback */
#cmakedefine WIN32_ELMCB_PCSTR ${WIN32_ELMCB_PCSTR}
/* Define to `int' if <sys/types.h> does not define. */
#undef pid_t
/* Define to `unsigned int' if <sys/types.h> does not define. */
#undef size_t
/* Define to a function replacing strtoll */
#cmakedefine strtoll ${strtoll}
/* Define to a function implementing strtoull */
#cmakedefine strtoull ${strtoull}
/* Define to a function implementing stricmp */
#cmakedefine stricmp ${stricmp}
/* Define to a function implementing strdup */
#cmakedefine strdup ${strdup}
/* Define to 1 if you have the `_chsize_s' function. */
#cmakedefine HAVE__CHSIZE_S ${HAVE__CHSIZE_S}
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/Config/config.h.in | /* include/llvm/Config/config.h.in. Generated from autoconf/configure.ac by autoheader. */
#ifndef CONFIG_H
#define CONFIG_H
/* Exported configuration */
#include "llvm/Config/llvm-config.h"
/* Bug report URL. */
#undef BUG_REPORT_URL
/* Default OpenMP runtime used by -fopenmp. */
#undef CLANG_DEFAULT_OPENMP_RUNTIME
/* Define if we have libxml2 */
#undef CLANG_HAVE_LIBXML
/* Multilib suffix for libdir. */
#undef CLANG_LIBDIR_SUFFIX
/* Relative directory for resource files */
#undef CLANG_RESOURCE_DIR
/* Directories clang will search for headers */
#undef C_INCLUDE_DIRS
/* Default <path> to all compiler invocations for --sysroot=<path>. */
#undef DEFAULT_SYSROOT
/* Define if you want backtraces on crash */
#undef ENABLE_BACKTRACES
/* Define to enable crash handling overrides */
#undef ENABLE_CRASH_OVERRIDES
/* Define if position independent code is enabled */
#undef ENABLE_PIC
/* Define if timestamp information (e.g., __DATE__) is allowed */
#undef ENABLE_TIMESTAMPS
/* Directory where gcc is installed. */
#undef GCC_INSTALL_PREFIX
/* Define to 1 if you have the `backtrace' function. */
#undef HAVE_BACKTRACE
/* Define to 1 if you have the <CrashReporterClient.h> header file. */
#undef HAVE_CRASHREPORTERCLIENT_H
/* can use __crashreporter_info__ */
#undef HAVE_CRASHREPORTER_INFO
/* Define to 1 if you have the <cxxabi.h> header file. */
#undef HAVE_CXXABI_H
/* Define to 1 if you have the declaration of `arc4random', and to 0 if you
don't. */
#undef HAVE_DECL_ARC4RANDOM
/* Define to 1 if you have the declaration of `FE_ALL_EXCEPT', and to 0 if you
don't. */
#undef HAVE_DECL_FE_ALL_EXCEPT
/* Define to 1 if you have the declaration of `FE_INEXACT', and to 0 if you
don't. */
#undef HAVE_DECL_FE_INEXACT
/* Define to 1 if you have the declaration of `strerror_s', and to 0 if you
don't. */
#undef HAVE_DECL_STRERROR_S
/* Define to 1 if you have the <dirent.h> header file, and it defines `DIR'.
*/
#undef HAVE_DIRENT_H
/* Define to 1 if you have the <dlfcn.h> header file. */
#undef HAVE_DLFCN_H
/* Define if dlopen() is available on this platform. */
#undef HAVE_DLOPEN
/* Define if the dot program is available */
#undef HAVE_DOT
/* Define to 1 if you have the <errno.h> header file. */
#undef HAVE_ERRNO_H
/* Define to 1 if you have the <execinfo.h> header file. */
#undef HAVE_EXECINFO_H
/* Define to 1 if you have the <fcntl.h> header file. */
#undef HAVE_FCNTL_H
/* Define to 1 if you have the <fenv.h> header file. */
#undef HAVE_FENV_H
/* Define if libffi is available on this platform. */
#undef HAVE_FFI_CALL
/* Define to 1 if you have the <ffi/ffi.h> header file. */
#undef HAVE_FFI_FFI_H
/* Define to 1 if you have the <ffi.h> header file. */
#undef HAVE_FFI_H
/* Define to 1 if you have the `futimens' function. */
#undef HAVE_FUTIMENS
/* Define to 1 if you have the `futimes' function. */
#undef HAVE_FUTIMES
/* Define to 1 if you have the `getcwd' function. */
#undef HAVE_GETCWD
/* Define to 1 if you have the `getpagesize' function. */
#undef HAVE_GETPAGESIZE
/* Define to 1 if you have the `getrlimit' function. */
#undef HAVE_GETRLIMIT
/* Define to 1 if you have the `getrusage' function. */
#undef HAVE_GETRUSAGE
/* Define to 1 if you have the `gettimeofday' function. */
#undef HAVE_GETTIMEOFDAY
/* Define to 1 if the system has the type `int64_t'. */
#undef HAVE_INT64_T
/* Define to 1 if you have the <inttypes.h> header file. */
#undef HAVE_INTTYPES_H
/* Define to 1 if you have the `isatty' function. */
#undef HAVE_ISATTY
/* Define if libedit is available on this platform. */
#undef HAVE_LIBEDIT
/* Define to 1 if you have the `m' library (-lm). */
#undef HAVE_LIBM
/* Define to 1 if you have the `ole32' library (-lole32). */
#undef HAVE_LIBOLE32
/* Define to 1 if you have the `psapi' library (-lpsapi). */
#undef HAVE_LIBPSAPI
/* Define to 1 if you have the `pthread' library (-lpthread). */
#undef HAVE_LIBPTHREAD
/* Define to 1 if you have the `shell32' library (-lshell32). */
#undef HAVE_LIBSHELL32
/* Define to 1 if you have the `z' library (-lz). */
#undef HAVE_LIBZ
/* Define if you can use -rdynamic. */
#undef HAVE_LINK_EXPORT_DYNAMIC
/* Define to 1 if you have the <link.h> header file. */
#undef HAVE_LINK_H
/* Define if you can use -Wl,-R. to pass -R. to the linker, in order to add
the current directory to the dynamic linker search path. */
#undef HAVE_LINK_R
/* Define to 1 if you have the `longjmp' function. */
#undef HAVE_LONGJMP
/* Define to 1 if you have the <mach/mach.h> header file. */
#undef HAVE_MACH_MACH_H
/* Define if mallinfo() is available on this platform. */
#undef HAVE_MALLINFO
/* Define if mallinfo() is available on this platform. */
#undef HAVE_MALLINFO2
/* Define to 1 if you have the <malloc.h> header file. */
#undef HAVE_MALLOC_H
/* Define to 1 if you have the <malloc/malloc.h> header file. */
#undef HAVE_MALLOC_MALLOC_H
/* Define to 1 if you have the `malloc_zone_statistics' function. */
#undef HAVE_MALLOC_ZONE_STATISTICS
/* Define to 1 if you have the <memory.h> header file. */
#undef HAVE_MEMORY_H
/* Define to 1 if you have the `mkdtemp' function. */
#undef HAVE_MKDTEMP
/* Define to 1 if you have the `mkstemp' function. */
#undef HAVE_MKSTEMP
/* Define to 1 if you have the `mktemp' function. */
#undef HAVE_MKTEMP
/* Define to 1 if you have a working `mmap' system call. */
#undef HAVE_MMAP
/* Define if mmap() uses MAP_ANONYMOUS to map anonymous pages, or undefine if
it uses MAP_ANON */
#undef HAVE_MMAP_ANONYMOUS
/* Define if mmap() can map files into memory */
#undef HAVE_MMAP_FILE
/* Define to 1 if you have the <ndir.h> header file, and it defines `DIR'. */
#undef HAVE_NDIR_H
/* Define to 1 if you have the `posix_spawn' function. */
#undef HAVE_POSIX_SPAWN
/* Define to 1 if you have the `pread' function. */
#undef HAVE_PREAD
/* Define to have the %a format string */
#undef HAVE_PRINTF_A
/* Have pthread_getspecific */
#undef HAVE_PTHREAD_GETSPECIFIC
/* Define to 1 if you have the <pthread.h> header file. */
#undef HAVE_PTHREAD_H
/* Have pthread_mutex_lock */
#undef HAVE_PTHREAD_MUTEX_LOCK
/* Have pthread_rwlock_init */
#undef HAVE_PTHREAD_RWLOCK_INIT
/* Define to 1 if srand48/lrand48/drand48 exist in <stdlib.h> */
#undef HAVE_RAND48
/* Define to 1 if you have the `realpath' function. */
#undef HAVE_REALPATH
/* Define to 1 if you have the `sbrk' function. */
#undef HAVE_SBRK
/* Define to 1 if you have the `setenv' function. */
#undef HAVE_SETENV
/* Define to 1 if you have the `setjmp' function. */
#undef HAVE_SETJMP
/* Define to 1 if you have the <setjmp.h> header file. */
#undef HAVE_SETJMP_H
/* Define to 1 if you have the `setrlimit' function. */
#undef HAVE_SETRLIMIT
/* Define to 1 if you have the `siglongjmp' function. */
#undef HAVE_SIGLONGJMP
/* Define to 1 if you have the <signal.h> header file. */
#undef HAVE_SIGNAL_H
/* Define to 1 if you have the `sigsetjmp' function. */
#undef HAVE_SIGSETJMP
/* Define to 1 if you have the <stdint.h> header file. */
#undef HAVE_STDINT_H
/* Define to 1 if you have the <stdlib.h> header file. */
#undef HAVE_STDLIB_H
/* Define to 1 if you have the `strerror' function. */
#undef HAVE_STRERROR
/* Define to 1 if you have the `strerror_r' function. */
#undef HAVE_STRERROR_R
/* Define to 1 if you have the <strings.h> header file. */
#undef HAVE_STRINGS_H
/* Define to 1 if you have the <string.h> header file. */
#undef HAVE_STRING_H
/* Define to 1 if you have the `strtoll' function. */
#undef HAVE_STRTOLL
/* Define to 1 if you have the `strtoq' function. */
#undef HAVE_STRTOQ
/* Define to 1 if you have the `sysconf' function. */
#undef HAVE_SYSCONF
/* Define to 1 if you have the <sys/dir.h> header file, and it defines `DIR'.
*/
#undef HAVE_SYS_DIR_H
/* Define to 1 if you have the <sys/ioctl.h> header file. */
#undef HAVE_SYS_IOCTL_H
/* Define to 1 if you have the <sys/mman.h> header file. */
#undef HAVE_SYS_MMAN_H
/* Define to 1 if you have the <sys/ndir.h> header file, and it defines `DIR'.
*/
#undef HAVE_SYS_NDIR_H
/* Define to 1 if you have the <sys/param.h> header file. */
#undef HAVE_SYS_PARAM_H
/* Define to 1 if you have the <sys/resource.h> header file. */
#undef HAVE_SYS_RESOURCE_H
/* Define to 1 if you have the <sys/stat.h> header file. */
#undef HAVE_SYS_STAT_H
/* Define to 1 if you have the <sys/time.h> header file. */
#undef HAVE_SYS_TIME_H
/* Define to 1 if you have the <sys/types.h> header file. */
#undef HAVE_SYS_TYPES_H
/* Define to 1 if you have the <sys/uio.h> header file. */
#undef HAVE_SYS_UIO_H
/* Define to 1 if you have <sys/wait.h> that is POSIX.1 compatible. */
#undef HAVE_SYS_WAIT_H
/* Define if the setupterm() function is supported this platform. */
#undef HAVE_TERMINFO
/* Define to 1 if you have the <termios.h> header file. */
#undef HAVE_TERMIOS_H
/* Define to 1 if the system has the type `uint64_t'. */
#undef HAVE_UINT64_T
/* Define to 1 if you have the <unistd.h> header file. */
#undef HAVE_UNISTD_H
/* Define to 1 if you have the <utime.h> header file. */
#undef HAVE_UTIME_H
/* Define to 1 if the system has the type `u_int64_t'. */
#undef HAVE_U_INT64_T
/* Define to 1 if you have the <valgrind/valgrind.h> header file. */
#undef HAVE_VALGRIND_VALGRIND_H
/* Define to 1 if you have the `writev' function. */
#undef HAVE_WRITEV
/* Define to 1 if you have the <zlib.h> header file. */
#undef HAVE_ZLIB_H
/* Have host's _alloca */
#undef HAVE__ALLOCA
/* Have host's __alloca */
#undef HAVE___ALLOCA
/* Have host's __ashldi3 */
#undef HAVE___ASHLDI3
/* Have host's __ashrdi3 */
#undef HAVE___ASHRDI3
/* Have host's __chkstk */
#undef HAVE___CHKSTK
/* Have host's __chkstk_ms */
#undef HAVE___CHKSTK_MS
/* Have host's __cmpdi2 */
#undef HAVE___CMPDI2
/* Have host's __divdi3 */
#undef HAVE___DIVDI3
/* Define to 1 if you have the `__dso_handle' function. */
#undef HAVE___DSO_HANDLE
/* Have host's __fixdfdi */
#undef HAVE___FIXDFDI
/* Have host's __fixsfdi */
#undef HAVE___FIXSFDI
/* Have host's __floatdidf */
#undef HAVE___FLOATDIDF
/* Have host's __lshrdi3 */
#undef HAVE___LSHRDI3
/* Have host's __main */
#undef HAVE___MAIN
/* Have host's __moddi3 */
#undef HAVE___MODDI3
/* Have host's __udivdi3 */
#undef HAVE___UDIVDI3
/* Have host's __umoddi3 */
#undef HAVE___UMODDI3
/* Have host's ___chkstk */
#undef HAVE____CHKSTK
/* Have host's ___chkstk_ms */
#undef HAVE____CHKSTK_MS
/* Linker version detected at compile time. */
#undef HOST_LINK_VERSION
/* Installation directory for binary executables */
#undef LLVM_BINDIR
/* Time at which LLVM was configured */
#undef LLVM_CONFIGTIME
/* Installation directory for data files */
#undef LLVM_DATADIR
/* Target triple LLVM will generate code for by default */
#undef LLVM_DEFAULT_TARGET_TRIPLE
/* Installation directory for documentation */
#undef LLVM_DOCSDIR
/* Define to enable checks that alter the LLVM C++ ABI */
#undef LLVM_ENABLE_ABI_BREAKING_CHECKS
/* Define if threads enabled */
#undef LLVM_ENABLE_THREADS
/* Define if zlib is enabled */
#undef LLVM_ENABLE_ZLIB
/* Installation directory for config files */
#undef LLVM_ETCDIR
/* Has gcc/MSVC atomic intrinsics */
#undef LLVM_HAS_ATOMICS
/* Host triple LLVM will be executed on */
#undef LLVM_HOST_TRIPLE
/* Installation directory for include files */
#undef LLVM_INCLUDEDIR
/* Installation directory for .info files */
#undef LLVM_INFODIR
/* Installation directory for man pages */
#undef LLVM_MANDIR
/* LLVM architecture name for the native architecture, if available */
#undef LLVM_NATIVE_ARCH
/* LLVM name for the native AsmParser init function, if available */
#undef LLVM_NATIVE_ASMPARSER
/* LLVM name for the native AsmPrinter init function, if available */
#undef LLVM_NATIVE_ASMPRINTER
/* LLVM name for the native Disassembler init function, if available */
#undef LLVM_NATIVE_DISASSEMBLER
/* LLVM name for the native Target init function, if available */
#undef LLVM_NATIVE_TARGET
/* LLVM name for the native TargetInfo init function, if available */
#undef LLVM_NATIVE_TARGETINFO
/* LLVM name for the native target MC init function, if available */
#undef LLVM_NATIVE_TARGETMC
/* Define if this is Unixish platform */
#undef LLVM_ON_UNIX
/* Define if this is Win32ish platform */
#undef LLVM_ON_WIN32
/* Define to path to dot program if found or 'echo dot' otherwise */
#undef LLVM_PATH_DOT
/* Installation prefix directory */
#undef LLVM_PREFIX
/* Define if we have the Intel JIT API runtime support library */
#undef LLVM_USE_INTEL_JITEVENTS
/* Define if we have the oprofile JIT-support library */
#undef LLVM_USE_OPROFILE
/* Major version of the LLVM API */
#undef LLVM_VERSION_MAJOR
/* Minor version of the LLVM API */
#undef LLVM_VERSION_MINOR
/* Patch version of the LLVM API */
#undef LLVM_VERSION_PATCH
/* LLVM version string */
#undef LLVM_VERSION_STRING
/* The shared library extension */
#undef LTDL_SHLIB_EXT
/* Define if /dev/zero should be used when mapping RWX memory, or undefine if
its not necessary */
#undef NEED_DEV_ZERO_FOR_MMAP
/* Define to the address where bug reports for this package should be sent. */
#undef PACKAGE_BUGREPORT
/* Define to the full name of this package. */
#undef PACKAGE_NAME
/* Define to the full name and version of this package. */
#undef PACKAGE_STRING
/* Define to the one symbol short name of this package. */
#undef PACKAGE_TARNAME
/* Define to the version of this package. */
#undef PACKAGE_VERSION
/* Define as the return type of signal handlers (`int' or `void'). */
#undef RETSIGTYPE
/* Define to 1 if the `S_IS*' macros in <sys/stat.h> do not work properly. */
#undef STAT_MACROS_BROKEN
/* Define to 1 if you have the ANSI C header files. */
#undef STDC_HEADERS
/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
#undef TIME_WITH_SYS_TIME
/* Define to 1 if your <sys/time.h> declares `struct tm'. */
#undef TM_IN_SYS_TIME
/* Type of 1st arg on ELM Callback */
#undef WIN32_ELMCB_PCSTR
/* Define to `int' if <sys/types.h> does not define. */
#undef pid_t
/* Define to `unsigned int' if <sys/types.h> does not define. */
#undef size_t
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/Config/llvm-config.h.cmake | /*===------- llvm/Config/llvm-config.h - llvm configuration -------*- C -*-===*/
/* */
/* The LLVM Compiler Infrastructure */
/* */
/* This file is distributed under the University of Illinois Open Source */
/* License. See LICENSE.TXT for details. */
/* */
/*===----------------------------------------------------------------------===*/
/* This file enumerates variables from the LLVM configuration so that they
can be in exported headers and won't override package specific directives.
This is a C header that can be included in the llvm-c headers. */
#ifndef LLVM_CONFIG_H
#define LLVM_CONFIG_H
/* Installation directory for binary executables */
#cmakedefine LLVM_BINDIR "${LLVM_BINDIR}"
/* Time at which LLVM was configured */
#cmakedefine LLVM_CONFIGTIME "${LLVM_CONFIGTIME}"
/* Installation directory for data files */
#cmakedefine LLVM_DATADIR "${LLVM_DATADIR}"
/* Target triple LLVM will generate code for by default */
#cmakedefine LLVM_DEFAULT_TARGET_TRIPLE "${LLVM_DEFAULT_TARGET_TRIPLE}"
/* Installation directory for documentation */
#cmakedefine LLVM_DOCSDIR "${LLVM_DOCSDIR}"
/* Define if threads enabled */
#cmakedefine01 LLVM_ENABLE_THREADS
/* Installation directory for config files */
#cmakedefine LLVM_ETCDIR "${LLVM_ETCDIR}"
/* Has gcc/MSVC atomic intrinsics */
#cmakedefine01 LLVM_HAS_ATOMICS
/* Host triple LLVM will be executed on */
#cmakedefine LLVM_HOST_TRIPLE "${LLVM_HOST_TRIPLE}"
/* Installation directory for include files */
#cmakedefine LLVM_INCLUDEDIR "${LLVM_INCLUDEDIR}"
/* Installation directory for .info files */
#cmakedefine LLVM_INFODIR "${LLVM_INFODIR}"
/* Installation directory for man pages */
#cmakedefine LLVM_MANDIR "${LLVM_MANDIR}"
/* LLVM architecture name for the native architecture, if available */
#cmakedefine LLVM_NATIVE_ARCH ${LLVM_NATIVE_ARCH}
/* LLVM name for the native AsmParser init function, if available */
#cmakedefine LLVM_NATIVE_ASMPARSER LLVMInitialize${LLVM_NATIVE_ARCH}AsmParser
/* LLVM name for the native AsmPrinter init function, if available */
#cmakedefine LLVM_NATIVE_ASMPRINTER LLVMInitialize${LLVM_NATIVE_ARCH}AsmPrinter
/* LLVM name for the native Disassembler init function, if available */
#cmakedefine LLVM_NATIVE_DISASSEMBLER LLVMInitialize${LLVM_NATIVE_ARCH}Disassembler
/* LLVM name for the native Target init function, if available */
#cmakedefine LLVM_NATIVE_TARGET LLVMInitialize${LLVM_NATIVE_ARCH}Target
/* LLVM name for the native TargetInfo init function, if available */
#cmakedefine LLVM_NATIVE_TARGETINFO LLVMInitialize${LLVM_NATIVE_ARCH}TargetInfo
/* LLVM name for the native target MC init function, if available */
#cmakedefine LLVM_NATIVE_TARGETMC LLVMInitialize${LLVM_NATIVE_ARCH}TargetMC
/* Define if this is Unixish platform */
#cmakedefine LLVM_ON_UNIX ${LLVM_ON_UNIX}
/* Define if this is Win32ish platform */
#cmakedefine LLVM_ON_WIN32 ${LLVM_ON_WIN32}
/* Installation prefix directory */
#cmakedefine LLVM_PREFIX "${LLVM_PREFIX}"
/* Define if we have the Intel JIT API runtime support library */
#cmakedefine LLVM_USE_INTEL_JITEVENTS 1
/* Define if we have the oprofile JIT-support library */
#cmakedefine LLVM_USE_OPROFILE 1
/* Major version of the LLVM API */
#define LLVM_VERSION_MAJOR ${LLVM_VERSION_MAJOR}
/* Minor version of the LLVM API */
#define LLVM_VERSION_MINOR ${LLVM_VERSION_MINOR}
/* Patch version of the LLVM API */
#define LLVM_VERSION_PATCH ${LLVM_VERSION_PATCH}
/* LLVM version string */
#define LLVM_VERSION_STRING "${PACKAGE_VERSION}"
/* Define if we link Polly to the tools */
#cmakedefine LINK_POLLY_INTO_TOOLS
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/Config/AsmPrinters.def.in | /*===- llvm/Config/AsmPrinters.def - LLVM Assembly Printers -----*- C++ -*-===*\
|* *|
|* The LLVM Compiler Infrastructure *|
|* *|
|* This file is distributed under the University of Illinois Open Source *|
|* License. See LICENSE.TXT for details. *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This file enumerates all of the assembly-language printers *|
|* supported by this build of LLVM. Clients of this file should define *|
|* the LLVM_ASM_PRINTER macro to be a function-like macro with a *|
|* single parameter (the name of the target whose assembly can be *|
|* generated); including this file will then enumerate all of the *|
|* targets with assembly printers. *|
|* *|
|* The set of targets supported by LLVM is generated at configuration *|
|* time, at which point this header is generated. Do not modify this *|
|* header directly. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_ASM_PRINTER
# error Please define the macro LLVM_ASM_PRINTER(TargetName)
#endif
@LLVM_ENUM_ASM_PRINTERS@
#undef LLVM_ASM_PRINTER
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/Config/Targets.def.in | /*===- llvm/Config/Targets.def - LLVM Target Architectures ------*- C++ -*-===*\
|* *|
|* The LLVM Compiler Infrastructure *|
|* *|
|* This file is distributed under the University of Illinois Open Source *|
|* License. See LICENSE.TXT for details. *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This file enumerates all of the target architectures supported by *|
|* this build of LLVM. Clients of this file should define the *|
|* LLVM_TARGET macro to be a function-like macro with a single *|
|* parameter (the name of the target); including this file will then *|
|* enumerate all of the targets. *|
|* *|
|* The set of targets supported by LLVM is generated at configuration *|
|* time, at which point this header is generated. Do not modify this *|
|* header directly. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_TARGET
# error Please define the macro LLVM_TARGET(TargetName)
#endif
@LLVM_ENUM_TARGETS@
#undef LLVM_TARGET
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/Config/Disassemblers.def.in | /*===- llvm/Config/Disassemblers.def - LLVM Assembly Parsers ----*- C++ -*-===*\
|* *|
|* The LLVM Compiler Infrastructure *|
|* *|
|* This file is distributed under the University of Illinois Open Source *|
|* License. See LICENSE.TXT for details. *|
|* *|
|*===----------------------------------------------------------------------===*|
|* *|
|* This file enumerates all of the assembly-language parsers *|
|* supported by this build of LLVM. Clients of this file should define *|
|* the LLVM_DISASSEMBLER macro to be a function-like macro with a *|
|* single parameter (the name of the target whose assembly can be *|
|* generated); including this file will then enumerate all of the *|
|* targets with assembly parsers. *|
|* *|
|* The set of targets supported by LLVM is generated at configuration *|
|* time, at which point this header is generated. Do not modify this *|
|* header directly. *|
|* *|
\*===----------------------------------------------------------------------===*/
#ifndef LLVM_DISASSEMBLER
# error Please define the macro LLVM_DISASSEMBLER(TargetName)
#endif
@LLVM_ENUM_DISASSEMBLERS@
#undef LLVM_DISASSEMBLER
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/Config/abi-breaking.h.cmake | /*===------- llvm/Config/abi-breaking.h - llvm configuration -------*- C -*-===*/
/* */
/* The LLVM Compiler Infrastructure */
/* */
/* This file is distributed under the University of Illinois Open Source */
/* License. See LICENSE.TXT for details. */
/* */
/*===----------------------------------------------------------------------===*/
/* This file controls the C++ ABI break introduced in LLVM public header. */
#ifndef LLVM_ABI_BREAKING_CHECKS_H
#define LLVM_ABI_BREAKING_CHECKS_H
/* Define to enable checks that alter the LLVM C++ ABI */
#cmakedefine01 LLVM_ENABLE_ABI_BREAKING_CHECKS
// ABI_BREAKING_CHECKS protection: provides link-time failure when clients build
// mismatch with LLVM
#if defined(_MSC_VER)
// Use pragma with MSVC
#define LLVM_XSTR(s) LLVM_STR(s)
#define LLVM_STR(s) #s
#pragma detect_mismatch("LLVM_ENABLE_ABI_BREAKING_CHECKS", LLVM_XSTR(LLVM_ENABLE_ABI_BREAKING_CHECKS))
#undef LLVM_XSTR
#undef LLVM_STR
#elif defined(__cplusplus)
namespace llvm {
#if LLVM_ENABLE_ABI_BREAKING_CHECKS
extern int EnableABIBreakingChecks;
__attribute__((weak, visibility ("hidden"))) int *VerifyEnableABIBreakingChecks = &EnableABIBreakingChecks;
#else
extern int DisableABIBreakingChecks;
__attribute__((weak, visibility ("hidden"))) int *VerifyDisableABIBreakingChecks = &DisableABIBreakingChecks;
#endif
}
#endif // _MSC_VER
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/Option/ArgList.h | //===--- ArgList.h - Argument List Management -------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_OPTION_ARGLIST_H
#define LLVM_OPTION_ARGLIST_H
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/OptSpecifier.h"
#include "llvm/Option/Option.h"
#include <list>
#include <memory>
#include <string>
#include <vector>
namespace llvm {
namespace opt {
class ArgList;
class Option;
/// arg_iterator - Iterates through arguments stored inside an ArgList.
class arg_iterator {
/// The current argument.
SmallVectorImpl<Arg*>::const_iterator Current;
/// The argument list we are iterating over.
const ArgList &Args;
/// Optional filters on the arguments which will be match. Most clients
/// should never want to iterate over arguments without filters, so we won't
/// bother to factor this into two separate iterator implementations.
//
// FIXME: Make efficient; the idea is to provide efficient iteration over
// all arguments which match a particular id and then just provide an
// iterator combinator which takes multiple iterators which can be
// efficiently compared and returns them in order.
OptSpecifier Id0, Id1, Id2;
void SkipToNextArg();
public:
typedef Arg * const * value_type;
typedef Arg * const & reference;
typedef Arg * const * pointer;
typedef std::forward_iterator_tag iterator_category;
typedef std::ptrdiff_t difference_type;
arg_iterator(SmallVectorImpl<Arg *>::const_iterator it, const ArgList &Args,
OptSpecifier Id0 = 0U, OptSpecifier Id1 = 0U,
OptSpecifier Id2 = 0U)
: Current(it), Args(Args), Id0(Id0), Id1(Id1), Id2(Id2) {
SkipToNextArg();
}
operator const Arg*() { return *Current; }
reference operator*() const { return *Current; }
pointer operator->() const { return Current; }
arg_iterator &operator++() {
++Current;
SkipToNextArg();
return *this;
}
arg_iterator operator++(int) {
arg_iterator tmp(*this);
++(*this);
return tmp;
}
friend bool operator==(arg_iterator LHS, arg_iterator RHS) {
return LHS.Current == RHS.Current;
}
friend bool operator!=(arg_iterator LHS, arg_iterator RHS) {
return !(LHS == RHS);
}
};
/// ArgList - Ordered collection of driver arguments.
///
/// The ArgList class manages a list of Arg instances as well as
/// auxiliary data and convenience methods to allow Tools to quickly
/// check for the presence of Arg instances for a particular Option
/// and to iterate over groups of arguments.
class ArgList {
public:
typedef SmallVector<Arg*, 16> arglist_type;
typedef arglist_type::iterator iterator;
typedef arglist_type::const_iterator const_iterator;
typedef arglist_type::reverse_iterator reverse_iterator;
typedef arglist_type::const_reverse_iterator const_reverse_iterator;
private:
/// The internal list of arguments.
arglist_type Args;
protected:
// Make the default special members protected so they won't be used to slice
// derived objects, but can still be used by derived objects to implement
// their own special members.
ArgList() = default;
// Explicit move operations to ensure the container is cleared post-move
// otherwise it could lead to a double-delete in the case of moving of an
// InputArgList which deletes the contents of the container. If we could fix
// up the ownership here (delegate storage/ownership to the derived class so
// it can be a container of unique_ptr) this would be simpler.
ArgList(ArgList &&RHS) : Args(std::move(RHS.Args)) { RHS.Args.clear(); }
ArgList &operator=(ArgList &&RHS) {
Args = std::move(RHS.Args);
RHS.Args.clear();
return *this;
}
// Protect the dtor to ensure this type is never destroyed polymorphically.
~ArgList() = default;
public:
/// @name Arg Access
/// @{
/// append - Append \p A to the arg list.
void append(Arg *A);
arglist_type &getArgs() { return Args; }
const arglist_type &getArgs() const { return Args; }
unsigned size() const { return Args.size(); }
/// @}
/// @name Arg Iteration
/// @{
iterator begin() { return Args.begin(); }
iterator end() { return Args.end(); }
reverse_iterator rbegin() { return Args.rbegin(); }
reverse_iterator rend() { return Args.rend(); }
const_iterator begin() const { return Args.begin(); }
const_iterator end() const { return Args.end(); }
const_reverse_iterator rbegin() const { return Args.rbegin(); }
const_reverse_iterator rend() const { return Args.rend(); }
arg_iterator filtered_begin(OptSpecifier Id0 = 0U, OptSpecifier Id1 = 0U,
OptSpecifier Id2 = 0U) const {
return arg_iterator(Args.begin(), *this, Id0, Id1, Id2);
}
arg_iterator filtered_end() const {
return arg_iterator(Args.end(), *this);
}
iterator_range<arg_iterator> filtered(OptSpecifier Id0 = 0U,
OptSpecifier Id1 = 0U,
OptSpecifier Id2 = 0U) const {
return make_range(filtered_begin(Id0, Id1, Id2), filtered_end());
}
/// @}
/// @name Arg Removal
/// @{
/// eraseArg - Remove any option matching \p Id.
void eraseArg(OptSpecifier Id);
/// @}
/// @name Arg Access
/// @{
/// hasArg - Does the arg list contain any option matching \p Id.
///
/// \p Claim Whether the argument should be claimed, if it exists.
bool hasArgNoClaim(OptSpecifier Id) const {
return getLastArgNoClaim(Id) != nullptr;
}
bool hasArg(OptSpecifier Id) const {
return getLastArg(Id) != nullptr;
}
bool hasArg(OptSpecifier Id0, OptSpecifier Id1) const {
return getLastArg(Id0, Id1) != nullptr;
}
bool hasArg(OptSpecifier Id0, OptSpecifier Id1, OptSpecifier Id2) const {
return getLastArg(Id0, Id1, Id2) != nullptr;
}
/// getLastArg - Return the last argument matching \p Id, or null.
///
/// \p Claim Whether the argument should be claimed, if it exists.
Arg *getLastArgNoClaim(OptSpecifier Id) const;
Arg *getLastArgNoClaim(OptSpecifier Id0, OptSpecifier Id1) const;
Arg *getLastArgNoClaim(OptSpecifier Id0, OptSpecifier Id1,
OptSpecifier Id2) const;
Arg *getLastArgNoClaim(OptSpecifier Id0, OptSpecifier Id1, OptSpecifier Id2,
OptSpecifier Id3) const;
Arg *getLastArg(OptSpecifier Id) const;
Arg *getLastArg(OptSpecifier Id0, OptSpecifier Id1) const;
Arg *getLastArg(OptSpecifier Id0, OptSpecifier Id1, OptSpecifier Id2) const;
Arg *getLastArg(OptSpecifier Id0, OptSpecifier Id1, OptSpecifier Id2,
OptSpecifier Id3) const;
Arg *getLastArg(OptSpecifier Id0, OptSpecifier Id1, OptSpecifier Id2,
OptSpecifier Id3, OptSpecifier Id4) const;
Arg *getLastArg(OptSpecifier Id0, OptSpecifier Id1, OptSpecifier Id2,
OptSpecifier Id3, OptSpecifier Id4, OptSpecifier Id5) const;
Arg *getLastArg(OptSpecifier Id0, OptSpecifier Id1, OptSpecifier Id2,
OptSpecifier Id3, OptSpecifier Id4, OptSpecifier Id5,
OptSpecifier Id6) const;
Arg *getLastArg(OptSpecifier Id0, OptSpecifier Id1, OptSpecifier Id2,
OptSpecifier Id3, OptSpecifier Id4, OptSpecifier Id5,
OptSpecifier Id6, OptSpecifier Id7) const;
/// getArgString - Return the input argument string at \p Index.
virtual const char *getArgString(unsigned Index) const = 0;
/// getNumInputArgStrings - Return the number of original argument strings,
/// which are guaranteed to be the first strings in the argument string
/// list.
virtual unsigned getNumInputArgStrings() const = 0;
/// @}
/// @name Argument Lookup Utilities
/// @{
/// getLastArgValue - Return the value of the last argument, or a default.
StringRef getLastArgValue(OptSpecifier Id,
StringRef Default = "") const;
/// getAllArgValues - Get the values of all instances of the given argument
/// as strings.
std::vector<std::string> getAllArgValues(OptSpecifier Id) const;
/// @}
/// @name Translation Utilities
/// @{
/// hasFlag - Given an option \p Pos and its negative form \p Neg, return
/// true if the option is present, false if the negation is present, and
/// \p Default if neither option is given. If both the option and its
/// negation are present, the last one wins.
bool hasFlag(OptSpecifier Pos, OptSpecifier Neg, bool Default=true) const;
/// hasFlag - Given an option \p Pos, an alias \p PosAlias and its negative
/// form \p Neg, return true if the option or its alias is present, false if
/// the negation is present, and \p Default if none of the options are
/// given. If multiple options are present, the last one wins.
bool hasFlag(OptSpecifier Pos, OptSpecifier PosAlias, OptSpecifier Neg,
bool Default = true) const;
/// AddLastArg - Render only the last argument match \p Id0, if present.
void AddLastArg(ArgStringList &Output, OptSpecifier Id0) const;
void AddLastArg(ArgStringList &Output, OptSpecifier Id0,
OptSpecifier Id1) const;
/// AddAllArgs - Render all arguments matching the given ids.
void AddAllArgs(ArgStringList &Output, OptSpecifier Id0,
OptSpecifier Id1 = 0U, OptSpecifier Id2 = 0U) const;
/// AddAllArgValues - Render the argument values of all arguments
/// matching the given ids.
void AddAllArgValues(ArgStringList &Output, OptSpecifier Id0,
OptSpecifier Id1 = 0U, OptSpecifier Id2 = 0U) const;
/// AddAllArgsTranslated - Render all the arguments matching the
/// given ids, but forced to separate args and using the provided
/// name instead of the first option value.
///
/// \param Joined - If true, render the argument as joined with
/// the option specifier.
void AddAllArgsTranslated(ArgStringList &Output, OptSpecifier Id0,
const char *Translation,
bool Joined = false) const;
/// ClaimAllArgs - Claim all arguments which match the given
/// option id.
void ClaimAllArgs(OptSpecifier Id0) const;
/// ClaimAllArgs - Claim all arguments.
///
void ClaimAllArgs() const;
/// @}
/// @name Arg Synthesis
/// @{
/// Construct a constant string pointer whose
/// lifetime will match that of the ArgList.
virtual const char *MakeArgStringRef(StringRef Str) const = 0;
const char *MakeArgString(const Twine &Str) const {
SmallString<256> Buf;
return MakeArgStringRef(Str.toStringRef(Buf));
}
/// \brief Create an arg string for (\p LHS + \p RHS), reusing the
/// string at \p Index if possible.
const char *GetOrMakeJoinedArgString(unsigned Index, StringRef LHS,
StringRef RHS) const;
/// @}
};
class InputArgList final : public ArgList {
private:
/// List of argument strings used by the contained Args.
///
/// This is mutable since we treat the ArgList as being the list
/// of Args, and allow routines to add new strings (to have a
/// convenient place to store the memory) via MakeIndex.
mutable ArgStringList ArgStrings;
/// Strings for synthesized arguments.
///
/// This is mutable since we treat the ArgList as being the list
/// of Args, and allow routines to add new strings (to have a
/// convenient place to store the memory) via MakeIndex.
mutable std::list<std::string> SynthesizedStrings;
/// The number of original input argument strings.
unsigned NumInputArgStrings;
/// Release allocated arguments.
void releaseMemory();
public:
InputArgList(const char* const *ArgBegin, const char* const *ArgEnd);
InputArgList(InputArgList &&RHS)
: ArgList(std::move(RHS)), ArgStrings(std::move(RHS.ArgStrings)),
SynthesizedStrings(std::move(RHS.SynthesizedStrings)),
NumInputArgStrings(RHS.NumInputArgStrings) {}
InputArgList &operator=(InputArgList &&RHS) {
releaseMemory();
ArgList::operator=(std::move(RHS));
ArgStrings = std::move(RHS.ArgStrings);
SynthesizedStrings = std::move(RHS.SynthesizedStrings);
NumInputArgStrings = RHS.NumInputArgStrings;
return *this;
}
~InputArgList() { releaseMemory(); }
const char *getArgString(unsigned Index) const override {
return ArgStrings[Index];
}
unsigned getNumInputArgStrings() const override {
return NumInputArgStrings;
}
/// @name Arg Synthesis
/// @{
public:
/// MakeIndex - Get an index for the given string(s).
unsigned MakeIndex(StringRef String0) const;
unsigned MakeIndex(StringRef String0, StringRef String1) const;
using ArgList::MakeArgString;
const char *MakeArgStringRef(StringRef Str) const override;
/// @}
};
/// DerivedArgList - An ordered collection of driver arguments,
/// whose storage may be in another argument list.
class DerivedArgList final : public ArgList {
const InputArgList &BaseArgs;
/// The list of arguments we synthesized.
mutable SmallVector<std::unique_ptr<Arg>, 16> SynthesizedArgs;
public:
/// Construct a new derived arg list from \p BaseArgs.
DerivedArgList(const InputArgList &BaseArgs);
const char *getArgString(unsigned Index) const override {
return BaseArgs.getArgString(Index);
}
unsigned getNumInputArgStrings() const override {
return BaseArgs.getNumInputArgStrings();
}
const InputArgList &getBaseArgs() const {
return BaseArgs;
}
/// @name Arg Synthesis
/// @{
/// AddSynthesizedArg - Add a argument to the list of synthesized arguments
/// (to be freed).
void AddSynthesizedArg(Arg *A);
using ArgList::MakeArgString;
const char *MakeArgStringRef(StringRef Str) const override;
/// AddFlagArg - Construct a new FlagArg for the given option \p Id and
/// append it to the argument list.
void AddFlagArg(const Arg *BaseArg, const Option Opt) {
append(MakeFlagArg(BaseArg, Opt));
}
/// AddPositionalArg - Construct a new Positional arg for the given option
/// \p Id, with the provided \p Value and append it to the argument
/// list.
void AddPositionalArg(const Arg *BaseArg, const Option Opt,
StringRef Value) {
append(MakePositionalArg(BaseArg, Opt, Value));
}
/// AddSeparateArg - Construct a new Positional arg for the given option
/// \p Id, with the provided \p Value and append it to the argument
/// list.
void AddSeparateArg(const Arg *BaseArg, const Option Opt,
StringRef Value) {
append(MakeSeparateArg(BaseArg, Opt, Value));
}
/// AddJoinedArg - Construct a new Positional arg for the given option
/// \p Id, with the provided \p Value and append it to the argument list.
void AddJoinedArg(const Arg *BaseArg, const Option Opt,
StringRef Value) {
append(MakeJoinedArg(BaseArg, Opt, Value));
}
/// MakeFlagArg - Construct a new FlagArg for the given option \p Id.
Arg *MakeFlagArg(const Arg *BaseArg, const Option Opt) const;
/// MakePositionalArg - Construct a new Positional arg for the
/// given option \p Id, with the provided \p Value.
Arg *MakePositionalArg(const Arg *BaseArg, const Option Opt,
StringRef Value) const;
/// MakeSeparateArg - Construct a new Positional arg for the
/// given option \p Id, with the provided \p Value.
Arg *MakeSeparateArg(const Arg *BaseArg, const Option Opt,
StringRef Value) const;
/// MakeJoinedArg - Construct a new Positional arg for the
/// given option \p Id, with the provided \p Value.
Arg *MakeJoinedArg(const Arg *BaseArg, const Option Opt,
StringRef Value) const;
/// @}
};
} // end namespace opt
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/Option/OptSpecifier.h | //===--- OptSpecifier.h - Option Specifiers ---------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_OPTION_OPTSPECIFIER_H
#define LLVM_OPTION_OPTSPECIFIER_H
#include "llvm/Support/Compiler.h"
namespace llvm {
namespace opt {
class Option;
/// OptSpecifier - Wrapper class for abstracting references to option IDs.
class OptSpecifier {
unsigned ID;
private:
explicit OptSpecifier(bool) = delete;
public:
OptSpecifier() : ID(0) {}
/*implicit*/ OptSpecifier(unsigned ID) : ID(ID) {}
/*implicit*/ OptSpecifier(const Option *Opt);
bool isValid() const { return ID != 0; }
unsigned getID() const { return ID; }
bool operator==(OptSpecifier Opt) const { return ID == Opt.getID(); }
bool operator!=(OptSpecifier Opt) const { return !(*this == Opt); }
};
}
}
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/Option/OptTable.h | //===--- OptTable.h - Option Table ------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_OPTION_OPTTABLE_H
#define LLVM_OPTION_OPTTABLE_H
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Option/OptSpecifier.h"
namespace llvm {
class raw_ostream;
namespace opt {
class Arg;
class ArgList;
class InputArgList;
class Option;
/// \brief Provide access to the Option info table.
///
/// The OptTable class provides a layer of indirection which allows Option
/// instance to be created lazily. In the common case, only a few options will
/// be needed at runtime; the OptTable class maintains enough information to
/// parse command lines without instantiating Options, while letting other
/// parts of the driver still use Option instances where convenient.
class OptTable {
public:
/// \brief Entry for a single option instance in the option data table.
struct Info {
/// A null terminated array of prefix strings to apply to name while
/// matching.
const char *const *Prefixes;
const char *Name;
const char *HelpText;
const char *MetaVar;
unsigned ID;
unsigned char Kind;
unsigned char Param;
unsigned long Flags;
unsigned short GroupID;
unsigned short AliasID;
const char *AliasArgs;
};
private:
/// \brief The static option information table.
const Info *OptionInfos;
unsigned NumOptionInfos;
bool IgnoreCase;
unsigned TheInputOptionID;
unsigned TheUnknownOptionID;
/// The index of the first option which can be parsed (i.e., is not a
/// special option like 'input' or 'unknown', and is not an option group).
unsigned FirstSearchableIndex;
/// The union of all option prefixes. If an argument does not begin with
/// one of these, it is an input.
StringSet<> PrefixesUnion;
std::string PrefixChars;
private:
const Info &getInfo(OptSpecifier Opt) const {
unsigned id = Opt.getID();
assert(id > 0 && id - 1 < getNumOptions() && "Invalid Option ID.");
return OptionInfos[id - 1];
}
protected:
OptTable(const Info *OptionInfos, unsigned NumOptionInfos,
bool IgnoreCase = false);
public:
~OptTable();
/// \brief Return the total number of option classes.
unsigned getNumOptions() const { return NumOptionInfos; }
/// \brief Get the given Opt's Option instance, lazily creating it
/// if necessary.
///
/// \return The option, or null for the INVALID option id.
const Option getOption(OptSpecifier Opt) const;
/// \brief Lookup the name of the given option.
const char *getOptionName(OptSpecifier id) const {
return getInfo(id).Name;
}
/// \brief Get the kind of the given option.
unsigned getOptionKind(OptSpecifier id) const {
return getInfo(id).Kind;
}
/// \brief Get the group id for the given option.
unsigned getOptionGroupID(OptSpecifier id) const {
return getInfo(id).GroupID;
}
/// \brief Get the help text to use to describe this option.
const char *getOptionHelpText(OptSpecifier id) const {
return getInfo(id).HelpText;
}
/// \brief Get the meta-variable name to use when describing
/// this options values in the help text.
const char *getOptionMetaVar(OptSpecifier id) const {
return getInfo(id).MetaVar;
}
/// \brief Parse a single argument; returning the new argument and
/// updating Index.
///
/// \param [in,out] Index - The current parsing position in the argument
/// string list; on return this will be the index of the next argument
/// string to parse.
/// \param [in] FlagsToInclude - Only parse options with any of these flags.
/// Zero is the default which includes all flags.
/// \param [in] FlagsToExclude - Don't parse options with this flag. Zero
/// is the default and means exclude nothing.
///
/// \return The parsed argument, or 0 if the argument is missing values
/// (in which case Index still points at the conceptual next argument string
/// to parse).
Arg *ParseOneArg(const ArgList &Args, unsigned &Index,
unsigned FlagsToInclude = 0,
unsigned FlagsToExclude = 0) const;
Option findOption(const char *normalizedName, unsigned FlagsToInclude = 0, unsigned FlagsToExclude = 0) const; // HLSL Change
/// \brief Parse an list of arguments into an InputArgList.
///
/// The resulting InputArgList will reference the strings in [\p ArgBegin,
/// \p ArgEnd), and their lifetime should extend past that of the returned
/// InputArgList.
///
/// The only error that can occur in this routine is if an argument is
/// missing values; in this case \p MissingArgCount will be non-zero.
///
/// \param MissingArgIndex - On error, the index of the option which could
/// not be parsed.
/// \param MissingArgCount - On error, the number of missing options.
/// \param FlagsToInclude - Only parse options with any of these flags.
/// Zero is the default which includes all flags.
/// \param FlagsToExclude - Don't parse options with this flag. Zero
/// is the default and means exclude nothing.
/// \return An InputArgList; on error this will contain all the options
/// which could be parsed.
InputArgList ParseArgs(ArrayRef<const char *> Args, unsigned &MissingArgIndex,
unsigned &MissingArgCount, unsigned FlagsToInclude = 0,
unsigned FlagsToExclude = 0) const;
/// \brief Render the help text for an option table.
///
/// \param OS - The stream to write the help text to.
/// \param Name - The name to use in the usage line.
/// \param Title - The title to use in the usage line.
/// \param FlagsToInclude - If non-zero, only include options with any
/// of these flags set.
/// \param FlagsToExclude - Exclude options with any of these flags set.
void PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
/* HLSL Change - version info */ const char *VersionInfo,
unsigned FlagsToInclude, unsigned FlagsToExclude) const;
void PrintHelp(raw_ostream &OS, const char *Name, const char *Title,
/* HLSL Change - version info */ const char *VersionInfo = "",
bool ShowHidden = false) const;
};
} // end namespace opt
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/Option/Arg.h | //===--- Arg.h - Parsed Argument Classes ------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Defines the llvm::Arg class for parsed arguments.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_OPTION_ARG_H
#define LLVM_OPTION_ARG_H
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Option/Option.h"
#include <string>
namespace llvm {
namespace opt {
class ArgList;
/// \brief A concrete instance of a particular driver option.
///
/// The Arg class encodes just enough information to be able to
/// derive the argument values efficiently.
class Arg {
Arg(const Arg &) = delete;
void operator=(const Arg &) = delete;
private:
/// \brief The option this argument is an instance of.
const Option Opt;
/// \brief The argument this argument was derived from (during tool chain
/// argument translation), if any.
const Arg *BaseArg;
/// \brief How this instance of the option was spelled.
StringRef Spelling;
/// \brief The index at which this argument appears in the containing
/// ArgList.
unsigned Index;
/// \brief Was this argument used to effect compilation?
///
/// This is used for generating "argument unused" diagnostics.
mutable unsigned Claimed : 1;
/// \brief Does this argument own its values?
mutable unsigned OwnsValues : 1;
/// \brief The argument values, as C strings.
SmallVector<const char *, 2> Values;
public:
Arg(const Option Opt, StringRef Spelling, unsigned Index,
const Arg *BaseArg = nullptr);
Arg(const Option Opt, StringRef Spelling, unsigned Index,
const char *Value0, const Arg *BaseArg = nullptr);
Arg(const Option Opt, StringRef Spelling, unsigned Index,
const char *Value0, const char *Value1, const Arg *BaseArg = nullptr);
~Arg();
const Option &getOption() const { return Opt; }
StringRef getSpelling() const { return Spelling; }
unsigned getIndex() const { return Index; }
/// \brief Return the base argument which generated this arg.
///
/// This is either the argument itself or the argument it was
/// derived from during tool chain specific argument translation.
const Arg &getBaseArg() const {
return BaseArg ? *BaseArg : *this;
}
void setBaseArg(const Arg *BaseArg) { this->BaseArg = BaseArg; }
bool getOwnsValues() const { return OwnsValues; }
void setOwnsValues(bool Value) const { OwnsValues = Value; }
bool isClaimed() const { return getBaseArg().Claimed; }
/// \brief Set the Arg claimed bit.
void claim() const { getBaseArg().Claimed = true; }
unsigned getNumValues() const { return Values.size(); }
const char *getValue(unsigned N = 0) const {
return Values[N];
}
SmallVectorImpl<const char *> &getValues() { return Values; }
const SmallVectorImpl<const char *> &getValues() const { return Values; }
bool containsValue(StringRef Value) const {
for (unsigned i = 0, e = getNumValues(); i != e; ++i)
if (Values[i] == Value)
return true;
return false;
}
/// \brief Append the argument onto the given array as strings.
void render(const ArgList &Args, ArgStringList &Output) const;
/// \brief Append the argument, render as an input, onto the given
/// array as strings.
///
/// The distinction is that some options only render their values
/// when rendered as a input (e.g., Xlinker).
void renderAsInput(const ArgList &Args, ArgStringList &Output) const;
void dump() const;
/// \brief Return a formatted version of the argument and
/// its values, for debugging and diagnostics.
std::string getAsString(const ArgList &Args) const;
};
} // end namespace opt
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/Option/Option.h | //===--- Option.h - Abstract Driver Options ---------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_OPTION_OPTION_H
#define LLVM_OPTION_OPTION_H
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Support/ErrorHandling.h"
namespace llvm {
namespace opt {
class Arg;
class ArgList;
/// ArgStringList - Type used for constructing argv lists for subprocesses.
typedef SmallVector<const char*, 16> ArgStringList;
/// Base flags for all options. Custom flags may be added after.
enum DriverFlag {
HelpHidden = (1 << 0),
RenderAsInput = (1 << 1),
RenderJoined = (1 << 2),
RenderSeparate = (1 << 3)
};
/// Option - Abstract representation for a single form of driver
/// argument.
///
/// An Option class represents a form of option that the driver
/// takes, for example how many arguments the option has and how
/// they can be provided. Individual option instances store
/// additional information about what group the option is a member
/// of (if any), if the option is an alias, and a number of
/// flags. At runtime the driver parses the command line into
/// concrete Arg instances, each of which corresponds to a
/// particular Option instance.
class Option {
public:
enum OptionClass {
GroupClass = 0,
InputClass,
UnknownClass,
FlagClass,
JoinedClass,
SeparateClass,
RemainingArgsClass,
CommaJoinedClass,
MultiArgClass,
JoinedOrSeparateClass,
JoinedAndSeparateClass
};
enum RenderStyleKind {
RenderCommaJoinedStyle,
RenderJoinedStyle,
RenderSeparateStyle,
RenderValuesStyle
};
protected:
const OptTable::Info *Info;
const OptTable *Owner;
public:
Option(const OptTable::Info *Info, const OptTable *Owner);
bool isValid() const {
return Info != nullptr;
}
unsigned getID() const {
assert(Info && "Must have a valid info!");
return Info->ID;
}
OptionClass getKind() const {
assert(Info && "Must have a valid info!");
return OptionClass(Info->Kind);
}
/// \brief Get the name of this option without any prefix.
StringRef getName() const {
assert(Info && "Must have a valid info!");
return Info->Name;
}
const Option getGroup() const {
assert(Info && "Must have a valid info!");
assert(Owner && "Must have a valid owner!");
return Owner->getOption(Info->GroupID);
}
const Option getAlias() const {
assert(Info && "Must have a valid info!");
assert(Owner && "Must have a valid owner!");
return Owner->getOption(Info->AliasID);
}
/// \brief Get the alias arguments as a \0 separated list.
/// E.g. ["foo", "bar"] would be returned as "foo\0bar\0".
const char *getAliasArgs() const {
assert(Info && "Must have a valid info!");
assert((!Info->AliasArgs || Info->AliasArgs[0] != 0) &&
"AliasArgs should be either 0 or non-empty.");
return Info->AliasArgs;
}
/// \brief Get the default prefix for this option.
StringRef getPrefix() const {
const char *Prefix = *Info->Prefixes;
return Prefix ? Prefix : StringRef();
}
/// \brief Get the name of this option with the default prefix.
std::string getPrefixedName() const {
std::string Ret = getPrefix();
Ret += getName();
return Ret;
}
unsigned getNumArgs() const { return Info->Param; }
bool hasNoOptAsInput() const { return Info->Flags & RenderAsInput;}
RenderStyleKind getRenderStyle() const {
if (Info->Flags & RenderJoined)
return RenderJoinedStyle;
if (Info->Flags & RenderSeparate)
return RenderSeparateStyle;
switch (getKind()) {
case GroupClass:
case InputClass:
case UnknownClass:
return RenderValuesStyle;
case JoinedClass:
case JoinedAndSeparateClass:
return RenderJoinedStyle;
case CommaJoinedClass:
return RenderCommaJoinedStyle;
case FlagClass:
case SeparateClass:
case MultiArgClass:
case JoinedOrSeparateClass:
case RemainingArgsClass:
return RenderSeparateStyle;
}
llvm_unreachable("Unexpected kind!");
}
/// Test if this option has the flag \a Val.
bool hasFlag(unsigned Val) const {
return Info->Flags & Val;
}
/// getUnaliasedOption - Return the final option this option
/// aliases (itself, if the option has no alias).
const Option getUnaliasedOption() const {
const Option Alias = getAlias();
if (Alias.isValid()) return Alias.getUnaliasedOption();
return *this;
}
/// getRenderName - Return the name to use when rendering this
/// option.
StringRef getRenderName() const {
return getUnaliasedOption().getName();
}
/// matches - Predicate for whether this option is part of the
/// given option (which may be a group).
///
/// Note that matches against options which are an alias should never be
/// done -- aliases do not participate in matching and so such a query will
/// always be false.
bool matches(OptSpecifier ID) const;
/// accept - Potentially accept the current argument, returning a
/// new Arg instance, or 0 if the option does not accept this
/// argument (or the argument is missing values).
///
/// If the option accepts the current argument, accept() sets
/// Index to the position where argument parsing should resume
/// (even if the argument is missing values).
///
/// \param ArgSize The number of bytes taken up by the matched Option prefix
/// and name. This is used to determine where joined values
/// start.
Arg *accept(const ArgList &Args, unsigned &Index, unsigned ArgSize) const;
void dump() const;
};
} // end namespace opt
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/AsmParser/Parser.h | //===-- Parser.h - Parser for LLVM IR text assembly files -------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// These classes are implemented by the lib/AsmParser library.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_ASMPARSER_PARSER_H
#define LLVM_ASMPARSER_PARSER_H
#include "llvm/Support/MemoryBuffer.h"
namespace llvm {
class LLVMContext;
class Module;
struct SlotMapping;
class SMDiagnostic;
/// This function is the main interface to the LLVM Assembly Parser. It parses
/// an ASCII file that (presumably) contains LLVM Assembly code. It returns a
/// Module (intermediate representation) with the corresponding features. Note
/// that this does not verify that the generated Module is valid, so you should
/// run the verifier after parsing the file to check that it is okay.
/// \brief Parse LLVM Assembly from a file
/// \param Filename The name of the file to parse
/// \param Error Error result info.
/// \param Context Context in which to allocate globals info.
/// \param Slots The optional slot mapping that will be initialized during
/// parsing.
std::unique_ptr<Module> parseAssemblyFile(StringRef Filename,
SMDiagnostic &Error,
LLVMContext &Context,
SlotMapping *Slots = nullptr);
/// The function is a secondary interface to the LLVM Assembly Parser. It parses
/// an ASCII string that (presumably) contains LLVM Assembly code. It returns a
/// Module (intermediate representation) with the corresponding features. Note
/// that this does not verify that the generated Module is valid, so you should
/// run the verifier after parsing the file to check that it is okay.
/// \brief Parse LLVM Assembly from a string
/// \param AsmString The string containing assembly
/// \param Error Error result info.
/// \param Context Context in which to allocate globals info.
/// \param Slots The optional slot mapping that will be initialized during
/// parsing.
std::unique_ptr<Module> parseAssemblyString(StringRef AsmString,
SMDiagnostic &Error,
LLVMContext &Context,
SlotMapping *Slots = nullptr);
/// parseAssemblyFile and parseAssemblyString are wrappers around this function.
/// \brief Parse LLVM Assembly from a MemoryBuffer.
/// \param F The MemoryBuffer containing assembly
/// \param Err Error result info.
/// \param Slots The optional slot mapping that will be initialized during
/// parsing.
std::unique_ptr<Module> parseAssembly(MemoryBufferRef F, SMDiagnostic &Err,
LLVMContext &Context,
SlotMapping *Slots = nullptr);
/// This function is the low-level interface to the LLVM Assembly Parser.
/// This is kept as an independent function instead of being inlined into
/// parseAssembly for the convenience of interactive users that want to add
/// recently parsed bits to an existing module.
///
/// \param F The MemoryBuffer containing assembly
/// \param M The module to add data to.
/// \param Err Error result info.
/// \param Slots The optional slot mapping that will be initialized during
/// parsing.
/// \return true on error.
bool parseAssemblyInto(MemoryBufferRef F, Module &M, SMDiagnostic &Err,
SlotMapping *Slots = nullptr);
} // End llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/AsmParser/SlotMapping.h | //===-- SlotMapping.h - Slot number mapping for unnamed values --*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declaration of the SlotMapping struct.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_ASMPARSER_SLOTMAPPING_H
#define LLVM_ASMPARSER_SLOTMAPPING_H
#include "llvm/IR/TrackingMDRef.h"
#include <map>
#include <vector>
namespace llvm {
class GlobalValue;
/// This struct contains the mapping from the slot numbers to unnamed metadata
/// nodes and global values.
struct SlotMapping {
std::vector<GlobalValue *> GlobalValues;
std::map<unsigned, TrackingMDNodeRef> MetadataNodes;
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/include/llvm | repos/DirectXShaderCompiler/include/llvm/Transforms/Scalar.h | //===-- Scalar.h - Scalar Transformations -----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This header file defines prototypes for accessor functions that expose passes
// in the Scalar transformations library.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_TRANSFORMS_SCALAR_H
#define LLVM_TRANSFORMS_SCALAR_H
#include "llvm/ADT/StringRef.h"
#include <functional>
namespace llvm {
class BasicBlockPass;
class Function;
class FunctionPass;
class ModulePass;
class Pass;
class GetElementPtrInst;
class PassInfo;
class TerminatorInst;
class TargetLowering;
class TargetMachine;
class PassRegistry; // HLSL Change - need this for registrations
//===----------------------------------------------------------------------===//
//
// ConstantPropagation - A worklist driven constant propagation pass
//
FunctionPass *createConstantPropagationPass();
//===----------------------------------------------------------------------===//
//
// AlignmentFromAssumptions - Use assume intrinsics to set load/store
// alignments.
//
FunctionPass *createAlignmentFromAssumptionsPass();
//===----------------------------------------------------------------------===//
//
// SCCP - Sparse conditional constant propagation.
//
FunctionPass *createSCCPPass();
//===----------------------------------------------------------------------===//
//
// DeadInstElimination - This pass quickly removes trivially dead instructions
// without modifying the CFG of the function. It is a BasicBlockPass, so it
// runs efficiently when queued next to other BasicBlockPass's.
//
Pass *createDeadInstEliminationPass();
//===----------------------------------------------------------------------===//
//
// DeadCodeElimination - This pass is more powerful than DeadInstElimination,
// because it is worklist driven that can potentially revisit instructions when
// their other instructions become dead, to eliminate chains of dead
// computations.
//
FunctionPass *createDeadCodeEliminationPass();
//===----------------------------------------------------------------------===//
//
// DeadStoreElimination - This pass deletes stores that are post-dominated by
// must-aliased stores and are not loaded used between the stores.
//
FunctionPass *createDeadStoreEliminationPass(unsigned ScanLimit = 0); // HLSL Change - Add ScanLimit
//===----------------------------------------------------------------------===//
//
// AggressiveDCE - This pass uses the SSA based Aggressive DCE algorithm. This
// algorithm assumes instructions are dead until proven otherwise, which makes
// it more successful are removing non-obviously dead instructions.
//
FunctionPass *createAggressiveDCEPass();
//===----------------------------------------------------------------------===//
//
// BitTrackingDCE - This pass uses a bit-tracking DCE algorithm in order to
// remove computations of dead bits.
//
FunctionPass *createBitTrackingDCEPass();
//===----------------------------------------------------------------------===//
//
// SROA - Replace aggregates or pieces of aggregates with scalar SSA values.
//
FunctionPass *createSROAPass(bool RequiresDomTree = true,
bool SkipHLSLMat = true);
//===----------------------------------------------------------------------===//
//
// ScalarReplAggregates - Break up alloca's of aggregates into multiple allocas
// if possible.
//
FunctionPass *createScalarReplAggregatesPass(signed Threshold = -1,
bool UseDomTree = true,
signed StructMemberThreshold = -1,
signed ArrayElementThreshold = -1,
signed ScalarLoadThreshold = -1);
// HLSL Change Begins
FunctionPass* createHLExpandStoreIntrinsicsPass();
void initializeHLExpandStoreIntrinsicsPass(PassRegistry&);
//===----------------------------------------------------------------------===//
//
// ScalarReplAggregatesHLSL - Break up argument's of aggregates into multiple arguments
// for hlsl. Array will not change, all structures will be broken up.
//
ModulePass *createSROA_Parameter_HLSL();
void initializeSROA_Parameter_HLSLPass(PassRegistry&);
//===----------------------------------------------------------------------===//
//
// Cleans up constant stores that didn't get a chance to be turned into initializers
//
Pass *createDxilFixConstArrayInitializerPass();
void initializeDxilFixConstArrayInitializerPass(PassRegistry&);
Pass *createDxilConditionalMem2RegPass(bool NoOpt);
void initializeDxilConditionalMem2RegPass(PassRegistry&);
Pass *createDxilLoopUnrollPass(unsigned MaxIterationAttempt, bool OnlyWarnOnFail, bool StructurizeLoopExits);
void initializeDxilLoopUnrollPass(PassRegistry&);
Pass *createDxilEraseDeadRegionPass();
void initializeDxilEraseDeadRegionPass(PassRegistry&);
Pass *createDxilEliminateVectorPass();
void initializeDxilEliminateVectorPass(PassRegistry&);
Pass *createDxilInsertPreservesPass(bool AllowPreserves);
void initializeDxilInsertPreservesPass(PassRegistry&);
Pass *createDxilFinalizePreservesPass();
void initializeDxilFinalizePreservesPass(PassRegistry&);
Pass *createDxilReinsertNopsPass();
void initializeDxilReinsertNopsPass(PassRegistry&);
Pass *createDxilPreserveToSelectPass();
void initializeDxilPreserveToSelectPass(PassRegistry&);
Pass *createDxilRemoveDeadBlocksPass();
void initializeDxilRemoveDeadBlocksPass(PassRegistry&);
Pass *createDxilRemoveUnstructuredLoopExitsPass();
void initializeDxilRemoveUnstructuredLoopExitsPass(PassRegistry &);
void initializeDxilRewriteOutputArgDebugInfoPass(PassRegistry&);
Pass *createDxilRewriteOutputArgDebugInfoPass();
//===----------------------------------------------------------------------===//
//
// LowerStaticGlobalIntoAlloca. Replace static globals with alloca if only used
// in one function.
//
ModulePass *createLowerStaticGlobalIntoAlloca();
void initializeLowerStaticGlobalIntoAllocaPass(PassRegistry&);
//===----------------------------------------------------------------------===//
//
// DynamicIndexingVectorToArray
// Replace vector with array if it has dynamic indexing.
//
ModulePass *createDynamicIndexingVectorToArrayPass(bool ReplaceAllVector = false);
void initializeDynamicIndexingVectorToArrayPass(PassRegistry&);
//===----------------------------------------------------------------------===//
// Flatten multi dim array into 1 dim.
//
ModulePass *createMultiDimArrayToOneDimArrayPass();
void initializeMultiDimArrayToOneDimArrayPass(PassRegistry&);
//===----------------------------------------------------------------------===//
// Flatten resource into handle.
//
ModulePass *createResourceToHandlePass();
void initializeResourceToHandlePass(PassRegistry&);
//===----------------------------------------------------------------------===//
// Flatten resource into handle.
//
ModulePass *createLowerWaveMatTypePass();
void initializeLowerWaveMatTypePass(PassRegistry &);
//===----------------------------------------------------------------------===//
// Hoist a local array initialized with constant values to a global array with
// a constant initializer.
//
ModulePass *createHoistConstantArrayPass();
void initializeHoistConstantArrayPass(PassRegistry&);
// HLSL Change Ends
//===----------------------------------------------------------------------===//
//
// InductiveRangeCheckElimination - Transform loops to elide range checks on
// linear functions of the induction variable.
//
Pass *createInductiveRangeCheckEliminationPass();
//===----------------------------------------------------------------------===//
//
// InductionVariableSimplify - Transform induction variables in a program to all
// use a single canonical induction variable per loop.
//
Pass *createIndVarSimplifyPass();
//===----------------------------------------------------------------------===//
//
// InstructionCombining - Combine instructions to form fewer, simple
// instructions. This pass does not modify the CFG, and has a tendency to make
// instructions dead, so a subsequent DCE pass is useful.
//
// This pass combines things like:
// %Y = add int 1, %X
// %Z = add int 1, %Y
// into:
// %Z = add int 2, %X
//
FunctionPass *createInstructionCombiningPass();
FunctionPass *createInstructionCombiningPass(bool HLSLSkipSinkSelect); // HLSL Change
//===----------------------------------------------------------------------===//
//
// LICM - This pass is a loop invariant code motion and memory promotion pass.
//
Pass *createLICMPass();
//===----------------------------------------------------------------------===//
//
// LoopInterchange - This pass interchanges loops to provide a more
// cache-friendly memory access patterns.
//
Pass *createLoopInterchangePass();
//===----------------------------------------------------------------------===//
//
// LoopStrengthReduce - This pass is strength reduces GEP instructions that use
// a loop's canonical induction variable as one of their indices.
//
Pass *createLoopStrengthReducePass();
//===----------------------------------------------------------------------===//
//
// GlobalMerge - This pass merges internal (by default) globals into structs
// to enable reuse of a base pointer by indexed addressing modes.
// It can also be configured to focus on size optimizations only.
//
Pass *createGlobalMergePass(const TargetMachine *TM, unsigned MaximalOffset,
bool OnlyOptimizeForSize = false);
//===----------------------------------------------------------------------===//
//
// LoopUnswitch - This pass is a simple loop unswitching pass.
//
Pass *createLoopUnswitchPass(bool OptimizeForSize = false);
//===----------------------------------------------------------------------===//
//
// LoopInstSimplify - This pass simplifies instructions in a loop's body.
//
Pass *createLoopInstSimplifyPass();
//===----------------------------------------------------------------------===//
//
// LoopUnroll - This pass is a simple loop unrolling pass.
//
Pass *createLoopUnrollPass(int Threshold = -1, int Count = -1,
int AllowPartial = -1, int Runtime = -1,
bool StructurizeLoopExits = false // HLSL Change
);
// Create an unrolling pass for full unrolling only.
Pass *createSimpleLoopUnrollPass();
//===----------------------------------------------------------------------===//
//
// LoopReroll - This pass is a simple loop rerolling pass.
//
Pass *createLoopRerollPass();
//===----------------------------------------------------------------------===//
//
// LoopRotate - This pass is a simple loop rotating pass.
//
Pass *createLoopRotatePass(int MaxHeaderSize = -1);
//===----------------------------------------------------------------------===//
//
// LoopIdiom - This pass recognizes and replaces idioms in loops.
//
Pass *createLoopIdiomPass();
//===----------------------------------------------------------------------===//
//
// PromoteMemoryToRegister - This pass is used to promote memory references to
// be register references. A simple example of the transformation performed by
// this pass is:
//
// FROM CODE TO CODE
// %X = alloca i32, i32 1 ret i32 42
// store i32 42, i32 *%X
// %Y = load i32* %X
// ret i32 %Y
//
FunctionPass *createPromoteMemoryToRegisterPass();
//===----------------------------------------------------------------------===//
//
// DemoteRegisterToMemoryPass - This pass is used to demote registers to memory
// references. In basically undoes the PromoteMemoryToRegister pass to make cfg
// hacking easier.
//
FunctionPass *createDemoteRegisterToMemoryPass();
extern char &DemoteRegisterToMemoryID;
// HLSL Change start
// Relaxed version (for HLSL usage).
FunctionPass *createDemoteRegisterToMemoryHlslPass();
extern char &DemoteRegisterToMemoryHlslID;
// HLSL Change end
//===----------------------------------------------------------------------===//
//
// Reassociate - This pass reassociates commutative expressions in an order that
// is designed to promote better constant propagation, GCSE, LICM, PRE...
//
// For example: 4 + (x + 5) -> x + (4 + 5)
//
FunctionPass *createReassociatePass();
FunctionPass *
createReassociatePass(bool HLSLEnableAggressiveReassociation); // HLSL Change
//===----------------------------------------------------------------------===//
//
// JumpThreading - Thread control through mult-pred/multi-succ blocks where some
// preds always go to some succ. Thresholds other than minus one override the
// internal BB duplication default threshold.
//
FunctionPass *createJumpThreadingPass(int Threshold = -1);
//===----------------------------------------------------------------------===//
//
// CFGSimplification - Merge basic blocks, eliminate unreachable blocks,
// simplify terminator instructions, etc...
//
FunctionPass *createCFGSimplificationPass(
int Threshold = -1, std::function<bool(const Function &)> Ftor = nullptr);
//===----------------------------------------------------------------------===//
//
// FlattenCFG - flatten CFG, reduce number of conditional branches by using
// parallel-and and parallel-or mode, etc...
//
FunctionPass *createFlattenCFGPass();
//===----------------------------------------------------------------------===//
//
// CFG Structurization - Remove irreducible control flow
//
Pass *createStructurizeCFGPass();
//===----------------------------------------------------------------------===//
//
// BreakCriticalEdges - Break all of the critical edges in the CFG by inserting
// a dummy basic block. This pass may be "required" by passes that cannot deal
// with critical edges. For this usage, a pass must call:
//
// AU.addRequiredID(BreakCriticalEdgesID);
//
// This pass obviously invalidates the CFG, but can update forward dominator
// (set, immediate dominators, tree, and frontier) information.
//
FunctionPass *createBreakCriticalEdgesPass();
extern char &BreakCriticalEdgesID;
//===----------------------------------------------------------------------===//
//
// LoopSimplify - Insert Pre-header blocks into the CFG for every function in
// the module. This pass updates dominator information, loop information, and
// does not add critical edges to the CFG.
//
// AU.addRequiredID(LoopSimplifyID);
//
Pass *createLoopSimplifyPass();
extern char &LoopSimplifyID;
//===----------------------------------------------------------------------===//
//
// TailCallElimination - This pass eliminates call instructions to the current
// function which occur immediately before return instructions.
//
FunctionPass *createTailCallEliminationPass();
//===----------------------------------------------------------------------===//
//
// LowerSwitch - This pass converts SwitchInst instructions into a sequence of
// chained binary branch instructions.
//
FunctionPass *createLowerSwitchPass();
extern char &LowerSwitchID;
//===----------------------------------------------------------------------===//
//
// LowerInvoke - This pass removes invoke instructions, converting them to call
// instructions.
//
FunctionPass *createLowerInvokePass();
extern char &LowerInvokePassID;
//===----------------------------------------------------------------------===//
//
// LCSSA - This pass inserts phi nodes at loop boundaries to simplify other loop
// optimizations.
//
Pass *createLCSSAPass();
extern char &LCSSAID;
//===----------------------------------------------------------------------===//
//
// EarlyCSE - This pass performs a simple and fast CSE pass over the dominator
// tree.
//
FunctionPass *createEarlyCSEPass();
//===----------------------------------------------------------------------===//
//
// MergedLoadStoreMotion - This pass merges loads and stores in diamonds. Loads
// are hoisted into the header, while stores sink into the footer.
//
FunctionPass *createMergedLoadStoreMotionPass();
//===----------------------------------------------------------------------===//
//
// GVN - This pass performs global value numbering and redundant load
// elimination cotemporaneously.
//
FunctionPass *createGVNPass(bool NoLoads = false);
//===----------------------------------------------------------------------===//
//
// MemCpyOpt - This pass performs optimizations related to eliminating memcpy
// calls and/or combining multiple stores into memset's.
//
FunctionPass *createMemCpyOptPass();
//===----------------------------------------------------------------------===//
//
// LoopDeletion - This pass performs DCE of non-infinite loops that it
// can prove are dead.
//
Pass *createLoopDeletionPass();
//===----------------------------------------------------------------------===//
//
// ConstantHoisting - This pass prepares a function for expensive constants.
//
FunctionPass *createConstantHoistingPass();
//===----------------------------------------------------------------------===//
//
// InstructionNamer - Give any unnamed non-void instructions "tmp" names.
//
FunctionPass *createInstructionNamerPass();
extern char &InstructionNamerID;
//===----------------------------------------------------------------------===//
//
// Sink - Code Sinking
//
FunctionPass *createSinkingPass();
//===----------------------------------------------------------------------===//
//
// LowerAtomic - Lower atomic intrinsics to non-atomic form
//
Pass *createLowerAtomicPass();
//===----------------------------------------------------------------------===//
//
// ValuePropagation - Propagate CFG-derived value information
//
Pass *createCorrelatedValuePropagationPass();
//===----------------------------------------------------------------------===//
//
// InstructionSimplifier - Remove redundant instructions.
//
FunctionPass *createInstructionSimplifierPass();
extern char &InstructionSimplifierID;
//===----------------------------------------------------------------------===//
//
// LowerExpectIntrinsics - Removes llvm.expect intrinsics and creates
// "block_weights" metadata.
FunctionPass *createLowerExpectIntrinsicPass();
//===----------------------------------------------------------------------===//
//
// PartiallyInlineLibCalls - Tries to inline the fast path of library
// calls such as sqrt.
//
FunctionPass *createPartiallyInlineLibCallsPass();
//===----------------------------------------------------------------------===//
//
// SampleProfilePass - Loads sample profile data from disk and generates
// IR metadata to reflect the profile.
FunctionPass *createSampleProfileLoaderPass();
FunctionPass *createSampleProfileLoaderPass(StringRef Name);
//===----------------------------------------------------------------------===//
//
// ScalarizerPass - Converts vector operations into scalar operations
//
FunctionPass *createScalarizerPass();
FunctionPass *createScalarizerPass(bool NoOpt);
//===----------------------------------------------------------------------===//
//
// AddDiscriminators - Add DWARF path discriminators to the IR.
FunctionPass *createAddDiscriminatorsPass();
//===----------------------------------------------------------------------===//
//
// SeparateConstOffsetFromGEP - Split GEPs for better CSE
//
FunctionPass *
createSeparateConstOffsetFromGEPPass(const TargetMachine *TM = nullptr,
bool LowerGEP = false);
//===----------------------------------------------------------------------===//
//
// SpeculativeExecution - Aggressively hoist instructions to enable
// speculative execution on targets where branches are expensive.
//
FunctionPass *createSpeculativeExecutionPass();
//===----------------------------------------------------------------------===//
//
// LoadCombine - Combine loads into bigger loads.
//
BasicBlockPass *createLoadCombinePass();
//===----------------------------------------------------------------------===//
//
// StraightLineStrengthReduce - This pass strength-reduces some certain
// instruction patterns in straight-line code.
//
FunctionPass *createStraightLineStrengthReducePass();
//===----------------------------------------------------------------------===//
//
// PlaceSafepoints - Rewrite any IR calls to gc.statepoints and insert any
// safepoint polls (method entry, backedge) that might be required. This pass
// does not generate explicit relocation sequences - that's handled by
// RewriteStatepointsForGC which can be run at an arbitrary point in the pass
// order following this pass.
//
FunctionPass *createPlaceSafepointsPass();
//===----------------------------------------------------------------------===//
//
// RewriteStatepointsForGC - Rewrite any gc.statepoints which do not yet have
// explicit relocations to include explicit relocations.
//
ModulePass *createRewriteStatepointsForGCPass();
//===----------------------------------------------------------------------===//
//
// Float2Int - Demote floats to ints where possible.
//
FunctionPass *createFloat2IntPass();
//===----------------------------------------------------------------------===//
//
// NaryReassociate - Simplify n-ary operations by reassociation.
//
FunctionPass *createNaryReassociatePass();
// //
///////////////////////////////////////////////////////////////////////////////
//
// LoopDistribute - Distribute loops.
//
FunctionPass *createLoopDistributePass();
} // End llvm namespace
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.