diff --git a/LICENSE.txt b/LICENSE.txt
new file mode 100644
index 0000000000000..fa6ac54000703
--- /dev/null
+++ b/LICENSE.txt
@@ -0,0 +1,279 @@
+==============================================================================
+The LLVM Project is under the Apache License v2.0 with LLVM Exceptions:
+==============================================================================
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+
+---- LLVM Exceptions to the Apache 2.0 License ----
+
+As an exception, if, as a result of your compiling your source code, portions
+of this Software are embedded into an Object form of such source code, you
+may redistribute such embedded portions in such Object form without complying
+with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
+
+In addition, if you combine or link compiled forms of this Software with
+software that is licensed under the GPLv2 ("Combined Software") and if a
+court of competent jurisdiction determines that the patent provision (Section
+3), the indemnity provision (Section 9) or other Section of the License
+conflicts with the conditions of the GPLv2, you may retroactively and
+prospectively choose to deem waived or otherwise exclude such Section(s) of
+the License, but only in their entirety and only with respect to the Combined
+Software.
+
+==============================================================================
+Software from third parties included in the LLVM Project:
+==============================================================================
+The LLVM Project contains third party software which is under different license
+terms. All such code will be identified clearly using at least one of two
+mechanisms:
+1) It will be in a separate directory tree with its own `LICENSE.txt` or
+ `LICENSE` file at the top containing the specific license and restrictions
+ which apply to that software, or
+2) It will contain specific license and restriction terms at the top of every
+ file.
+
+==============================================================================
+Legacy LLVM License (https://llvm.org/docs/DeveloperPolicy.html#legacy):
+==============================================================================
+University of Illinois/NCSA
+Open Source License
+
+Copyright (c) 2003-2019 University of Illinois at Urbana-Champaign.
+All rights reserved.
+
+Developed by:
+
+ LLVM Team
+
+ University of Illinois at Urbana-Champaign
+
+ http://llvm.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal with
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimers.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimers in the
+ documentation and/or other materials provided with the distribution.
+
+ * Neither the names of the LLVM Team, University of Illinois at
+ Urbana-Champaign, nor the names of its contributors may be used to
+ endorse or promote products derived from this Software without specific
+ prior written permission.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
+SOFTWARE.
+
diff --git a/README.md b/README.md
index da06ed76b8adf..b83ac2e7989c7 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,11 @@
+# Apple's fork of llvm-project
+
+This is Apple's fork of llvm-project. For more information on Apple's
+branching scheme, please see
+[apple-docs/AppleBranchingScheme.md](https://github.com/apple/llvm-project/tree/apple/master/apple-docs/AppleBranchingScheme.md).
+
+The LLVM project's main README follows.
+
# The LLVM Compiler Infrastructure
This directory and its subdirectories contain source code for LLVM,
diff --git a/apple-docs/AppleBranchingScheme.md b/apple-docs/AppleBranchingScheme.md
new file mode 100644
index 0000000000000..806d0a39416ff
--- /dev/null
+++ b/apple-docs/AppleBranchingScheme.md
@@ -0,0 +1,105 @@
+# Apple's branching scheme for llvm-project
+
+There are currently three namespaces for branches on
+[github.com/apple/llvm-project](https://github.com/apple/llvm-project):
+
+ 1. `llvm.org/*`, for forwarded branches from
+ [github.com/llvm](https://github.com/llvm/llvm-project);
+ 2. `apple/*`, for standalone downstream content; and
+ 3. `swift/*`, for downstream content that depends on
+ [Swift](https://github.com/apple/swift).
+
+## Forwarded branches from [github.com/llvm](https://github.com/llvm/llvm-project)
+
+The `llvm.org/*` branches are forwarded, unchanged, from
+[github.com/llvm/llvm-project](https://github.com/llvm/llvm-project). These
+are read-only, exact copies of the upstream LLVM project's branches. They are
+forwarded here as a convenience for easy reference, to avoid the need for extra
+remotes.
+
+- [llvm.org/master](https://github.com/apple/llvm-project/tree/llvm.org/master)
+ is the most important branch here, matching the LLVM project's
+ [master](https://github.com/llvm/llvm-project/tree/master) branch.
+
+## Downstream branches that are standalone
+
+The `apple/*` branches have downstream content, besides what is in the LLVM
+project. This content includes some patches that have not yet been fully
+upstreamed to the LLVM project, including some special support for Swift.
+Critically, however, none of these branches *depend on* the
+[github.com/apple/swift](https://github.com/apple/swift) repository.
+
+Although there are a few non-trivial differences from LLVM, the goal is to
+minimize this difference, and do almost all development upstream.
+
+- [apple/master](https://github.com/apple/llvm-project/tree/apple/master) is
+ directly downstream of
+ [llvm.org/master](https://github.com/apple/llvm-project/tree/llvm.org/master).
+ There is a gated automerger that does testing before merging in. Most
+ changes to this branch should be redirected to
+ (see also ).
+- `apple/stable/*`: These branches are periodic stabilization branches, where
+ fixes are cherry-picked from LLVM. At time of writing:
+ - [apple/stable/20191106](https://github.com/apple/llvm-project/tree/apple/stable/20191106)
+ is the most recent stabilization branch.
+ - [apple/stable/20190619](https://github.com/apple/llvm-project/tree/apple/stable/20190619)
+ is the current stabilization branch for
+ [swift/master](https://github.com/apple/llvm-project/tree/swift/master)
+ (see below).
+
+## Downstream branches that depend on [Swift](https://github.com/apple/swift)
+
+The `swift/*` branches are downstream of `apple/*`, and include content that
+depends [Swift](https://github.com/apple/swift). The naming scheme is
+`swift/`, where `` is the aligned Swift branch.
+
+The branches are automerged from a branch in the `apple/*` namespace. They are
+expected to have zero differences outside the `lldb/` and `apple-llvm-config/`
+directories.
+
+These are the most important branches:
+
+- [swift/master-next](https://github.com/apple/llvm-project/tree/swift/master-next)
+ is downstream of
+ [apple/master](https://github.com/apple/llvm-project/tree/apple/master) and
+ aligned with Swift's
+ [master-next](https://github.com/apple/swift/tree/master-next) branch.
+- [swift/master](https://github.com/apple/llvm-project/tree/swift/master) is
+ downstream of a stabilization branch in `apple/stable/*`
+ ([apple/stable/20190619](https://github.com/apple/llvm-project/tree/apple/stable/20190619),
+ as of time of writing) and aligned with Swift's
+ [master](https://github.com/apple/swift/tree/master) branch.
+
+## Historical trivia: mappings to branches from before the monorepo transition
+
+Before the LLVM project's monorepo transition, Apple maintained downstream
+forks of various split repositories. Here is a mapping from a few of the new
+branches in the llvm-project monorepo to their original split repositories.
+
+- [apple/master](https://github.com/apple/llvm-project/tree/apple/master) was
+ generated from the `upstream-with-swift` branches in
+ [swift-clang](https://github.com/apple/swift-clang/),
+ [swift-llvm](https://github.com/apple/swift-llvm/),
+ [swift-compiler-rt](https://github.com/apple/swift-compiler-rt/),
+ [swift-clang-tools-extra](https://github.com/apple/swift-clang-tools-extra/),
+ and [swift-libcxx](https://github.com/apple/swift-libcxx/), with the notable
+ **exclusion** of [swift-lldb](https://github.com/apple/swift-lldb/),
+- [swift/master-next](https://github.com/apple/llvm-project/tree/swift/master-next)
+ was generated from the `upstream-with-swift` branch in
+ [swift-lldb](https://github.com/apple/swift-lldb/), interleaved with merges
+ from [apple/master](https://github.com/apple/llvm-project/tree/apple/master).
+- [apple/stable/20190104](https://github.com/apple/llvm-project/tree/apple/stable/20190104)
+ was generated from the `swift-5.1-branch` branches in
+ [swift-clang](https://github.com/apple/swift-clang/),
+ [swift-llvm](https://github.com/apple/swift-llvm/),
+ [swift-compiler-rt](https://github.com/apple/swift-compiler-rt/),
+ [swift-clang-tools-extra](https://github.com/apple/swift-clang-tools-extra/),
+ and [swift-libcxx](https://github.com/apple/swift-libcxx/), with the notable
+ **exclusion** of [swift-lldb](https://github.com/apple/swift-lldb/),
+- [swift/swift-5.1-branch](https://github.com/apple/llvm-project/tree/swift/swift-5.1-branch)
+ was generated from the `swift-5.1-branch` branch in
+ [swift-lldb](https://github.com/apple/swift-lldb/), interleaved with merges
+ from
+ [apple/stable/20190104](https://github.com/apple/llvm-project/tree/apple/stable/20190104).
+- [swift/master](https://github.com/apple/llvm-project/tree/swift/master) was
+ generated from the `stable` branch from all six split repos.
diff --git a/apple-llvm-config/am/apple-master.json b/apple-llvm-config/am/apple-master.json
new file mode 100644
index 0000000000000..427b8b4bbf218
--- /dev/null
+++ b/apple-llvm-config/am/apple-master.json
@@ -0,0 +1,3 @@
+{
+ "upstream": "llvm.org/master"
+}
diff --git a/apple-llvm-config/pr.json b/apple-llvm-config/pr.json
new file mode 100644
index 0000000000000..9de9ce6265850
--- /dev/null
+++ b/apple-llvm-config/pr.json
@@ -0,0 +1,9 @@
+{
+"type": "github",
+"domain": "github.com",
+"user": "apple",
+"repo": "llvm-project",
+"test": {
+ "type":"swift-ci"
+}
+}
diff --git a/clang/CONTRIBUTING.md b/clang/CONTRIBUTING.md
new file mode 100644
index 0000000000000..a0c1644fc66a2
--- /dev/null
+++ b/clang/CONTRIBUTING.md
@@ -0,0 +1,14 @@
+By submitting a pull request, you represent that you have the right to license
+your contribution to Apple and the community, and agree by submitting the patch
+that your contributions are licensed under the [Swift
+license](https://swift.org/LICENSE.txt).
+
+---
+
+Changes to this repository follow special considerations as described on
+Swift.org under "[LLVM and Swift](https://swift.org/contributing/#llvm-and-swift)".
+Please make sure your change is appropriate for this repository.
+
+Before submitting a pull request, please make sure you have tested your
+changes and that they follow the Swift project [guidelines for contributing
+code](https://swift.org/contributing/#contributing-code).
diff --git a/clang/docs/APINotes.rst b/clang/docs/APINotes.rst
new file mode 100644
index 0000000000000..83ce634623ca9
--- /dev/null
+++ b/clang/docs/APINotes.rst
@@ -0,0 +1,361 @@
+================================================
+API Notes: Annotations Without Modifying Headers
+================================================
+
+**The Problem:** You have headers you want to use, but you also want to add
+extra information to some of the APIs. You don't want to put that information
+in the headers themselves---perhaps because you want to keep them clean for
+other clients, or perhaps because they're from some open source project and you
+don't want to modify them at all.
+
+**Incomplete solution:** Redeclare all the interesting APIs in your own header
+and add the attributes you want. Unfortunately, this:
+
+* doesn't work with attributes that must be present on a definition
+* doesn't allow changing the definition in other ways
+* requires your header to be included in any client code to take effect
+
+**Better solution:** Provide a "sidecar" file with the information you want to
+add, and have that automatically get picked up by the module-building logic in
+the compiler.
+
+That's API notes.
+
+API notes use a YAML-based file format. YAML is a format best explained by
+example, so here is a `small example`__ from the compiler test suite of API
+notes for a hypothetical "SomeKit" framework.
+
+__ https://github.com/apple/swift-clang/blob/upstream-with-swift/test/APINotes/Inputs/Frameworks/SomeKit.framework/Headers/SomeKit.apinotes
+
+
+Usage
+=====
+
+API notes files are found relative to the module map that defines a module,
+under the name "SomeKit.apinotes" for a module named "SomeKit". Additionally, a
+file named "SomeKit_private.apinotes" will also be picked up to go with a
+private module map. For bare modules these two files will be in the same
+directory as the corresponding module map; for framework modules, they should
+be placed in the Headers and PrivateHeaders directories, respectively. The
+module map for a private top-level framework module should be placed in the
+PrivateHeaders directory as well, though it does not need an additional
+"_private" suffix on its name.
+
+Clang will search for API notes files next to module maps only when passed the
+``-fapinotes-modules`` option.
+
+
+Limitations
+===========
+
+- Since they're identified by module name, API notes cannot be used to modify
+ arbitrary textual headers.
+
+
+"Versioned" API Notes
+=====================
+
+Many API notes affect how a C API is imported into Swift. In order to change
+that behavior while still remaining backwards-compatible, API notes can be
+selectively applied based on the Swift compatibility version provided to the
+compiler (e.g. ``-fapinotes-swift-version=5``). The rule is that an
+explicitly-versioned API note applies to that version *and all earlier
+versions,* and any applicable explicitly-versioned API note takes precedence
+over an unversioned API note.
+
+
+Reference
+=========
+
+An API notes file contains a YAML dictionary with the following top-level
+entries:
+
+:Name:
+
+ The name of the module (the framework name, for frameworks). Note that this
+ is always the name of a top-level module, even within a private API notes
+ file.
+
+ ::
+
+ Name: MyFramework
+
+:Classes, Protocols, Tags, Typedefs, Globals, Enumerators, Functions:
+
+ Arrays of top-level declarations. Each entry in the array must have a
+ 'Name' key with its Objective-C name. "Tags" refers to structs, enums, and
+ unions; "Enumerators" refers to enum cases.
+
+ ::
+
+ Classes:
+ - Name: MyController
+ …
+ - Name: MyView
+ …
+
+:SwiftVersions:
+
+ Contains explicit information for backwards compatibility. Each entry in
+ the array contains a 'Version' key, which should be set to '4' for
+ annotations that only apply to Swift 4 mode and earlier. The other entries
+ in this dictionary are the same declaration entries as at the top level:
+ Classes, Protocols, Tags, Typedefs, Globals, Enumerators, and Functions.
+
+ ::
+
+ SwiftVersions:
+ - Version: 4
+ Classes: …
+ Protocols: …
+
+Each entry under 'Classes' and 'Protocols' can contain "Methods" and
+"Properties" arrays, in addition to the attributes described below:
+
+:Methods:
+
+ Identified by 'Selector' and 'MethodKind'; the MethodKind is either
+ "Instance" or "Class".
+
+ ::
+
+ Classes:
+ - Name: UIViewController
+ Methods:
+ - Selector: "presentViewController:animated:"
+ MethodKind: Instance
+ …
+
+:Properties:
+
+ Identified by 'Name' and 'PropertyKind'; the PropertyKind is also either
+ "Instance" or "Class".
+
+ ::
+
+ Classes:
+ - Name: UIView
+ Properties:
+ - Name: subviews
+ PropertyKind: Instance
+ …
+
+Each declaration supports the following annotations (if relevant to that
+declaration kind), all of which are optional:
+
+:SwiftName:
+
+ Equivalent to NS_SWIFT_NAME. For a method, must include the full Swift name
+ with all arguments. Use "_" to omit an argument label.
+
+ ::
+
+ - Selector: "presentViewController:animated:"
+ MethodKind: Instance
+ SwiftName: "present(_:animated:)"
+
+ - Class: NSBundle
+ SwiftName: Bundle
+
+:Availability, AvailabilityMsg:
+
+ A value of "nonswift" is equivalent to NS_SWIFT_UNAVAILABLE. A value of
+ "available" can be used in the "SwiftVersions" section to undo the effect of
+ "nonswift".
+
+ ::
+
+ - Selector: "dealloc"
+ MethodKind: Instance
+ Availability: nonswift
+ AvailabilityMsg: "prefer 'deinit'"
+
+:SwiftPrivate:
+
+ Equivalent to NS_REFINED_FOR_SWIFT.
+
+ ::
+
+ - Name: CGColorEqualToColor
+ SwiftPrivate: true
+
+:Nullability:
+
+ Used for properties and globals. There are four options, identified by their
+ initials:
+
+ - "N"onnull (``_Nonnull``)
+ - "O"ptional (``_Nullable``)
+ - "U"nspecified (``_Null_unspecified``)
+ - "S"calar (deprecated)
+
+ Note that 'Nullability' is overridden by 'Type', even in a "SwiftVersions"
+ section.
+
+ .. note::
+
+ 'Nullability' can also be used to describe the argument types of methods
+ and functions, but this usage is deprecated in favor of 'Parameters' (see
+ below).
+
+ ::
+
+ - Name: dataSource
+ Nullability: O
+
+:NullabilityOfRet:
+
+ Used for methods and functions. Describes the nullability of the return type.
+
+ Note that 'NullabilityOfRet' is overridden by 'ResultType', even in a
+ "SwiftVersions" section.
+
+ .. warning::
+
+ Due to a compiler bug, 'NullabilityOfRet' may change nullability of the
+ parameters as well (rdar://30544062). Avoid using it and instead use
+ 'ResultType' and specify the return type along with a nullability
+ annotation (see documentation for 'ResultType').
+
+ ::
+
+ - Selector: superclass
+ MethodKind: Class
+ NullabilityOfRet: O
+
+:Type:
+
+ Used for properties and globals. This completely overrides the type of the
+ declaration; it should ideally only be used for Swift backwards
+ compatibility, when existing type information has been made more precise in a
+ header. Prefer 'Nullability' and other annotations when possible.
+
+ Note that the type is *not* parsed in the context where it will be used,
+ which means that macros are not available and nullability must be applied
+ explicitly (even in an ``NS_ASSUME_NONNULL_BEGIN`` section).
+
+ ::
+
+ - Name: delegate
+ PropertyKind: Instance
+ Type: "id"
+
+:ResultType:
+
+ Used for methods and functions. This completely overrides the return type; it
+ should ideally only be used for Swift backwards compatibility, when existing
+ type information has been made more precise in a header.
+
+ Note that the type is *not* parsed in the context where it will be used,
+ which means that macros are not available and nullability must be applied
+ explicitly (even in an ``NS_ASSUME_NONNULL_BEGIN`` section).
+
+ ::
+
+ - Selector: "subviews"
+ MethodKind: Instance
+ ResultType: "NSArray * _Nonnull"
+
+:SwiftImportAsAccessors:
+
+ Used for properties. If true, the property will be exposed in Swift as its
+ accessor methods, rather than as a computed property using ``var``.
+
+ ::
+
+ - Name: currentContext
+ PropertyKind: Class
+ SwiftImportAsAccessors: true
+
+:NSErrorDomain:
+
+ Used for NSError code enums. The value is the name of the associated domain
+ NSString constant; an empty string ("") means the enum is a normal enum
+ rather than an error code.
+
+ ::
+
+ - Name: MKErrorCode
+ NSErrorDomain: MKErrorDomain
+
+:SwiftWrapper:
+
+ Controls NS_STRING_ENUM and NS_EXTENSIBLE_STRING_ENUM. There are three
+ options:
+
+ - "struct" (extensible)
+ - "enum"
+ - "none"
+
+ Note that even an "enum" wrapper is still presented as a struct in Swift;
+ it's just a "more enum-like" struct.
+
+ ::
+
+ - Name: AVMediaType
+ SwiftWrapper: none
+
+:EnumKind:
+
+ Has the same effect as NS_ENUM and NS_OPTIONS. There are four options:
+
+ - "NSEnum" / "CFEnum"
+ - "NSClosedEnum" / "CFClosedEnum"
+ - "NSOptions" / "CFOptions"
+ - "none"
+
+ ::
+
+ - Name: GKPhotoSize
+ EnumKind: none
+
+:Parameters:
+
+ Used for methods and functions. Parameters are identified by a 0-based
+ 'Position' and support the 'Nullability', 'NoEscape', and 'Type' keys.
+
+ .. note::
+
+ Using 'Parameters' within a parameter entry to describe the parameters of a
+ block is not implemented. Use 'Type' on the entire parameter instead.
+
+ ::
+
+ - Selector: "isEqual:"
+ MethodKind: Instance
+ Parameters:
+ - Position: 0
+ Nullability: O
+
+:NoEscape:
+
+ Used only for block parameters. Equivalent to NS_NOESCAPE.
+
+ ::
+
+ - Name: dispatch_sync
+ Parameters:
+ - Position: 0
+ NoEscape: true
+
+:SwiftBridge:
+
+ Used for Objective-C class types bridged to Swift value types. An empty
+ string ("") means a type is not bridged. Not supported outside of Apple
+ frameworks (the Swift side of it requires conforming to implementation-detail
+ protocols that are subject to change).
+
+ ::
+
+ - Name: NSIndexSet
+ SwiftBridge: IndexSet
+
+:DesignatedInit:
+
+ Used for init methods. Equivalent to NS_DESIGNATED_INITIALIZER.
+
+ ::
+
+ - Selector: "initWithFrame:"
+ MethodKind: Instance
+ DesignatedInit: true
diff --git a/clang/docs/LanguageExtensions.rst b/clang/docs/LanguageExtensions.rst
index b0f57202e0797..343dd7daf8a0a 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -13,6 +13,7 @@ Clang Language Extensions
BlockLanguageSpec
Block-ABI-Apple
AutomaticReferenceCounting
+ PointerAuthentication
Introduction
============
@@ -2552,6 +2553,10 @@ reordering of memory accesses and side effect instructions. Other instructions
like simple arithmetic may be reordered around the intrinsic. If you expect to
have no reordering at all, use inline assembly instead.
+Pointer Authentication
+^^^^^^^^^^^^^^^^^^^^^^
+See :doc:`PointerAuthentication`.
+
X86/X86-64 Language Extensions
------------------------------
diff --git a/clang/docs/PointerAuthentication.rst b/clang/docs/PointerAuthentication.rst
new file mode 100644
index 0000000000000..04adc52c900a0
--- /dev/null
+++ b/clang/docs/PointerAuthentication.rst
@@ -0,0 +1,877 @@
+Pointer Authentication
+======================
+
+.. contents::
+ :local:
+
+Introduction
+------------
+
+Pointer authentication is a technology which offers strong probabilistic protection against exploiting a broad class of memory bugs to take control of program execution. When adopted consistently in a language ABI, it provides a form of relatively fine-grained control flow integrity (CFI) check that resists both return-oriented programming (ROP) and jump-oriented programming (JOP) attacks.
+
+While pointer authentication can be implemented purely in software, direct hardware support (e.g. as provided by ARMv8.3) can dramatically lower the execution speed and code size costs. Similarly, while pointer authentication can be implemented on any architecture, taking advantage of the (typically) excess addressing range of a target with 64-bit pointers minimizes the impact on memory performance and can allow interoperation with existing code (by disabling pointer authentication dynamically). This document will generally attempt to present the pointer authentication feature independent of any hardware implementation or ABI. Considerations that are implementation-specific are clearly identified throughout.
+
+Note that there are several different terms in use:
+
+- **Pointer authentication** is a target-independent language technology.
+
+- **ARMv8.3** is an AArch64 architecture revision of that provides hardware support for pointer authentication. It is implemented on several shipping processors, including the Apple A12 and later.
+
+* **arm64e** is a specific ABI for (not yet fully stable) for implementing pointer authentication on ARMv8.3 on certain Apple operating systems.
+
+This document serves four purposes:
+
+- It describes the basic ideas of pointer authentication.
+
+- It documents several language extensions that are useful on targets using pointer authentication.
+
+- It presents a theory of operation for the security mitigation, describing the basic requirements for correctness, various weaknesses in the mechanism, and ways in which programmers can strengthen its protections (including recommendations for language implementors).
+
+- It documents the language ABIs currently used for C, C++, Objective-C, and Swift on arm64e, although these are not yet stable on any target.
+
+Basic Concepts
+--------------
+
+The simple address of an object or function is a **raw pointer**. A raw pointer can be **signed** to produce a **signed pointer**. A signed pointer can be then **authenticated** in order to verify that it was **validly signed** and extract the original raw pointer. These terms reflect the most likely implementation technique: computing and storing a cryptographic signature along with the pointer. The security of pointer authentication does not rely on attackers not being able to separately overwrite the signature.
+
+An **abstract signing key** is a name which refers to a secret key which can used to sign and authenticate pointers. The key value for a particular name is consistent throughout a process.
+
+A **discriminator** is an arbitrary value used to **diversify** signed pointers so that one validly-signed pointer cannot simply be copied over another. A discriminator is simply opaque data of some implementation-defined size that is included in the signature as a salt.
+
+Nearly all aspects of pointer authentication use just these two primary operations:
+
+- ``sign(raw_pointer, key, discriminator)`` produces a signed pointer given a raw pointer, an abstract signing key, and a discriminator.
+
+- ``auth(signed_pointer, key, discriminator)`` produces a raw pointer given a signed pointer, an abstract signing key, and a discriminator.
+
+``auth(sign(raw_pointer, key, discriminator), key, discriminator)`` must succeed and produce ``raw_pointer``. ``auth`` applied to a value that was ultimately produced in any other way is expected to immediately halt the program. However, it is permitted for ``auth`` to fail to detect that a signed pointer was not produced in this way, in which case it may return anything; this is what makes pointer authentication a probabilistic mitigation rather than a perfect one.
+
+There are two secondary operations which are required only to implement certain intrinsics in ````:
+
+- ``strip(signed_pointer, key)`` produces a raw pointer given a signed pointer and a key it was presumptively signed with. This is useful for certain kinds of tooling, such as crash backtraces; it should generally not be used in the basic language ABI except in very careful ways.
+
+- ``sign_generic(value)`` produces a cryptographic signature for arbitrary data, not necessarily a pointer. This is useful for efficiently verifying that non-pointer data has not been tampered with.
+
+Whenever any of these operations is called for, the key value must be known statically. This is because the layout of a signed pointer may vary according to the signing key. (For example, in ARMv8.3, the layout of a signed pointer depends on whether TBI is enabled, which can be set independently for code and data pointers.)
+
+.. admonition:: Note for API designers and language implementors
+
+ These are the *primitive* operations of pointer authentication, provided for clarity of description. They are not suitable either as high-level interfaces or as primitives in a compiler IR because they expose raw pointers. Raw pointers require special attention in the language implementation to avoid the accidental creation of exploitable code sequences; see the section on `Attackable code sequences`_.
+
+The following details are all implementation-defined:
+
+- the nature of a signed pointer
+- the size of a discriminator
+- the number and nature of the signing keys
+- the implementation of the ``sign``, ``auth``, ``strip``, and ``sign_generic`` operations
+
+While the use of the terms "sign" and "signed pointer" suggest the use of a cryptographic signature, other implementations may be possible. See `Alternative implementations`_ for an exploration of implementation options.
+
+.. admonition:: Implementation example: ARMv8.3
+
+ Readers may find it helpful to know how these terms map to ARMv8.3:
+
+ - A signed pointer is a pointer with a signature stored in the otherwise-unused high bits. The kernel configures the signature width based on the system's addressing needs, accounting for whether the AArch64 TBI feature is enabled for the kind of pointer (code or data).
+
+ - A discriminator is a 64-bit integer. Constant discriminators are 16-bit integers. Blending a constant discriminator into an address consists of replacing the top 16 bits of the address with the constant.
+
+ - There are five 128-bit signing-key registers, each of which can only be directly read or set by privileged code. Of these, four are used for signing pointers, and the fifth is used only for ``sign_generic``. The key data is simply a pepper added to the hash, not an encryption key, and so can be initialized using random data.
+
+ - ``sign`` computes a cryptographic hash of the pointer, discriminator, and signing key, and stores it in the high bits as the signature. ``auth`` removes the signature, computes the same hash, and compares the result with the stored signature. ``strip`` removes the signature without authenticating it. While ARMv8.3's ``aut*`` instructions do not themselves trap on failure, the compiler only ever emits them in sequences that will trap.
+
+ - ``sign_generic`` corresponds to the ``pacga`` instruction, which takes two 64-bit values and produces a 64-bit cryptographic hash. Implementations of this instruction may not produce meaningful data in all bits of the result.
+
+Discriminators
+~~~~~~~~~~~~~~
+
+A discriminator is arbitrary extra data which alters the signature on a pointer. When two pointers are signed differently --- either with different keys or with different discriminators --- an attacker cannot simply replace one pointer with the other. For more information on why discriminators are important and how to use them effectively, see the section on `Substitution attacks`_.
+
+To use standard cryptographic terminology, a discriminator acts as a salt in the signing of a pointer, and the key data acts as a pepper. That is, both the discriminator and key data are ultimately just added as inputs to the signing algorithm along with the pointer, but they serve significantly different roles. The key data is a common secret added to every signature, whereas the discriminator is a signing-specific value that can be derived from the circumstances of how a pointer is signed. However, unlike a password salt, it's important that discriminators be *independently* derived from the circumstances of the signing; they should never simply be stored alongside a pointer.
+
+The intrinsic interface in ```` allows an arbitrary discriminator value to be provided, but can only be used when running normal code. The discriminators used by language ABIs must be restricted to make it feasible for the loader to sign pointers stored in global memory without needing excessive amounts of metadata. Under these restrictions, a discriminator may consist of either or both of the following:
+
+- The address at which the pointer is stored in memory. A pointer signed with a discriminator which incorporates its storage address is said to have **address diversity**. In general, using address diversity means that a pointer cannot be reliably replaced by an attacker or used to reliably replace a different pointer. However, an attacker may still be able to attack a larger call sequence if they can alter the address through which the pointer is accessed. Furthermore, some situations cannot use address diversity because of language or other restrictions.
+
+- A constant integer, called a **constant discriminator**. A pointer signed with a non-zero constant discriminator is said to have **constant diversity**. If the discriminator is specific to a single declaration, it is said to have **declaration diversity**; if the discriminator is specific to a type of value, it is said to have **type diversity**. For example, C++ v-tables on arm64e sign their component functions using a hash of their method names and signatures, which provides declaration diversity; similarly, C++ member function pointers sign their invocation functions using a hash of the member pointer type, which provides type diversity.
+
+The implementation may need to restrict constant discriminators to be significantly smaller than the full size of a discriminator. For example, on arm64e, constant discriminators are only 16-bit values. This is believed to not significantly weaken the mitigation, since collisions remain uncommon.
+
+The algorithm for blending a constant discriminator with a storage address is implementation-defined.
+
+.. _Signing schemas:
+
+Signing schemas
+~~~~~~~~~~~~~~~
+
+Correct use of pointer authentication requires the signing code and the authenticating code to agree about the **signing schema** for the pointer:
+
+- the abstract signing key with which the pointer should be signed and
+- an algorithm for computing the discriminator.
+
+As described in the section above on `Discriminators`_, in most situations, the discriminator is produced by taking a constant discriminator and optionally blending it with the storage address of the pointer. In these situations, the signing schema breaks down even more simply:
+
+- the abstract signing key,
+- a constant discriminator, and
+- whether to use address diversity.
+
+It is important that the signing schema be independently derived at all signing and authentication sites. Preferably, the schema should be hard-coded everywhere it is needed, but at the very least, it must not be derived by inspecting information stored along with the pointer. See the section on `Attacks on pointer authentication`_ for more information.
+
+
+
+
+
+Language Features
+-----------------
+
+There are three levels of the pointer authentication language feature:
+
+- The language implementation automatically signs and authenticates function pointers (and certain data pointers) across a variety of standard situations, including return addresses, function pointers, and C++ virtual functions. The intent is for all pointers to code in program memory to be signed in some way and for all branches to code in program text to authenticate those signatures.
+
+- The language also provides extensions to override the default rules used by the language implementation. For example, the ``__ptrauth`` type qualifier can be used to change how pointers are signed when they are stored in a particular variable or field; this provides much stronger protection than is guaranteed by the default rules for C function and data pointers.
+
+- FInally, the language provides the ```` intrinsic interface for manually signing and authenticating pointers in code. These can be used in circumstances where very specific behavior is required.
+
+Language implementation
+~~~~~~~~~~~~~~~~~~~~~~~
+
+For the most part, pointer authentication is an unobserved detail of the implementation of the programming language. Any element of the language implementation that would perform an indirect branch to a pointer is implicitly altered so that the pointer is signed when first constructed and authenticated when the branch is performed. This includes:
+
+- indirect-call features in the programming language, such as C function pointers, C++ virtual functions, C++ member function pointers, the "blocks" C extension, and so on;
+
+- returning from a function, no matter how it is called; and
+
+- indirect calls introduced by the implementation, such as branches through the global offset table (GOT) used to implement direct calls to functions defined outside of the current shared object.
+
+For more information about this, see the `Language ABI`_ section.
+
+However, some aspects of the implementation are observable by the programmer or otherwise require special notice.
+
+C data pointers
+^^^^^^^^^^^^^^^
+
+The current implementation in Clang does not sign pointers to ordinary data by default. For a partial explanation of the reasoning behind this, see the `Theory of Operation`_ section.
+
+A specific data pointer which is more security-sensitive than most can be signed using the `__ptrauth qualifier`_ or using the ```` intrinsics.
+
+C function pointers
+^^^^^^^^^^^^^^^^^^^
+
+The C standard imposes restrictions on the representation and semantics of function pointer types which make it difficult to achieve satisfactory signature diversity in the default language rules. See `Attacks on pointer authentication`_ for more information about signature diversity. Programmers should strongly consider using the ``__ptrauth`` qualifier to improve the protections for important function pointers, such as the components of of a hand-rolled "v-table"; see the section on the `__ptrauth qualifier`_ for details.
+
+The value of a pointer to a C function includes a signature, even when the value is cast to a non-function-pointer type like ``void*`` or ``intptr_t``. On implementations that use high bits to store the signature, this means that relational comparisons and hashes will vary according to the exact signature value, which is likely to change between executions of a program. In some implementations, it may also vary based on the exact function pointer type.
+
+Null pointers
+^^^^^^^^^^^^^
+
+In principle, an implementation could derive the signed null pointer value simply by applying the standard signing algorithm to the raw null pointer value. However, for likely signing algorithms, this would mean that the signed null pointer value would no longer be statically known, which would have many negative consequences. For one, it would become substantially more expensive to emit null pointer values or to perform null-pointer checks. For another, the pervasive (even if technically unportable) assumption that null pointers are bitwise zero would be invalidated, making it substantially more difficult to adopt pointer authentication, as well as weakening common optimizations for zero-initialized memory such as the use of ``.bzz`` sections. Therefore it is beneficial to treat null pointers specially by giving them their usual representation. On AArch64, this requires additional code when working with possibly-null pointers, such as when copying a pointer field that has been signed with address diversity.
+
+Return addresses and frame pointers
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The current implementation in Clang implicitly signs both return addresses and frame pointers. While these values are technically implementation details of a function, there are some important libraries and development tools which rely on manually walking the chain of stack frames. These tools must be updated to correctly account for pointer authentication, either by stripping signatures (if security is not important for the tool, e.g. if it is capturing a stack trace during a crash) or properly authenticating them. More information about how these values are signed is available in the `Language ABI`_ section.
+
+C++ virtual functions
+^^^^^^^^^^^^^^^^^^^^^
+
+The current implementation in Clang signs virtual function pointers with a discriminator derived from the full signature of the overridden method, including the method name and parameter types. It is possible to write C++ code that relies on v-table layout remaining constant despite changes to a method signature; for example, a parameter might be a ``typedef`` that resolves to a different type based on a build setting. Such code violates C++'s One Definition Rule (ODR), but that violation is not normally detected; however, pointer authentication will detect it.
+
+
+Language extensions
+~~~~~~~~~~~~~~~~~~~
+
+Feature testing
+^^^^^^^^^^^^^^^
+
+Whether the current target uses pointer authentication can be tested for with a number of different tests.
+
+- ``__has_feature(ptrauth_intrinsics)`` is true if ```` provides its normal interface. This may be true even on targets where pointer authentication is not enabled by default.
+
+- ``__has_feature(ptrauth_returns)`` is true if the target uses pointer authentication to protect return addresses.
+
+- ``__has_feature(ptrauth_calls)`` is true if the target uses pointer authentication to protect indirect branches. This implies ``__has_feature(ptrauth_returns)`` and ``__has_feature(ptrauth_intrinsics)``.
+
+Clang provides several other tests only for historical purposes; for current purposes they are all equivalent to ``ptrauth_calls``.
+
+__ptrauth qualifier
+^^^^^^^^^^^^^^^^^^^
+
+``__ptrauth(key, address, discriminator)`` is an extended type qualifier which causes so-qualified objects to hold pointers signed using the specified schema rather than the default schema for such types.
+
+In the current implementation in Clang, the qualified type must be a C pointer type, either to a function or to an object. It currently cannot be an Objective-C pointer type, a C++ reference type, or a block pointer type; these restrictions may be lifted in the future.
+
+The current implementation in Clang is known to not provide adequate safety guarantees against the creation of `signing oracles`_ when assigning data pointers to ``__ptrauth``-qualified gl-values. See the section on `safe derivation`_ for more information.
+
+The qualifier's operands are as follows:
+
+- ``key`` - an expression evaluating to a key value from ````; must be a constant expression
+
+- ``address`` - whether to use address diversity (1) or not (0); must be a constant expression with one of these two values
+
+- ``discriminator`` - a constant discriminator; must be a constant expression
+
+See `Discriminators`_ for more information about discriminators.
+
+Currently the operands must be constant-evaluable even within templates. In the future this restriction may be lifted to allow value-dependent expressions as long as they instantiate to a constant expression.
+
+Consistent with the ordinary C/C++ rule for parameters, top-level ``__ptrauth`` qualifiers on a parameter (after parameter type adjustment) are ignored when deriving the type of the function. The parameter will be passed using the default ABI for the unqualified pointer type.
+
+If ``x`` is an object of type ``__ptrauth(key, address, discriminator) T``, then the signing schema of the value stored in ``x`` is a key of ``key`` and a discriminator determined as follows:
+
+- if ``address`` is 0, then the discriminator is ``discriminator``;
+
+- if ``address`` is 1 and ``discriminator`` is 0, then the discriminator is ``&x``; otherwise
+
+- if ``address`` is 1 and ``discriminator`` is non-zero, then the discriminator is ``ptrauth_blend_discriminator(&x, discriminator)``; see `ptrauth_blend_discriminator`_.
+
+Non-triviality from address diversity
++++++++++++++++++++++++++++++++++++++
+
+Address diversity must impose additional restrictions in order to allow the implementation to correctly copy values. In C++, a type qualified with address diversity is treated like a class type with non-trivial copy/move constructors and assignment operators, with the usual effect on containing classes and unions. C does not have a standard concept of non-triviality, and so we must describe the basic rules here, with the intention of imitating the emergent rules of C++:
+
+- A type may be **non-trivial to copy**.
+
+- A type may also be **illegal to copy**. Types that are illegal to copy are always non-trivial to copy.
+
+- A type may also be **address-sensitive**.
+
+- A type qualified with a ``ptrauth`` qualifier that requires address diversity is non-trivial to copy and address-sensitive.
+
+- An array type is illegal to copy, non-trivial to copy, or address-sensitive if its element type is illegal to copy, non-trivial to copy, or address-sensitive, respectively.
+
+- A struct type is illegal to copy, non-trivial to copy, or address-sensitive if it has a field whose type is illegal to copy, non-trivial to copy, or address-sensitive, respectively.
+
+- A union type is both illegal and non-trivial to copy if it has a field whose type is non-trivial or illegal to copy.
+
+- A union type is address-sensitive if it has a field whose type is address-sensitive.
+
+- A program is ill-formed if it uses a type that is illegal to copy as a function parameter, argument, or return type.
+
+- A program is ill-formed if an expression requires a type to be copied that is illegal to copy.
+
+- Otherwise, copying a type that is non-trivial to copy correctly copies its subobjects.
+
+- Types that are address-sensitive must always be passed and returned indirectly. Thus, changing the address-sensitivity of a type may be ABI-breaking even if its size and alignment do not change.
+
+````
+~~~~~~~~~~~~~~~
+
+This header defines the following types and operations:
+
+``ptrauth_key``
+^^^^^^^^^^^^^^^
+
+This ``enum`` is the type of abstract signing keys. In addition to defining the set of implementation-specific signing keys (for example, ARMv8.3 defines ``ptrauth_key_asia``), it also defines some portable aliases for those keys. For example, ``ptrauth_key_function_pointer`` is the key generally used for C function pointers, which will generally be suitable for other function-signing schemas.
+
+In all the operation descriptions below, key values must be constant values corresponding to one of the implementation-specific abstract signing keys from this ``enum``.
+
+``ptrauth_extra_data_t``
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+This is a ``typedef`` of a standard integer type of the correct size to hold a discriminator value.
+
+In the signing and authentication operation descriptions below, discriminator values must have either pointer type or integer type. If the discriminator is an integer, it will be coerced to ``ptrauth_extra_data_t``.
+
+``ptrauth_blend_discriminator``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. code-block:: c
+
+ ptrauth_blend_discriminator(pointer, integer)
+
+Produce a discriminator value which blends information from the given pointer and the given integer.
+
+Implementations may ignore some bits from each value, which is to say, the blending algorithm may be chosen for speed and convenience over theoretical strength as a hash-combining algorithm. For example, arm64e simply overwrites the high 16 bits of the pointer with the low 16 bits of the integer, which can be done in a single instruction with an immediate integer.
+
+``pointer`` must have pointer type, and ``integer`` must have integer type. The result has type ``ptrauth_extra_data_t``.
+
+``ptrauth_string_discriminator``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. code-block:: c
+
+ ptrauth_string_discriminator(string)
+
+Produce a discriminator value for the given string. ``string`` must be a string literal of ``char`` character type. The result has type ``ptrauth_extra_data_t``.
+
+The result is always a constant expression. The result value is never zero and always within range for both the ``__ptrauth`` qualifier and ``ptrauth_blend_discriminator``.
+
+``ptrauth_strip``
+^^^^^^^^^^^^^^^^^
+
+.. code-block:: c
+
+ ptrauth_strip(signedPointer, key)
+
+Given that ``signedPointer`` matches the layout for signed pointers signed with the given key, extract the raw pointer from it. This operation does not trap and cannot fail, even if the pointer is not validly signed.
+
+``ptrauth_sign_constant``
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. code-block:: c
+
+ ptrauth_sign_constant(pointer, key, discriminator)
+
+Return a signed pointer for a constant address in a manner which guarantees a non-attackable sequence.
+
+``pointer`` must be a constant expression of pointer type which evaluates to a non-null pointer. The result will have the same type as ``discriminator``.
+
+Calls to this are constant expressions if the discriminator is a null-pointer constant expression or an integer constant expression. Implementations may make allow other pointer expressions as well.
+
+``ptrauth_sign_unauthenticated``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. code-block:: c
+
+ ptrauth_sign_unauthenticated(pointer, key, discriminator)
+
+Produce a signed pointer for the given raw pointer without applying any authentication or extra treatment. This operation is not required to have the same behavior on a null pointer that the language implementation would.
+
+This is a treacherous operation that can easily result in `signing oracles`_. Programs should use it seldom and carefully.
+
+``ptrauth_auth_and_resign``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. code-block:: c
+
+ ptrauth_auth_and_resign(pointer, oldKey, oldDiscriminator, newKey, newDiscriminator)
+
+Authenticate that ``pointer`` is signed with ``oldKey`` and ``oldDiscriminator`` and then resign the raw-pointer result of that authentication with ``newKey`` and ``newDiscriminator``.
+
+``pointer`` must have pointer type. The result will have the same type as ``pointer``. This operation is not required to have the same behavior on a null pointer that the language implementation would.
+
+The code sequence produced for this operation must not be directly attackable. However, if the discriminator values are not constant integers, their computations may still be attackable. In the future, Clang should be enhanced to guaranteed non-attackability if these expressions are :ref:`safely-derived`.
+
+``ptrauth_auth_function``
+^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. code-block:: c
+
+ ptrauth_auth_function(pointer, key, discriminator)
+
+Authenticate that ``pointer`` is signed with ``key`` and ``discriminator`` and re-sign it to the standard schema for a function pointer of its type.
+
+``pointer`` must have function pointer type. The result will have the same type as ``pointer``. This operation is not required to have the same behavior on a null pointer that the language implementation would.
+
+This operation makes the same attackability guarantees as ``ptrauth_auth_and_resign``.
+
+If this operation appears syntactically as the function operand of a call, Clang guarantees that the call will directly authenticate the function value using the given schema rather than re-signing to the standard schema.
+
+``ptrauth_auth_data``
+^^^^^^^^^^^^^^^^^^^^^
+
+.. code-block:: c
+
+ ptrauth_auth_data(pointer, key, discriminator)
+
+Authenticate that ``pointer`` is signed with ``key`` and ``discriminator`` and remove the signature.
+
+``pointer`` must have object pointer type. The result will have the same type as ``pointer``. This operation is not required to have the same behavior on a null pointer that the language implementation would.
+
+In the future when Clang makes `safe derivation`_ guarantees, the result of this operation should be considered safely-derived.
+
+``ptrauth_sign_generic_data``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+.. code-block:: c
+
+ ptrauth_sign_generic_data(value1, value2)
+
+Computes a signature for the given pair of values, incorporating a secret signing key.
+
+This operation can be used to verify that arbitrary data has not be tampered with by computing a signature for the data, storing that signature, and then repeating this process and verifying that it yields the same result. This can be reasonably done in any number of ways; for example, a library could compute an ordinary checksum of the data and just sign the result in order to get the tamper-resistance advantages of the secret signing key (since otherwise an attacker could reliably overwrite both the data and the checksum).
+
+``value1`` and ``value2`` must be either pointers or integers. If the integers are larger than ``uintptr_t`` then data not representable in ``uintptr_t`` may be discarded.
+
+The result will have type ``ptrauth_generic_signature_t``, which is an integer type. Implementations are not required to make all bits of the result equally significant; in particular, some implementations are known to not leave meaningful data in the low bits.
+
+Standard ``__ptrauth`` qualifiers
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+```` additionally provides several macros which expand to ``__ptrauth`` qualifiers for common ABI situations.
+
+For convenience, these macros expand to nothing when pointer authentication is disabled.
+
+These macros can be found in the header; some details of these macros may be unstable or implementation-specific.
+
+
+
+
+
+Theory of Operation
+-------------------
+
+The threat model of pointer authentication is as follows:
+
+- The attacker has the ability to read and write to a certain range of addresses, possibly the entire address space. However, they are constrained by the normal rules of the process: for example, they cannot write to memory that is mapped read-only, and if they access unmapped memory it will trigger a trap.
+
+- The attacker has no ability to add arbitrary executable code to the program. For example, the program does not include malicious code to begin with, and the attacker cannot alter existing instructions, load a malicious shared library, or remap writable pages as executable. If the attacker wants to get the process to perform a specific sequence of actions, they must somehow subvert the normal control flow of the process.
+
+In both of the above paragraphs, it is merely assumed that the attacker's *current* capabilities are restricted; that is, their current exploit does not directly give them the power to do these things. The attacker's immediate goal may well be to leverage their exploit to gain these capabilities, e.g. to load a malicious dynamic library into the process, even though the process does not directly contain code to do so.
+
+Note that any bug that fits the above threat model can be immediately exploited as a denial-of-service attack by simply performing an illegal access and crashing the program. Pointer authentication cannot protect against this. While denial-of-service attacks are unfortunate, they are also unquestionably the best possible result of a bug this severe. Therefore, pointer authentication enthusiastically embraces the idea of halting the program on a pointer authentication failure rather than continuing in a possibly-compromised state.
+
+Pointer authentication is a form of control-flow integrity (CFI) enforcement. The basic security hypothesis behind CFI enforcement is that many bugs can only be usefully exploited (other than as a denial-of-service) by leveraging them to subvert the control flow of the program. If this is true, then by inhibiting or limiting that subversion, it may be possible to largely mitigate the security consequences of those bugs by rendering them impractical (or, ideally, impossible) to exploit.
+
+Every indirect branch in a program has a purpose. Using human intelligence, a programmer can describe where a particular branch *should* go according to this purpose: a ``return`` in ``printf`` should return to the call site, a particular call in ``qsort`` should call the comparator that was passed in as an argument, and so on. But for CFI to enforce that every branch in a program goes where it *should* in this sense would require CFI to perfectly enforce every semantic rule of the program's abstract machine; that is, it would require making the programming environment perfectly sound. That is out of scope. Instead, the goal of CFI is merely to catch attempts to make a branch go somewhere that its obviously *shouldn't* for its purpose: for example, to stop a call from branching into the middle of a function rather than its beginning. As the information available to CFI gets better about the purpose of the branch, CFI can enforce tighter and tighter restrictions on where the branch is permitted to go. Still, ultimately CFI cannot make the program sound. This may help explain why pointer authentication makes some of the choices it does: for example, to sign and authenticate mostly code pointers rather than every pointer in the program. Preventing attackers from redirecting branches is both particularly important and particularly approachable as a goal. Detecting corruption more broadly is infeasible with these techniques, and the attempt would have far higher cost.
+
+Attacks on pointer authentication
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Pointer authentication works as follows. Every indirect branch in a program has a purpose. For every purpose, the implementation chooses a :ref:`signing schema`. At some place where a pointer is known to be correct for its purpose, it is signed according to the purpose's schema. At every place where the pointer is needed for its purpose, it is authenticated according to the purpose's schema. If that authentication fails, the program is halted.
+
+There are a variety of ways to attack this.
+
+Attacks of interest to programmers
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+These attacks arise from weaknesses in the default protections offered by pointer authentication. They can be addressed by using attributes or intrinsics to opt in to stronger protection.
+
+Substitution attacks
+++++++++++++++++++++
+
+An attacker can simply overwrite a pointer intended for one purpose with a pointer intended for another purpose if both purposes use the same signing schema and that schema does not use address diversity.
+
+The most common source of this weakness is when code relies on using the default language rules for C function pointers. The current implementation uses the exact same signing schema for all C function pointers, even for functions of substantially different type. While efforts are ongoing to improve constant diversity for C function pointers of different type, there are necessary limits to this. The C standard requires function pointers to be copyable with ``memcpy``, which means that function pointers can never use address diversity. Furthermore, even if a function pointer can only be replaced with another function of the exact same type, that can still be useful to an attacker, as in the following example of a hand-rolled "v-table":
+
+.. code-block:: c
+
+ struct ObjectOperations {
+ void (*retain)(Object *);
+ void (*release)(Object *);
+ void (*deallocate)(Object *);
+ void (*logStatus)(Object *);
+ };
+
+This weakness can be mitigated by using a more specific signing schema for each purpose. For example, in this example, the ``__ptrauth`` qualifier can be used with a different constant discriminator for each field. Since there's no particular reason it's important for this v-table to be copyable with ``memcpy``, the functions can also be signed with address diversity:
+
+.. code-block:: c
+
+ #if __has_feature(ptrauth_calls)
+ #define objectOperation(discriminator) \
+ __ptrauth(ptrauth_key_function_pointer, 1, discriminator)
+ #else
+ #define objectOperation(discriminator)
+ #endif
+
+ struct ObjectOperations {
+ void (*objectOperation(0xf017) retain)(Object *);
+ void (*objectOperation(0x2639) release)(Object *);
+ void (*objectOperation(0x8bb0) deallocate)(Object *);
+ void (*objectOperation(0xc5d4) logStatus)(Object *);
+ };
+
+This weakness can also sometimes be mitigated by simply keeping the signed pointer in constant memory, but this is less effective than using better signing diversity.
+
+.. _Access path attacks:
+
+Access path attacks
++++++++++++++++++++
+
+If a signed pointer is often accessed indirectly (that is, by first loading the address of the object where the signed pointer is stored), an attacker can affect uses of it by overwriting the intermediate pointer in the access path.
+
+The most common scenario exhibiting this weakness is an object with a pointer to a "v-table" (a structure holding many function pointers). An attacker does not need to replace a signed function pointer in the v-table if they can instead simply replace the v-table pointer in the object with their own pointer --- perhaps to memory where they've constructed their own v-table, or to existing memory that coincidentally happens to contain a signed pointer at the right offset that's been signed with the right signing schema.
+
+This attack arises because data pointers are not signed by default. It works even if the signed pointer uses address diversity: address diversity merely means that each pointer is signed with its own storage address, which (by design) is invariant to changes in the accessing pointer.
+
+Using sufficiently diverse signing schemas within the v-table can provide reasonably strong mitigation against this weakness. Always use address diversity in v-tables to prevent attackers from assembling their own v-table. Avoid re-using constant discriminators to prevent attackers from replacing a v-table pointer with a pointer to totally unrelated memory that just happens to contain an similarly-signed pointer.
+
+Further mitigation can be attained by signing pointers to v-tables. Any signature at all should prevent attackers from forging v-table pointers; they will need to somehow harvest an existing signed pointer from elsewhere in memory. Using a meaningful constant discriminator will force this to be harvested from an object with similar structure (e.g. a different implementation of the same interface). Using address diversity will prevent such harvesting entirely. However, care must be taken when sourcing the v-table pointer originally; do not blindly sign a pointer that is not :ref:`safely derived`.
+
+.. _Signing oracles:
+
+Signing oracles
++++++++++++++++
+
+A signing oracle is a bit of code which can be exploited by an attacker to sign an arbitrary pointer in a way that can later be recovered. Such oracles can be used by attackers to forge signatures matching the oracle's signing schema, which is likely to cause a total compromise of pointer authentication's effectiveness.
+
+This attack only affects ordinary programmers if they are using certain treacherous patterns of code. Currently this includes:
+
+- all uses of the ``__ptrauth_sign_unauthenticated`` intrinsic and
+- assigning data pointers to ``__ptrauth``-qualified l-values.
+
+Care must be taken in these situations to ensure that the pointer being signed has been :ref:`safely derived` or is otherwise not possible to attack. (In some cases, this may be challenging without compiler support.)
+
+A diagnostic will be added in the future for implicitly dangerous patterns of code, such as assigning a non-safely-derived data pointer to a ``__ptrauth``-qualified l-value.
+
+.. _Authentication oracles:
+
+Authentication oracles
+++++++++++++++++++++++
+
+An authentication oracle is a bit of code which can be exploited by an attacker to leak whether a signed pointer is validly signed without halting the program if it isn't. Such oracles can be used to forge signatures matching the oracle's signing schema if the attacker can repeatedly invoke the oracle for different candidate signed pointers. This is likely to cause a total compromise of pointer authentication's effectiveness.
+
+There should be no way for an ordinary programmer to create an authentication oracle using the current set of operations. However, implementation flaws in the past have occasionally given rise to authentication oracles due to a failure to immediately trap on authentication failure.
+
+The likelihood of creating an authentication oracle is why there is currently no intrinsic which queries whether a signed pointer is validly signed.
+
+
+Attacks of interest to implementors
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+These attacks are not inherent to the model; they arise from mistakes in either implementing or using the `sign` and `auth` operations. Avoiding these mistakes requires careful work throughout the system.
+
+Failure to trap on authentication failure
++++++++++++++++++++++++++++++++++++++++++
+
+Any failure to halt the program on an authentication failure is likely to be exploitable by attackers to create an :ref:`authentication oracle`.
+
+There are several different ways to introduce this problem:
+
+- The implementation might try to halt the program in some way that can be intercepted.
+
+ For example, the ``auth`` instruction in ARMv8.3 does not directly trap; instead it corrupts its result so that it is always an invalid pointer. If the program subsequently attempts to use that pointer, that will be a bad memory access, and it will trap into the kernel. However, kernels do not usually immediately halt programs that trigger traps due to bad memory accesses; instead they notify the process to give it an opportunity to recover. If this happens with an ``auth`` failure, the attacker may be able to exploit the recovery path in a way that creates an oracle. Kernels should ensure that these sorts of traps are not recoverable.
+
+- A compiler might use an intermediate representation (IR) for ``sign`` and ``auth`` operations that cannot make adequate correctness guarantees.
+
+ For example, suppose that an IR uses ARMv8.3-like semantics for ``auth``: the operation merely corrupts its result on failure instead of promising the trap. A frontend might emit patterns of IR that always follow an ``auth`` with a memory access, thinking that this ensures correctness. But if the IR can be transformed to insert code between the ``auth`` and the access, or if the ``auth`` can be speculated, then this potentially creates an oracle. It is better for ``auth`` to semantically guarantee to trap, potentially requiring an explicit check in the generated code. An ARMv8.3-like target can avoid this explicit check in the common case by recognizing the pattern of an ``auth`` followed immediately by an access.
+
+Attackable code sequences
++++++++++++++++++++++++++
+
+If code that is part of a pointer authentication operation is interleaved with code that may itself be vulnerable to attacks, an attacker may be able to use this to create a :ref:`signing` or :ref:`authentication` oracle.
+
+For example, suppose that the compiler is generating a call to a function and passing two arguments: a signed constant pointer and a value derived from a call. In ARMv8.3, this code might look like so:
+
+.. code-block:: asm
+
+ adr x19, _callback. ; compute &_callback
+ paciza x19 ; sign it with a constant discriminator of 0
+ blr _argGenerator ; call _argGenerator() (returns in x0)
+ mov x1, x0 ; move call result to second arg register
+ mov x0, x19 ; move signed &_callback to first arg register
+ blr _function ; call _function
+
+This code is correct, as would be a sequencing that does *both* the ``adr`` and the ``paciza`` after the call to ``_argGenerator``. But a sequence that computes the address of ``_callback`` but leaves it as a raw pointer in a register during the call to ``_argGenerator`` would be vulnerable:
+
+.. code-block:: asm
+
+ adr x19, _callback. ; compute &_callback
+ blr _argGenerator ; call _argGenerator() (returns in x0)
+ mov x1, x0 ; move call result to second arg register
+ paciza x19 ; sign &_callback
+ mov x0, x19 ; move signed &_callback to first arg register
+ blr _function ; call _function
+
+If ``_argGenerator`` spills ``x19`` (a callee-save register), and if the attacker can perform a write during this call, then the attacker can overwrite the spill slot with an arbitrary pointer that will eventually be unconditionally signed after the function returns. This would be a signing oracle.
+
+The implementation can avoid this by obeying two basic rules:
+
+- The compiler's intermediate representations (IR) should not provide operations that expose intermediate raw pointers. This may require providing extra operations that perform useful combinations of operations.
+
+ For example, there should be an "atomic" auth-and-resign operation that should be used instead of emitting an ``auth`` operation whose result is fed into a ``sign``.
+
+ Similarly, if a pointer should be authenticated as part of doing a memory access or a call, then the access or call should be decorated with enough information to perform the authentication; there should not be a separate ``auth`` whose result is used as the pointer operand for the access or call. (In LLVM IR, we do this for calls, but not yet for loads or stores.)
+
+ "Operations" includes things like materializing a signed pointer to a known function or global variable. The compiler must be able to recognize and emit this as a unified operation, rather than potentially splitting it up as in the example above.
+
+- The compiler backend should not be too aggressive about scheduling instructions that are part of a pointer authentication operation. This may require custom code-generation of these operations in some cases.
+
+Register clobbering
++++++++++++++++++++
+
+As a refinement of the section on `Attackable code sequences`_, if the attacker has the ability to modify arbitrary *register* state at arbitrary points in the program, then special care must be taken.
+
+For example, ARMv8.3 might materialize a signed function pointer like so:
+
+.. code-block:: asm
+
+ adr x0, _callback. ; compute &_callback
+ paciza x0 ; sign it with a constant discriminator of 0
+
+If an attacker has the ability to overwrite ``x0`` between these two instructions, this code sequence is vulnerable to becoming a signing oracle.
+
+For the most part, this sort of attack is not possible: it is a basic element of the design of modern computation that register state is private and inviolable. However, in systems that support asynchronous interrupts, this property requires the cooperation of the interrupt-handling code. If that code saves register state to memory, and that memory can be overwritten by an attacker, then essentially the attack can overwrite arbitrary register state at an arbitrary point. This could be a concern if the threat model includes attacks on the kernel or if the program uses user-space preemptive multitasking.
+
+(Readers might object that an attacker cannot rely on asynchronous interrupts triggering at an exact instruction boundary. In fact, researchers have had some success in doing exactly that. Even ignoring that, though, we should aim to protect against lucky attackers just as much as good ones.)
+
+To protect against this, saved register state must be at least partially signed (using something like `ptrauth_sign_generic_data`_). This is required for correctness anyway because saved thread states include security-critical registers such as SP, FP, PC, and LR (where applicable). Ideally, this signature would cover all the registers, but since saving and restoring registers can be very performance-sensitive, that may not be acceptable. It is sufficient to set aside a small number of scratch registers that will be guaranteed to be preserved correctly; the compiler can then be careful to only store critical values like intermediate raw pointers in those registers.
+
+``setjmp`` and ``longjmp`` should sign and authenticate the core registers (SP, FP, PC, and LR), but they do not need to worry about intermediate values because ``setjmp`` can only be called synchronously, and the compiler should never schedule pointer-authentication operations interleaved with arbitrary calls.
+
+.. _Relative addresses:
+
+Attacks on relative addressing
+++++++++++++++++++++++++++++++
+
+Relative addressing is a technique used to compress and reduce the load-time cost of infrequently-used global data. The pointer authentication system is unlikely to support signing or authenticating a relative address, and in most cases it would defeat the point to do so: it would take additional storage space, and applying the signature would take extra work at load time.
+
+Relative addressing is not precluded by the use of pointer authentication, but it does take extra considerations to make it secure:
+
+- Relative addresses must only be stored in read-only memory. A writable relative address can be overwritten to point nearly anywhere, making it inherently insecure; this danger can only be compensated for with techniques for protecting arbitrary data like `ptrauth_sign_generic_data`_.
+
+- Relative addresses must only be accessed through signed pointers with adequate diversity. If an attacker can perform an `access path attack` to replace the pointer through which the relative address is accessed, they can easily cause the relative address to point wherever they want.
+
+Signature forging
++++++++++++++++++
+
+If an attacker can exactly reproduce the behavior of the signing algorithm, and they know all the correct inputs to it, then they can perfectly forge a signature on an arbitrary pointer.
+
+There are three components to avoiding this mistake:
+
+- The abstract signing algorithm should be good: it should not have glaring flaws which would allow attackers to predict its result with better than random accuracy without knowing all the inputs (like the key values).
+
+- The key values should be kept secret. If at all possible, they should never be stored in accessible memory, or perhaps only stored encrypted.
+
+- Contexts that are meant to be independently protected should use different key values. For example, the kernel should not use the same keys as user processes. Different user processes should also use different keys from each other as much as possible, although this may pose its own technical challenges.
+
+Remapping
++++++++++
+
+If an attacker can change the memory protections on certain pages of the program's memory, that can substantially weaken the protections afforded by pointer authentication.
+
+- If an attacker can inject their own executable code, they can also certainly inject code that can be used as a :ref:`signing oracle`. The same is true if they can write to the instruction stream.
+
+- If an attacker can remap read-only program sections to be writable, then any use of :ref:`relative addresses` in global data becomes insecure.
+
+- If an attacker can remap read-only program sections to be writable, then it is unsafe to use unsigned pointers in `global offset tables`_.
+
+Remapping memory in this way often requires the attacker to have already substantively subverted the control flow of the process. Nonetheless, if the operating system has a mechanism for mapping pages in a way that cannot be remapped, this should be used wherever possible.
+
+
+
+.. _Safe Derivation:
+
+Safe derivation
+~~~~~~~~~~~~~~~
+
+Whether a data pointer is stored, even briefly, as a raw pointer can affect the security-correctness of a program. (Function pointers are never implicitly stored as raw pointers; raw pointers to functions can only be produced with the ```` intrinsics.) Repeated re-signing can also impact performance. Clang makes a modest set of guarantees in this area:
+
+- An expression of pointer type is said to be **safely derived** if:
+
+ - it takes the address of a global variable or function, or
+
+ - it is a load from a gl-value of ``__ptrauth``-qualified type.
+
+- If a value that is safely derived is assigned to a ``__ptrauth``-qualified object, including by initialization, then the value will be directly signed as appropriate for the target qualifier and will not be stored as a raw pointer.
+
+- If the function expression of a call is a gl-value of ``__ptrauth``-qualified type, then the call will be authenticated directly according to the source qualifier and will not be resigned to the default rule for a function pointer of its type.
+
+These guarantees are known to be inadequate for data pointer security. In particular, Clang should be enhanced to make the following guarantees:
+
+- A pointer should additionally be considered safely derived if it is:
+
+ - the address of a gl-value that is safely derived,
+
+ - the result of pointer arithmetic on a pointer that is safely derived (with some restrictions on the integer operand),
+
+ - the result of a comma operator where the second operand is safely derived,
+
+ - the result of a conditional operator where the selected operand is safely derived, or
+
+ - the result of loading from a safely derived gl-value.
+
+- A gl-value should be considered safely derived if it is:
+
+ - a dereference of a safely derived pointer,
+
+ - a member access into a safely derived gl-value, or
+
+ - a reference to a variable.
+
+- An access to a safely derived gl-value should be guaranteed to not allow replacement of any of the safely-derived component values at any point in the access. "Access" should include loading a function pointer.
+
+- Assignments should include pointer-arithmetic operators like ``+=``.
+
+Making these guarantees will require further work, including significant new support in LLVM IR.
+
+Furthermore, Clang should implement a warning when assigning a data pointer that is not safely derived to a ``__ptrauth``-qualified gl-value.
+
+
+
+Language ABI
+------------
+
+This section describes the pointer-authentication ABI currently implemented in Clang for the Apple arm64e target. As other targets adopt pointer authentication, this section should be generalized to express their ABIs as well.
+
+Key assignments
+~~~~~~~~~~~~~~~
+
+ARMv8.3 provides four abstract signing keys: ``IA``, ``IB``, ``DA``, and ``DB``. The architecture designates ``IA`` and ``IB`` for signing code pointers and ``DA`` and ``DB`` for signing data pointers; this is reinforced by two properties:
+
+- The ISA provides instructions that perform combined auth+call and auth+load operations; these instructions can only use the ``I`` keys and ``D`` keys, respectively.
+
+- AArch64's TBI feature can be separately enabled for code pointers (controlling whether indirect-branch instructions ignore those bits) and data pointers (controlling whether memory-access instructions) ignore those bits. If TBI is enabled for a kind of pointer, the sign and auth operations preserve the TBI bits when signing with an associated keys (at the cost of shrinking the number of available signing bits by 8).
+
+arm64e then further subdivides the keys as follows:
+
+- The ``A`` keys are used for primarily "global" purposes like signing v-tables and function pointers. These keys are sometimes called *process-independent* or *cross-process* because on existing OSes they are not changed when changing processes, although this is not a platform guarantee.
+
+- The ``B`` keys are used for primarily "local" purposes like signing return addresses and frame pointers. These keys are sometimes called *process-specific* because they are typically different between processes. However, they are in fact shared across processes in one situation: systems which provide ``fork`` cannot change these keys in the child process; they can only be changed during ``exec``.
+
+Implementation-defined algorithms and quantities
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The cryptographic hash algorithm used to compute signatures in ARMv8.3 is a private detail of the hardware implementation.
+
+arm64e restricts constant discriminators (used in ``__ptrauth`` and ``ptrauth_blend_discriminator``) to the range from 0 to 65535, inclusive. A 0 discriminator generally signifies that no blending is required; see the documentation for ``ptrauth_blend_discriminator``. This range is somewhat narrow but has two advantages:
+
+- The AArch64 ISA allows an arbitrary 16-bit immediate to be written over the top 16 bits of a register in a single instruction:
+
+ .. code-block:: asm
+
+ movk xN, #0x4849, LSL 48
+
+ This is ideal for the discriminator blending operation because it adds minimal code-size overhead and avoids overwriting any interesting bits from the pointer. Blending in a wider constant discriminator would either clobber interesting bits (e.g. if it was loaded with ``movk xN, #0x4c4f, LSL 32``) or require significantly more code (e.g. if the discriminator was loaded with a ``mov+bfi`` sequence).
+
+- It is possible to pack a 16-bit discriminator into loader metadata with minimal compromises, whereas a wider discriminator would require extra metadata storage and therefore significantly impact load times.
+
+The string hash used by ``ptrauth_string_discriminator`` is a 64-bit SipHash-2-4 using the constant seed ``b5d4c9eb79104a796fec8b1b428781d4`` (big-endian), with the result reduced by modulo to the range of non-zero discriminators (i.e. ``(rawHash % 65535) + 1``).
+
+Return addresses
+~~~~~~~~~~~~~~~~
+
+The kernel must ensure that attackers cannot replace LR due to an asynchronous exception; see `Register clobbering`_. If this is done by generally protecting LR, then functions which don't spill LR to the stack can avoid signing it entirely. Otherwise, the return address must be signed; on arm64e it is signed with the ``IB`` key using the stack pointer on entry as the discriminator.
+
+Protecting return addresses is of such particular importance that the ``IB`` key is almost entirely reserved for this purpose.
+
+Global offset tables
+~~~~~~~~~~~~~~~~~~~~
+
+The global offset table (GOT) is not ABI, but it is a common implementation technique for dynamic linking which deserves special discussion here.
+
+Whenever possible, signed pointers should be materialized directly in code rather than via the GOT, e.g. using an ``adrp+add+pac`` sequence on ARMv8.3. This decreases the amount of work necessary at load time to initialize the GOT, but more importantly, it defines away the potential for several attacks:
+
+- Attackers cannot change instructions, so there is no way to cause this code sequence to materialize a different pointer, whereas an access via the GOT always has *at minimum* a probabilistic chance to be the target of successful `substitution attacks`_.
+
+- The GOT is a dense pool of fixed pointers at a fixed offset relative to code; attackers can search this pool for useful pointers that can be used in `substitution attacks`_, whereas pointers that are only materialized directly are not so easily available.
+
+- Similarly, attackers can use `access path attacks`_ to replace a pointer to a signed pointer with a pointer to the GOT if the signing schema used within the GOT happens to be the same as the original pointer. This kind of collision becomes much less likely to be useful the fewer pointers are in the GOT in the first place.
+
+If this can be done for a symbol, then the compiler need only ensure that it materializes the signed pointer using registers that are safe against `register clobbering`_.
+
+However, many symbols can only be accessed via the GOT, e.g. because they resolve to definitions outside of the current image. In this case, care must be taken to ensure that using the GOT does not introduce weaknesses.
+
+- If the entire GOT can be mapped read-only after loading, then no signing is required within the GOT. In fact, not signing pointers in the GOT is preferable in this case because it makes the GOT useless for the harvesting and access-path attacks above. Storing raw pointers in this way is usually extremely unsafe, but for the special case of an immutable GOT entry it's fine because the GOT is always accessed via an address that is directly materialized in code and thus provably unattackable. (But see `Remapping`_.)
+
+- Otherwise, GOT entries which are used for producing a signed pointer constant must be signed. The signing schema used in the GOT need not match the target signing schema for the signed constant. To counteract the threats of substitution attacks, it's best if GOT entries can be signed with address diversity. Using a good constant discriminator as well (perhaps derived from the symbol name) can make it less useful to use a pointer to the GOT as the replacement in an :ref:`access path attack`.
+
+In either case, the compiler must ensure that materializing the address of a GOT entry as part of producing a signed pointer constant is not vulnerable to `register clobbering`_. If the linker also generates code for this, e.g. for call stubs, this generated code must take the same precautions.
+
+C function pointers
+~~~~~~~~~~~~~~~~~~~
+
+On arm64e, C function pointers are currently signed with the ``IA`` key without address diversity and with a constant discriminator of 0.
+
+The C and C++ standards do not permit C function pointers to be signed with address diversity by default: in C++ terms, function pointer types are required to be trivially copyable, which means they must be copyable with ``memcpy``.
+
+The use of a uniform constant discriminator is seen as a serious defect which should be remedied, and improving this is under investigation.
+
+C++ virtual tables
+~~~~~~~~~~~~~~~~~~
+
+The pointer to a C++ virtual table is currently signed with the ``DA`` key, no address diversity, and a constant discriminator of 0. The use of no address diversity, as well as the uniform constant discriminator, are seen as weaknesses. Not using address diversity allows attackers to simply copy valid v-table pointers from one object to another. However, using a uniform discriminator of 0 does have positive performance and code-size implications on ARMv8.3, and diversity for the most important v-table access pattern (virtual dispatch) is already better assured by the signing schemas used on the virtual functions. It is also known that some code in practice copies objects containing v-tables with ``memcpy``, and while this is not permitted formally, it is something that may be invasive to eliminate.
+
+Virtual functions in a C++ virtual table are signed with the ``IA`` key, address diversity, and a constant discriminator equal to the string hash (see `ptrauth_string_discriminator`_) of the mangled name of the function which originally gave rise to the v-table slot.
+
+C++ member function pointers
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+A member function pointer is signed with the ``IA`` key, no address diversity, and a constant discriminator equal to the string hash (see `ptrauth_string_discriminator`_) of the member pointer type. Address diversity is not permitted by C++ for member function pointers because they must be trivially-copyable types.
+
+The Itanium C++ ABI specifies that member function pointers to virtual functions simply store an offset to the correct v-table slot. This ABI cannot be used securely with pointer authentication because there is no safe place to store the constant discriminator for the target v-table slot: if it's stored with the offset, an attacker can simply overwrite it with the right discriminator for the offset. Even if the programmer never uses pointers to virtual functions, the existence of this code path makes all member function pointer dereferences insecure.
+
+arm64e changes this ABI so that virtual function pointers are stored using dispatch thunks with vague linkage. Because arm64e supports interoperation with ``arm64`` code when pointer authentication is disabled, an arm64e member function pointer dereference still recognizes the virtual-function representation but uses an bogus discriminator on that path that should always trap if pointer authentication is enabled dynamically.
+
+The use of dispatch thunks means that ``==`` on member function pointers is no longer reliable for virtual functions, but this is acceptable because the standard makes no guarantees about it in the first place.
+
+The use of dispatch thunks also potentially enables v-tables to be signed using a declaration-specific constant discriminator in the future; otherwise this discriminator would also need to be stored in the member pointer.
+
+Blocks
+~~~~~~
+
+Block pointers are data pointers which must interoperate with the ObjC `id` type and therefore cannot be signed themselves.
+
+The invocation pointer in a block is signed with the ``IA`` key using address diversity and a constant dicriminator of 0. Using a uniform discriminator is seen as a weakness to be potentially improved, but this is tricky due to the subtype polymorphism directly permitted for blocks.
+
+Block descriptors and ``__block`` variables can contain pointers to functions that can be used to copy or destroy the object. These functions are signed with the ``IA`` key, address diversity, and a constant discriminator of 0. The structure of block descriptors is under consideration for improvement.
+
+Objective-C methods
+~~~~~~~~~~~~~~~~~~~
+
+Objective-C method lists sign methods with the ``IA`` key using address diversity and a constant discriminator of 0. Using a uniform constant discriminator is believed to be acceptable because these tables are only accessed internally to the Objective-C runtime.
+
+The Objective-C runtime provides additional protection to methods that have been loaded into the Objective-C method cache; this protection is private to the runtime.
+
+Pointer authentication cannot protect against access-path atacks against the Objective-C ``isa`` pointer, through which all dispatch occurs, because of compatibility requirements and existing and important usage of high bits in the pointer.
+
+Swift class methods
+~~~~~~~~~~~~~~~~~~~
+
+Class methods in Swift are signed in the class object with the ``IA`` key using address diversity and a constant discriminator equal to the string hash (see `ptrauth_string_discriminator`_) of the mangling of the original overridable method.
+
+Resilient class-method lookup relies on passing a method descriptor; this method descriptor should be signed but currently isn't. The lookup function returns a function pointer that is signed using ``IA`` without address diversity and with the correct constant discriminator for the looked-up method.
+
+Swift's equivalent of a C++ v-table pointer is the ``isa`` pointer of an object. On arm64e, this is constrained by Objective-C compatibility and cannot be a signed pointer.
+
+Swift heap destructors
+~~~~~~~~~~~~~~~~~~~~~~
+
+Objects that are retained and released with Swift's native reference-counting system, including both native classes and temporary "box" allocations, must provide a destructor function in their metadata. This destructor function is signed with the ``IA`` key using address diversity and a constant discriminator of ``0xbbbf``.
+
+Swift protocol requirements
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Protocol function requirements are signed in the protocol witness table with the ``IA`` key using address diversity and a constant discriminator equal to the string hash (see `ptrauth_string_discriminator`_) of the mangling of the protocol requirement.
+
+Swift function types
+~~~~~~~~~~~~~~~~~~~~
+
+The invocation pointers of Swift function values are signed using the ``IA`` key without address diversity and with a constant discriminator derived loosely from the function type.
+
+Address diversity cannot be used by default for function values because function types are intended to be a "loadable" type which can be held and passed in registers.
+
+The constant discriminator currently accounts for potential abstraction in the function signature in ways that decrease the diversity of signatures; improving this is under investigation.
+
+Swift metadata
+~~~~~~~~~~~~~~
+
+Type metadata pointers in Swift are not signed.
+
+Type context descriptors must be signed because they frequently contain `relative addresses`_. Type context descriptors are signed with the ``DA`` key without address diversity (except when stored in type metadata) and with a constant discriminator of ``0xae86``.
+
+Swift value witnesses
+~~~~~~~~~~~~~~~~~~~~~
+
+Value witness functions in Swift are signed in the value witness table using the ``IA`` key with address diversity and an operation-specific constant discriminator which can be found in the Swift project headers.
+
+Swift coroutines
+~~~~~~~~~~~~~~~~
+
+Resumption functions for Swift coroutines are signed using the ``IA`` key without address diversity and with a constant discriminator derived from the yield type of the coroutine. Resumption functions cannot be signed with address diversity as they are returned directly in registers from the coroutine.
+
+
+
+
+
+Alternative implementations
+---------------------------
+
+Signature storage
+~~~~~~~~~~~~~~~~~
+
+It is not critical for the security of pointer authentication that the signature be stored "together" with the pointer, as it is in ARMv8.3. An implementation could just as well store the signature in a separate word, so that the ``sizeof`` a signed pointer would be larger than the ``sizeof`` a raw pointer.
+
+Storing the signature in the high bits, as ARMv8.3 does, has several trade-offs:
+
+- Disadvantage: there are substantially fewer bits available for the signature, weakening the mitigation by making it much easier for an attacker to simply guess the correct signature.
+
+- Disadvantage: future growth of the address space will necessarily further weaken the mitigation.
+
+- Advantage: memory layouts don't change, so it's possible for pointer-authentication-enabled code (for example, in a system library) to efficiently interoperate with existing code, as long as pointer authentication can be disabled dynamically.
+
+- Advantage: the size of a signed pointer doesn't grow, which might significantly increase memory requirements, code size, and register pressure.
+
+- Advantage: the size of a signed pointer is the same as a raw pointer, so generic APIs which work in types like `void *` (such as `dlsym`) can still return signed pointers. This means that clients of these APIs will not require insecure code in order to correctly receive a function pointer.
+
+Hashing vs. encrypting pointers
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+ARMv8.3 implements ``sign`` by computing a cryptographic hash and storing that in the spare bits of the pointer. This means that there are relatively few possible values for the valid signed pointer, since the bits corresponding to the raw pointer are known. Together with an ``auth`` oracle, this can make it computationally feasible to discover the correct signature with brute force. (The implementation should of course endeavor not to introduce ``auth`` oracles, but this can be difficult, and attackers can be devious.)
+
+If the implementation can instead *encrypt* the pointer during ``sign`` and *decrypt* it during ``auth``, this brute-force attack becomes far less feasible, even with an ``auth`` oracle. However, there are several problems with this idea:
+
+- It's unclear whether this kind of encryption is even possible without increasing the storage size of a signed pointer. If the storage size can be increased, brute-force atacks can be equally well mitigated by simply storing a larger signature.
+
+- It would likely be impossible to implement a ``strip`` operation, which might make debuggers and other out-of-process tools far more difficult to write, as well as generally making primitive debugging more challenging.
+
+- Implementations can benefit from being able to extract the raw pointer immediately from a signed pointer. An ARMv8.3 processor executing an ``auth``-and-load instruction can perform the load and ``auth`` in parallel; a processor which instead encrypted the pointer would be forced to perform these operations serially.
diff --git a/clang/docs/index.rst b/clang/docs/index.rst
index 493f736f2be4f..1c91f13b9375a 100644
--- a/clang/docs/index.rst
+++ b/clang/docs/index.rst
@@ -44,6 +44,7 @@ Using Clang as a Compiler
OpenCLSupport
OpenMPSupport
ThinLTO
+ APINotes
CommandGuide/index
FAQ
diff --git a/clang/include/clang-c/CXErrorCode.h b/clang/include/clang-c/CXErrorCode.h
index b3a0b9d66d5f8..510f8d6f300ef 100644
--- a/clang/include/clang-c/CXErrorCode.h
+++ b/clang/include/clang-c/CXErrorCode.h
@@ -53,7 +53,25 @@ enum CXErrorCode {
/**
* An AST deserialization error has occurred.
*/
- CXError_ASTReadError = 4
+ CXError_ASTReadError = 4,
+
+ /**
+ * \brief A refactoring action is not available at the given location
+ * or in the given source range.
+ */
+ CXError_RefactoringActionUnavailable = 5,
+
+ /**
+ * \brief A refactoring action is not able to use the given name because
+ * it contains an unexpected number of strings.
+ */
+ CXError_RefactoringNameSizeMismatch = 6,
+
+ /**
+ * \brief A name of a symbol is invalid, i.e. it is reserved by the source
+ * language and can't be used as a name for this symbol.
+ */
+ CXError_RefactoringNameInvalid = 7
};
LLVM_CLANG_C_EXTERN_C_END
diff --git a/clang/include/clang-c/Refactor.h b/clang/include/clang-c/Refactor.h
new file mode 100644
index 0000000000000..a196403cb09f6
--- /dev/null
+++ b/clang/include/clang-c/Refactor.h
@@ -0,0 +1,1313 @@
+/*==-- clang-c/Refactor.h - Refactoring Public C Interface --------*- C -*-===*\
+|* *|
+|* The LLVM Compiler Infrastructure *|
+|* *|
+|* This file is distributed under the University of Illinois Open Source *|
+|* License. See LICENSE.TXT for details. *|
+|* *|
+|*===----------------------------------------------------------------------===*|
+|* *|
+|* This header provides a public inferface to a Clang library for performing *|
+|* refactoring actions on projects without exposing the full Clang C++ API. *|
+|* *|
+\*===----------------------------------------------------------------------===*/
+
+#ifndef LLVM_CLANG_C_REFACTOR_H
+#define LLVM_CLANG_C_REFACTOR_H
+
+#include "clang-c/Index.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \defgroup CINDEX_REFACTOR Refactoring options.
+ *
+ * @{
+ */
+
+/**
+ * \brief The refactoring options that can be specified for each refactoring
+ * action.
+ */
+enum CXRefactoringOption {
+ /**
+ * \brief The refactoring actions like 'rename' will avoid looking for
+ * occurrences of the renamed symbol in comments if this option is enabled.
+ */
+ CXRefactorOption_AvoidTextualMatches = 1
+};
+
+/**
+ * \brief Opaque pointer representing a set of options that can be given to
+ * a refactoring action.
+ */
+typedef void *CXRefactoringOptionSet;
+
+/**
+ * \brief Returns a new option set.
+ */
+CINDEX_LINKAGE
+CXRefactoringOptionSet clang_RefactoringOptionSet_create(void);
+
+/**
+ * \brief Parses and returns a new option set or NULL if the given string is
+ * invalid.
+ */
+CINDEX_LINKAGE
+CXRefactoringOptionSet
+clang_RefactoringOptionSet_createFromString(const char *String);
+
+/**
+ * \brief Adds a new option to the given refactoring option set.
+ */
+CINDEX_LINKAGE
+void clang_RefactoringOptionSet_add(CXRefactoringOptionSet Set,
+ enum CXRefactoringOption Option);
+
+/**
+ * \brief Converts the given refactoring option set to a string value.
+ */
+CINDEX_LINKAGE
+CXString clang_RefactoringOptionSet_toString(CXRefactoringOptionSet Set);
+
+/**
+ * \brief Free the given option set.
+ *
+ * Option sets should be freed by this function only when they were created
+ * using the \c clang_RefactoringOptionSet_create* methods.
+ */
+CINDEX_LINKAGE
+void clang_RefactoringOptionSet_dispose(CXRefactoringOptionSet Set);
+
+/**
+ * @}
+ */
+
+/**
+ * \defgroup CINDEX_REFACTOR Refactoring actions.
+ *
+ * @{
+ */
+
+/**
+ * \brief The refactoring actions that can be performed by libclang.
+ */
+enum CXRefactoringActionType {
+ /**
+ * \brief The 'rename' refactoring action.
+ */
+ CXRefactor_Rename = 0,
+
+ /**
+ * \brief The local 'rename' refactoring action.
+ */
+ CXRefactor_Rename_Local = 1,
+
+ /**
+ * \brief The 'extract' refactoring action extracts source code into a
+ * new function.
+ */
+ CXRefactor_Extract = 2,
+
+ /**
+ * \brief The sub-action of 'extract' that extracts source code into a new
+ * method.
+ */
+ CXRefactor_Extract_Method = 3,
+
+ /**
+ * \brief The action that converts an if/else constructs to a switch block.
+ */
+ CXRefactor_IfSwitchConversion = 4,
+
+ /**
+ * \brief The action that wraps an Objective-C string literal in an
+ * NSLocalizedString macro.
+ */
+ CXRefactor_LocalizeObjCStringLiteral = 5,
+
+ /**
+ * \brief The action that adds missing switch cases to an switch over an enum.
+ */
+ CXRefactor_FillInEnumSwitchCases = 6,
+
+ /**
+ * \brief The action that adds missing protocol methods to an Objective-C
+ * class.
+ */
+ CXRefactor_FillInMissingProtocolStubs = 7,
+
+ /**
+ * \brief The action that extracts an expression that's repeated in a function
+ * into a new variable.
+ */
+ CXRefactor_ExtractRepeatedExpressionIntoVariable = 8,
+
+ /**
+ * \brief The action that adds missing abstract class method overrides to a
+ * class.
+ */
+ CXRefactor_FillInMissingMethodStubsFromAbstractClasses = 9,
+
+ /**
+ * \brief The action that generates dummy method definitions for method
+ * declarations without respective definitions.
+ */
+ CXRefactor_ImplementDeclaredMethods = 10,
+
+ /**
+ * \brief The sub-action of 'extract' that extracts source expression into a
+ * new variable.
+ */
+ CXRefactor_Extract_Expression = 11,
+};
+
+/**
+ * \brief Return the name of the given refactoring action.
+ */
+CINDEX_LINKAGE
+CXString
+clang_RefactoringActionType_getName(enum CXRefactoringActionType Action);
+
+/**
+ * \brief A set of refactoring actions that can be performed at some specific
+ * location in a source file.
+ *
+ * The actions in the action set are ordered by their priority: most important
+ * actions are placed before the less important ones.
+ */
+typedef struct {
+ const enum CXRefactoringActionType *Actions;
+ unsigned NumActions;
+} CXRefactoringActionSet;
+
+/**
+ * \brief Free the given refactoring action set.
+ */
+CINDEX_LINKAGE void
+clang_RefactoringActionSet_dispose(CXRefactoringActionSet *Set);
+
+typedef struct {
+ enum CXRefactoringActionType Action;
+ /**
+ * \brief The set of diagnostics that describes the reason why this action
+ * couldn't be initiated. This set of diagnostics is managed by the
+ * \c CXRefactoringActionSetWithDiagnostics and shouldn't be freed manually.
+ */
+ CXDiagnosticSet Diagnostics;
+} CXRefactoringActionWithDiagnostics;
+
+/**
+ * \brief A set of refactoring actions that couldn't be initiated at some
+ * location and their respective diagnostics that describe the reason why
+ * the initiation failed.
+ */
+typedef struct {
+ CXRefactoringActionWithDiagnostics *Actions;
+ unsigned NumActions;
+} CXRefactoringActionSetWithDiagnostics;
+
+/**
+ * \brief Free the given refactoring action set with diagnostics.
+ */
+CINDEX_LINKAGE void clang_RefactoringActionSetWithDiagnostics_dispose(
+ CXRefactoringActionSetWithDiagnostics *Set);
+
+/**
+ * \brief Find the set of refactoring actions that can be performed at the given
+ * location.
+ *
+ * This function examines the AST around the given source range and creates a
+ * \c CXRefactoringActionSet that contains all of the actions that can be
+ * performed in the given source range.
+ *
+ * \param TU The translation unit which contains the given source range.
+ *
+ * \param Location The location at which the refactoring action will be
+ * performed.
+ *
+ * \param SelectionRange The range in which the AST should be checked. Usually
+ * corresponds to the selection range or location of the cursor in the editor.
+ * Can be a null range.
+ *
+ * \param Options The optional refactoring options that might influence the way
+ * the search is performed.
+ *
+ * \param[out] OutSet A non-NULL pointer to store the created
+ * \c CXRefactoringActionSet.
+ *
+ * \returns Zero on success, CXError_RefactoringActionUnavailable when
+ * there are no actions available in the given range, or an error code
+ * otherwise.
+ */
+CINDEX_LINKAGE
+enum CXErrorCode
+clang_Refactoring_findActionsAt(CXTranslationUnit TU, CXSourceLocation Location,
+ CXSourceRange SelectionRange,
+ CXRefactoringOptionSet Options,
+ CXRefactoringActionSet *OutSet);
+
+/**
+ * \brief Find the set of refactoring actions that can be performed at the given
+ * location.
+ *
+ * This function examines the AST around the given source range and creates a
+ * \c CXRefactoringActionSet that contains all of the actions that can be
+ * performed in the given source range. It also creates a
+ * \c CXRefactoringActionSetWithDiagnostics that might describe the reason why
+ * some refactoring actions are not be available.
+ *
+ * \param TU The translation unit which contains the given source range.
+ *
+ * \param Location The location at which the refactoring action will be
+ * performed.
+ *
+ * \param SelectionRange The range in which the AST should be checked. Usually
+ * corresponds to the selection range or location of the cursor in the editor.
+ * Can be a null range.
+ *
+ * \param Options The optional refactoring options that might influence the way
+ * the search is performed.
+ *
+ * \param[out] OutSet A non-NULL pointer to store the created
+ * \c CXRefactoringActionSet.
+ *
+ * \param[out] OutFailureSet An optional pointer to store the created
+ * \c CXRefactoringActionSetWithDiagnostics that describes the failures reasons
+ * for some of the refactoring actions.
+ *
+ * \returns Zero on success, CXError_RefactoringActionUnavailable when
+ * there are no actions available in the given range, or an error code
+ * otherwise.
+ */
+CINDEX_LINKAGE
+enum CXErrorCode clang_Refactoring_findActionsWithInitiationFailureDiagnosicsAt(
+ CXTranslationUnit TU, CXSourceLocation Location,
+ CXSourceRange SelectionRange, CXRefactoringOptionSet Options,
+ CXRefactoringActionSet *OutSet,
+ CXRefactoringActionSetWithDiagnostics *OutFailureSet);
+
+/**
+ * @}
+ */
+
+/**
+ * \defgroup CINDEX_REFACTOR_INITIATE Refactoring initiation
+ *
+ * @{
+ */
+
+/**
+ * \brief Opaque pointer representing the initiated refactoring action.
+ */
+typedef void *CXRefactoringAction;
+
+/**
+ * \brief Free the given refactoring action.
+ *
+ * The refactoring action should be freed before the initiation and/or
+ * implementation translation units.
+ */
+CINDEX_LINKAGE void clang_RefactoringAction_dispose(CXRefactoringAction Action);
+
+/**
+ * \brief Return the source range that's associated with the initiated
+ * refactoring action.
+ *
+ * The returned source range covers the source that will be modified by the
+ * given refactoring action. If the action has no associated source range,
+ * then this function will return a null \c CXSourceRange.
+ */
+CINDEX_LINKAGE CXSourceRange
+clang_RefactoringAction_getSourceRangeOfInterest(CXRefactoringAction Action);
+
+/**
+ * \brief Return the type of the initiated action, which might be different
+ * to the type of the requested action. For an operation 'rename', the action
+ * could actually initiate the local 'rename' operation.
+ */
+CINDEX_LINKAGE
+enum CXRefactoringActionType
+clang_RefactoringAction_getInitiatedActionType(CXRefactoringAction Action);
+
+/**
+ * \brief Return a non-zero value when the refactoring action requires access
+ * to an additional translation unit that contains an implementation of some
+ * declaration.
+ */
+// TODO: Remove (this is no longer needed due to refactoring continuations).
+CINDEX_LINKAGE
+int clang_RefactoringAction_requiresImplementationTU(
+ CXRefactoringAction Action);
+
+/**
+ * \brief Return a USR that corresponds to the declaration whose implementation
+ * is required in order for the given refactoring action to work correctly.
+ */
+// TODO: Remove (this is no longer needed due to refactoring continuations).
+CINDEX_LINKAGE
+CXString clang_RefactoringAction_getUSRThatRequiresImplementationTU(
+ CXRefactoringAction Action);
+
+/**
+ * \brief Set the translation unit that contains the declaration whose
+ * implementation is required for the given refactoring action to work
+ * correctly.
+ */
+// TODO: Remove (this is no longer needed due to refactoring continuations).
+CINDEX_LINKAGE
+enum CXErrorCode
+clang_RefactoringAction_addImplementationTU(CXRefactoringAction Action,
+ CXTranslationUnit TU);
+
+/**
+ * \brief A refactoring candidate determines on which piece of source code the
+ * action should be applied.
+ *
+ * Most refactoring actions have just one candidate, but some actions, like
+ * 'Extract' can produce multiple candidates.
+ *
+ * The candidates are managed by the refactoring action, and their description
+ * string doesn't need to be freed manually.
+ */
+typedef struct { CXString Description; } CXRefactoringCandidate;
+
+/**
+ * \brief A set of refactoring candidates on which the previously initiatied
+ * refactoring action can be performed.
+ *
+ * The candidates in the candidate set are ordered by their priority: the
+ * ones that are more likely to be selected are placed before the other ones.
+ *
+ * A non-empty refactoring candidate set always has more than one refactoring
+ * candidate, because when a refactoring action has just one candidate,
+ * \c clang_RefactoringAction_getRefactoringCandidates will return an empty
+ * candidate set.
+ */
+typedef struct {
+ const CXRefactoringCandidate *Candidates;
+ unsigned NumCandidates;
+} CXRefactoringCandidateSet;
+
+/**
+ * \brief Returns the given action's refactoring candidates.
+ *
+ * The resulting refactoring candidate set will be empty when the given \c
+ * CXRefactoringAction has just one refactoring candidate.
+ *
+ * \param Action A previously initiated \c CXRefactoringAction.
+ *
+ * \param[out] OutRefactoringCandidateSet An pointer to store the action's
+ * refactoring candidate set.
+ *
+ * \returns Zero on success, or an error code otherwise.
+ */
+CINDEX_LINKAGE
+enum CXErrorCode clang_RefactoringAction_getRefactoringCandidates(
+ CXRefactoringAction Action,
+ CXRefactoringCandidateSet *OutRefactoringCandidateSet);
+
+/**
+ * \brief Tells the given refactoring action that it has to perform the
+ * operation on the refactoring candidate that's located at \p Index in the \c
+ * CXRefactoringCandidateSet.
+ */
+CINDEX_LINKAGE
+enum CXErrorCode
+clang_RefactoringAction_selectRefactoringCandidate(CXRefactoringAction Action,
+ unsigned Index);
+
+// TODO: Remove.
+CINDEX_LINKAGE
+enum CXErrorCode clang_Refactoring_initiateActionAt(
+ CXTranslationUnit TU, CXSourceLocation Location,
+ CXSourceRange SelectionRange, enum CXRefactoringActionType ActionType,
+ CXRefactoringOptionSet Options, CXRefactoringAction *OutAction,
+ CXString *OutFailureReason);
+
+/**
+ * \brief Initiate a specific refactoring action at the given location.
+ *
+ * This function initiates an \p ActionType refactoring action when it can
+ * be initiated at the given location and creates a \c CXRefactoringAction
+ * action that will allow the control.
+ *
+ * \param TU The translation unit in which the action should be initiated.
+ *
+ * \param Location The location at which the refactoring action will be
+ * performed.
+ *
+ * \param SelectionRange The range in which the AST should be checked. Usually
+ * corresponds to the selection range or location of the cursor in the editor.
+ * Can be a null range.
+ *
+ * \param ActionType The type of action that should be initiated.
+ *
+ * \param Options The optional refactoring options that might have an influence
+ * on the initiation process.
+ *
+ * \param[out] OutAction A non-NULL pointer to store the created
+ * \c CXRefactoringAction.
+ *
+ * \param[out] OutDiagnostics An optional pointer to store any diagnostics that
+ * describe why the action wasn't initiated.
+ *
+ * \returns Zero on success, CXError_RefactoringActionUnavailable when
+ * the given refactoring action can't be performed at the given location, or an
+ * error code otherwise.
+ */
+CINDEX_LINKAGE
+enum CXErrorCode clang_Refactoring_initiateAction(
+ CXTranslationUnit TU, CXSourceLocation Location,
+ CXSourceRange SelectionRange, enum CXRefactoringActionType ActionType,
+ CXRefactoringOptionSet Options, CXRefactoringAction *OutAction,
+ CXDiagnosticSet *OutDiagnostics);
+
+/**
+ * \brief Initiate a specific refactoring action on a particular declaration.
+ *
+ * This function searches for the declaration that corresponds to \p DeclUSR
+ * and initiates an \p ActionType a refactoring action on that declaration
+ * if possible.
+ *
+ * \param TU The translation unit in which the declaration is defined.
+ *
+ * \param DeclUSR The USR that corresponds to the declaration of interest.
+ *
+ * \param ActionType The type of action that should be initiated.
+ *
+ * \param Options The optional refactoring options that might have an influence
+ * on the initiation process.
+ *
+ * \param[out] OutAction A non-NULL pointer to store the created
+ * \c CXRefactoringAction.
+ *
+ * \returns Zero on success, CXError_RefactoringActionUnavailable when
+ * the given refactoring action can't be performed on the found declaration, or
+ * an error code otherwise.
+ */
+// TODO: Remove (not needed).
+CINDEX_LINKAGE
+enum CXErrorCode clang_Refactoring_initiateActionOnDecl(
+ CXTranslationUnit TU, const char *DeclUSR,
+ enum CXRefactoringActionType ActionType, CXRefactoringOptionSet Options,
+ CXRefactoringAction *OutAction, CXString *OutFailureReason);
+
+/**
+ * @}
+ */
+
+/**
+ * \defgroup CINDEX_REFACTOR_REPLACEMENT Refactoring replacement
+ *
+ * @{
+ */
+
+/**
+ * \brief A source location in a single file that is independent of \c
+ * CXTranslationUnit.
+ */
+typedef struct { unsigned Line, Column; } CXFileLocation;
+
+/**
+ * \brief A source range in a single file that is independent of \c
+ * CXTranslationUnit.
+ */
+typedef struct { CXFileLocation Begin, End; } CXFileRange;
+
+// TODO: Remove
+typedef struct {
+ CXFileRange Range;
+ CXString ReplacementString;
+} CXRefactoringReplacement_Old;
+
+// TODO: Remove
+typedef struct {
+ CXString Filename;
+ const CXRefactoringReplacement_Old *Replacements;
+ unsigned NumReplacements;
+} CXRefactoringFileReplacementSet_Old;
+
+// TODO: Remove
+typedef struct {
+ const CXRefactoringFileReplacementSet_Old *FileReplacementSets;
+ unsigned NumFileReplacementSets;
+} CXRefactoringReplacements_Old;
+
+/**
+ * \brief Identifies a character range in the source code of a single file that
+ * should be replaced with the replacement string.
+ *
+ * Replacements are managed by the result of a specific refactoring action,
+ * like \c CXRenamingResult, and are invalidated when the refactoring result is
+ * destroyed.
+ */
+typedef struct {
+ CXFileRange Range;
+ CXString ReplacementString;
+ void *AssociatedData;
+} CXRefactoringReplacement;
+
+/**
+* \brief A set of refactoring replacements that are applicable to a certain
+ * file.
+ */
+typedef struct {
+ CXString Filename;
+ const CXRefactoringReplacement *Replacements;
+ unsigned NumReplacements;
+} CXRefactoringFileReplacementSet;
+
+/**
+ * \brief A set of refactoring replacements that have been produced by a
+ * refactoring operation.
+ *
+ * The refactoring replacements depend on \c CXRefactoringResult, and can't be
+ * used after the refactoring result is freed.
+ */
+typedef struct {
+ const CXRefactoringFileReplacementSet *FileReplacementSets;
+ unsigned NumFileReplacementSets;
+} CXRefactoringReplacements;
+
+/**
+ * @}
+ */
+
+/**
+ * \defgroup CINDEX_SYMBOL_OPERATION Symbol-based refactoring operation
+ * (e.g. Rename).
+ *
+ * @{
+ */
+
+/**
+ * \brief The type of a symbol occurrence.
+ *
+ * The occurrence kind determines if an occurrence can be renamed automatically
+ * or if the user has to make the decision whether or not this occurrence
+ * should be renamed.
+ */
+enum CXSymbolOccurrenceKind {
+ /**
+ * \brief This occurrence is an exact match and can be renamed automatically.
+ */
+ CXSymbolOccurrence_MatchingSymbol = 0,
+
+ /**
+ * \brief This is an occurrence of a matching selector. It can't be renamed
+ * automatically unless the indexer proves that this selector refers only
+ * to the declarations that correspond to the renamed symbol.
+ */
+ CXSymbolOccurrence_MatchingSelector = 1,
+
+ /**
+ * \brief This is an occurrence of an implicit property that uses the
+ * renamed method.
+ */
+ CXSymbolOccurrence_MatchingImplicitProperty = 2,
+
+ /**
+ * \brief This is an occurrence of an symbol name in a comment.
+ */
+ CXSymbolOccurrence_MatchingCommentString = 3,
+
+ /**
+ * \brief This is an occurrence of an symbol name in a documentation comment.
+ */
+ CXSymbolOccurrence_MatchingDocCommentString = 4,
+
+ /**
+ * \brief This is an occurrence of an symbol name in a filename in an inclusion
+ * directive.
+ */
+ CXSymbolOccurrence_MatchingFilename = 5,
+
+ /**
+ * \brief This is an occurrence of an symbol name in a string literal.
+ */
+ CXSymbolOccurrence_MatchingStringLiteral = 6,
+
+ /**
+ * \brief This is an occurrence of a symbol name that belongs to the extracted
+ * declaration. Note: this occurrence can be in two replacements as we might
+ * extract an out-of-line method that will be both declared and defined.
+ */
+ CXSymbolOccurrence_ExtractedDeclaration = 100,
+
+ /**
+ * \brief This is an occurrence of a symbol name that references the extracted
+ * declaration.
+ */
+ CXSymbolOccurrence_ExtractedDeclaration_Reference = 101,
+};
+
+// TODO: Remove
+typedef struct {
+ const CXRefactoringReplacement_Old *Replacements;
+ unsigned ReplacementCount;
+ enum CXSymbolOccurrenceKind Kind;
+ /**
+ * Whether or not this occurrence is inside a macro. When this is true, the
+ * replacements of the occurrence contain just a single empty replacement that
+ * points to the location of the macro expansion.
+ */
+ int IsMacroExpansion;
+} CXRenamedSymbolOccurrence;
+
+/**
+ * \brief An occurrence of a symbol.
+ *
+ * Contains the source ranges that represent the pieces of the name of the
+ * symbol. The occurrences are managed by \c CXRenamingResult, and are
+ * invalidated when \c CXRenamingResult is destroyed.
+ */
+typedef struct {
+ const CXFileRange *NamePieces;
+ unsigned NumNamePieces;
+ enum CXSymbolOccurrenceKind Kind;
+ /**
+ * Whether or not this occurrence is inside a macro. When this is true, the
+ * replacements of the occurrence contain just a single empty replacement that
+ * points to the location of the macro expansion.
+ */
+ int IsMacroExpansion;
+ unsigned SymbolIndex;
+} CXSymbolOccurrence;
+
+// TODO: Remove
+typedef struct {
+ CXString Filename;
+ const CXRenamedSymbolOccurrence *Occurrences;
+ unsigned NumOccurrences;
+} CXFileRenamingResult; // TODO: Remove
+
+/**
+* \brief A set of symbol occurrences that occur in a single file.
+ */
+typedef struct {
+ CXString Filename;
+ /**
+ * The set of occurrences for each symbol of interest.
+ */
+ const CXSymbolOccurrence *Occurrences;
+ unsigned NumOccurrences;
+} CXSymbolOccurrencesInFile;
+
+/**
+ * \brief Opaque pointer representing all of the renames that should take place
+ * in a single translation unit.
+ *
+ * The result of a renaming action is indepedent from \c CXRenamingAction, and
+ * remains valid after \c CXRenamingAction is destroyed.
+ */
+typedef void *CXRenamingResult;
+
+/**
+ * \brief Opaque pointer representing all of the symbol occurrences from a
+ * single TU/file.
+ *
+ * The result of a symbol search occurrence search operation is indepedent from
+ * \c CXRefactoringAction, and remains valid after \c CXRefactoringAction is
+ * destroyed.
+ */
+typedef void *CXSymbolOccurrencesResult;
+
+/**
+ * \brief Find the cursor that's being renamed at the given location.
+ *
+ * \param TU The translation unit in which the cursor is present.
+ *
+ * \param Location The location at which the refactoring action will be
+ * performed.
+ *
+ * \param SelectionRange The range in which the AST should be checked. Usually
+ * corresponds to the selection range or location of the cursor in the editor.
+ * Can be a null range.
+ *
+ * \returns Zero on success, CXError_RefactoringActionUnavailable when
+ * there's no suitable cursor at the given location, or an error code otherwise.
+ */
+CINDEX_LINKAGE
+enum CXErrorCode clang_Refactoring_findRenamedCursor(
+ CXTranslationUnit TU, CXSourceLocation Location,
+ CXSourceRange SelectionRange, CXCursor *OutCursor);
+
+/**
+ * \brief Initiates a renaming operation on a previously initiated refactoring
+ * action.
+ *
+ * The initiation process finds the symbols that have to be renamed for a
+ * previously initiated \c CXRefactor_Rename refactoring action.
+ *
+ * \returns Zero on success, or an error code otherwise.
+ */
+// TODO: Remove
+CINDEX_LINKAGE
+enum CXErrorCode
+clang_Refactoring_initiateRenamingOperation(CXRefactoringAction Action);
+
+/**
+ * \brief Set the new name of the renamed symbol in the given \c
+ * RenamingAction.
+ *
+ * \returns Zero on success, CXError_RefactoringNameInvalid when the new name
+ * isn't a valid identifier, CXError_RefactoringNameSizeMismatch when the new
+ * name has an incorrect number of pieces or a different error code otherwise.
+ */
+// TODO: Remove
+CINDEX_LINKAGE
+enum CXErrorCode clang_RenamingOperation_setNewName(CXRefactoringAction Action,
+ const char *NewName);
+
+/**
+ * \brief Return the number of symbols that are renamed by the given renaming
+ * action.
+ *
+ * A renaming action typically works on just one symbol. However, there are
+ * certain language constructs that require work with more than one symbol in
+ * order for them to be renamed correctly. Property declarations in Objective-C
+ * are the perfect example: in addition to the actual property, the action has
+ * to rename the corresponding getters and setters, as well as the backing ivar.
+ */
+// TODO: Remove
+CINDEX_LINKAGE
+unsigned clang_RenamingOperation_getNumSymbols(CXRefactoringAction Action);
+
+/**
+ * \brief Return the USR of the declaration that was found for the symbol at the
+ * given \p Index in the given renaming action.
+ */
+// TODO: Remove
+CINDEX_LINKAGE
+CXString clang_RenamingOperation_getUSRForSymbol(CXRefactoringAction Action,
+ unsigned Index);
+
+// TODO: Remove
+CINDEX_LINKAGE
+CXRenamingResult clang_Refactoring_findRenamedOccurrencesInPrimaryTUs(
+ CXRefactoringAction Action, const char *const *CommandLineArgs,
+ int NumCommandLineArgs, struct CXUnsavedFile *UnsavedFiles,
+ unsigned NumUnsavedFiles);
+
+/**
+ * \brief Find all of the occurrences of the symbol that is being searched for
+ * by the given refactoring action in the translation unit that was used to
+ * initiate the refactoring action.
+ *
+ * This function searches for all of the \c CXSymbolOccurrence in the
+ * translation units that are referenced by the given \c CXRefactoringAction by
+ * iterating through the AST of the each translation unit. The occurrences that
+ * are found don't have to be from the main file in the translation unit, they
+ * can be from files included in that translation unit.
+ *
+ * \param Action The \c CXRefactoringAction operation that was inititated by
+ * \c clang_Refactoring_initiateActionAt().
+ *
+ * \param CommandLineArgs The command-line arguments that would be
+ * passed to the \c clang executable if it were being invoked out-of-process.
+ *
+ * \param NumCommandLineArgs The number of command-line arguments in
+ * \c CommandLineArgs.
+ *
+ * \param UnsavedFiles the files that have not yet been saved to disk
+ * but may be required for parsing, including the contents of
+ * those files. The contents and name of these files (as specified by
+ * CXUnsavedFile) are copied when necessary, so the client only needs to
+ * guarantee their validity until the call to this function returns.
+ *
+ * \param NumUnsavedFiles the number of unsaved file entries in \p
+ * UnsavedFiles.
+ *
+ * \returns If successful, a new \c CXSymbolOccurrencesResult structure
+ * containing the occurrences of the symbol in the initiation translation unit,
+ * which should eventually be freed with \c clang_SymbolOccurrences_dispose().
+ * If symbol search fails, returns NULL.
+ */
+CINDEX_LINKAGE
+CXSymbolOccurrencesResult clang_Refactoring_findSymbolOccurrencesInInitiationTU(
+ CXRefactoringAction Action, const char *const *CommandLineArgs,
+ int NumCommandLineArgs, struct CXUnsavedFile *UnsavedFiles,
+ unsigned NumUnsavedFiles);
+
+// TODO: Remove
+typedef struct {
+ CXFileLocation Location;
+ /**
+ * The kind of the declaration/expression that was indexed at this location.
+ * This is particularly important for Objective-C selectors. The refactoring
+ * engine requires the following cursor kinds for the following indexed
+ * occurrences:
+ * - ObjC method declaration: CXCursor_ObjC(Instance/Class)MethodDecl
+ * - ObjC method message send: CXCursor_ObjCMessageExpr
+ * Other occurrences can use any other cursor cursor kinds.
+ */
+ enum CXCursorKind CursorKind;
+} CXRenamedIndexedSymbolLocation;
+
+// TODO: Remove
+typedef struct {
+ /**
+ * An array of occurrences that represent indexed occurrences of a symbol.
+ * It's valid to pass-in no indexed locations, the refactoring engine will
+ * just perform textual search in that case.
+ */
+ const CXRenamedIndexedSymbolLocation *IndexedLocations;
+ unsigned IndexedLocationCount;
+ /**
+ * The kind of the declaration that is being renamed.
+ * This is particularly important for Objective-C selectors. The refactoring
+ * engine requires the following cursor kinds for the following renamed
+ * declaration:
+ * - ObjC methods: CXCursor_ObjC(Instance/Class)MethodDecl
+ * Other declarations can use any other cursor cursor kinds.
+ */
+ enum CXCursorKind CursorKind;
+ const char *Name;
+ const char *NewName;
+} CXRenamedIndexedSymbol;
+
+// TODO: Remove
+CINDEX_LINKAGE
+enum CXErrorCode clang_Refactoring_findRenamedOccurrencesInIndexedFile(
+ const CXRenamedIndexedSymbol *Symbols, unsigned NumSymbols, CXIndex CIdx,
+ const char *Filename, const char *const *CommandLineArgs,
+ int NumCommandLineArgs, struct CXUnsavedFile *UnsavedFiles,
+ unsigned NumUnsavedFiles, CXRefactoringOptionSet Options,
+ CXRenamingResult *OutResult);
+
+/**
+ * \brief A location of an already known occurrence of a symbol.
+ *
+ * Used for rename-indexed operation where the renaming is performed on an
+ * already indexed source file.
+ */
+typedef struct {
+ CXFileLocation Location;
+ /**
+ * The kind of the declaration/expression that was indexed at this location.
+ * This is particularly important for Objective-C selectors. The refactoring
+ * engine requires the following cursor kinds for the following indexed
+ * occurrences:
+ * - ObjC method declaration: CXCursor_ObjC(Instance/Class)MethodDecl
+ * - ObjC method message send: CXCursor_ObjCMessageExpr
+ * - filename in an #include: CXCursor_InclusionDirective
+ * Other occurrences can use any other cursor cursor kinds.
+ */
+ enum CXCursorKind CursorKind;
+} CXIndexedSymbolLocation;
+
+/**
+ * \brief A symbol that should be found the an indexer symbol search operation.
+ *
+ * Used for rename-indexed operation where the renaming is performed on an
+ * already indexed source file.
+ */
+typedef struct {
+ /**
+ * An array of occurrences that represent indexed occurrences of a symbol.
+ * It's valid to pass-in no indexed locations, the refactoring engine will
+ * just perform textual search in that case.
+ */
+ const CXIndexedSymbolLocation *IndexedLocations;
+ unsigned IndexedLocationCount;
+ /**
+ * The kind of the declaration that is being renamed.
+ * This is particularly important for Objective-C selectors. The refactoring
+ * engine requires the following cursor kinds for the following renamed
+ * declaration:
+ * - ObjC methods: CXCursor_ObjC(Instance/Class)MethodDecl
+ * - ObjC class: CXCursor_ObjCInterfaceDecl
+ * Other declarations can use any other cursor cursor kinds.
+ */
+ enum CXCursorKind CursorKind;
+ /**
+ * The name of the symbol. Objective-C selector names should be specified
+ * using the ':' separator for selector pieces.
+ */
+ const char *Name;
+} CXIndexedSymbol;
+
+/**
+ * \brief Find all of the occurrences of a symbol in an indexed file.
+ *
+ * This function searches for all of the \c CXIndexedSymbol in the
+ * given file by inspecting the source code at the given indexed locations.
+ *
+ * The indexed operations are thread-safe and can be performed concurrently.
+ *
+ * \param Symbols The information about the symbols that includes the locations
+ * for a symbol in the file as determined by the indexer.
+ *
+ * \param NumSymbols The number of symbols in \p Symbols.
+ *
+ * \param CIdx The index object with which the translation unit will be
+ * associated.
+ *
+ * \param Filename The name of the source file that contains the given
+ * \p Locations.
+ *
+ * \param CommandLineArgs The command-line arguments that would be
+ * passed to the \c clang executable if it were being invoked out-of-process.
+ * These command-line options will be parsed and will affect how the translation
+ * unit is parsed.
+ *
+ * \param NumCommandLineArgs The number of command-line arguments in
+ * \c CommandLineArgs.
+ *
+ * \param UnsavedFiles the files that have not yet been saved to disk
+ * but may be required for parsing, including the contents of
+ * those files. The contents and name of these files (as specified by
+ * CXUnsavedFile) are copied when necessary, so the client only needs to
+ * guarantee their validity until the call to this function returns.
+ *
+ * \param NumUnsavedFiles the number of unsaved file entries in \p
+ * UnsavedFiles.
+ *
+ * \param Options The optional refactoring options that might have an influence
+ * on the initiation process.
+ *
+ * \param[out] OutResult A non-NULL pointer to store the created
+ * \c CXSymbolOccurrencesResult.
+ *
+ * \returns Zero on success, or a different error code otherwise.
+ */
+CINDEX_LINKAGE
+enum CXErrorCode clang_Refactoring_findSymbolOccurrencesInIndexedFile(
+ const CXIndexedSymbol *Symbols, unsigned NumSymbols, CXIndex CIdx,
+ const char *Filename, const char *const *CommandLineArgs,
+ int NumCommandLineArgs, struct CXUnsavedFile *UnsavedFiles,
+ unsigned NumUnsavedFiles, CXRefactoringOptionSet Options,
+ CXSymbolOccurrencesResult *OutResult);
+
+// TODO: Remove
+CINDEX_LINKAGE
+unsigned clang_RenamingResult_getNumModifiedFiles(CXRenamingResult Result);
+
+// TODO: Remove
+CINDEX_LINKAGE
+void clang_RenamingResult_getResultForFile(CXRenamingResult Result,
+ unsigned FileIndex,
+ CXFileRenamingResult *OutResult);
+
+// TODO: Remove
+CINDEX_LINKAGE
+void clang_RenamingResult_dispose(CXRenamingResult Result);
+
+/**
+ * \brief Return the number of files that have occurrences of the specific
+ * symbol.
+ */
+CINDEX_LINKAGE
+unsigned clang_SymbolOccurrences_getNumFiles(CXSymbolOccurrencesResult Result);
+
+/**
+ * \brief Return the set of symbol occurrences in a single file.
+ *
+ * The resulting \c CXSymbolOccurrencesInFile is managed by the
+ * \c CXSymbolOccurrencesResult and doesn't have to be disposed of manually.
+ */
+CINDEX_LINKAGE
+void clang_SymbolOccurrences_getOccurrencesForFile(
+ CXSymbolOccurrencesResult Result, unsigned FileIndex,
+ CXSymbolOccurrencesInFile *OutResult);
+
+// TODO: Support refactoring continuations for \c CXSymbolOccurrencesResult,
+// e.g. for function parameter name rename.
+
+/**
+ * \brief Free the given symbol occurrences result.
+ */
+CINDEX_LINKAGE
+void clang_SymbolOccurrences_dispose(CXSymbolOccurrencesResult Result);
+
+/**
+ * @}
+ */
+
+/**
+ * \defgroup CINDEX_REFACTOR_PERFORM Performing refactoring operations.
+ *
+ * @{
+ */
+
+/**
+ * \brief Opaque pointer representing the results of the refactoring operation.
+ *
+ * The result of a refactoring action depends on the \c CXRefactoringAction, and
+ * is invalidated after \c CXRefactoringAction is destroyed.
+ */
+typedef void *CXRefactoringResult;
+
+/**
+ * \brief Opaque pointer representing a refactoring continuation.
+ *
+ * Refactoring continuations allow refactoring operations to run in external
+ * AST units with some results that were obtained after querying the indexer.
+ *
+ * The refactoring continuation is not dependent on the \c CXRefactoringAction
+ * or \c CXRefactoringResult. It does depend on the initiation
+ * \c CXTranslationUnit initially, but that dependency can be terminated.
+ */
+typedef void *CXRefactoringContinuation;
+
+/**
+ * \brief Opaque pointer representing a query to the indexer.
+ */
+typedef void *CXIndexerQuery;
+
+/**
+ * \brief Performs the previously initiated refactoring operation.
+ *
+ * This function executes the refactoring operation which produces a set of
+ * candidate source replacements that can be applied to the source files.
+ *
+ * \param Action The refactoring action.
+ *
+ * \param CommandLineArgs The command-line arguments that would be
+ * passed to the \c clang executable if it were being invoked out-of-process.
+ * These command-line options will be parsed and will affect how the translation
+ * unit is parsed.
+ *
+ * \param NumCommandLineArgs The number of command-line arguments in
+ * \c CommandLineArgs.
+ *
+ * \param UnsavedFiles the files that have not yet been saved to disk
+ * but may be required for parsing, including the contents of
+ * those files. The contents and name of these files (as specified by
+ * CXUnsavedFile) are copied when necessary, so the client only needs to
+ * guarantee their validity until the call to this function returns.
+ *
+ * \param NumUnsavedFiles the number of unsaved file entries in \p
+ * UnsavedFiles.
+ *
+ * \param Options The optional refactoring options that might have an influence
+ * on the way the particular action will be performed.
+ *
+ * \param[out] OutFailureReason An optional pointer to store a message that
+ * describes why the action wasn't performed.
+ *
+ * \returns If successful, a new \c CXRefactoringResult structure containing the
+ * source replacement candidates, which should eventually be freed with
+ * \c clang_RefactoringResult_dispose(). If the refactoring operation fails,
+ * returns NULL.
+ */
+CINDEX_LINKAGE
+CXRefactoringResult clang_Refactoring_performOperation(
+ CXRefactoringAction Action, const char *const *CommandLineArgs,
+ int NumCommandLineArgs, struct CXUnsavedFile *UnsavedFiles,
+ unsigned NumUnsavedFiles, CXRefactoringOptionSet Options,
+ CXString *OutFailureReason);
+
+// TODO: Remove. This is the deprecated API.
+CINDEX_LINKAGE
+void clang_RefactoringResult_getReplacements(
+ CXRefactoringResult Result, CXRefactoringReplacements_Old *OutReplacements);
+
+/**
+ * \brief Return the set of refactoring source replacements.
+ *
+ * The resulting \c CXRefactoringReplacements are managed by the
+ * \c CXRefactoringResult and don't have to be disposed of manually.
+ */
+CINDEX_LINKAGE
+CXRefactoringReplacements
+clang_RefactoringResult_getSourceReplacements(CXRefactoringResult Result);
+
+/**
+ * \brief Represents a set of symbol occurrences that are associated with a
+ * single refactoring replacement.
+ *
+ * The symbol occurrences depend on \c CXRefactoringResult, and can't be
+ * used after the refactoring result is freed.
+ */
+typedef struct {
+ const CXSymbolOccurrence *AssociatedSymbolOccurrences;
+ unsigned NumAssociatedSymbolOccurrences;
+} CXRefactoringReplacementAssociatedSymbolOccurrences;
+
+/**
+ * \brief Return the set of symbol occurrences that are associated with the
+ * given \p Replacement.
+ */
+CINDEX_LINKAGE
+CXRefactoringReplacementAssociatedSymbolOccurrences
+clang_RefactoringReplacement_getAssociatedSymbolOccurrences(
+ CXRefactoringReplacement Replacement);
+
+/**
+ * \brief Returns the refactoring continuation associated with this result, or
+ * NULL if this result has no refactoring continuation.
+ */
+CINDEX_LINKAGE
+CXRefactoringContinuation
+clang_RefactoringResult_getContinuation(CXRefactoringResult Result);
+
+/**
+ * \brief Free the given refactoring result.
+ */
+CINDEX_LINKAGE
+void clang_RefactoringResult_dispose(CXRefactoringResult Result);
+
+/**
+ * \brief Load the indexer query results from a YAML string.
+ *
+ * Mainly used for testing.
+ */
+CINDEX_LINKAGE
+enum CXErrorCode
+clang_RefactoringContinuation_loadSerializedIndexerQueryResults(
+ CXRefactoringContinuation Continuation, const char *Source);
+
+/**
+ * \brief Return the number of indexer queries that a refactoring continuation
+ * has.
+ */
+CINDEX_LINKAGE
+unsigned clang_RefactoringContinuation_getNumIndexerQueries(
+ CXRefactoringContinuation Continuation);
+
+/**
+ * \brief Return the indexer query at index \p Index.
+ */
+CINDEX_LINKAGE
+CXIndexerQuery clang_RefactoringContinuation_getIndexerQuery(
+ CXRefactoringContinuation Continuation, unsigned Index);
+
+/**
+ * \brief Verify that the all of the indexer queries are satisfied by the
+ * continuation.
+ *
+ * \returns Null if all of the queries are satisfied an no errors have been
+ * reported, or a set of diagnostics that describes why the continuation should
+ * not be run.
+ */
+CINDEX_LINKAGE
+CXDiagnosticSet clang_RefactoringContinuation_verifyBeforeFinalizing(
+ CXRefactoringContinuation Continuation);
+
+/**
+ * \brief Terminate the connection between the initiation TU and the refactoring
+ * continuation.
+ *
+ * The continuation converts all the TU-specific state to TU-independent state.
+ * The indexer queries that are associate with this continuation are also
+ * invalidated.
+ */
+CINDEX_LINKAGE
+void clang_RefactoringContinuation_finalizeEvaluationInInitationTU(
+ CXRefactoringContinuation Continuation);
+
+/**
+ * \brief Continue performing the previously initiated and performed refactoring
+ * operation in the given translation unit \p TU.
+ */
+CINDEX_LINKAGE
+CXRefactoringResult clang_RefactoringContinuation_continueOperationInTU(
+ CXRefactoringContinuation Continuation, CXTranslationUnit TU,
+ CXString *OutFailureReason);
+
+/**
+ * \brief Free the given refactoring continuation.
+ */
+CINDEX_LINKAGE
+void clang_RefactoringContinuation_dispose(
+ CXRefactoringContinuation Continuation);
+
+/**
+ * @}
+ */
+
+/**
+ * \defgroup CINDEX_REFACTOR_INDEXER_QUERY Indexer Queries.
+ *
+ * @{
+ */
+
+/**
+ * \brief The types of indexer queries.
+ */
+enum CXIndexerQueryKind {
+ CXIndexerQuery_Unknown = 0,
+
+ /**
+ * \brief The indexer should find the file that contains/should contain the
+ * implementation of some declaration.
+ * A file result is expected.
+ */
+ CXIndexerQuery_Decl_FileThatShouldImplement = 1,
+
+ /**
+ * \brief The indexer should determine if the some declaration is defined.
+ * An integer result is expected.
+ */
+ CXIndexerQuery_Decl_IsDefined = 2,
+};
+
+/**
+ * \brief Return the kind of the indexer query \p Query.
+ */
+CINDEX_LINKAGE
+enum CXIndexerQueryKind clang_IndexerQuery_getKind(CXIndexerQuery Query);
+
+/**
+ * \brief Return the number of cursors that the \p Query has.
+ */
+CINDEX_LINKAGE
+unsigned clang_IndexerQuery_getNumCursors(CXIndexerQuery Query);
+
+/**
+ * \brief Return the cursor at the given \p CursorIndex.
+ */
+CINDEX_LINKAGE
+CXCursor clang_IndexerQuery_getCursor(CXIndexerQuery Query,
+ unsigned CursorIndex);
+
+/**
+ * \brief The action that the indexer should take after evaluating the query.
+ */
+enum CXIndexerQueryAction {
+ /**
+ * \brief This result requires no further action.
+ */
+ CXIndexerQueryAction_None = 0,
+
+ /**
+ * \brief The indexer should run the \c CXRefactoringContinuaton in a
+ * translation unit that contains this file.
+ */
+ CXIndexerQueryAction_RunContinuationInTUThatHasThisFile = 1,
+};
+
+/**
+ * \brief Consumes an integer/boolean query result.
+ */
+CINDEX_LINKAGE
+enum CXIndexerQueryAction
+clang_IndexerQuery_consumeIntResult(CXIndexerQuery Query, unsigned CursorIndex,
+ int Value);
+
+/**
+ * \brief Consumes a filename query result.
+ *
+ * This function may return
+ * \c CXIndexerQueryAction_RunContinuationInTUThatHasThisFile which
+ * should tell the indexer that it has to run the refactoring continuation in
+ * the TU that contains this file.
+ */
+CINDEX_LINKAGE
+enum CXIndexerQueryAction
+clang_IndexerQuery_consumeFileResult(CXIndexerQuery Query, unsigned CursorIndex,
+ const char *Filename);
+
+/**
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LLVM_CLANG_C_REFACTOR_H */
diff --git a/clang/include/clang/APINotes/APINotesManager.h b/clang/include/clang/APINotes/APINotesManager.h
new file mode 100644
index 0000000000000..faedf2d44db23
--- /dev/null
+++ b/clang/include/clang/APINotes/APINotesManager.h
@@ -0,0 +1,144 @@
+//===--- APINotesManager.h - Manage API Notes Files -------------*- 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 APINotesManager interface.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_APINOTES_APINOTESMANAGER_H
+#define LLVM_CLANG_APINOTES_APINOTESMANAGER_H
+
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/Module.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/PointerUnion.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/VersionTuple.h"
+#include
+#include
+
+namespace clang {
+
+class DirectoryEntry;
+class FileEntry;
+class LangOptions;
+class SourceManager;
+
+namespace api_notes {
+
+class APINotesReader;
+
+/// The API notes manager helps find API notes associated with declarations.
+///
+/// API notes are externally-provided annotations for declarations that can
+/// introduce new attributes (covering availability, nullability of
+/// parameters/results, and so on) for specific declarations without directly
+/// modifying the headers that contain those declarations.
+///
+/// The API notes manager is responsible for finding and loading the
+/// external API notes files that correspond to a given header. Its primary
+/// operation is \c findAPINotes(), which finds the API notes reader that
+/// provides information about the declarations at that location.
+class APINotesManager {
+ typedef llvm::PointerUnion
+ ReaderEntry;
+
+ SourceManager &SourceMgr;
+
+ /// Whether to implicitly search for API notes files based on the
+ /// source file from which an entity was declared.
+ bool ImplicitAPINotes;
+
+ /// The Swift version to use when interpreting versioned API notes.
+ llvm::VersionTuple SwiftVersion;
+
+ /// API notes readers for the current module.
+ ///
+ /// There can be up to two of these, one for public headers and one
+ /// for private headers.
+ APINotesReader *CurrentModuleReaders[2] = { nullptr, nullptr };
+
+ /// A mapping from header file directories to the API notes reader for
+ /// that directory, or a redirection to another directory entry that may
+ /// have more information, or NULL to indicate that there is no API notes
+ /// reader for this directory.
+ llvm::DenseMap Readers;
+
+ /// Load the API notes associated with the given file, whether it is
+ /// the binary or source form of API notes.
+ ///
+ /// \returns the API notes reader for this file, or null if there is
+ /// a failure.
+ std::unique_ptr loadAPINotes(const FileEntry *apiNotesFile);
+
+ /// Load the given API notes file for the given header directory.
+ ///
+ /// \param HeaderDir The directory at which we
+ ///
+ /// \returns true if an error occurred.
+ bool loadAPINotes(const DirectoryEntry *HeaderDir,
+ const FileEntry *APINotesFile);
+
+ /// Look for API notes in the given directory.
+ ///
+ /// This might find either a binary or source API notes.
+ const FileEntry *findAPINotesFile(const DirectoryEntry *directory,
+ StringRef filename,
+ bool wantPublic = true);
+
+ /// Attempt to load API notes for the given framework.
+ ///
+ /// \param FrameworkPath The path to the framework.
+ /// \param Public Whether to load the public API notes. Otherwise, attempt
+ /// to load the private API notes.
+ ///
+ /// \returns the header directory entry (e.g., for Headers or PrivateHeaders)
+ /// for which the API notes were successfully loaded, or NULL if API notes
+ /// could not be loaded for any reason.
+ const DirectoryEntry *loadFrameworkAPINotes(llvm::StringRef FrameworkPath,
+ llvm::StringRef FrameworkName,
+ bool Public);
+
+public:
+ APINotesManager(SourceManager &sourceMgr, const LangOptions &langOpts);
+ ~APINotesManager();
+
+ /// Set the Swift version to use when filtering API notes.
+ void setSwiftVersion(llvm::VersionTuple swiftVersion) {
+ SwiftVersion = swiftVersion;
+ }
+
+ /// Load the API notes for the current module.
+ ///
+ /// \param module The current module.
+ /// \param lookInModule Whether to look inside the module itself.
+ /// \param searchPaths The paths in which we should search for API notes
+ /// for the current module.
+ ///
+ /// \returns true if API notes were successfully loaded, \c false otherwise.
+ bool loadCurrentModuleAPINotes(const Module *module,
+ bool lookInModule,
+ ArrayRef searchPaths);
+
+ /// Retrieve the set of API notes readers for the current module.
+ ArrayRef getCurrentModuleReaders() const {
+ unsigned numReaders = static_cast(CurrentModuleReaders[0] != nullptr) +
+ static_cast(CurrentModuleReaders[1] != nullptr);
+ return llvm::makeArrayRef(CurrentModuleReaders).slice(0, numReaders);
+ }
+
+ /// Find the API notes readers that correspond to the given source location.
+ llvm::SmallVector findAPINotes(SourceLocation Loc);
+};
+
+} // end namespace api_notes
+} // end namespace clang
+
+#endif
diff --git a/clang/include/clang/APINotes/APINotesOptions.h b/clang/include/clang/APINotes/APINotesOptions.h
new file mode 100644
index 0000000000000..4c15e7fc56e15
--- /dev/null
+++ b/clang/include/clang/APINotes/APINotesOptions.h
@@ -0,0 +1,40 @@
+//===--- APINotesOptions.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 defines the APINotesOptions class.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_APINOTES_APINOTESOPTIONS_H
+#define LLVM_CLANG_APINOTES_APINOTESOPTIONS_H
+
+#include
+#include
+#include "llvm/Support/VersionTuple.h"
+
+namespace clang {
+
+/// APINotesOptions - Track various options which control how API
+/// notes are found and handled.
+class APINotesOptions {
+public:
+ /// The Swift version which should be used for API notes.
+ llvm::VersionTuple SwiftVersion;
+
+ /// The set of search paths where we API notes can be found for
+ /// particular modules.
+ ///
+ /// The API notes in this directory are stored as .apinotes,
+ /// and are only applied when building the module .
+ std::vector ModuleSearchPaths;
+};
+
+} // end namespace clang
+
+#endif
diff --git a/clang/include/clang/APINotes/APINotesReader.h b/clang/include/clang/APINotes/APINotesReader.h
new file mode 100644
index 0000000000000..f3ad7533b6b3f
--- /dev/null
+++ b/clang/include/clang/APINotes/APINotesReader.h
@@ -0,0 +1,214 @@
+//===--- APINotesReader.h - API Notes Reader ----------------------*- 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 \c APINotesReader class that reads source
+// API notes data providing additional information about source code as
+// a separate input, such as the non-nil/nilable annotations for
+// method parameters.
+//
+//===----------------------------------------------------------------------===//
+#ifndef LLVM_CLANG_API_NOTES_READER_H
+#define LLVM_CLANG_API_NOTES_READER_H
+
+#include "clang/APINotes/Types.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/VersionTuple.h"
+#include
+
+namespace clang {
+namespace api_notes {
+
+/// A class that reads API notes data from a binary file that was written by
+/// the \c APINotesWriter.
+class APINotesReader {
+ class Implementation;
+
+ Implementation &Impl;
+
+ APINotesReader(llvm::MemoryBuffer *inputBuffer, bool ownsInputBuffer,
+ llvm::VersionTuple swiftVersion, bool &failed);
+
+public:
+ /// Create a new API notes reader from the given member buffer, which
+ /// contains the contents of a binary API notes file.
+ ///
+ /// \returns the new API notes reader, or null if an error occurred.
+ static std::unique_ptr
+ get(std::unique_ptr inputBuffer,
+ llvm::VersionTuple swiftVersion);
+
+ /// Create a new API notes reader from the given member buffer, which
+ /// contains the contents of a binary API notes file.
+ ///
+ /// \returns the new API notes reader, or null if an error occurred.
+ static std::unique_ptr
+ getUnmanaged(llvm::MemoryBuffer *inputBuffer,
+ llvm::VersionTuple swiftVersion);
+
+ ~APINotesReader();
+
+ APINotesReader(const APINotesReader &) = delete;
+ APINotesReader &operator=(const APINotesReader &) = delete;
+
+ /// Retrieve the name of the module for which this reader is providing API
+ /// notes.
+ StringRef getModuleName() const;
+
+ /// Retrieve the size and modification time of the source file from
+ /// which this API notes file was created, if known.
+ Optional> getSourceFileSizeAndModTime() const;
+
+ /// Retrieve the module options
+ ModuleOptions getModuleOptions() const;
+
+ /// Captures the completed versioned information for a particular part of
+ /// API notes, including both unversioned API notes and each versioned API
+ /// note for that particular entity.
+ template
+ class VersionedInfo {
+ /// The complete set of results.
+ SmallVector, 1> Results;
+
+ /// The index of the result that is the "selected" set based on the desired
+ /// Swift version, or \c Results.size() if nothing matched.
+ unsigned Selected;
+
+ public:
+ /// Form an empty set of versioned information.
+ VersionedInfo(llvm::NoneType) : Selected(0) { }
+
+ /// Form a versioned info set given the desired version and a set of
+ /// results.
+ VersionedInfo(llvm::VersionTuple version,
+ SmallVector, 1> results);
+
+ /// Determine whether there is a result that should be applied directly
+ /// to the AST.
+ explicit operator bool() const { return Selected != size(); }
+
+ /// Retrieve the information to apply directly to the AST.
+ const T& operator*() const {
+ assert(*this && "No result to apply directly");
+ return (*this)[Selected].second;
+ }
+
+ /// Retrieve the selected index in the result set.
+ Optional getSelected() const {
+ if (Selected == Results.size()) return None;
+ return Selected;
+ }
+
+ /// Return the number of versioned results we know about.
+ unsigned size() const { return Results.size(); }
+
+ /// Access all versioned results.
+ const std::pair *begin() const { return Results.begin(); }
+ const std::pair *end() const { return Results.end(); }
+
+ /// Access a specific versioned result.
+ const std::pair &operator[](unsigned index) const {
+ return Results[index];
+ }
+ };
+
+ /// Look for the context ID of the given Objective-C class.
+ ///
+ /// \param name The name of the class we're looking for.
+ ///
+ /// \returns The ID, if known.
+ Optional lookupObjCClassID(StringRef name);
+
+ /// Look for information regarding the given Objective-C class.
+ ///
+ /// \param name The name of the class we're looking for.
+ ///
+ /// \returns The information about the class, if known.
+ VersionedInfo lookupObjCClassInfo(StringRef name);
+
+ /// Look for the context ID of the given Objective-C protocol.
+ ///
+ /// \param name The name of the protocol we're looking for.
+ ///
+ /// \returns The ID of the protocol, if known.
+ Optional lookupObjCProtocolID(StringRef name);
+
+ /// Look for information regarding the given Objective-C protocol.
+ ///
+ /// \param name The name of the protocol we're looking for.
+ ///
+ /// \returns The information about the protocol, if known.
+ VersionedInfo lookupObjCProtocolInfo(StringRef name);
+
+ /// Look for information regarding the given Objective-C property in
+ /// the given context.
+ ///
+ /// \param contextID The ID that references the context we are looking for.
+ /// \param name The name of the property we're looking for.
+ /// \param isInstance Whether we are looking for an instance property (vs.
+ /// a class property).
+ ///
+ /// \returns Information about the property, if known.
+ VersionedInfo lookupObjCProperty(ContextID contextID,
+ StringRef name,
+ bool isInstance);
+
+ /// Look for information regarding the given Objective-C method in
+ /// the given context.
+ ///
+ /// \param contextID The ID that references the context we are looking for.
+ /// \param selector The selector naming the method we're looking for.
+ /// \param isInstanceMethod Whether we are looking for an instance method.
+ ///
+ /// \returns Information about the method, if known.
+ VersionedInfo lookupObjCMethod(ContextID contextID,
+ ObjCSelectorRef selector,
+ bool isInstanceMethod);
+
+ /// Look for information regarding the given global variable.
+ ///
+ /// \param name The name of the global variable.
+ ///
+ /// \returns information about the global variable, if known.
+ VersionedInfo lookupGlobalVariable(StringRef name);
+
+ /// Look for information regarding the given global function.
+ ///
+ /// \param name The name of the global function.
+ ///
+ /// \returns information about the global function, if known.
+ VersionedInfo lookupGlobalFunction(StringRef name);
+
+ /// Look for information regarding the given enumerator.
+ ///
+ /// \param name The name of the enumerator.
+ ///
+ /// \returns information about the enumerator, if known.
+ VersionedInfo lookupEnumConstant(StringRef name);
+
+ /// Look for information regarding the given tag
+ /// (struct/union/enum/C++ class).
+ ///
+ /// \param name The name of the tag.
+ ///
+ /// \returns information about the tag, if known.
+ VersionedInfo lookupTag(StringRef name);
+
+ /// Look for information regarding the given typedef.
+ ///
+ /// \param name The name of the typedef.
+ ///
+ /// \returns information about the typedef, if known.
+ VersionedInfo lookupTypedef(StringRef name);
+};
+
+} // end namespace api_notes
+} // end namespace clang
+
+#endif // LLVM_CLANG_API_NOTES_READER_H
diff --git a/clang/include/clang/APINotes/APINotesWriter.h b/clang/include/clang/APINotes/APINotesWriter.h
new file mode 100644
index 0000000000000..222f33b728a13
--- /dev/null
+++ b/clang/include/clang/APINotes/APINotesWriter.h
@@ -0,0 +1,126 @@
+//===--- APINotesWriter.h - API Notes Writer ----------------------*- 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 \c APINotesWriter class that writes out source
+// API notes data providing additional information about source code as
+// a separate input, such as the non-nil/nilable annotations for
+// method parameters.
+//
+//===----------------------------------------------------------------------===//
+#ifndef LLVM_CLANG_API_NOTES_WRITER_H
+#define LLVM_CLANG_API_NOTES_WRITER_H
+
+#include "clang/APINotes/Types.h"
+#include "llvm/Support/VersionTuple.h"
+
+namespace llvm {
+ class raw_ostream;
+}
+
+namespace clang {
+
+class FileEntry;
+
+namespace api_notes {
+
+/// A class that writes API notes data to a binary representation that can be
+/// read by the \c APINotesReader.
+class APINotesWriter {
+ class Implementation;
+ Implementation &Impl;
+
+public:
+ /// Create a new API notes writer with the given module name and
+ /// (optional) source file.
+ APINotesWriter(StringRef moduleName, const FileEntry *sourceFile);
+ ~APINotesWriter();
+
+ APINotesWriter(const APINotesWriter &) = delete;
+ APINotesWriter &operator=(const APINotesWriter &) = delete;
+
+ /// Write the API notes data to the given stream.
+ void writeToStream(llvm::raw_ostream &os);
+
+ /// Add information about a specific Objective-C class or protocol.
+ ///
+ /// \param name The name of this class/protocol.
+ /// \param isClass Whether this is a class (vs. a protocol).
+ /// \param info Information about this class/protocol.
+ ///
+ /// \returns the ID of the class or protocol, which can be used to add
+ /// properties and methods to the class/protocol.
+ ContextID addObjCContext(StringRef name, bool isClass,
+ const ObjCContextInfo &info,
+ llvm::VersionTuple swiftVersion);
+
+ /// Add information about a specific Objective-C property.
+ ///
+ /// \param contextID The context in which this property resides.
+ /// \param name The name of this property.
+ /// \param info Information about this property.
+ void addObjCProperty(ContextID contextID, StringRef name,
+ bool isInstanceProperty,
+ const ObjCPropertyInfo &info,
+ llvm::VersionTuple swiftVersion);
+
+ /// Add information about a specific Objective-C method.
+ ///
+ /// \param contextID The context in which this method resides.
+ /// \param selector The selector that names this method.
+ /// \param isInstanceMethod Whether this method is an instance method
+ /// (vs. a class method).
+ /// \param info Information about this method.
+ void addObjCMethod(ContextID contextID, ObjCSelectorRef selector,
+ bool isInstanceMethod, const ObjCMethodInfo &info,
+ llvm::VersionTuple swiftVersion);
+
+ /// Add information about a global variable.
+ ///
+ /// \param name The name of this global variable.
+ /// \param info Information about this global variable.
+ void addGlobalVariable(StringRef name, const GlobalVariableInfo &info,
+ llvm::VersionTuple swiftVersion);
+
+ /// Add information about a global function.
+ ///
+ /// \param name The name of this global function.
+ /// \param info Information about this global function.
+ void addGlobalFunction(StringRef name, const GlobalFunctionInfo &info,
+ llvm::VersionTuple swiftVersion);
+
+ /// Add information about an enumerator.
+ ///
+ /// \param name The name of this enumerator.
+ /// \param info Information about this enumerator.
+ void addEnumConstant(StringRef name, const EnumConstantInfo &info,
+ llvm::VersionTuple swiftVersion);
+
+ /// Add information about a tag (struct/union/enum/C++ class).
+ ///
+ /// \param name The name of this tag.
+ /// \param info Information about this tag.
+ void addTag(StringRef name, const TagInfo &info,
+ llvm::VersionTuple swiftVersion);
+
+ /// Add information about a typedef.
+ ///
+ /// \param name The name of this typedef.
+ /// \param info Information about this typedef.
+ void addTypedef(StringRef name, const TypedefInfo &info,
+ llvm::VersionTuple swiftVersion);
+
+ /// Add module options
+ void addModuleOptions(ModuleOptions opts);
+};
+
+} // end namespace api_notes
+} // end namespace clang
+
+#endif // LLVM_CLANG_API_NOTES_WRITER_H
+
diff --git a/clang/include/clang/APINotes/APINotesYAMLCompiler.h b/clang/include/clang/APINotes/APINotesYAMLCompiler.h
new file mode 100644
index 0000000000000..fa991d3a3d0fc
--- /dev/null
+++ b/clang/include/clang/APINotes/APINotesYAMLCompiler.h
@@ -0,0 +1,49 @@
+//=== APINotesYAMLCompiler.h - API Notes YAML to binary compiler *- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file reads sidecar API notes specified in YAML format.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_API_NOTES_YAML_COMPILER_H
+#define LLVM_CLANG_API_NOTES_YAML_COMPILER_H
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/SourceMgr.h"
+#include
+
+namespace llvm {
+ class raw_ostream;
+ class MemoryBuffer;
+}
+
+namespace clang {
+
+class FileEntry;
+
+namespace api_notes {
+
+ enum class ActionType {
+ None,
+ YAMLToBinary,
+ BinaryToYAML,
+ Dump,
+ };
+
+ /// Converts API notes from YAML format to binary format.
+ bool compileAPINotes(llvm::StringRef yamlInput,
+ const FileEntry *sourceFile,
+ llvm::raw_ostream &os,
+ llvm::SourceMgr::DiagHandlerTy diagHandler = nullptr,
+ void *diagHandlerCtxt = nullptr);
+
+ bool parseAndDumpAPINotes(llvm::StringRef yamlInput);
+} // end namespace api_notes
+} // end namespace clang
+
+#endif // LLVM_CLANG_API_NOTES_YAML_COMPILER_H
diff --git a/clang/include/clang/APINotes/Types.h b/clang/include/clang/APINotes/Types.h
new file mode 100644
index 0000000000000..b2ca595b0c3b0
--- /dev/null
+++ b/clang/include/clang/APINotes/Types.h
@@ -0,0 +1,783 @@
+//===--- Types.h - API Notes Data Types --------------------------*- 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 data types used in the representation of API notes data.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_API_NOTES_TYPES_H
+#define LLVM_CLANG_API_NOTES_TYPES_H
+#include "clang/Basic/LLVM.h"
+#include "clang/Basic/Specifiers.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/ADT/StringRef.h"
+#include
+#include
+
+namespace clang {
+namespace api_notes {
+
+/// The file extension used for the source representation of API notes.
+static const char SOURCE_APINOTES_EXTENSION[] = "apinotes";
+
+/// Opaque context ID used to refer to an Objective-C class or protocol.
+class ContextID {
+public:
+ unsigned Value;
+
+ explicit ContextID(unsigned value) : Value(value) { }
+};
+
+enum class RetainCountConventionKind {
+ None,
+ CFReturnsRetained,
+ CFReturnsNotRetained,
+ NSReturnsRetained,
+ NSReturnsNotRetained,
+};
+
+
+/// Describes API notes data for any entity.
+///
+/// This is used as the base of all API notes.
+class CommonEntityInfo {
+public:
+ /// Message to use when this entity is unavailable.
+ std::string UnavailableMsg;
+
+ /// Whether this entity is marked unavailable.
+ unsigned Unavailable : 1;
+
+ /// Whether this entity is marked unavailable in Swift.
+ unsigned UnavailableInSwift : 1;
+
+private:
+ /// Whether SwiftPrivate was specified.
+ unsigned SwiftPrivateSpecified : 1;
+
+ /// Whether this entity is considered "private" to a Swift overlay.
+ unsigned SwiftPrivate : 1;
+
+public:
+ /// Swift name of this entity.
+ std::string SwiftName;
+
+ CommonEntityInfo()
+ : Unavailable(0), UnavailableInSwift(0), SwiftPrivateSpecified(0),
+ SwiftPrivate(0) { }
+
+ Optional isSwiftPrivate() const {
+ if (!SwiftPrivateSpecified) return None;
+ return SwiftPrivate;
+ }
+
+ void setSwiftPrivate(Optional swiftPrivate) {
+ if (swiftPrivate) {
+ SwiftPrivateSpecified = 1;
+ SwiftPrivate = *swiftPrivate;
+ } else {
+ SwiftPrivateSpecified = 0;
+ SwiftPrivate = 0;
+ }
+ }
+
+ friend bool operator==(const CommonEntityInfo &lhs,
+ const CommonEntityInfo &rhs) {
+ return lhs.UnavailableMsg == rhs.UnavailableMsg &&
+ lhs.Unavailable == rhs.Unavailable &&
+ lhs.UnavailableInSwift == rhs.UnavailableInSwift &&
+ lhs.SwiftPrivateSpecified == rhs.SwiftPrivateSpecified &&
+ lhs.SwiftPrivate == rhs.SwiftPrivate &&
+ lhs.SwiftName == rhs.SwiftName;
+ }
+
+ friend bool operator!=(const CommonEntityInfo &lhs,
+ const CommonEntityInfo &rhs) {
+ return !(lhs == rhs);
+ }
+
+ friend CommonEntityInfo &operator|=(CommonEntityInfo &lhs,
+ const CommonEntityInfo &rhs) {
+ // Merge unavailability.
+ if (rhs.Unavailable) {
+ lhs.Unavailable = true;
+ if (rhs.UnavailableMsg.length() != 0 &&
+ lhs.UnavailableMsg.length() == 0) {
+ lhs.UnavailableMsg = rhs.UnavailableMsg;
+ }
+ }
+
+ if (rhs.UnavailableInSwift) {
+ lhs.UnavailableInSwift = true;
+ if (rhs.UnavailableMsg.length() != 0 &&
+ lhs.UnavailableMsg.length() == 0) {
+ lhs.UnavailableMsg = rhs.UnavailableMsg;
+ }
+ }
+
+ if (rhs.SwiftPrivateSpecified && !lhs.SwiftPrivateSpecified) {
+ lhs.SwiftPrivateSpecified = 1;
+ lhs.SwiftPrivate = rhs.SwiftPrivate;
+ }
+
+ if (rhs.SwiftName.length() != 0 &&
+ lhs.SwiftName.length() == 0)
+ lhs.SwiftName = rhs.SwiftName;
+
+ return lhs;
+ }
+};
+
+/// Describes API notes for types.
+class CommonTypeInfo : public CommonEntityInfo {
+ /// The Swift type to which a given type is bridged.
+ ///
+ /// Reflects the swift_bridge attribute.
+ Optional SwiftBridge;
+
+ /// The NS error domain for this type.
+ Optional NSErrorDomain;
+
+public:
+ CommonTypeInfo() : CommonEntityInfo() { }
+
+ const Optional &getSwiftBridge() const { return SwiftBridge; }
+
+ void setSwiftBridge(const Optional &swiftType) {
+ SwiftBridge = swiftType;
+ }
+
+ void setSwiftBridge(const Optional &swiftType) {
+ if (swiftType)
+ SwiftBridge = *swiftType;
+ else
+ SwiftBridge = None;
+ }
+
+ const Optional &getNSErrorDomain() const {
+ return NSErrorDomain;
+ }
+
+ void setNSErrorDomain(const Optional &domain) {
+ NSErrorDomain = domain;
+ }
+
+ void setNSErrorDomain(const Optional &domain) {
+ if (domain)
+ NSErrorDomain = *domain;
+ else
+ NSErrorDomain = None;
+ }
+
+ friend CommonTypeInfo &operator|=(CommonTypeInfo &lhs,
+ const CommonTypeInfo &rhs) {
+ static_cast(lhs) |= rhs;
+ if (!lhs.SwiftBridge && rhs.SwiftBridge)
+ lhs.SwiftBridge = rhs.SwiftBridge;
+ if (!lhs.NSErrorDomain && rhs.NSErrorDomain)
+ lhs.NSErrorDomain = rhs.NSErrorDomain;
+ return lhs;
+ }
+
+ friend bool operator==(const CommonTypeInfo &lhs,
+ const CommonTypeInfo &rhs) {
+ return static_cast(lhs) == rhs &&
+ lhs.SwiftBridge == rhs.SwiftBridge &&
+ lhs.NSErrorDomain == rhs.NSErrorDomain;
+ }
+
+ friend bool operator!=(const CommonTypeInfo &lhs,
+ const CommonTypeInfo &rhs) {
+ return !(lhs == rhs);
+ }
+};
+
+/// Describes API notes data for an Objective-C class or protocol.
+class ObjCContextInfo : public CommonTypeInfo {
+ /// Whether this class has a default nullability.
+ unsigned HasDefaultNullability : 1;
+
+ /// The default nullability.
+ unsigned DefaultNullability : 2;
+
+ /// Whether this class has designated initializers recorded.
+ unsigned HasDesignatedInits : 1;
+
+ unsigned SwiftImportAsNonGenericSpecified : 1;
+ unsigned SwiftImportAsNonGeneric : 1;
+
+ unsigned SwiftObjCMembersSpecified : 1;
+ unsigned SwiftObjCMembers : 1;
+
+public:
+ ObjCContextInfo()
+ : CommonTypeInfo(),
+ HasDefaultNullability(0),
+ DefaultNullability(0),
+ HasDesignatedInits(0),
+ SwiftImportAsNonGenericSpecified(false),
+ SwiftImportAsNonGeneric(false),
+ SwiftObjCMembersSpecified(false),
+ SwiftObjCMembers(false)
+ { }
+
+ /// Determine the default nullability for properties and methods of this
+ /// class.
+ ///
+ /// \returns the default nullability, if implied, or None if there is no
+ Optional getDefaultNullability() const {
+ if (HasDefaultNullability)
+ return static_cast(DefaultNullability);
+
+ return None;
+ }
+
+ /// Set the default nullability for properties and methods of this class.
+ void setDefaultNullability(NullabilityKind kind) {
+ HasDefaultNullability = true;
+ DefaultNullability = static_cast(kind);
+ }
+
+ bool hasDesignatedInits() const { return HasDesignatedInits; }
+ void setHasDesignatedInits(bool value) { HasDesignatedInits = value; }
+
+ Optional getSwiftImportAsNonGeneric() const {
+ if (SwiftImportAsNonGenericSpecified)
+ return SwiftImportAsNonGeneric;
+ return None;
+ }
+ void setSwiftImportAsNonGeneric(Optional value) {
+ if (value.hasValue()) {
+ SwiftImportAsNonGenericSpecified = true;
+ SwiftImportAsNonGeneric = value.getValue();
+ } else {
+ SwiftImportAsNonGenericSpecified = false;
+ SwiftImportAsNonGeneric = false;
+ }
+ }
+
+ Optional getSwiftObjCMembers() const {
+ if (SwiftObjCMembersSpecified)
+ return SwiftObjCMembers;
+ return None;
+ }
+ void setSwiftObjCMembers(Optional value) {
+ SwiftObjCMembersSpecified = value.hasValue();
+ SwiftObjCMembers = value.hasValue() ? *value : false;
+ }
+
+ /// Strip off any information within the class information structure that is
+ /// module-local, such as 'audited' flags.
+ void stripModuleLocalInfo() {
+ HasDefaultNullability = false;
+ DefaultNullability = 0;
+ }
+
+ friend bool operator==(const ObjCContextInfo &lhs, const ObjCContextInfo &rhs) {
+ return static_cast(lhs) == rhs &&
+ lhs.getDefaultNullability() == rhs.getDefaultNullability() &&
+ lhs.HasDesignatedInits == rhs.HasDesignatedInits &&
+ lhs.getSwiftImportAsNonGeneric() ==
+ rhs.getSwiftImportAsNonGeneric() &&
+ lhs.getSwiftObjCMembers() == rhs.getSwiftObjCMembers();
+ }
+
+ friend bool operator!=(const ObjCContextInfo &lhs, const ObjCContextInfo &rhs) {
+ return !(lhs == rhs);
+ }
+
+ friend ObjCContextInfo &operator|=(ObjCContextInfo &lhs,
+ const ObjCContextInfo &rhs) {
+ // Merge inherited info.
+ static_cast(lhs) |= rhs;
+
+ // Merge nullability.
+ if (!lhs.getDefaultNullability()) {
+ if (auto nullable = rhs.getDefaultNullability()) {
+ lhs.setDefaultNullability(*nullable);
+ }
+ }
+
+ if (!lhs.SwiftImportAsNonGenericSpecified &&
+ rhs.SwiftImportAsNonGenericSpecified) {
+ lhs.SwiftImportAsNonGenericSpecified = true;
+ lhs.SwiftImportAsNonGeneric = rhs.SwiftImportAsNonGeneric;
+ }
+
+ if (!lhs.SwiftObjCMembersSpecified && rhs.SwiftObjCMembersSpecified) {
+ lhs.SwiftObjCMembersSpecified = true;
+ lhs.SwiftObjCMembers = rhs.SwiftObjCMembers;
+ }
+
+ lhs.HasDesignatedInits |= rhs.HasDesignatedInits;
+
+ return lhs;
+ }
+
+ void dump(llvm::raw_ostream &os);
+};
+
+/// API notes for a variable/property.
+class VariableInfo : public CommonEntityInfo {
+ /// Whether this property has been audited for nullability.
+ unsigned NullabilityAudited : 1;
+
+ /// The kind of nullability for this property. Only valid if the nullability
+ /// has been audited.
+ unsigned Nullable : 2;
+
+ /// The C type of the variable, as a string.
+ std::string Type;
+
+public:
+ VariableInfo()
+ : CommonEntityInfo(),
+ NullabilityAudited(false),
+ Nullable(0) { }
+
+ Optional getNullability() const {
+ if (NullabilityAudited)
+ return static_cast(Nullable);
+
+ return None;
+ }
+
+ void setNullabilityAudited(NullabilityKind kind) {
+ NullabilityAudited = true;
+ Nullable = static_cast(kind);
+ }
+
+ const std::string &getType() const { return Type; }
+ void setType(const std::string &type) { Type = type; }
+
+ friend bool operator==(const VariableInfo &lhs, const VariableInfo &rhs) {
+ return static_cast(lhs) == rhs &&
+ lhs.NullabilityAudited == rhs.NullabilityAudited &&
+ lhs.Nullable == rhs.Nullable &&
+ lhs.Type == rhs.Type;
+ }
+
+ friend bool operator!=(const VariableInfo &lhs, const VariableInfo &rhs) {
+ return !(lhs == rhs);
+ }
+
+ friend VariableInfo &operator|=(VariableInfo &lhs,
+ const VariableInfo &rhs) {
+ static_cast(lhs) |= rhs;
+ if (!lhs.NullabilityAudited && rhs.NullabilityAudited)
+ lhs.setNullabilityAudited(*rhs.getNullability());
+ if (lhs.Type.empty() && !rhs.Type.empty())
+ lhs.Type = rhs.Type;
+ return lhs;
+ }
+};
+
+/// Describes API notes data for an Objective-C property.
+class ObjCPropertyInfo : public VariableInfo {
+ unsigned SwiftImportAsAccessorsSpecified : 1;
+ unsigned SwiftImportAsAccessors : 1;
+
+public:
+ ObjCPropertyInfo()
+ : VariableInfo(), SwiftImportAsAccessorsSpecified(false),
+ SwiftImportAsAccessors(false) {}
+
+ /// Merge class-wide information into the given property.
+ friend ObjCPropertyInfo &operator|=(ObjCPropertyInfo &lhs,
+ const ObjCContextInfo &rhs) {
+ static_cast(lhs) |= rhs;
+
+ // Merge nullability.
+ if (!lhs.getNullability()) {
+ if (auto nullable = rhs.getDefaultNullability()) {
+ lhs.setNullabilityAudited(*nullable);
+ }
+ }
+
+ return lhs;
+ }
+
+ Optional getSwiftImportAsAccessors() const {
+ if (SwiftImportAsAccessorsSpecified)
+ return SwiftImportAsAccessors;
+ return None;
+ }
+ void setSwiftImportAsAccessors(Optional value) {
+ if (value.hasValue()) {
+ SwiftImportAsAccessorsSpecified = true;
+ SwiftImportAsAccessors = value.getValue();
+ } else {
+ SwiftImportAsAccessorsSpecified = false;
+ SwiftImportAsAccessors = false;
+ }
+ }
+
+ friend ObjCPropertyInfo &operator|=(ObjCPropertyInfo &lhs,
+ const ObjCPropertyInfo &rhs) {
+ lhs |= static_cast(rhs);
+ if (!lhs.SwiftImportAsAccessorsSpecified &&
+ rhs.SwiftImportAsAccessorsSpecified) {
+ lhs.SwiftImportAsAccessorsSpecified = true;
+ lhs.SwiftImportAsAccessors = rhs.SwiftImportAsAccessors;
+ }
+ return lhs;
+ }
+
+ friend bool operator==(const ObjCPropertyInfo &lhs,
+ const ObjCPropertyInfo &rhs) {
+ return static_cast(lhs) == rhs &&
+ lhs.getSwiftImportAsAccessors() == rhs.getSwiftImportAsAccessors();
+ }
+};
+
+/// Describes a function or method parameter.
+class ParamInfo : public VariableInfo {
+ /// Whether noescape was specified.
+ unsigned NoEscapeSpecified : 1;
+
+ /// Whether the this parameter has the 'noescape' attribute.
+ unsigned NoEscape : 1;
+
+ /// A biased RetainCountConventionKind, where 0 means "unspecified".
+ ///
+ /// Only relevant for out-parameters.
+ unsigned RawRetainCountConvention : 3;
+
+public:
+ ParamInfo() : VariableInfo(), NoEscapeSpecified(false), NoEscape(false),
+ RawRetainCountConvention() { }
+
+ Optional isNoEscape() const {
+ if (!NoEscapeSpecified) return None;
+ return NoEscape;
+ }
+ void setNoEscape(Optional noescape) {
+ if (noescape) {
+ NoEscapeSpecified = true;
+ NoEscape = *noescape;
+ } else {
+ NoEscapeSpecified = false;
+ NoEscape = false;
+ }
+ }
+
+ Optional getRetainCountConvention() const {
+ if (!RawRetainCountConvention)
+ return None;
+ return static_cast(RawRetainCountConvention - 1);
+ }
+ void setRetainCountConvention(Optional convention){
+ if (convention)
+ RawRetainCountConvention = static_cast(convention.getValue())+1;
+ else
+ RawRetainCountConvention = 0;
+ assert(getRetainCountConvention() == convention && "bitfield too small");
+ }
+
+ friend ParamInfo &operator|=(ParamInfo &lhs, const ParamInfo &rhs) {
+ static_cast(lhs) |= rhs;
+ if (!lhs.NoEscapeSpecified && rhs.NoEscapeSpecified) {
+ lhs.NoEscapeSpecified = true;
+ lhs.NoEscape = rhs.NoEscape;
+ }
+ if (!lhs.RawRetainCountConvention)
+ lhs.RawRetainCountConvention = rhs.RawRetainCountConvention;
+ return lhs;
+ }
+
+ friend bool operator==(const ParamInfo &lhs, const ParamInfo &rhs) {
+ return static_cast(lhs) == rhs &&
+ lhs.NoEscapeSpecified == rhs.NoEscapeSpecified &&
+ lhs.NoEscape == rhs.NoEscape &&
+ lhs.RawRetainCountConvention == rhs.RawRetainCountConvention;
+ }
+
+ friend bool operator!=(const ParamInfo &lhs, const ParamInfo &rhs) {
+ return !(lhs == rhs);
+ }
+};
+
+/// A temporary reference to an Objective-C selector, suitable for
+/// referencing selector data on the stack.
+///
+/// Instances of this struct do not store references to any of the
+/// data they contain; it is up to the user to ensure that the data
+/// referenced by the identifier list persists.
+struct ObjCSelectorRef {
+ unsigned NumPieces;
+ ArrayRef Identifiers;
+};
+
+/// API notes for a function or method.
+class FunctionInfo : public CommonEntityInfo {
+private:
+ static unsigned const NullabilityKindMask = 0x3;
+ static unsigned const NullabilityKindSize = 2;
+
+public:
+ /// Whether the signature has been audited with respect to nullability.
+ /// If yes, we consider all types to be non-nullable unless otherwise noted.
+ /// If this flag is not set, the pointer types are considered to have
+ /// unknown nullability.
+ unsigned NullabilityAudited : 1;
+
+ /// Number of types whose nullability is encoded with the NullabilityPayload.
+ unsigned NumAdjustedNullable : 8;
+
+ /// A biased RetainCountConventionKind, where 0 means "unspecified".
+ unsigned RawRetainCountConvention : 3;
+
+ /// Stores the nullability of the return type and the parameters.
+ // NullabilityKindSize bits are used to encode the nullability. The info
+ // about the return type is stored at position 0, followed by the nullability
+ // of the parameters.
+ uint64_t NullabilityPayload = 0;
+
+ /// The result type of this function, as a C type.
+ std::string ResultType;
+
+ /// The function parameters.
+ std::vector Params;
+
+ FunctionInfo()
+ : CommonEntityInfo(),
+ NullabilityAudited(false),
+ NumAdjustedNullable(0),
+ RawRetainCountConvention() { }
+
+ static unsigned getMaxNullabilityIndex() {
+ return ((sizeof(NullabilityPayload) * CHAR_BIT)/NullabilityKindSize);
+ }
+
+ void addTypeInfo(unsigned index, NullabilityKind kind) {
+ assert(index <= getMaxNullabilityIndex());
+ assert(static_cast(kind) < NullabilityKindMask);
+ NullabilityAudited = true;
+ if (NumAdjustedNullable < index + 1)
+ NumAdjustedNullable = index + 1;
+
+ // Mask the bits.
+ NullabilityPayload &= ~(NullabilityKindMask << (index * NullabilityKindSize));
+
+ // Set the value.
+ unsigned kindValue =
+ (static_cast(kind)) << (index * NullabilityKindSize);
+ NullabilityPayload |= kindValue;
+ }
+
+ /// Adds the return type info.
+ void addReturnTypeInfo(NullabilityKind kind) {
+ addTypeInfo(0, kind);
+ }
+
+ /// Adds the parameter type info.
+ void addParamTypeInfo(unsigned index, NullabilityKind kind) {
+ addTypeInfo(index + 1, kind);
+ }
+
+private:
+ NullabilityKind getTypeInfo(unsigned index) const {
+ assert(NullabilityAudited &&
+ "Checking the type adjustment on non-audited method.");
+ // If we don't have info about this parameter, return the default.
+ if (index > NumAdjustedNullable)
+ return NullabilityKind::NonNull;
+ return static_cast(( NullabilityPayload
+ >> (index * NullabilityKindSize) )
+ & NullabilityKindMask);
+ }
+
+public:
+ NullabilityKind getParamTypeInfo(unsigned index) const {
+ return getTypeInfo(index + 1);
+ }
+
+ NullabilityKind getReturnTypeInfo() const {
+ return getTypeInfo(0);
+ }
+
+ Optional getRetainCountConvention() const {
+ if (!RawRetainCountConvention)
+ return None;
+ return static_cast(RawRetainCountConvention - 1);
+ }
+ void setRetainCountConvention(Optional convention){
+ if (convention)
+ RawRetainCountConvention = static_cast(convention.getValue())+1;
+ else
+ RawRetainCountConvention = 0;
+ assert(getRetainCountConvention() == convention && "bitfield too small");
+ }
+
+ friend bool operator==(const FunctionInfo &lhs, const FunctionInfo &rhs) {
+ return static_cast(lhs) == rhs &&
+ lhs.NullabilityAudited == rhs.NullabilityAudited &&
+ lhs.NumAdjustedNullable == rhs.NumAdjustedNullable &&
+ lhs.NullabilityPayload == rhs.NullabilityPayload &&
+ lhs.ResultType == rhs.ResultType &&
+ lhs.Params == rhs.Params &&
+ lhs.RawRetainCountConvention == rhs.RawRetainCountConvention;
+ }
+
+ friend bool operator!=(const FunctionInfo &lhs, const FunctionInfo &rhs) {
+ return !(lhs == rhs);
+ }
+
+};
+
+/// Describes API notes data for an Objective-C method.
+class ObjCMethodInfo : public FunctionInfo {
+public:
+ /// Whether this is a designated initializer of its class.
+ unsigned DesignatedInit : 1;
+
+ /// Whether this is a required initializer.
+ unsigned Required : 1;
+
+ ObjCMethodInfo()
+ : FunctionInfo(),
+ DesignatedInit(false),
+ Required(false) { }
+
+ friend bool operator==(const ObjCMethodInfo &lhs, const ObjCMethodInfo &rhs) {
+ return static_cast(lhs) == rhs &&
+ lhs.DesignatedInit == rhs.DesignatedInit &&
+ lhs.Required == rhs.Required;
+ }
+
+ friend bool operator!=(const ObjCMethodInfo &lhs, const ObjCMethodInfo &rhs) {
+ return !(lhs == rhs);
+ }
+
+ void mergePropInfoIntoSetter(const ObjCPropertyInfo &pInfo);
+
+ void mergePropInfoIntoGetter(const ObjCPropertyInfo &pInfo);
+
+ /// Merge class-wide information into the given method.
+ friend ObjCMethodInfo &operator|=(ObjCMethodInfo &lhs,
+ const ObjCContextInfo &rhs) {
+ // Merge nullability.
+ if (!lhs.NullabilityAudited) {
+ if (auto nullable = rhs.getDefaultNullability()) {
+ lhs.NullabilityAudited = true;
+ lhs.addTypeInfo(0, *nullable);
+ }
+ }
+
+ return lhs;
+ }
+
+ void dump(llvm::raw_ostream &os);
+};
+
+/// Describes API notes data for a global variable.
+class GlobalVariableInfo : public VariableInfo {
+public:
+ GlobalVariableInfo() : VariableInfo() { }
+};
+
+/// Describes API notes data for a global function.
+class GlobalFunctionInfo : public FunctionInfo {
+public:
+ GlobalFunctionInfo() : FunctionInfo() { }
+};
+
+/// Describes API notes data for an enumerator.
+class EnumConstantInfo : public CommonEntityInfo {
+public:
+ EnumConstantInfo() : CommonEntityInfo() { }
+};
+
+/// The payload for an enum_extensibility attribute. This is a tri-state rather
+/// than just a boolean because the presence of the attribute indicates
+/// auditing.
+enum class EnumExtensibilityKind {
+ None,
+ Open,
+ Closed,
+};
+
+/// Describes API notes data for a tag.
+class TagInfo : public CommonTypeInfo {
+ unsigned HasFlagEnum : 1;
+ unsigned IsFlagEnum : 1;
+public:
+ Optional EnumExtensibility;
+
+ Optional isFlagEnum() const {
+ if (HasFlagEnum)
+ return IsFlagEnum;
+ return None;
+ }
+ void setFlagEnum(Optional Value) {
+ if (Value.hasValue()) {
+ HasFlagEnum = true;
+ IsFlagEnum = Value.getValue();
+ } else {
+ HasFlagEnum = false;
+ }
+ }
+
+ TagInfo() : CommonTypeInfo(), HasFlagEnum(0), IsFlagEnum(0) { }
+
+ friend TagInfo &operator|=(TagInfo &lhs, const TagInfo &rhs) {
+ lhs |= static_cast(rhs);
+ if (!lhs.HasFlagEnum && rhs.HasFlagEnum) {
+ lhs.HasFlagEnum = true;
+ lhs.IsFlagEnum = rhs.IsFlagEnum;
+ }
+ if (!lhs.EnumExtensibility.hasValue() && rhs.EnumExtensibility.hasValue())
+ lhs.EnumExtensibility = rhs.EnumExtensibility;
+ return lhs;
+ }
+
+ friend bool operator==(const TagInfo &lhs, const TagInfo &rhs) {
+ return static_cast(lhs) == rhs &&
+ lhs.isFlagEnum() == rhs.isFlagEnum() &&
+ lhs.EnumExtensibility == rhs.EnumExtensibility;
+ }
+};
+
+/// The kind of a swift_wrapper/swift_newtype.
+enum class SwiftWrapperKind {
+ None,
+ Struct,
+ Enum
+};
+
+/// Describes API notes data for a typedef.
+class TypedefInfo : public CommonTypeInfo {
+public:
+ Optional SwiftWrapper;
+
+ TypedefInfo() : CommonTypeInfo() { }
+
+ friend TypedefInfo &operator|=(TypedefInfo &lhs, const TypedefInfo &rhs) {
+ lhs |= static_cast(rhs);
+ if (!lhs.SwiftWrapper.hasValue() && rhs.SwiftWrapper.hasValue())
+ lhs.SwiftWrapper = rhs.SwiftWrapper;
+ return lhs;
+ }
+
+ friend bool operator==(const TypedefInfo &lhs, const TypedefInfo &rhs) {
+ return static_cast(lhs) == rhs &&
+ lhs.SwiftWrapper == rhs.SwiftWrapper;
+ }
+};
+
+/// Descripts a series of options for a module
+struct ModuleOptions {
+ bool SwiftInferImportAsMember = false;
+};
+
+} // end namespace api_notes
+} // end namespace clang
+
+#endif // LLVM_CLANG_API_NOTES_TYPES_H
diff --git a/clang/include/clang/AST/ASTContext.h b/clang/include/clang/AST/ASTContext.h
index d5ade9340c8eb..e4a7617bbd174 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -1143,6 +1143,9 @@ class ASTContext : public RefCountedBase {
/// space.
QualType removeAddrSpaceQualType(QualType T) const;
+ /// Return the "other" type-specific discriminator for the given type.
+ uint16_t getPointerAuthTypeDiscriminator(QualType T);
+
/// Apply Objective-C protocol qualifiers to the given type.
/// \param allowOnPointerType specifies if we can apply protocol
/// qualifiers on ObjCObjectPointerType. It can be set to true when
@@ -1992,6 +1995,16 @@ class ASTContext : public RefCountedBase {
return getQualifiedType(type.getUnqualifiedType(), Qs);
}
+ /// \brief Return a type with the given __ptrauth qualifier.
+ QualType getPointerAuthType(QualType type, PointerAuthQualifier pointerAuth) {
+ assert(!type.getPointerAuth());
+ assert(pointerAuth);
+
+ Qualifiers qs;
+ qs.setPointerAuth(pointerAuth);
+ return getQualifiedType(type, qs);
+ }
+
unsigned char getFixedPointScale(QualType Ty) const;
unsigned char getFixedPointIBits(QualType Ty) const;
FixedPointSemantics getFixedPointSemantics(QualType Ty) const;
diff --git a/clang/include/clang/AST/AbstractBasicReader.h b/clang/include/clang/AST/AbstractBasicReader.h
index d7b3a9da88ec2..1ee63d0640ca0 100644
--- a/clang/include/clang/AST/AbstractBasicReader.h
+++ b/clang/include/clang/AST/AbstractBasicReader.h
@@ -178,9 +178,9 @@ class DataStreamBasicReader : public BasicReaderBase {
}
Qualifiers readQualifiers() {
- static_assert(sizeof(Qualifiers().getAsOpaqueValue()) <= sizeof(uint32_t),
+ static_assert(sizeof(Qualifiers().getAsOpaqueValue()) <= sizeof(uint64_t),
"update this if the value size changes");
- uint32_t value = asImpl().readUInt32();
+ uint64_t value = asImpl().readUInt64();
return Qualifiers::fromOpaqueValue(value);
}
diff --git a/clang/include/clang/AST/AbstractBasicWriter.h b/clang/include/clang/AST/AbstractBasicWriter.h
index 0a6730c86bbfe..f16add0c96cd1 100644
--- a/clang/include/clang/AST/AbstractBasicWriter.h
+++ b/clang/include/clang/AST/AbstractBasicWriter.h
@@ -164,9 +164,9 @@ class DataStreamBasicWriter : public BasicWriterBase {
}
void writeQualifiers(Qualifiers value) {
- static_assert(sizeof(value.getAsOpaqueValue()) <= sizeof(uint32_t),
+ static_assert(sizeof(value.getAsOpaqueValue()) <= sizeof(uint64_t),
"update this if the value size changes");
- asImpl().writeUInt32(value.getAsOpaqueValue());
+ asImpl().writeUInt64(value.getAsOpaqueValue());
}
void writeExceptionSpecInfo(
diff --git a/clang/include/clang/AST/Attr.h b/clang/include/clang/AST/Attr.h
index bbaa46363d971..eaa9eb40ab1c8 100644
--- a/clang/include/clang/AST/Attr.h
+++ b/clang/include/clang/AST/Attr.h
@@ -24,6 +24,7 @@
#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/Sanitizers.h"
#include "clang/Basic/SourceLocation.h"
+#include "llvm/ADT/PointerEmbeddedInt.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/VersionTuple.h"
diff --git a/clang/include/clang/AST/AttrIterator.h b/clang/include/clang/AST/AttrIterator.h
index 78ce9314a2bba..ad87e142a2167 100644
--- a/clang/include/clang/AST/AttrIterator.h
+++ b/clang/include/clang/AST/AttrIterator.h
@@ -95,6 +95,8 @@ class specific_attr_iterator {
specific_attr_iterator Right) {
return !(Left == Right);
}
+
+ Iterator getCurrent() const { return Current; }
};
template
diff --git a/clang/include/clang/AST/Decl.h b/clang/include/clang/AST/Decl.h
index cd97c6dcf8d5c..10beb79071e85 100644
--- a/clang/include/clang/AST/Decl.h
+++ b/clang/include/clang/AST/Decl.h
@@ -3716,6 +3716,7 @@ class RecordDecl : public TagDecl {
// to save some space. Use the provided accessors to access it.
public:
friend class DeclContext;
+ friend class ASTDeclReader;
/// Enum that represents the different ways arguments are passed to and
/// returned from function calls. This takes into account the target-specific
/// and version-specific rules along with the rules determined by the
@@ -3960,9 +3961,19 @@ class RecordDecl : public TagDecl {
/// nullptr is returned if no named data member exists.
const FieldDecl *findFirstNamedDataMember() const;
+ /// Get precomputed ODRHash or add a new one.
+ unsigned getODRHash();
+
private:
/// Deserialize just the fields.
void LoadFieldsFromExternalStorage() const;
+
+ /// True if a valid hash is stored in ODRHash.
+ bool hasODRHash() const { return RecordDeclBits.HasODRHash; }
+ void setHasODRHash(bool Hash = true) { RecordDeclBits.HasODRHash = Hash; }
+
+ /// Store the ODR hash for this decl.
+ unsigned ODRHash;
};
class FileScopeAsmDecl : public Decl {
diff --git a/clang/include/clang/AST/DeclBase.h b/clang/include/clang/AST/DeclBase.h
index 91c372585b071..badf688aeba8d 100644
--- a/clang/include/clang/AST/DeclBase.h
+++ b/clang/include/clang/AST/DeclBase.h
@@ -1452,10 +1452,13 @@ class DeclContext {
/// Represents the way this type is passed to a function.
uint64_t ArgPassingRestrictions : 2;
+
+ /// True if a valid hash is stored in ODRHash.
+ uint64_t HasODRHash : 1;
};
/// Number of non-inherited bits in RecordDeclBitfields.
- enum { NumRecordDeclBits = 14 };
+ enum { NumRecordDeclBits = 15 };
/// Stores the bits used by OMPDeclareReductionDecl.
/// If modified NumOMPDeclareReductionDeclBits and the accessor
diff --git a/clang/include/clang/AST/DeclObjC.h b/clang/include/clang/AST/DeclObjC.h
index b98aef6b499d4..8372747b1c1d4 100644
--- a/clang/include/clang/AST/DeclObjC.h
+++ b/clang/include/clang/AST/DeclObjC.h
@@ -917,6 +917,11 @@ class ObjCPropertyDecl : public NamedDecl {
return Assign;
}
+ /// Return true if this property has an explicitly specified getter name.
+ bool hasExplicitGetterName() const {
+ return (PropertyAttributes & OBJC_PR_getter);
+ }
+
Selector getGetterName() const { return GetterName; }
SourceLocation getGetterNameLoc() const { return GetterNameLoc; }
@@ -925,6 +930,11 @@ class ObjCPropertyDecl : public NamedDecl {
GetterNameLoc = Loc;
}
+ /// Return true if this property has an explicitly specified setter name.
+ bool hasExplicitSetterName() const {
+ return (PropertyAttributes & OBJC_PR_setter);
+ }
+
Selector getSetterName() const { return SetterName; }
SourceLocation getSetterNameLoc() const { return SetterNameLoc; }
@@ -2743,17 +2753,25 @@ raw_ostream &operator<<(raw_ostream &OS, const ObjCImplementationDecl &ID);
class ObjCCompatibleAliasDecl : public NamedDecl {
/// Class that this is an alias of.
ObjCInterfaceDecl *AliasedClass;
+ /// The location of the name of the referenced class.
+ SourceLocation AliasedClassLoc;
+ /// The location of the '@'.
+ SourceLocation AtLoc;
- ObjCCompatibleAliasDecl(DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
- ObjCInterfaceDecl* aliasedClass)
- : NamedDecl(ObjCCompatibleAlias, DC, L, Id), AliasedClass(aliasedClass) {}
+ ObjCCompatibleAliasDecl(DeclContext *DC, SourceLocation NameLoc,
+ IdentifierInfo *Id, ObjCInterfaceDecl *AliasedClass,
+ SourceLocation AliasedClassLoc, SourceLocation AtLoc)
+ : NamedDecl(ObjCCompatibleAlias, DC, NameLoc, Id),
+ AliasedClass(AliasedClass), AliasedClassLoc(AliasedClassLoc),
+ AtLoc(AtLoc) {}
void anchor() override;
public:
- static ObjCCompatibleAliasDecl *Create(ASTContext &C, DeclContext *DC,
- SourceLocation L, IdentifierInfo *Id,
- ObjCInterfaceDecl* aliasedClass);
+ static ObjCCompatibleAliasDecl *
+ Create(ASTContext &C, DeclContext *DC, SourceLocation NameLoc,
+ IdentifierInfo *Id, ObjCInterfaceDecl *AliasedClass,
+ SourceLocation AliasedClassLoc, SourceLocation AtLoc);
static ObjCCompatibleAliasDecl *CreateDeserialized(ASTContext &C,
unsigned ID);
@@ -2762,6 +2780,17 @@ class ObjCCompatibleAliasDecl : public NamedDecl {
ObjCInterfaceDecl *getClassInterface() { return AliasedClass; }
void setClassInterface(ObjCInterfaceDecl *D) { AliasedClass = D; }
+ SourceLocation getClassInterfaceLoc() const { return AliasedClassLoc; }
+
+ void setClassInterfaceLoc(SourceLocation Loc) { AliasedClassLoc = Loc; }
+
+ SourceLocation getAtLoc() const { return AtLoc; }
+ void setAtLoc(SourceLocation Loc) { AtLoc = Loc; }
+
+ SourceRange getSourceRange() const override LLVM_READONLY {
+ return SourceRange(AtLoc, AtLoc);
+ }
+
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == ObjCCompatibleAlias; }
};
diff --git a/clang/include/clang/AST/DependentASTVisitor.h b/clang/include/clang/AST/DependentASTVisitor.h
new file mode 100644
index 0000000000000..4177344f0ae75
--- /dev/null
+++ b/clang/include/clang/AST/DependentASTVisitor.h
@@ -0,0 +1,91 @@
+//===--- DependentASTVisitor.h - Helper for dependent nodes -----*- 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 DependentASTVisitor RecursiveASTVisitor layer, which
+// is responsible for visiting unresolved symbol references.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_AST_DEPENDENT_AST_VISITOR_H
+#define LLVM_CLANG_AST_DEPENDENT_AST_VISITOR_H
+
+#include "clang/AST/DeclCXX.h"
+#include "clang/AST/DeclTemplate.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/AST/Type.h"
+
+namespace clang {
+
+// TODO: Use in the indexer.
+template
+class DependentASTVisitor : public RecursiveASTVisitor {
+private:
+ bool visitDependentReference(
+ const Type *T, const DeclarationName &Name, SourceLocation Loc,
+ llvm::function_ref Filter) {
+ if (!T)
+ return true;
+ const TemplateSpecializationType *TST =
+ T->getAs();
+ if (!TST)
+ return true;
+ TemplateName TN = TST->getTemplateName();
+ const ClassTemplateDecl *TD =
+ dyn_cast_or_null(TN.getAsTemplateDecl());
+ if (!TD)
+ return true;
+ CXXRecordDecl *RD = TD->getTemplatedDecl();
+ if (!RD->hasDefinition())
+ return true;
+ RD = RD->getDefinition();
+ std::vector Symbols =
+ RD->lookupDependentName(Name, Filter);
+ // FIXME: Improve overload handling.
+ if (Symbols.size() != 1)
+ return true;
+ if (Loc.isInvalid())
+ return true;
+ return RecursiveASTVisitor::getDerived()
+ .VisitDependentSymbolReference(Symbols[0], Loc);
+ }
+
+public:
+ bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
+ const DeclarationNameInfo &Info = E->getMemberNameInfo();
+ return visitDependentReference(
+ E->getBaseType().getTypePtrOrNull(), Info.getName(), Info.getLoc(),
+ [](const NamedDecl *D) { return D->isCXXInstanceMember(); });
+ }
+
+ bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
+ const DeclarationNameInfo &Info = E->getNameInfo();
+ const NestedNameSpecifier *NNS = E->getQualifier();
+ return visitDependentReference(
+ NNS->getAsType(), Info.getName(), Info.getLoc(),
+ [](const NamedDecl *D) { return !D->isCXXInstanceMember(); });
+ }
+
+ bool VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
+ const DependentNameType *DNT = TL.getTypePtr();
+ const NestedNameSpecifier *NNS = DNT->getQualifier();
+ DeclarationName Name(DNT->getIdentifier());
+ return visitDependentReference(
+ NNS->getAsType(), Name, TL.getNameLoc(),
+ [](const NamedDecl *ND) { return isa(ND); });
+ }
+
+ bool VisitDependentSymbolReference(const NamedDecl *Symbol,
+ SourceLocation SymbolNameLoc) {
+ return true;
+ }
+};
+
+} // end namespace clang
+
+#endif // LLVM_CLANG_AST_DEPENDENT_AST_VISITOR_H
diff --git a/clang/include/clang/AST/GlobalDecl.h b/clang/include/clang/AST/GlobalDecl.h
index 145e961a23a38..5ceb5e24f47a6 100644
--- a/clang/include/clang/AST/GlobalDecl.h
+++ b/clang/include/clang/AST/GlobalDecl.h
@@ -106,6 +106,10 @@ class GlobalDecl {
LHS.MultiVersionIndex == RHS.MultiVersionIndex;
}
+ bool operator!=(const GlobalDecl &Other) const {
+ return !(*this == Other);
+ }
+
void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
static GlobalDecl getFromOpaquePtr(void *P) {
diff --git a/clang/include/clang/AST/NestedNameSpecifier.h b/clang/include/clang/AST/NestedNameSpecifier.h
index c6fae6f465ff6..c37836cbecff6 100644
--- a/clang/include/clang/AST/NestedNameSpecifier.h
+++ b/clang/include/clang/AST/NestedNameSpecifier.h
@@ -229,6 +229,23 @@ class NestedNameSpecifier : public llvm::FoldingSetNode {
void dump() const;
void dump(llvm::raw_ostream &OS) const;
void dump(llvm::raw_ostream &OS, const LangOptions &LO) const;
+
+ /// \brief Compute the qualification required to get from the current context
+ /// (\p CurContext) to the target context (\p TargetContext).
+ ///
+ /// \param Context the AST context in which the qualification will be used.
+ ///
+ /// \param CurContext the context where an entity is being named, which is
+ /// typically based on the current scope.
+ ///
+ /// \param TargetContext the context in which the named entity actually
+ /// resides.
+ ///
+ /// \returns a nested name specifier that refers into the target context, or
+ /// NULL if no qualification is needed.
+ static NestedNameSpecifier *
+ getRequiredQualification(ASTContext &Context, const DeclContext *CurContext,
+ const DeclContext *TargetContext);
};
/// A C++ nested-name-specifier augmented with source location
diff --git a/clang/include/clang/AST/NonTrivialTypeVisitor.h b/clang/include/clang/AST/NonTrivialTypeVisitor.h
index aafcedb9d10b8..ce389178b7b22 100644
--- a/clang/include/clang/AST/NonTrivialTypeVisitor.h
+++ b/clang/include/clang/AST/NonTrivialTypeVisitor.h
@@ -93,6 +93,8 @@ struct CopiedTypeVisitor {
return asDerived().visitARCStrong(FT, std::forward(Args)...);
case QualType::PCK_ARCWeak:
return asDerived().visitARCWeak(FT, std::forward(Args)...);
+ case QualType::PCK_PtrAuth:
+ return asDerived().visitPtrAuth(FT, std::forward(Args)...);
case QualType::PCK_Struct:
return asDerived().visitStruct(FT, std::forward(Args)...);
case QualType::PCK_Trivial:
diff --git a/clang/include/clang/AST/ODRHash.h b/clang/include/clang/AST/ODRHash.h
index cd4a6f37f5db3..61c79a76ad7d4 100644
--- a/clang/include/clang/AST/ODRHash.h
+++ b/clang/include/clang/AST/ODRHash.h
@@ -55,6 +55,10 @@ class ODRHash {
// more information than the AddDecl class.
void AddCXXRecordDecl(const CXXRecordDecl *Record);
+ // Use this for ODR checking records in C/Objective-C between modules. This
+ // method compares more information than the AddDecl class.
+ void AddRecordDecl(const RecordDecl *Record);
+
// Use this for ODR checking functions between modules. This method compares
// more information than the AddDecl class. SkipBody will process the
// hash as if the function has no body.
diff --git a/clang/include/clang/AST/PrettyPrinter.h b/clang/include/clang/AST/PrettyPrinter.h
index 80eec6a5a8be3..310be3d0a51de 100644
--- a/clang/include/clang/AST/PrettyPrinter.h
+++ b/clang/include/clang/AST/PrettyPrinter.h
@@ -48,6 +48,7 @@ struct PrintingPolicy {
/// Create a default printing policy for the specified language.
PrintingPolicy(const LangOptions &LO)
: Indentation(2), SuppressSpecifiers(false),
+ SupressStorageClassSpecifiers(false),
SuppressTagKeyword(LO.CPlusPlus), IncludeTagDefinition(false),
SuppressScope(false), SuppressUnwrittenScope(false),
SuppressInitializers(false), ConstantArraySizeAsWritten(false),
@@ -59,8 +60,8 @@ struct PrintingPolicy {
PolishForDeclaration(false), Half(LO.Half),
MSWChar(LO.MicrosoftExt && !LO.WChar), IncludeNewlines(true),
MSVCFormatting(false), ConstantsAsWritten(false),
- SuppressImplicitBase(false), FullyQualifiedName(false),
- PrintCanonicalTypes(false) {}
+ SuppressImplicitBase(false), UseStdFunctionForLambda(false),
+ FullyQualifiedName(false), PrintCanonicalTypes(false) {}
/// Adjust this printing policy for cases where it's known that we're
/// printing C++ code (for instance, if AST dumping reaches a C++-only
@@ -91,6 +92,10 @@ struct PrintingPolicy {
/// "const int" type specifier and instead only print the "*y".
unsigned SuppressSpecifiers : 1;
+ /// \brief Whether we should supress the printing of the actual storage class
+ /// specifiers for the given declaration.
+ bool SupressStorageClassSpecifiers : 1;
+
/// Whether type printing should skip printing the tag keyword.
///
/// This is used when printing the inner type of elaborated types,
@@ -230,6 +235,9 @@ struct PrintingPolicy {
/// When true, don't print the implicit 'self' or 'this' expressions.
unsigned SuppressImplicitBase : 1;
+ /// \brief Whether we should use std::function<...> for lambda record types.
+ bool UseStdFunctionForLambda : 1;
+
/// When true, print the fully qualified name of function declarations.
/// This is the opposite of SuppressScope and thus overrules it.
unsigned FullyQualifiedName : 1;
diff --git a/clang/include/clang/AST/StableHash.h b/clang/include/clang/AST/StableHash.h
new file mode 100644
index 0000000000000..5c6f900a37289
--- /dev/null
+++ b/clang/include/clang/AST/StableHash.h
@@ -0,0 +1,46 @@
+//===--- StableHash.h - An ABI-stable string hash ---------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// The interface to an ABI-stable string hash algorithm.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef CLANG_AST_STABLEHASH_H
+#define CLANG_AST_STABLEHASH_H
+
+#include
+
+namespace llvm {
+class StringRef;
+}
+
+namespace clang {
+class ASTContext;
+
+/// Compute a stable 64-bit hash of the given string.
+///
+/// The exact algorithm is the little-endian interpretation of the
+/// non-doubled (i.e. 64-bit) result of applying a SipHash-2-4 using
+/// a specific key value which can be found in the source.
+///
+/// By "stable" we mean that the result of this hash algorithm will
+/// the same across different compiler versions and target platforms.
+uint64_t getStableStringHash(llvm::StringRef string);
+
+/// Compute a pointer-auth extra discriminator for the given string,
+/// suitable for both the blend operation and the __ptrauth qualifier.
+///
+/// The result of this hash will be the same across different compiler
+/// versions but may vary between targets due to differences in the
+/// range of discriminators desired by the target.
+uint64_t getPointerAuthStringDiscriminator(const ASTContext &ctx,
+ llvm::StringRef string);
+
+} // end namespace clang
+
+#endif
diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index f5955c45fafc5..78aa294f37143 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -133,6 +133,99 @@ using CanQualType = CanQual;
#define TYPE(Class, Base) class Class##Type;
#include "clang/AST/TypeNodes.inc"
+/// Pointer-authentication qualifiers.
+class PointerAuthQualifier {
+ enum {
+ EnabledShift = 0,
+ EnabledBits = 1,
+ EnabledMask = 1 << EnabledShift,
+ AddressDiscriminatedShift = EnabledShift + EnabledBits,
+ AddressDiscriminatedBits = 1,
+ AddressDiscriminatedMask = 1 << AddressDiscriminatedBits,
+ KeyShift = AddressDiscriminatedShift + AddressDiscriminatedBits,
+ KeyBits = 14,
+ KeyMask = ((1 << KeyBits) - 1) << KeyShift,
+ DiscriminatorShift = KeyShift + KeyBits,
+ DiscriminatorBits = 16
+ };
+
+ // bits: |0 |1 |2..15|16 ... 31|
+ // |Enabled|Address|Key |Discriminator|
+ uint32_t Data;
+
+public:
+ enum {
+ /// The maximum supported pointer-authentication key.
+ MaxKey = (1u << KeyBits) - 1,
+
+ /// The maximum supported pointer-authentication discriminator.
+ MaxDiscriminator = (1u << DiscriminatorBits) - 1
+ };
+
+public:
+ PointerAuthQualifier() : Data(0) {}
+ PointerAuthQualifier(unsigned key, bool isAddressDiscriminated,
+ unsigned extraDiscriminator)
+ : Data(EnabledMask
+ | (isAddressDiscriminated ? AddressDiscriminatedMask : 0)
+ | (key << KeyShift)
+ | (extraDiscriminator << DiscriminatorShift)) {
+ assert(key <= MaxKey);
+ assert(extraDiscriminator <= MaxDiscriminator);
+ }
+
+ bool isPresent() const {
+ return Data != 0;
+ }
+
+ explicit operator bool() const {
+ return isPresent();
+ }
+
+ unsigned getKey() const {
+ assert(isPresent());
+ return (Data & KeyMask) >> KeyShift;
+ }
+
+ bool isAddressDiscriminated() const {
+ assert(isPresent());
+ return (Data & AddressDiscriminatedMask) >> AddressDiscriminatedShift;
+ }
+
+ unsigned getExtraDiscriminator() const {
+ assert(isPresent());
+ return (Data >> DiscriminatorShift);
+ }
+
+ friend bool operator==(PointerAuthQualifier lhs, PointerAuthQualifier rhs) {
+ return lhs.Data == rhs.Data;
+ }
+ friend bool operator!=(PointerAuthQualifier lhs, PointerAuthQualifier rhs) {
+ return lhs.Data != rhs.Data;
+ }
+
+ uint32_t getAsOpaqueValue() const {
+ return Data;
+ }
+
+ // Deserialize pointer-auth qualifiers from an opaque representation.
+ static PointerAuthQualifier fromOpaqueValue(uint32_t opaque) {
+ PointerAuthQualifier result;
+ result.Data = opaque;
+ return result;
+ }
+
+ std::string getAsString() const;
+ std::string getAsString(const PrintingPolicy &Policy) const;
+
+ bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
+ void print(raw_ostream &OS, const PrintingPolicy &Policy) const;
+
+ void Profile(llvm::FoldingSetNodeID &ID) const {
+ ID.AddInteger(Data);
+ }
+};
+
/// The collection of all-type qualifiers we support.
/// Clang supports five independent qualifiers:
/// * C99: const, volatile, and restrict
@@ -188,6 +281,8 @@ class Qualifiers {
FastMask = (1 << FastWidth) - 1
};
+ Qualifiers() : Mask(0), PtrAuth() {}
+
/// Returns the common set of qualifiers while removing them from
/// the given sets.
static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
@@ -223,6 +318,13 @@ class Qualifiers {
L.removeAddressSpace();
R.removeAddressSpace();
}
+
+ if (L.PtrAuth == R.PtrAuth) {
+ Q.PtrAuth = L.PtrAuth;
+ L.PtrAuth = PointerAuthQualifier();
+ R.PtrAuth = PointerAuthQualifier();
+ }
+
return Q;
}
@@ -245,15 +347,16 @@ class Qualifiers {
}
// Deserialize qualifiers from an opaque representation.
- static Qualifiers fromOpaqueValue(unsigned opaque) {
+ static Qualifiers fromOpaqueValue(uint64_t opaque) {
Qualifiers Qs;
- Qs.Mask = opaque;
+ Qs.Mask = uint32_t(opaque);
+ Qs.PtrAuth = PointerAuthQualifier::fromOpaqueValue(uint32_t(opaque >> 32));
return Qs;
}
// Serialize these qualifiers into an opaque representation.
- unsigned getAsOpaqueValue() const {
- return Mask;
+ uint64_t getAsOpaqueValue() const {
+ return uint64_t(Mask) | (uint64_t(PtrAuth.getAsOpaqueValue()) << 32);
}
bool hasConst() const { return Mask & Const; }
@@ -386,6 +489,16 @@ class Qualifiers {
setAddressSpace(space);
}
+ PointerAuthQualifier getPointerAuth() const {
+ return PtrAuth;
+ }
+ void setPointerAuth(PointerAuthQualifier q) {
+ PtrAuth = q;
+ }
+ void removePtrAuth() {
+ PtrAuth = PointerAuthQualifier();
+ }
+
// Fast qualifiers are those that can be allocated directly
// on a QualType object.
bool hasFastQualifiers() const { return getFastQualifiers(); }
@@ -408,7 +521,9 @@ class Qualifiers {
/// Return true if the set contains any qualifiers which require an ExtQuals
/// node to be allocated.
- bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
+ bool hasNonFastQualifiers() const {
+ return (Mask & ~FastMask) || PtrAuth;
+ }
Qualifiers getNonFastQualifiers() const {
Qualifiers Quals = *this;
Quals.setFastQualifiers(0);
@@ -416,8 +531,8 @@ class Qualifiers {
}
/// Return true if the set contains any qualifiers.
- bool hasQualifiers() const { return Mask; }
- bool empty() const { return !Mask; }
+ bool hasQualifiers() const { return Mask || PtrAuth; }
+ bool empty() const { return !hasQualifiers(); }
/// Add the qualifiers from the given set to this set.
void addQualifiers(Qualifiers Q) {
@@ -434,6 +549,9 @@ class Qualifiers {
if (Q.hasObjCLifetime())
addObjCLifetime(Q.getObjCLifetime());
}
+
+ if (Q.PtrAuth)
+ PtrAuth = Q.PtrAuth;
}
/// Remove the qualifiers from the given set from this set.
@@ -451,6 +569,9 @@ class Qualifiers {
if (getAddressSpace() == Q.getAddressSpace())
removeAddressSpace();
}
+
+ if (PtrAuth == Q.PtrAuth)
+ PtrAuth = PointerAuthQualifier();
}
/// Add the qualifiers from the given set to this set, given that
@@ -462,7 +583,10 @@ class Qualifiers {
!hasObjCGCAttr() || !qs.hasObjCGCAttr());
assert(getObjCLifetime() == qs.getObjCLifetime() ||
!hasObjCLifetime() || !qs.hasObjCLifetime());
+ assert(!PtrAuth || !qs.PtrAuth || PtrAuth == qs.PtrAuth);
Mask |= qs.Mask;
+ if (qs.PtrAuth)
+ PtrAuth = qs.PtrAuth;
}
/// Returns true if address space A is equal to or a superset of B.
@@ -498,6 +622,8 @@ class Qualifiers {
// be changed.
(getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
!other.hasObjCGCAttr()) &&
+ // Pointer-auth qualifiers must match exactly.
+ PtrAuth == other.PtrAuth &&
// ObjC lifetime qualifiers must match exactly.
getObjCLifetime() == other.getObjCLifetime() &&
// CVR qualifiers may subset.
@@ -530,8 +656,12 @@ class Qualifiers {
/// another set of qualifiers, not considering qualifier compatibility.
bool isStrictSupersetOf(Qualifiers Other) const;
- bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
- bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
+ bool operator==(Qualifiers Other) const {
+ return Mask == Other.Mask && PtrAuth == Other.PtrAuth;
+ }
+ bool operator!=(Qualifiers Other) const {
+ return Mask != Other.Mask || PtrAuth != Other.PtrAuth;
+ }
explicit operator bool() const { return hasQualifiers(); }
@@ -569,6 +699,7 @@ class Qualifiers {
void Profile(llvm::FoldingSetNodeID &ID) const {
ID.AddInteger(Mask);
+ PtrAuth.Profile(ID);
}
private:
@@ -576,6 +707,8 @@ class Qualifiers {
// |C R V|U|GCAttr|Lifetime|AddressSpace|
uint32_t Mask = 0;
+ PointerAuthQualifier PtrAuth;
+
static const uint32_t UMask = 0x8;
static const uint32_t UShift = 3;
static const uint32_t GCAttrMask = 0x30;
@@ -1091,6 +1224,14 @@ class QualType {
// true when Type is objc's weak and weak is enabled but ARC isn't.
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
+ PointerAuthQualifier getPointerAuth() const;
+
+ bool hasAddressDiscriminatedPointerAuth() const {
+ if (auto ptrauth = getPointerAuth())
+ return ptrauth.isAddressDiscriminated();
+ return false;
+ }
+
enum PrimitiveDefaultInitializeKind {
/// The type does not fall into any of the following categories. Note that
/// this case is zero-valued so that values of this enum can be used as a
@@ -1136,6 +1277,9 @@ class QualType {
/// with the ARC __weak qualifier.
PCK_ARCWeak,
+ /// The type is an address-discriminated signed pointer type.
+ PCK_PtrAuth,
+
/// The type is a struct containing a field whose type is neither
/// PCK_Trivial nor PCK_VolatileTrivial.
/// Note that a C++ struct type does not necessarily match this; C++ copying
@@ -6345,6 +6489,11 @@ inline Qualifiers::GC QualType::getObjCGCAttr() const {
return getQualifiers().getObjCGCAttr();
}
+/// Return the pointer-auth qualifier of this type.
+inline PointerAuthQualifier QualType::getPointerAuth() const {
+ return getQualifiers().getPointerAuth();
+}
+
inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD);
diff --git a/clang/include/clang/AST/VTableBuilder.h b/clang/include/clang/AST/VTableBuilder.h
index 43c84292c0915..3a98c7ca08798 100644
--- a/clang/include/clang/AST/VTableBuilder.h
+++ b/clang/include/clang/AST/VTableBuilder.h
@@ -345,6 +345,10 @@ class VTableContextBase {
};
class ItaniumVTableContext : public VTableContextBase {
+public:
+ typedef llvm::DenseMap
+ OriginalMethodMapTy;
+
private:
/// Contains the index (relative to the vtable address point)
@@ -368,6 +372,10 @@ class ItaniumVTableContext : public VTableContextBase {
VirtualBaseClassOffsetOffsetsMapTy;
VirtualBaseClassOffsetOffsetsMapTy VirtualBaseClassOffsetOffsets;
+ /// Map from a virtual method to the nearest method in the primary base class
+ /// chain that it overrides.
+ OriginalMethodMapTy OriginalMethodMap;
+
void computeVTableRelatedInformation(const CXXRecordDecl *RD) override;
public:
@@ -399,6 +407,27 @@ class ItaniumVTableContext : public VTableContextBase {
CharUnits getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
const CXXRecordDecl *VBase);
+ /// Return the method that added the v-table slot that will be used to call
+ /// the given method.
+ ///
+ /// In the Itanium ABI, where overrides always cause methods to be added to
+ /// the primary v-table if they're not already there, this will be the first
+ /// declaration in the primary base class chain for which the return type
+ /// adjustment is trivial.
+ GlobalDecl findOriginalMethod(GlobalDecl GD);
+
+ const CXXMethodDecl *findOriginalMethodInMap(const CXXMethodDecl *MD) const;
+
+ void setOriginalMethod(const CXXMethodDecl *Key, const CXXMethodDecl *Val) {
+ OriginalMethodMap[Key] = Val;
+ }
+
+ /// This method is reserved for the implementation and shouldn't be used
+ /// directly.
+ const OriginalMethodMapTy &getOriginalMethodMap() {
+ return OriginalMethodMap;
+ }
+
static bool classof(const VTableContextBase *VT) {
return !VT->isMicrosoft();
}
diff --git a/clang/include/clang/Basic/ABI.h b/clang/include/clang/Basic/ABI.h
index 2401ffa20494e..b367bae66de90 100644
--- a/clang/include/clang/Basic/ABI.h
+++ b/clang/include/clang/Basic/ABI.h
@@ -184,7 +184,10 @@ struct ThunkInfo {
/// Holds a pointer to the overridden method this thunk is for,
/// if needed by the ABI to distinguish different thunks with equal
- /// adjustments. Otherwise, null.
+ /// adjustments.
+ /// In the Itanium ABI, this field can hold the method that created the
+ /// vtable entry for this thunk.
+ /// Otherwise, null.
/// CAUTION: In the unlikely event you need to sort ThunkInfos, consider using
/// an ABI-specific comparator.
const CXXMethodDecl *Method;
diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td
index d9ca121b6510f..f1b64849d8c03 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -101,6 +101,10 @@ def NonStaticNonConstCXXMethod
[{!S->isStatic() && !S->isConst()}],
"non-static non-const member functions">;
+def ObjCClassMethod : SubsetSubjectisInstanceMethod()}],
+ "Objective-C class methods">;
+
def ObjCInstanceMethod : SubsetSubjectisInstanceMethod()}],
"Objective-C instance methods">;
@@ -234,6 +238,9 @@ class VariadicEnumArgument values,
list Enums = enums;
}
+// Represents an attribute wrapped by another attribute.
+class AttrArgument : Argument;
+
// This handles one spelling of an attribute.
class Spelling {
string Name = name;
@@ -1777,6 +1784,12 @@ def ObjCBridgeRelated : InheritableAttr {
let Documentation = [Undocumented];
}
+def NSErrorDomain : Attr {
+ let Spellings = [GNU<"ns_error_domain">];
+ let Args = [IdentifierArgument<"ErrorDomain">];
+ let Documentation = [NSErrorDomainDocs];
+}
+
def NSReturnsRetained : DeclOrTypeAttr {
let Spellings = [Clang<"ns_returns_retained">];
// let Subjects = SubjectList<[ObjCMethod, ObjCProperty, Function]>;
@@ -1870,6 +1883,12 @@ def ObjCSubclassingRestricted : InheritableAttr {
let Documentation = [ObjCSubclassingRestrictedDocs];
}
+def ObjCCompleteDefinition : InheritableAttr {
+ let Spellings = [GNU<"objc_complete_definition">];
+ let Subjects = SubjectList<[ObjCInterface], ErrorDiag>;
+ let Documentation = [Undocumented];
+}
+
def ObjCExplicitProtocolImpl : InheritableAttr {
let Spellings = [Clang<"objc_protocol_requires_explicit_implementation">];
let Subjects = SubjectList<[ObjCProtocol], ErrorDiag>;
@@ -1999,6 +2018,101 @@ def Regparm : TypeAttr {
let ASTNode = 0;
}
+def SwiftBridge : Attr {
+ let Spellings = [GNU<"swift_bridge">];
+ let Subjects = SubjectList<[Tag, TypedefName, ObjCInterface, ObjCProtocol],
+ ErrorDiag, "ExpectedType">;
+ let Args = [StringArgument<"SwiftType">];
+ let Documentation = [SwiftBridgeDocs];
+}
+
+def SwiftBridgedTypedef : Attr {
+ let Spellings = [GNU<"swift_bridged_typedef">];
+ let Subjects = SubjectList<[TypedefName], ErrorDiag, "typedefs">;
+ let Args = [];
+ let Documentation = [SwiftBridgedTypedefDocs];
+}
+
+def SwiftObjCMembers : Attr {
+ let Spellings = [GNU<"swift_objc_members">];
+ let Subjects = SubjectList<[ObjCInterface], ErrorDiag>;
+ let Documentation = [SwiftObjCMembersDocs];
+}
+
+def SwiftError : InheritableAttr {
+ let Spellings = [GCC<"swift_error">];
+ let Args = [EnumArgument<"Convention", "ConventionKind",
+ ["none", "nonnull_error", "null_result", "zero_result", "nonzero_result"],
+ ["None", "NonNullError", "NullResult", "ZeroResult", "NonZeroResult"]>];
+ let Subjects = SubjectList<[Function, ObjCMethod], ErrorDiag>;
+ let Documentation = [SwiftErrorDocs];
+}
+
+def SwiftName : InheritableAttr {
+ let Spellings = [GCC<"swift_name">];
+ let Args = [StringArgument<"Name">];
+ // Proper subject list disabled because of the custom error needed.
+ // Let's avoid merge conflicts for now.
+// let Subjects = SubjectList<[EnumConstant, ObjCProtocol, ObjCClassMethod],
+// ErrorDiag, "ExpectedSwiftNameSubjects">;
+ let Documentation = [Undocumented];
+}
+
+def SwiftNewtype : InheritableAttr {
+ let Spellings = [GNU<"swift_newtype">, GNU<"swift_wrapper">];
+ let Subjects = SubjectList<[TypedefName], ErrorDiag, "ExpectedType">;
+ let Args = [EnumArgument<"NewtypeKind", "NewtypeKind",
+ ["struct", "enum"],
+ ["NK_Struct", "NK_Enum"]>];
+ let Documentation = [SwiftNewtypeDocs];
+}
+
+def SwiftPrivate : InheritableAttr {
+ let Spellings = [GCC<"swift_private">];
+ let Documentation = [Undocumented];
+}
+
+def SwiftImportAsNonGeneric : InheritableAttr {
+ // This attribute has no spellings as it is only ever created implicitly
+ // from API notes.
+ let Spellings = [];
+ let SemaHandler = 0;
+ let Documentation = [Undocumented];
+}
+
+def SwiftImportPropertyAsAccessors : InheritableAttr {
+ // This attribute has no spellings as it is only ever created implicitly
+ // from API notes.
+ let Spellings = [];
+ let SemaHandler = 0;
+ let Documentation = [Undocumented];
+}
+
+def SwiftVersioned : Attr {
+ // This attribute has no spellings as it is only ever created implicitly
+ // from API notes.
+ let Spellings = [];
+ let Args = [VersionArgument<"Version">, AttrArgument<"AttrToAdd">,
+ BoolArgument<"IsReplacedByActive">];
+ let SemaHandler = 0;
+ let Documentation = [Undocumented];
+}
+
+def SwiftVersionedRemoval : Attr {
+ // This attribute has no spellings as it is only ever created implicitly
+ // from API notes.
+ let Spellings = [];
+ let Args = [VersionArgument<"Version">, UnsignedArgument<"RawKind">,
+ BoolArgument<"IsReplacedByActive">];
+ let SemaHandler = 0;
+ let Documentation = [Undocumented];
+ let AdditionalMembers = [{
+ attr::Kind getAttrKindToRemove() const {
+ return static_cast(getRawKind());
+ }
+ }];
+}
+
def NoDeref : TypeAttr {
let Spellings = [Clang<"noderef">];
let Documentation = [NoDerefDocs];
@@ -2332,6 +2446,14 @@ def ObjCRequiresPropertyDefs : InheritableAttr {
let Documentation = [Undocumented];
}
+def PointerAuth : TypeAttr {
+ let Spellings = [Keyword<"__ptrauth">];
+ let Args = [IntArgument<"Key">,
+ BoolArgument<"AddressDiscriminated", 1>,
+ IntArgument<"ExtraDiscriminator", 1>];
+ let Documentation = [PtrAuthDocs];
+}
+
def Unused : InheritableAttr {
let Spellings = [CXX11<"", "maybe_unused", 201603>, GCC<"unused">,
C2x<"", "maybe_unused">];
diff --git a/clang/include/clang/Basic/AttrDocs.td b/clang/include/clang/Basic/AttrDocs.td
index 515476df3fddc..15ac3b86382b4 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -1425,6 +1425,165 @@ Also see the documentation for `@available
}];
}
+def PtrAuthDocs : Documentation {
+ let Category = DocCatVariable;
+ let Content = [{
+The ``__ptrauth`` qualifier allows the programmer to directly control
+how pointers are signed when they are stored in a particular variable.
+This can be used to strengthen the default protections of pointer
+authentication and make it more difficult for an attacker to escalate
+an ability to alter memory into full control of a process.
+
+.. code-block:: c
+
+ #include
+
+ typedef void (*my_callback)(const void*);
+ my_callback __ptrauth(ptrauth_key_process_dependent_code, 1, 0xe27a) callback;
+
+The first argument to ``__ptrauth`` is the name of the signing key.
+Valid key names for the target are defined in ````.
+
+On ARM64, there are four keys:
+
+- ``ptrauth_key_process_independent_data``
+- ``ptrauth_key_process_dependent_data``
+- ``ptrauth_key_process_independent_code``
+- ``ptrauth_key_process_dependent_code``
+
+In general, prefer using a code key for function pointers and a data key
+for object pointers. The ARM64 architecture allows loads and calls to
+execute more efficiently when the pointer is signed with an appropriate
+key. Using code keys only for function pointers also substantially lessens
+the risk of creating a so-called "signing oracle" for function pointers;
+see the general pointer authentication language documentation.
+
+Using a process-dependent key provides stronger protection against
+cross-process attacks. However, it also inhibits certain memory
+optimizations when a shared library is loaded into multiple processes.
+Using a process-independent key also allows signed pointers to be passed
+in shared memory. Note that even the process-independent keys may change
+after a reboot, so signed values should never be serialized.
+
+The second argument to ``__ptrauth`` is a flag (0 or 1) specifying whether
+the object should use address discrimination. If only one argument is
+given, the flag defaults to 0. Address discrimination provides strong
+protection against attacks which copy signed pointers around in memory.
+An attacker cannot usefully copy an arbitrary signed pointer over an
+address-discriminated object. Nor can a value taken from an
+address-discriminated object be usefully copied over some other signed
+pointer. However, it is more expensive to copy values from one
+address-discriminated object to another, even if the other arguments to
+``__ptrauth`` are the same, and it is not valid to copy them with
+``memcpy``. It is also not valid to map memory containing an
+address-discriminated object into different places in the address
+space, e.g. with ``mmap``.
+
+The third argument to ``__ptrauth`` is a small non-negative integer
+which allows additional discrimination between objects. Using a
+unique extra discriminator provides strong protection against attacks
+which work by substituting one signed value for another. For example,
+an attacker cannot usefully overwrite an object with a pointer from an
+object using a different extra discriminator; this protection is similar
+to the protection offered by address discrimination. A unique extra
+discriminator also protects against "slide" attacks where an attacker
+alters a pointer instead of altering the memory that the pointer points to.
+The extra discriminator must be a constant expression. On ARM64,
+its value must be between 0 and 65535. If the argument is not provided,
+the default value is 0. It is generally preferable not to use the value 0,
+especially with the process-independent keys, as this combination is used
+in various places in the standard language ABI.
+
+The type qualified by ``__ptrauth`` must be a pointer type. Currently
+only C pointer types are allowed and not block pointers, Objective-C
+object pointers, or C++ references. ``__ptrauth`` is parsed and interpreted
+using the same language rules as qualifiers like ``const`` and ``volatile``.
+For example:
+
+.. code-block:: c
+
+ __ptrauth(...) int *ex0; /* invalid: qualifies 'int', which is not a pointer type */
+ int * __ptrauth(...) ex1; /* valid: ex1 has qualified type */
+ int * __ptrauth(...) *ex2; /* valid: ex2 is a pointer to a qualified object */
+
+ typedef int *intp;
+ __ptrauth(...) intp ex3; /* valid: ex3 has qualified type */
+ intp __ptrauth(...) ex4; /* valid: means the exact same thing as ex3 */
+
+Assigning a non-null pointer to a ``__ptrauth``-qualified l-value, or
+initializing a ``__ptrauth``-qualified object with a non-null pointer,
+causes the pointer to be signed according to the described schema before
+being stored into memory. If such an initialization is a constant
+initialization, then the signing is also done as part of constant
+initialization: that is, it is done when the program is loaded, before
+any dynamic initialization occurs. Loading a non-null pointer from a
+``__ptrauth``-qualified l-value causes the pointer to be authenticated
+according to the describe schema before being produced as the result
+of the expression. A null pointer keeps its standard representation when
+stored in a ``__ptrauth``-qualified object; on a typical target where this
+is an all-zero pattern, this means that operations like ``bzero`` and
+``calloc`` do still correctly initialize objects with null.
+
+If a ``__ptrauth``-qualified l-value of function pointer type is
+used as the function operand of a call expression, the function pointer
+will be authenticated "atomically" with the call, such that an attacker
+will not be able to corrupt the destination of the call even in the
+presence of undefined behavior. (That is, the compiler must not
+leave an un-signed pointer that it will later unconditionally trust
+in a place where it could be feasibly overwritten by an attacker,
+such as the stack or a callee-save register during an intervening call.
+The compiler is not required to protect against improbable attacks
+such as corruption of the register file, as might occur with a
+corrupted kernel. It also need not guard against jumps to an arbitrary
+place in the instruction stream, since such jumps would require an
+attacker to already fully control the PC.)
+
+If the ABI specifies that a pointer is always signed --- that is,
+if the pointer is a function pointer and the target uses ABI function
+pointer authentication --- then signing and authenticating it as part
+of a load/store actually means resigning it to/from the standard ABI
+signature schema. Similarly, if both operands of a simple assignment
+operator are ``__ptrauth``-qualified, the pointer copied by the
+assignment is resigned from the right-hand operand's schema to the
+left-hand operand's schema. These resigning operations are also done
+"atomically" in the same sense as above.
+
+As a final guarantee, if the right-hand operand of an assignment or
+the expression used to initialize a ``__ptrauth``-qualified object is
+a direct reference to an object or function (e.g. ``&my_var``), the
+signing of that pointer is atomic with the evaluaton of the reference
+in this same sense.
+
+Otherwise, there are no guarantees of atomicity, and it is the
+programmer's responsibility to avoid allowing a store into a
+``__ptrauth``-qualified object to create a potential "signing oracle"
+which an attacker could use to sign an arbitrary pointer of their choice.
+Such oracles are particularly problematic when the signing uses a code
+key because the oracle could potentially be used to allow an attacker
+to construct a validly-signed function pointer, v-table entry, or
+return address that points to an arbitrary instruction, allowing them
+to completely take over the PC. Programmers attempting to use
+``__ptrauth`` to protect a data pointer, or to protect function pointers
+on targets that do not use ABI function pointer authentication, should
+aim to maintain a "chain of authentication" from initialization all
+the way to the point at which the pointer is used. If this is infeasible,
+they should consider using ``ptrauth_sign_generic_data`` instead.
+
+Types that are written in r-value positions, such as return types,
+parameter types, and cast types, may not be ``__ptrauth``-qualified
+at the outermost level. This may be supported in the future.
+
+In C++, the arguments to ``__ptrauth`` may not be instantiation-dependent.
+This may be supported in the future.
+
+This feature may be tested for with ``__has_feature(ptrauth_qualifier)``.
+It is enabled whenever the ``ptrauth`` intrinsics are enabled.
+
+```` provides predefined qualifiers for various language
+features that implicitly use pointer authentication.
+ }];
+}
+
def ExternalSourceSymbolDocs : Documentation {
let Category = DocCatDecl;
let Content = [{
@@ -3327,6 +3486,72 @@ where clause is one of the following:
}];
}
+def SwiftDocs : DocumentationCategory<"Controlling Swift Import"> {
+ let Content = [{
+Clang supports additional attributes for controlling how APIs are imported into Swift.
+ }];
+}
+
+def NSErrorDomainDocs : Documentation {
+ let Category = DocCatFunction;
+ let Content = [{
+The ``ns_error_domain`` attribute indicates a global constant representing the error domain.
+ }];
+}
+
+def SwiftBridgeDocs : Documentation {
+ let Category = SwiftDocs;
+ let Content = [{
+The ``swift_bridge`` attribute indicates that the type to which the attribute appertains is bridged to the named Swift type.
+ }];
+}
+
+def SwiftBridgedTypedefDocs : Documentation {
+ let Category = SwiftDocs;
+ let Content = [{
+The ``swift_bridged_typedef`` attribute indicates that, when the typedef to which the attribute appertains is imported into Swift, it should refer to the bridged Swift type (e.g., Swift's ``String``) rather than the Objective-C type as written (e.g., ``NSString``).
+ }];
+}
+
+def SwiftObjCMembersDocs : Documentation {
+ let Category = SwiftDocs;
+ let Content = [{
+The ``swift_objc_members`` attribute maps to the Swift ``@objcMembers`` attribute, which indicates that Swift members of this class, its subclasses, and all of the extensions thereof, will implicitly be exposed back to Objective-C.
+ }];
+}
+
+def SwiftErrorDocs : Documentation {
+ let Category = SwiftDocs;
+ let Heading = "swift_error";
+ let Content = [{
+The ``swift_error`` attribute controls whether a particular function (or Objective-C method) is imported into Swift as a throwing function, and if so, the dynamic convention it uses.
+
+All of these conventions except ``none`` require the function to have an error parameter. Currently, the error parameter is always the last parameter of type ``NSError**`` or ``CFErrorRef*``. Swift will remove the error parameter from the imported API, and dynamically will always pass a valid address initialized to a null pointer.
+
+* ``swift_error(none)`` means that the function should not be imported as throwing. The error parameter and result type will be left alone.
+
+* ``swift_error(null_result)`` means that calls to the function should be considered to have thrown if they return a null value. The return type must be a pointer type, and it will be imported into Swift with a non-optional type. This is the default error convention for Objective-C methods that return pointers.
+
+* ``swift_error(zero_result)`` means that calls to the function should be considered to have thrown if they return a zero result. The return type must be an integral type. If the return type would have been imported as ``Bool``, it is instead imported as ``Void``. This is the default error convention for Objective-C methods that return a type that would be imported as ``Bool``.
+
+* ``swift_error(nonzero_result)`` means that calls to the function should be considered to have thrown if they return a non-zero result. The return type must be an integral type. If the return type would have been imported as ``Bool``, it is instead imported as ``Void``.
+
+* ``swift_error(nonnull_error)`` means that calls to the function should be considered to have thrown if they leave a non-null error in the error parameter. The return type is left unmodified.
+
+}];
+}
+
+def SwiftNewtypeDocs : Documentation {
+ let Category = SwiftDocs;
+ let Heading = "swift_newtype";
+ let Content = [{
+The ``swift_newtype`` attribute indicates that the typedef to which the attribute appertains is imported as a new Swift type of the typedef's name.
+* ``swift_newtype(struct)`` means that a Swift struct will be created for this typedef.
+* ``swift_newtype(enum)`` means that a Swift enum will be created for this typedef.
+ }];
+}
+
+
def OMPDeclareTargetDocs : Documentation {
let Category = DocCatFunction;
let Heading = "#pragma omp declare target";
diff --git a/clang/include/clang/Basic/Builtins.def b/clang/include/clang/Basic/Builtins.def
index 51d3500df8aee..95a0a5ed611cb 100644
--- a/clang/include/clang/Basic/Builtins.def
+++ b/clang/include/clang/Basic/Builtins.def
@@ -1503,6 +1503,16 @@ BUILTIN(__builtin_coro_end, "bv*Ib", "n")
BUILTIN(__builtin_coro_suspend, "cIb", "n")
BUILTIN(__builtin_coro_param, "bv*v*", "n")
+// Pointer authentication builtins.
+BUILTIN(__builtin_ptrauth_strip, "v*v*i", "tnc")
+BUILTIN(__builtin_ptrauth_blend_discriminator, "zv*i", "tnc")
+BUILTIN(__builtin_ptrauth_sign_constant, "v*v*iv*", "tnc")
+BUILTIN(__builtin_ptrauth_sign_unauthenticated, "v*v*iv*", "tnc")
+BUILTIN(__builtin_ptrauth_sign_generic_data, "zv*v*", "tnc")
+BUILTIN(__builtin_ptrauth_auth_and_resign, "v*v*iv*iv*", "tn")
+BUILTIN(__builtin_ptrauth_auth, "v*v*iv*", "tn")
+BUILTIN(__builtin_ptrauth_string_discriminator, "zcC*", "nc")
+
// OpenCL v2.0 s6.13.16, s9.17.3.5 - Pipe functions.
// We need the generic prototype, since the packet type could be anything.
LANGBUILTIN(read_pipe, "i.", "tn", OCLC20_LANG)
diff --git a/clang/include/clang/Basic/CodeGenOptions.def b/clang/include/clang/Basic/CodeGenOptions.def
index 7f26ca8b4d619..b86de2b56badb 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -132,6 +132,7 @@ CODEGENOPT(IncrementalLinkerCompatible, 1, 0) ///< Emit an object file which can
///< linker.
CODEGENOPT(MergeAllConstants , 1, 1) ///< Merge identical constants.
CODEGENOPT(MergeFunctions , 1, 0) ///< Set when -fmerge-functions is enabled.
+CODEGENOPT(SplitColdCode , 1, 0) ///< Set when -fsplit-cold-code is enabled.
CODEGENOPT(MSVolatile , 1, 0) ///< Set when /volatile:ms is enabled.
CODEGENOPT(NoCommon , 1, 0) ///< Set when -fno-common or C++ is enabled.
CODEGENOPT(NoDwarfDirectoryAsm , 1, 0) ///< Set when -fno-dwarf-directory-asm is
diff --git a/clang/include/clang/Basic/CodeGenOptions.h b/clang/include/clang/Basic/CodeGenOptions.h
index 900620a39292d..c5e1c6d54eade 100644
--- a/clang/include/clang/Basic/CodeGenOptions.h
+++ b/clang/include/clang/Basic/CodeGenOptions.h
@@ -14,6 +14,7 @@
#define LLVM_CLANG_BASIC_CODEGENOPTIONS_H
#include "clang/Basic/DebugInfoOptions.h"
+#include "clang/Basic/PointerAuthOptions.h"
#include "clang/Basic/Sanitizers.h"
#include "clang/Basic/XRayInstr.h"
#include "llvm/ADT/FloatingPointMode.h"
@@ -298,6 +299,9 @@ class CodeGenOptions : public CodeGenOptionsBase {
std::vector Reciprocals;
+ /// Configuration for pointer-signing.
+ PointerAuthOptions PointerAuth;
+
/// The preferred width for auto-vectorization transforms. This is intended to
/// override default transforms based on the width of the architected vector
/// registers.
diff --git a/clang/include/clang/Basic/Diagnostic.td b/clang/include/clang/Basic/Diagnostic.td
index 48ba8c0f469f8..20e4676bf6f75 100644
--- a/clang/include/clang/Basic/Diagnostic.td
+++ b/clang/include/clang/Basic/Diagnostic.td
@@ -149,4 +149,3 @@ include "DiagnosticParseKinds.td"
include "DiagnosticRefactoringKinds.td"
include "DiagnosticSemaKinds.td"
include "DiagnosticSerializationKinds.td"
-
diff --git a/clang/include/clang/Basic/DiagnosticCommonKinds.td b/clang/include/clang/Basic/DiagnosticCommonKinds.td
index d6281f157eea7..2b8b0a6aca087 100644
--- a/clang/include/clang/Basic/DiagnosticCommonKinds.td
+++ b/clang/include/clang/Basic/DiagnosticCommonKinds.td
@@ -303,6 +303,19 @@ def note_mt_message : Note<"[rewriter] %0">;
def warn_arcmt_nsalloc_realloc : Warning<"[rewriter] call returns pointer to GC managed memory; it will become unmanaged in ARC">;
def err_arcmt_nsinvocation_ownership : Error<"NSInvocation's %0 is not safe to be used with an object with ownership other than __unsafe_unretained">;
+// API notes
+def err_apinotes_message : Error<"%0">;
+def warn_apinotes_message : Warning<"%0">, InGroup>;
+def note_apinotes_message : Note<"%0">;
+
+class NonportablePrivateAPINotesPath : Warning<
+ "private API notes file for module '%0' should be named "
+ "'%0_private.apinotes', not '%1'">;
+def warn_apinotes_private_case : NonportablePrivateAPINotesPath,
+ InGroup>;
+def warn_apinotes_private_case_system : NonportablePrivateAPINotesPath,
+ DefaultIgnore, InGroup>;
+
// C++ for OpenCL.
def err_openclcxx_not_supported : Error<
"'%0' is not supported in C++ for OpenCL">;
diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 39242c972ea28..8bb20aa84d657 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -206,6 +206,8 @@ def warn_invalid_ios_deployment_target : Warning<
"invalid iOS deployment version '%0', iOS 10 is the maximum deployment "
"target for 32-bit targets">, InGroup,
DefaultError;
+def err_invalid_macos_32bit_deployment_target : Error<
+ "32-bit targets are not supported when building for Mac Catalyst">;
def err_drv_conflicting_deployment_targets : Error<
"conflicting deployment targets, both '%0' and '%1' are present in environment">;
def err_arc_unsupported_on_runtime : Error<
@@ -237,6 +239,9 @@ def err_drv_omp_host_ir_file_not_found : Error<
"The provided host compiler IR file '%0' is required to generate code for OpenMP target regions but cannot be found.">;
def err_drv_omp_host_target_not_supported : Error<
"The target '%0' is not a supported OpenMP host target.">;
+def err_drv_ptrauth_not_supported : Error<
+ "target '%0' does not support native pointer authentication">;
+
def err_drv_expecting_fopenmp_with_fopenmp_targets : Error<
"The option -fopenmp-targets must be used in conjunction with a -fopenmp option compatible with offloading, please use -fopenmp=libomp or -fopenmp=libiomp5.">;
def warn_drv_omp_offload_target_duplicate : Warning<
diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
index a798b498d4e9a..f2efe577c5ead 100644
--- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -216,6 +216,10 @@ def err_modules_embed_file_not_found :
def err_module_header_file_not_found :
Error<"module header file '%0' not found">, DefaultFatal;
+def remark_index_producing_module_file_data : Remark<"producing index data for "
+ "module file '%0'">,
+ InGroup;
+
def err_test_module_file_extension_version : Error<
"test module file extension '%0' has different version (%1.%2) than expected "
"(%3.%4)">;
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td b/clang/include/clang/Basic/DiagnosticGroups.td
index a15fb908c5374..d5fd557271069 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -411,6 +411,7 @@ def ModuleBuild : DiagGroup<"module-build">;
def ModuleImport : DiagGroup<"module-import">;
def ModuleConflict : DiagGroup<"module-conflict">;
def ModuleFileExtension : DiagGroup<"module-file-extension">;
+def IndexStore : DiagGroup<"index-store">;
def NewlineEOF : DiagGroup<"newline-eof">;
def Nullability : DiagGroup<"nullability">;
def NullabilityDeclSpec : DiagGroup<"nullability-declspec">;
@@ -534,6 +535,7 @@ def StringCompare : DiagGroup<"string-compare">;
def StringPlusInt : DiagGroup<"string-plus-int">;
def StringPlusChar : DiagGroup<"string-plus-char">;
def StrncatSize : DiagGroup<"strncat-size">;
+def SwiftNameAttribute : DiagGroup<"swift-name-attribute">;
def IntInBoolContext : DiagGroup<"int-in-bool-context">;
def TautologicalTypeLimitCompare : DiagGroup<"tautological-type-limit-compare">;
def TautologicalUnsignedZeroCompare : DiagGroup<"tautological-unsigned-zero-compare">;
@@ -700,8 +702,7 @@ def DeallocInCategory:DiagGroup<"dealloc-in-category">;
def SelectorTypeMismatch : DiagGroup<"selector-type-mismatch">;
def Selector : DiagGroup<"selector", [SelectorTypeMismatch]>;
def Protocol : DiagGroup<"protocol">;
-// No longer in use, preserve for backwards compatibility.
-def : DiagGroup<"at-protocol">;
+def AtProtocol : DiagGroup<"at-protocol">;
def PropertyAccessDotSyntax: DiagGroup<"property-access-dot-syntax">;
def PropertyAttr : DiagGroup<"property-attribute-mismatch">;
def SuperSubClassMismatch : DiagGroup<"super-class-method-mismatch">;
@@ -717,6 +718,7 @@ def ZeroLengthArray : DiagGroup<"zero-length-array">;
def GNUZeroLineDirective : DiagGroup<"gnu-zero-line-directive">;
def GNUZeroVariadicMacroArguments : DiagGroup<"gnu-zero-variadic-macro-arguments">;
def Fallback : DiagGroup<"fallback">;
+def PtrAuthNullPointers : DiagGroup<"ptrauth-null-pointers">;
def MisleadingIndentation : DiagGroup<"misleading-indentation">;
// This covers both the deprecated case (in C++98)
diff --git a/clang/include/clang/Basic/DiagnosticIDs.h b/clang/include/clang/Basic/DiagnosticIDs.h
index 5b9391b5a4527..57f87f64ad112 100644
--- a/clang/include/clang/Basic/DiagnosticIDs.h
+++ b/clang/include/clang/Basic/DiagnosticIDs.h
@@ -29,7 +29,7 @@ namespace clang {
enum {
DIAG_SIZE_COMMON = 300,
DIAG_SIZE_DRIVER = 200,
- DIAG_SIZE_FRONTEND = 150,
+ DIAG_SIZE_FRONTEND = 151, // swift-clang has 1 extra diag
DIAG_SIZE_SERIALIZATION = 120,
DIAG_SIZE_LEX = 400,
DIAG_SIZE_PARSE = 600,
diff --git a/clang/include/clang/Basic/DiagnosticLexKinds.td b/clang/include/clang/Basic/DiagnosticLexKinds.td
index b64cbc23f8100..deab09d5b2c87 100644
--- a/clang/include/clang/Basic/DiagnosticLexKinds.td
+++ b/clang/include/clang/Basic/DiagnosticLexKinds.td
@@ -752,7 +752,7 @@ def warn_quoted_include_in_framework_header : Warning<
>, InGroup, DefaultIgnore;
def warn_framework_include_private_from_public : Warning<
"public framework header includes private framework header '%0'"
- >, InGroup;
+ >, InGroup, DefaultIgnore;
def warn_auto_module_import : Warning<
"treating #%select{include|import|include_next|__include_macros}0 as an "
diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 63221d8758fc6..8a5b1d7a97fc5 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -277,7 +277,7 @@ def err_atimport : Error<
def warn_atimport_in_framework_header : Warning<
"use of '@import' in framework header is discouraged, "
"including this header requires -fmodules">,
- InGroup;
+ InGroup, DefaultIgnore;
def err_invalid_reference_qualifier_application : Error<
"'%0' qualifier may not be applied to a reference">;
@@ -1259,6 +1259,9 @@ def err_pragma_invalid_keyword : Error<
def err_pragma_pipeline_invalid_keyword : Error<
"invalid argument; expected 'disable'">;
+// API notes.
+def err_type_unparsed : Error<"unparsed tokens following type">;
+
// Pragma unroll support.
def warn_pragma_unroll_cuda_value_in_parens : Warning<
"argument to '#pragma unroll' should not be in parentheses in CUDA C/C++">,
diff --git a/clang/include/clang/Basic/DiagnosticRefactoringKinds.td b/clang/include/clang/Basic/DiagnosticRefactoringKinds.td
index 5446b32efbdd4..0c7da26de7aef 100644
--- a/clang/include/clang/Basic/DiagnosticRefactoringKinds.td
+++ b/clang/include/clang/Basic/DiagnosticRefactoringKinds.td
@@ -30,4 +30,29 @@ def err_refactor_extract_prohibited_expression : Error<"the selected "
}
+// On github swift-clang only; to be upstreamed:
+
+let CategoryName = "Rename Issue" in {
+def err_rename_builtin_function : Error<"%0 is a builtin function that "
+ "cannot be renamed">;
+def err_rename_sys_header : Error<"%0 cannot be renamed because it is "
+ "declared in a system header">;
+def err_method_rename_override_sys_framework : Error<"method %0 cannot be "
+ "renamed because it overrides a method declared in a system framework">;
+def err_rename_external_source_symbol : Error<"%0 is declared in a %1 file; "
+ "rename can be initiated in a %1 file only">;
+}
+
+let CategoryName = "Refactoring Continuation Issue" in {
+
+def err_ref_continuation_missing_implementation : Error<
+ "no %select{implementation file|@implementation declaration}0 for the "
+ "selected %select{declaration|@interface}0 %1; please add one and run the "
+ "refactoring action again">;
+
+def err_implement_declared_methods_all_implemented : Error<
+ "the selected methods are already implemented">;
+
+}
+
} // end of Refactoring diagnostics
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index dd9649bcb5c31..47adade030b28 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -741,6 +741,56 @@ def warn_fortify_source_size_mismatch : Warning<
"'%0' size argument is too large; destination buffer has size %1,"
" but size argument is %2">, InGroup;
+def err_ptrauth_disabled_target :
+ Error<"this target does not support pointer authentication">;
+def err_ptrauth_disabled :
+ Error<"pointer authentication is disabled for the current target">;
+def err_ptrauth_invalid_key :
+ Error<"%0 does not identify a valid pointer authentication key for "
+ "the current target">;
+def err_ptrauth_value_bad_type :
+ Error<"%select{signed value|extra discriminator|blended pointer|blended "
+ "integer}0 must have %select{pointer|integer|pointer or integer}1 "
+ "type; type here is %2">;
+def err_ptrauth_bad_constant_pointer :
+ Error<"argument to ptrauth_sign_constant must refer to a global variable "
+ "or function">;
+def err_ptrauth_bad_constant_discriminator :
+ Error<"discriminator argument to ptrauth_sign_constant must be a constant "
+ "integer, the address of the global variable where the result "
+ "will be stored, or a blend of the two">;
+def warn_ptrauth_sign_null_pointer :
+ Warning<"signing a null pointer will yield a non-null pointer">,
+ InGroup;
+def warn_ptrauth_auth_null_pointer :
+ Warning<"authenticating a null pointer will almost certainly trap">,
+ InGroup;
+def err_ptrauth_string_not_literal : Error<
+ "argument must be a string literal%select{| of char type}0">;
+def err_ptrauth_type_disc_variably_modified : Error<
+ "cannot pass variably-modified type %0 to "
+ "'__builtin_ptrauth_type_discriminator'">;
+
+// __ptrauth qualifier
+def err_ptrauth_qualifier_return : Error<
+ "return types may not be qualified with __ptrauth; type is %0">;
+def err_ptrauth_qualifier_param : Error<
+ "parameter types may not be qualified with __ptrauth; type is %0">;
+def err_ptrauth_qualifier_cast : Error<
+ "cast types may not be qualified with __ptrauth; type is %0">;
+def err_ptrauth_qualifier_nonpointer : Error<
+ "__ptrauth qualifier may only be applied to pointer types; type here is %0">;
+def err_ptrauth_qualifier_redundant : Error<
+ "type %0 is already __ptrauth-qualified">;
+def err_ptrauth_qualifier_bad_arg_count : Error<
+ "__ptrauth qualifier must take between 1 and 3 arguments">;
+def err_ptrauth_qualifier_arg_not_ice : Error<
+ "argument to __ptrauth must be an integer constant expression">;
+def err_ptrauth_qualifier_address_discrimination_invalid : Error<
+ "address discrimination flag for __ptrauth must be 0 or 1; value is %0">;
+def err_ptrauth_qualifier_extra_discriminator_invalid : Error<
+ "extra discriminator for __ptrauth must between 0 and %1; value is %0">;
+
/// main()
// static main() is not an error in C, just in C++.
def warn_static_main : Warning<"'main' should not be declared static">,
@@ -911,8 +961,8 @@ def err_protocol_has_circular_dependency : Error<
"protocol has circular dependency">;
def err_undeclared_protocol : Error<"cannot find protocol declaration for %0">;
def warn_undef_protocolref : Warning<"cannot find protocol definition for %0">;
-def err_atprotocol_protocol : Error<
- "@protocol is using a forward protocol declaration of %0">;
+def warn_atprotocol_protocol : Warning<
+ "@protocol is using a forward protocol declaration of %0">, InGroup;
def warn_readonly_property : Warning<
"attribute 'readonly' of property %0 restricts attribute "
"'readwrite' of property inherited from %1">,
@@ -1331,6 +1381,12 @@ def warn_unimplemented_selector: Warning<
InGroup, DefaultIgnore;
def warn_unimplemented_protocol_method : Warning<
"method %0 in protocol %1 not implemented">, InGroup;
+def warn_class_does_not_conform_protocol : Warning<
+ "%select{class|category}0 %1 does not conform to protocol"
+ "%plural{1: %3|2:s %3 and %4|3:s %3, %4 and %5|:s %3, %4, %5, ...}2">,
+ InGroup;
+def note_add_missing_protocol_stubs : Note<
+ "add stubs for missing protocol requirements">;
def warn_multiple_selectors: Warning<
"several methods with selector %0 of mismatched types are found "
"for the @selector expression">,
@@ -3603,6 +3659,9 @@ def warn_attribute_nonnull_no_pointers : Warning<
def warn_attribute_nonnull_parm_no_args : Warning<
"'nonnull' attribute when used on parameters takes no arguments">,
InGroup;
+def warn_attribute_noescape_non_pointer : Warning<
+ "'noescape' attribute ignored on parameter of non-pointer type %0">,
+ InGroup;
def note_declared_nonnull : Note<
"declared %select{'returns_nonnull'|'nonnull'}0 here">;
def warn_attribute_sentinel_named_arguments : Warning<
@@ -3743,6 +3802,67 @@ def err_objc_bridged_related_known_method : Error<
def err_objc_attr_protocol_requires_definition : Error<
"attribute %0 can only be applied to @protocol definitions, not forward declarations">;
+// Swift attributes
+def warn_attr_swift_name_decl_kind : Warning<
+ "%0 attribute cannot be applied to this declaration">,
+ InGroup;
+def warn_attr_swift_name_function : Warning<
+ "parameter of %0 attribute must be a Swift function name string">,
+ InGroup;
+def warn_attr_swift_name_function_no_prototype : Warning<
+ "%0 attribute can only be applied to function declarations with prototypes">,
+ InGroup;
+def warn_attr_swift_name_context_name_invalid_identifier : Warning<
+ "%0 attribute has invalid identifier for context name">,
+ InGroup;
+def warn_attr_swift_name_basename_invalid_identifier : Warning<
+ "%0 attribute has invalid identifier for base name">,
+ InGroup;
+def warn_attr_swift_name_parameter_invalid_identifier : Warning<
+ "%0 attribute has invalid identifier for parameter name">,
+ InGroup;
+def warn_attr_swift_name_missing_parameters : Warning<
+ "%0 attribute is missing parameter label clause">,
+ InGroup;
+def warn_attr_swift_name_subscript_not_accessor : Warning<
+ "%0 attribute for 'subscript' must be a getter or setter">,
+ InGroup;
+def warn_attr_swift_name_subscript_no_parameter : Warning<
+ "%0 attribute for 'subscript' must take at least one parameter">,
+ InGroup;
+def warn_attr_swift_name_subscript_getter_newValue : Warning<
+ "%0 attribute for 'subscript' getter cannot take a 'newValue:' parameter">,
+ InGroup;
+def warn_attr_swift_name_subscript_setter_no_newValue : Warning<
+ "%0 attribute for 'subscript' setter must take a 'newValue:' parameter">,
+ InGroup;
+def warn_attr_swift_name_subscript_setter_multiple_newValues : Warning<
+ "%0 attribute for 'subscript' setter cannot take multiple 'newValue:' parameters">,
+ InGroup;
+def warn_attr_swift_name_getter_parameters : Warning<
+ "%0 attribute for getter must not take any parameters besides 'self:'">,
+ InGroup;
+def warn_attr_swift_name_setter_parameters : Warning<
+ "%0 attribute for setter must take one parameter for new value">,
+ InGroup;
+def warn_attr_swift_name_multiple_selfs : Warning<
+ "%0 attribute cannot specify more than one 'self:' parameter">,
+ InGroup;
+def warn_attr_swift_name_static_subscript : Warning<
+ "%0 attribute for 'subscript' must take a 'self:' parameter">,
+ InGroup;
+def warn_attr_swift_name_num_params : Warning<
+ "too %select{few|many}0 parameters in %1 attribute (expected %2; got %3)">,
+ InGroup;
+def err_attr_swift_error_no_error_parameter : Error<
+ "%0 attribute can only be applied to a %select{function|method}1 "
+ "with an error parameter">;
+def err_attr_swift_error_return_type : Error<
+ "%0 attribute with '%1' convention can only be applied to a "
+ "%select{function|method}2 returning %select{an integral type|a pointer}3">;
+def warn_swift_newtype_attribute_non_typedef : Warning<
+ "'swift_newtype' attribute may be put on a typedef only; "
+ "attribute is ignored">, InGroup>;
def warn_ignored_objc_externally_retained : Warning<
"'objc_externally_retained' can only be applied to local variables "
"%select{of retainable type|with strong ownership}0">,
@@ -4954,7 +5074,7 @@ def note_deleted_special_member_class_subobject : Note<
"%select{default|corresponding|default|default|default}4 constructor}0|"
"destructor}5"
"%select{||s||}4"
- "|is an ObjC pointer}6">;
+ "|is an ObjC pointer|has an address-discriminated ptrauth qualifier}6">;
def note_deleted_default_ctor_uninit_field : Note<
"%select{default constructor of|constructor inherited by}0 "
"%1 is implicitly deleted because field %2 of "
@@ -7406,6 +7526,19 @@ def err_typecheck_incompatible_ownership : Error<
"sending to parameter of different type}0,1"
"|%diff{casting $ to type $|casting between types}0,1}2"
" changes retain/release properties of pointer">;
+def err_typecheck_incompatible_ptrauth : Error<
+ "%select{%diff{assigning $ to $|assigning to different types}1,0"
+ "|%diff{passing $ to parameter of type $|"
+ "passing to parameter of different type}0,1"
+ "|%diff{returning $ from a function with result type $|"
+ "returning from function with different return type}0,1"
+ "|%diff{converting $ to type $|converting between types}0,1"
+ "|%diff{initializing $ with an expression of type $|"
+ "initializing with expression of different type}0,1"
+ "|%diff{sending $ to parameter of type $|"
+ "sending to parameter of different type}0,1"
+ "|%diff{casting $ to type $|casting between types}0,1}2"
+ " changes pointer-authentication of pointee type">;
def err_typecheck_comparison_of_distinct_blocks : Error<
"comparison of distinct block types%diff{ ($ and $)|}0,1">;
@@ -7708,6 +7841,8 @@ def ext_typecheck_cond_pointer_integer_mismatch : ExtWarn<
"pointer/integer type mismatch in conditional expression"
"%diff{ ($ and $)|}0,1">,
InGroup>;
+def err_typecheck_cond_incompatible_ptrauth : Error<
+ "__ptrauth qualification mismatch%diff{ ($ and $)|}0,1">;
def err_typecheck_choose_expr_requires_constant : Error<
"'__builtin_choose_expr' requires a constant expression">;
def warn_unused_expr : Warning<"expression result unused">,
@@ -8674,6 +8809,7 @@ def warn_missing_case : Warning<"%plural{"
"3:enumeration values %1, %2, and %3 not handled in switch|"
":%0 enumeration values not handled in switch: %1, %2, %3...}0">,
InGroup;
+def note_fill_in_missing_cases : Note<"add missing switch cases">;
def warn_unannotated_fallthrough : Warning<
"unannotated fall-through between switch labels">,
@@ -8976,6 +9112,14 @@ def err_nsconsumed_attribute_mismatch : Error<
def err_nsreturns_retained_attribute_mismatch : Error<
"overriding method has mismatched ns_returns_%select{not_retained|retained}0"
" attributes">;
+def err_nserrordomain_not_tagdecl : Error<
+ "ns_error_domain attribute only valid on "
+ "%select{enums, structs, and unions|enums, structs, unions, and classes}0">;
+def err_nserrordomain_invalid_decl : Error<
+ "domain argument %0 does not refer to global constant">;
+def err_nserrordomain_requires_identifier : Error<
+ "domain argument must be an identifier">;
+
def warn_nsconsumed_attribute_mismatch : Warning<
err_nsconsumed_attribute_mismatch.Text>, InGroup;
def warn_nsreturns_retained_attribute_mismatch : Warning<
@@ -9276,6 +9420,13 @@ def warn_mig_server_routine_does_not_return_kern_return_t : Warning<
InGroup;
} // end of sema category
+let CategoryName = "API Notes Issue" in {
+
+def err_incompatible_replacement_type : Error<
+ "API notes replacement type %0 has a different size from original type %1">;
+
+}
+
let CategoryName = "OpenMP Issue" in {
// OpenMP support.
def err_omp_expected_var_arg : Error<
diff --git a/clang/include/clang/Basic/Features.def b/clang/include/clang/Basic/Features.def
index 28eb694ba9a89..0f7b9b9290946 100644
--- a/clang/include/clang/Basic/Features.def
+++ b/clang/include/clang/Basic/Features.def
@@ -56,6 +56,7 @@ FEATURE(attribute_availability_app_extension, true)
FEATURE(attribute_availability_with_version_underscores, true)
FEATURE(attribute_availability_tvos, true)
FEATURE(attribute_availability_watchos, true)
+FEATURE(attribute_availability_swift, true)
FEATURE(attribute_availability_with_strict, true)
FEATURE(attribute_availability_with_replacement, true)
FEATURE(attribute_availability_in_templates, true)
@@ -82,6 +83,7 @@ FEATURE(c_thread_safety_attributes, true)
FEATURE(cxx_exceptions, LangOpts.CXXExceptions)
FEATURE(cxx_rtti, LangOpts.RTTI &&LangOpts.RTTIData)
FEATURE(enumerator_attributes, true)
+FEATURE(generalized_swift_name, true)
FEATURE(nullability, true)
FEATURE(nullability_on_arrays, true)
FEATURE(memory_sanitizer,
@@ -89,6 +91,11 @@ FEATURE(memory_sanitizer,
SanitizerKind::KernelMemory))
FEATURE(thread_sanitizer, LangOpts.Sanitize.has(SanitizerKind::Thread))
FEATURE(dataflow_sanitizer, LangOpts.Sanitize.has(SanitizerKind::DataFlow))
+FEATURE(ptrauth_intrinsics, LangOpts.PointerAuthIntrinsics)
+FEATURE(ptrauth_qualifier, LangOpts.PointerAuthIntrinsics)
+FEATURE(ptrauth_calls, LangOpts.PointerAuthCalls)
+FEATURE(ptrauth_returns, LangOpts.PointerAuthReturns)
+FEATURE(ptrauth_indirect_gotos, LangOpts.PointerAuthIndirectGotos)
FEATURE(scudo, LangOpts.Sanitize.hasOneOf(SanitizerKind::Scudo))
// Objective-C features
FEATURE(objc_arr, LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
diff --git a/clang/include/clang/Basic/IdentifierTable.h b/clang/include/clang/Basic/IdentifierTable.h
index ea5d7adeb2da6..bbdc818a6e5c4 100644
--- a/clang/include/clang/Basic/IdentifierTable.h
+++ b/clang/include/clang/Basic/IdentifierTable.h
@@ -94,10 +94,6 @@ class alignas(IdentifierInfoAlignment) IdentifierInfo {
// loaded from an AST file.
unsigned ChangedAfterLoad : 1;
- // True if the identifier's frontend information has changed from the
- // definition loaded from an AST file.
- unsigned FEChangedAfterLoad : 1;
-
// True if revertTokenIDToIdentifier was called.
unsigned RevertedTokenID : 1;
@@ -108,7 +104,7 @@ class alignas(IdentifierInfoAlignment) IdentifierInfo {
// True if this is the 'import' contextual keyword.
unsigned IsModulesImport : 1;
- // 29 bits left in a 64-bit word.
+ // 30 bits left in a 64-bit word.
// Managed by the language front-end.
void *FETokenInfo = nullptr;
@@ -120,7 +116,7 @@ class alignas(IdentifierInfoAlignment) IdentifierInfo {
HadMacro(false), IsExtension(false), IsFutureCompatKeyword(false),
IsPoisoned(false), IsCPPOperatorKeyword(false),
NeedsHandleIdentifier(false), IsFromAST(false), ChangedAfterLoad(false),
- FEChangedAfterLoad(false), RevertedTokenID(false), OutOfDate(false),
+ RevertedTokenID(false), OutOfDate(false),
IsModulesImport(false) {}
public:
@@ -333,18 +329,6 @@ class alignas(IdentifierInfoAlignment) IdentifierInfo {
ChangedAfterLoad = true;
}
- /// Determine whether the frontend token information for this
- /// identifier has changed since it was loaded from an AST file.
- bool hasFETokenInfoChangedSinceDeserialization() const {
- return FEChangedAfterLoad;
- }
-
- /// Note that the frontend token information for this identifier has
- /// changed since it was loaded from an AST file.
- void setFETokenInfoChangedSinceDeserialization() {
- FEChangedAfterLoad = true;
- }
-
/// Determine whether the information for this identifier is out of
/// date with respect to the external source.
bool isOutOfDate() const { return OutOfDate; }
diff --git a/clang/include/clang/Basic/LangOptions.def b/clang/include/clang/Basic/LangOptions.def
index 068f206f44847..a7624d206c88f 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -144,6 +144,12 @@ LANGOPT(GNUAsm , 1, 1, "GNU-style inline assembly")
LANGOPT(Coroutines , 1, 0, "C++20 coroutines")
LANGOPT(DllExportInlines , 1, 1, "dllexported classes dllexport inline methods")
LANGOPT(RelaxedTemplateTemplateArgs, 1, 0, "C++17 relaxed matching of template template arguments")
+LANGOPT(PointerAuthIntrinsics, 1, 0, "pointer authentication intrinsics")
+LANGOPT(PointerAuthCalls , 1, 0, "function pointer authentication")
+LANGOPT(PointerAuthReturns, 1, 0, "return pointer authentication")
+LANGOPT(PointerAuthIndirectGotos, 1, 0, "indirect gotos pointer authentication")
+LANGOPT(PointerAuthAuthTraps, 1, 0, "pointer authentication failure traps")
+LANGOPT(SoftPointerAuth , 1, 0, "software emulation of pointer authentication")
LANGOPT(DoubleSquareBracketAttributes, 1, 0, "'[[]]' attributes extension for all language standard modes")
@@ -167,6 +173,7 @@ COMPATIBLE_LANGOPT(ModulesStrictDeclUse, 1, 0, "requiring declaration of module
BENIGN_LANGOPT(ModulesErrorRecovery, 1, 1, "automatically importing modules as needed when performing error recovery")
BENIGN_LANGOPT(ImplicitModules, 1, 1, "building modules that are not specified via -fmodule-file")
COMPATIBLE_LANGOPT(ModulesLocalVisibility, 1, 0, "local submodule visibility")
+COMPATIBLE_LANGOPT(ModulesHashErrorDiags, 1, 0, "hash out diagnostic errors as part of the module hash")
COMPATIBLE_LANGOPT(Optimize , 1, 0, "__OPTIMIZE__ predefined macro")
COMPATIBLE_LANGOPT(OptimizeSize , 1, 0, "__OPTIMIZE_SIZE__ predefined macro")
COMPATIBLE_LANGOPT(Static , 1, 0, "__STATIC__ predefined macro (as opposed to __DYNAMIC__)")
@@ -312,6 +319,9 @@ ENUM_LANGOPT(VtorDispMode, MSVtorDispMode, 2, MSVtorDispMode::ForVBaseOverride,
LANGOPT(ApplePragmaPack, 1, 0, "Apple gcc-compatible #pragma pack handling")
LANGOPT(RetainCommentsFromSystemHeaders, 1, 0, "retain documentation comments from system headers in the AST")
+LANGOPT(APINotes, 1, 0, "use external API notes")
+LANGOPT(APINotesModules, 1, 0, "use external API notes")
+LANGOPT(NeededByPCHOrCompilationUsesPCH, 1, 0, "compilation involves pch")
LANGOPT(SanitizeAddressFieldPadding, 2, 0, "controls how aggressive is ASan "
"field padding (0: none, 1:least "
diff --git a/clang/include/clang/Basic/Module.h b/clang/include/clang/Basic/Module.h
index 0f2549f099435..e0399b82a47c7 100644
--- a/clang/include/clang/Basic/Module.h
+++ b/clang/include/clang/Basic/Module.h
@@ -268,6 +268,9 @@ class Module {
/// to a regular (public) module map.
unsigned ModuleMapIsPrivate : 1;
+ /// \brief Whether this is a module who has its swift_names inferred.
+ unsigned IsSwiftInferImportAsMember : 1;
+
/// Describes the visibility of the various names within a
/// particular module.
enum NameVisibilityKind {
diff --git a/clang/include/clang/Basic/PointerAuthOptions.h b/clang/include/clang/Basic/PointerAuthOptions.h
new file mode 100644
index 0000000000000..936ba12148b8d
--- /dev/null
+++ b/clang/include/clang/Basic/PointerAuthOptions.h
@@ -0,0 +1,203 @@
+//===--- PointerAuthOptions.h -----------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines options for configuring pointer-auth technologies
+// like ARMv8.3.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_BASIC_POINTERAUTHOPTIONS_H
+#define LLVM_CLANG_BASIC_POINTERAUTHOPTIONS_H
+
+#include "clang/Basic/LLVM.h"
+#include "llvm/ADT/Optional.h"
+#include "llvm/Target/TargetOptions.h"
+#include