diff --git a/.gitmodules b/.gitmodules
index 926807336d791..2082ec9ef455f 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -51,3 +51,7 @@
path = src/tools/enzyme
url = https://github.com/EnzymeAD/Enzyme.git
shallow = true
+[submodule "src/gcc"]
+ path = src/gcc
+ url = https://github.com/rust-lang/gcc.git
+ shallow = true
diff --git a/LICENSES/GCC-exception-3.1.txt b/LICENSES/GCC-exception-3.1.txt
new file mode 100644
index 0000000000000..eecede4d0707e
--- /dev/null
+++ b/LICENSES/GCC-exception-3.1.txt
@@ -0,0 +1,30 @@
+GCC RUNTIME LIBRARY EXCEPTION
+
+Version 3.1, 31 March 2009
+
+Copyright © 2009 Free Software Foundation, Inc.
+
+Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
+
+This GCC Runtime Library Exception ("Exception") is an additional permission under section 7 of the GNU General Public License, version 3 ("GPLv3"). It applies to a given file (the "Runtime Library") that bears a notice placed by the copyright holder of the file stating that the file is governed by GPLv3 along with this Exception.
+
+When you use GCC to compile a program, GCC may combine portions of certain GCC header files and runtime libraries with the compiled program. The purpose of this Exception is to allow compilation of non-GPL (including proprietary) programs to use, in this way, the header files and runtime libraries covered by this Exception.
+0. Definitions.
+
+A file is an "Independent Module" if it either requires the Runtime Library for execution after a Compilation Process, or makes use of an interface provided by the Runtime Library, but is not otherwise based on the Runtime Library.
+
+"GCC" means a version of the GNU Compiler Collection, with or without modifications, governed by version 3 (or a specified later version) of the GNU General Public License (GPL) with the option of using any subsequent versions published by the FSF.
+
+"GPL-compatible Software" is software whose conditions of propagation, modification and use would permit combination with GCC in accord with the license of GCC.
+
+"Target Code" refers to output from any compiler for a real or virtual target processor architecture, in executable form or suitable for input to an assembler, loader, linker and/or execution phase. Notwithstanding that, Target Code does not include data in any format that is used as a compiler intermediate representation, or used for producing a compiler intermediate representation.
+
+The "Compilation Process" transforms code entirely represented in non-intermediate languages designed for human-written code, and/or in Java Virtual Machine byte code, into Target Code. Thus, for example, use of source code generators and preprocessors need not be considered part of the Compilation Process, since the Compilation Process can be understood as starting with the output of the generators or preprocessors.
+
+A Compilation Process is "Eligible" if it is done using GCC, alone or with other GPL-compatible software, or if it is done without using any work based on GCC. For example, using non-GPL-compatible Software to optimize any GCC intermediate representations would not qualify as an Eligible Compilation Process.
+1. Grant of Additional Permission.
+
+You have permission to propagate a work of Target Code formed by combining the Runtime Library with Independent Modules, even if such propagation would otherwise violate the terms of GPLv3, provided that all Target Code was generated by Eligible Compilation Processes. You may then convey such a combination under terms of your choice, consistent with the licensing of the Independent Modules.
+2. No Weakening of GCC Copyleft.
+
+The availability of this Exception does not imply any general presumption that third-party software is unaffected by the copyleft requirements of the license of GCC.
diff --git a/LICENSES/GPL-2.0-only.txt b/LICENSES/GPL-2.0-only.txt
new file mode 100644
index 0000000000000..492485e09b411
--- /dev/null
+++ b/LICENSES/GPL-2.0-only.txt
@@ -0,0 +1,133 @@
+GNU GENERAL PUBLIC LICENSE
+
+Version 2, June 1991
+
+Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
+
+Everyone is permitted to copy and distribute verbatim copies
+of this license document, but changing it is not allowed.
+
+Preamble
+
+The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
+
+When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
+
+To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
+
+For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
+
+We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
+
+Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
+
+Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
+
+The precise terms and conditions for copying, distribution and modification follow.
+TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
+
+1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
+
+2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
+ b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
+ c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
+
+3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
+ b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
+ c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
+
+If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
+
+4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
+
+5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
+
+6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
+
+7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
+
+This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
+
+8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
+
+9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
+
+10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
+
+NO WARRANTY
+
+11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+END OF TERMS AND CONDITIONS
+How to Apply These Terms to Your New Programs
+
+If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
+
+To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
+
+one line to give the program's name and an idea of what it does.
+Copyright (C) yyyy name of author
+
+This program is free software; you can redistribute it and/or
+modify it under the terms of the GNU General Public License
+as published by the Free Software Foundation; either version 2
+of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this when it starts in an interactive mode:
+
+Gnomovision version 69, Copyright (C) year name of author
+Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
+type `show w'. This is free software, and you are welcome
+to redistribute it under certain conditions; type `show c'
+for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:
+
+Yoyodyne, Inc., hereby disclaims all copyright
+interest in the program `Gnomovision'
+(which makes passes at compilers) written
+by James Hacker.
+
+signature of Ty Coon, 1 April 1989
+Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License.
diff --git a/LICENSES/GPL-3.0-or-later.txt b/LICENSES/GPL-3.0-or-later.txt
new file mode 100644
index 0000000000000..37b6b8e91b85e
--- /dev/null
+++ b/LICENSES/GPL-3.0-or-later.txt
@@ -0,0 +1,202 @@
+GNU GENERAL PUBLIC LICENSE
+
+Version 3, 29 June 2007
+
+Copyright © 2007 Free Software Foundation, Inc.
+
+Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
+
+Preamble
+
+The GNU General Public License is a free, copyleft license for software and other kinds of works.
+
+The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
+
+When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
+
+To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
+
+For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
+
+Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
+
+For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
+
+Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
+
+Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
+
+The precise terms and conditions for copying, distribution and modification follow.
+
+TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based on the Program.
+
+ To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
+ 1. Source Code.
+ The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
+
+ A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
+
+ The Corresponding Source for a work in source code form is that same work.
+ 2. Basic Permissions.
+ All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+ No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
+
+ When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
+ 4. Conveying Verbatim Copies.
+ You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
+ 5. Conveying Modified Source Versions.
+ You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
+ a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
+ b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
+ c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
+ d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
+
+ A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
+ 6. Conveying Non-Source Forms.
+ You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
+ a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
+ b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
+ c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
+ d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
+ e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
+
+ If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
+
+ The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
+ 7. Additional Terms.
+ "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
+ a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
+ b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
+ c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
+ d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
+ e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
+ f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
+
+ All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
+ 8. Termination.
+ You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
+
+ However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
+ 9. Acceptance Not Required for Having Copies.
+ You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
+ 10. Automatic Licensing of Downstream Recipients.
+ Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
+ 11. Patents.
+ A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
+ 12. No Surrender of Others' Freedom.
+ If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
+ 13. Use with the GNU Affero General Public License.
+ Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
+ 14. Revised Versions of this License.
+ The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
+
+ Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
+ 15. Disclaimer of Warranty.
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+ 16. Limitation of Liability.
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
+
+END OF TERMS AND CONDITIONS
+
+How to Apply These Terms to Your New Programs
+
+If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
+
+To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
+
+
+Copyright (C)
+
+This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box".
+
+You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see .
+
+The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read .
diff --git a/LICENSES/ISC.txt b/LICENSES/ISC.txt
new file mode 100644
index 0000000000000..6f41c8c63b96e
--- /dev/null
+++ b/LICENSES/ISC.txt
@@ -0,0 +1,7 @@
+ISC License
+
+
+
+Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/REUSE.toml b/REUSE.toml
index efd705552478d..3005bb56609b5 100644
--- a/REUSE.toml
+++ b/REUSE.toml
@@ -168,3 +168,37 @@ SPDX-FileCopyrightText = [
"2003-2019 University of Illinois at Urbana-Champaign.",
]
SPDX-License-Identifier = "NCSA AND Apache-2.0 WITH LLVM-exception"
+
+[[annotations]]
+path = "src/gcc/**"
+precedence = "override"
+SPDX-FileCopyrightText = [
+ "Copyright (C) 1997-2024 Free Software Foundation, Inc.",
+]
+SPDX-License-Identifier = "GPL-3.0-or-later"
+
+[[annotations]]
+path = "src/gcc/gcc/testsuite/**"
+precedence = "override"
+SPDX-FileCopyrightText = [
+ "Copyright (C) 2000-2024 Free Software Foundation, Inc.",
+]
+SPDX-License-Identifier = "GPL-2.0-only"
+
+[[annotations]]
+path = "src/gcc/gcc/testsuite/c-c++-common/analyzer/*.c"
+precedence = "override"
+SPDX-FileCopyrightText = [
+ "Copyright (c) 2007-2011 Atheros Communications Inc.",
+ "Copyright (c) 2011-2012,2017 Qualcomm Atheros, Inc.",
+ "Copyright (c) 2016-2017 Erik Stromdahl ",
+]
+SPDX-License-Identifier = "ISC"
+
+[[annotations]]
+path = "src/gcc/libstdc++-v3/config/os/aix/os_defines.h"
+precedence = "override"
+SPDX-FileCopyrightText = [
+ "Copyright (C) 2000-2024 Free Software Foundation, Inc.",
+]
+SPDX-License-Identifier = "GCC-exception-3.1"
diff --git a/compiler/rustc_arena/src/lib.rs b/compiler/rustc_arena/src/lib.rs
index 260c9fe44ba80..cecf223b96193 100644
--- a/compiler/rustc_arena/src/lib.rs
+++ b/compiler/rustc_arena/src/lib.rs
@@ -614,34 +614,34 @@ pub macro declare_arena([$($a:tt $name:ident: $ty:ty,)*]) {
pub trait ArenaAllocatable<'tcx, C = rustc_arena::IsNotCopy>: Sized {
#[allow(clippy::mut_from_ref)]
- fn allocate_on<'a>(self, arena: &'a Arena<'tcx>) -> &'a mut Self;
+ fn allocate_on(self, arena: &'tcx Arena<'tcx>) -> &'tcx mut Self;
#[allow(clippy::mut_from_ref)]
- fn allocate_from_iter<'a>(
- arena: &'a Arena<'tcx>,
+ fn allocate_from_iter(
+ arena: &'tcx Arena<'tcx>,
iter: impl ::std::iter::IntoIterator- ,
- ) -> &'a mut [Self];
+ ) -> &'tcx mut [Self];
}
// Any type that impls `Copy` can be arena-allocated in the `DroplessArena`.
impl<'tcx, T: Copy> ArenaAllocatable<'tcx, rustc_arena::IsCopy> for T {
#[inline]
#[allow(clippy::mut_from_ref)]
- fn allocate_on<'a>(self, arena: &'a Arena<'tcx>) -> &'a mut Self {
+ fn allocate_on(self, arena: &'tcx Arena<'tcx>) -> &'tcx mut Self {
arena.dropless.alloc(self)
}
#[inline]
#[allow(clippy::mut_from_ref)]
- fn allocate_from_iter<'a>(
- arena: &'a Arena<'tcx>,
+ fn allocate_from_iter(
+ arena: &'tcx Arena<'tcx>,
iter: impl ::std::iter::IntoIterator
- ,
- ) -> &'a mut [Self] {
+ ) -> &'tcx mut [Self] {
arena.dropless.alloc_from_iter(iter)
}
}
$(
impl<'tcx> ArenaAllocatable<'tcx, rustc_arena::IsNotCopy> for $ty {
#[inline]
- fn allocate_on<'a>(self, arena: &'a Arena<'tcx>) -> &'a mut Self {
+ fn allocate_on(self, arena: &'tcx Arena<'tcx>) -> &'tcx mut Self {
if !::std::mem::needs_drop::() {
arena.dropless.alloc(self)
} else {
@@ -651,10 +651,10 @@ pub macro declare_arena([$($a:tt $name:ident: $ty:ty,)*]) {
#[inline]
#[allow(clippy::mut_from_ref)]
- fn allocate_from_iter<'a>(
- arena: &'a Arena<'tcx>,
+ fn allocate_from_iter(
+ arena: &'tcx Arena<'tcx>,
iter: impl ::std::iter::IntoIterator
- ,
- ) -> &'a mut [Self] {
+ ) -> &'tcx mut [Self] {
if !::std::mem::needs_drop::() {
arena.dropless.alloc_from_iter(iter)
} else {
@@ -667,7 +667,7 @@ pub macro declare_arena([$($a:tt $name:ident: $ty:ty,)*]) {
impl<'tcx> Arena<'tcx> {
#[inline]
#[allow(clippy::mut_from_ref)]
- pub fn alloc, C>(&self, value: T) -> &mut T {
+ pub fn alloc, C>(&'tcx self, value: T) -> &mut T {
value.allocate_on(self)
}
@@ -691,7 +691,7 @@ pub macro declare_arena([$($a:tt $name:ident: $ty:ty,)*]) {
#[allow(clippy::mut_from_ref)]
pub fn alloc_from_iter, C>(
- &self,
+ &'tcx self,
iter: impl ::std::iter::IntoIterator
- ,
) -> &mut [T] {
T::allocate_from_iter(self, iter)
diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs
index 85d38a0e28b0f..f433f2eca1a80 100644
--- a/compiler/rustc_ast/src/ast.rs
+++ b/compiler/rustc_ast/src/ast.rs
@@ -1188,14 +1188,7 @@ impl Expr {
///
/// Does not ensure that the path resolves to a const param, the caller should check this.
pub fn is_potential_trivial_const_arg(&self) -> bool {
- let this = if let ExprKind::Block(block, None) = &self.kind
- && let [stmt] = block.stmts.as_slice()
- && let StmtKind::Expr(expr) = &stmt.kind
- {
- expr
- } else {
- self
- };
+ let this = self.maybe_unwrap_block();
if let ExprKind::Path(None, path) = &this.kind
&& path.is_potential_trivial_const_arg()
@@ -1206,6 +1199,17 @@ impl Expr {
}
}
+ pub fn maybe_unwrap_block(&self) -> &Expr {
+ if let ExprKind::Block(block, None) = &self.kind
+ && let [stmt] = block.stmts.as_slice()
+ && let StmtKind::Expr(expr) = &stmt.kind
+ {
+ expr
+ } else {
+ self
+ }
+ }
+
pub fn to_bound(&self) -> Option {
match &self.kind {
ExprKind::Path(None, path) => Some(GenericBound::Trait(
@@ -2418,11 +2422,22 @@ impl InlineAsmOperand {
}
}
+#[derive(Clone, Copy, Encodable, Decodable, Debug, HashStable_Generic)]
+pub enum AsmMacro {
+ /// The `asm!` macro
+ Asm,
+ /// The `global_asm!` macro
+ GlobalAsm,
+ /// The `naked_asm!` macro
+ NakedAsm,
+}
+
/// Inline assembly.
///
/// E.g., `asm!("NOP");`.
#[derive(Clone, Encodable, Decodable, Debug)]
pub struct InlineAsm {
+ pub asm_macro: AsmMacro,
pub template: Vec,
pub template_strs: Box<[(Symbol, Option, Span)]>,
pub operands: Vec<(InlineAsmOperand, Span)>,
@@ -2591,12 +2606,12 @@ impl CoroutineKind {
}
}
- pub fn is_async(self) -> bool {
- matches!(self, CoroutineKind::Async { .. })
- }
-
- pub fn is_gen(self) -> bool {
- matches!(self, CoroutineKind::Gen { .. })
+ pub fn as_str(self) -> &'static str {
+ match self {
+ CoroutineKind::Async { .. } => "async",
+ CoroutineKind::Gen { .. } => "gen",
+ CoroutineKind::AsyncGen { .. } => "async gen",
+ }
}
pub fn closure_id(self) -> NodeId {
@@ -3475,7 +3490,7 @@ impl From for ItemKind {
fn from(foreign_item_kind: ForeignItemKind) -> ItemKind {
match foreign_item_kind {
ForeignItemKind::Static(box static_foreign_item) => {
- ItemKind::Static(Box::new(static_foreign_item.into()))
+ ItemKind::Static(Box::new(static_foreign_item))
}
ForeignItemKind::Fn(fn_kind) => ItemKind::Fn(fn_kind),
ForeignItemKind::TyAlias(ty_alias_kind) => ItemKind::TyAlias(ty_alias_kind),
@@ -3489,9 +3504,7 @@ impl TryFrom for ForeignItemKind {
fn try_from(item_kind: ItemKind) -> Result {
Ok(match item_kind {
- ItemKind::Static(box static_item) => {
- ForeignItemKind::Static(Box::new(static_item.into()))
- }
+ ItemKind::Static(box static_item) => ForeignItemKind::Static(Box::new(static_item)),
ItemKind::Fn(fn_kind) => ForeignItemKind::Fn(fn_kind),
ItemKind::TyAlias(ty_alias_kind) => ForeignItemKind::TyAlias(ty_alias_kind),
ItemKind::MacCall(a) => ForeignItemKind::MacCall(a),
diff --git a/compiler/rustc_ast/src/ast_traits.rs b/compiler/rustc_ast/src/ast_traits.rs
index 6b95fb7dd36b8..60f8c6e10481b 100644
--- a/compiler/rustc_ast/src/ast_traits.rs
+++ b/compiler/rustc_ast/src/ast_traits.rs
@@ -153,7 +153,7 @@ impl HasTokens for StmtKind {
StmtKind::Let(local) => local.tokens.as_ref(),
StmtKind::Item(item) => item.tokens(),
StmtKind::Expr(expr) | StmtKind::Semi(expr) => expr.tokens(),
- StmtKind::Empty => return None,
+ StmtKind::Empty => None,
StmtKind::MacCall(mac) => mac.tokens.as_ref(),
}
}
@@ -162,7 +162,7 @@ impl HasTokens for StmtKind {
StmtKind::Let(local) => Some(&mut local.tokens),
StmtKind::Item(item) => item.tokens_mut(),
StmtKind::Expr(expr) | StmtKind::Semi(expr) => expr.tokens_mut(),
- StmtKind::Empty => return None,
+ StmtKind::Empty => None,
StmtKind::MacCall(mac) => Some(&mut mac.tokens),
}
}
diff --git a/compiler/rustc_ast/src/entry.rs b/compiler/rustc_ast/src/entry.rs
index 60a12614f06e8..53276e0847a74 100644
--- a/compiler/rustc_ast/src/entry.rs
+++ b/compiler/rustc_ast/src/entry.rs
@@ -45,18 +45,16 @@ pub fn entry_point_type(
EntryPointType::Start
} else if attr::contains_name(attrs, sym::rustc_main) {
EntryPointType::RustcMainAttr
- } else {
- if let Some(name) = name
- && name == sym::main
- {
- if at_root {
- // This is a top-level function so it can be `main`.
- EntryPointType::MainNamed
- } else {
- EntryPointType::OtherMain
- }
+ } else if let Some(name) = name
+ && name == sym::main
+ {
+ if at_root {
+ // This is a top-level function so it can be `main`.
+ EntryPointType::MainNamed
} else {
- EntryPointType::None
+ EntryPointType::OtherMain
}
+ } else {
+ EntryPointType::None
}
}
diff --git a/compiler/rustc_ast/src/mut_visit.rs b/compiler/rustc_ast/src/mut_visit.rs
index 7c8af6c4a5564..1bef51aa73f7b 100644
--- a/compiler/rustc_ast/src/mut_visit.rs
+++ b/compiler/rustc_ast/src/mut_visit.rs
@@ -1388,6 +1388,7 @@ fn walk_anon_const(vis: &mut T, AnonConst { id, value }: &mut Ano
fn walk_inline_asm(vis: &mut T, asm: &mut InlineAsm) {
// FIXME: Visit spans inside all this currently ignored stuff.
let InlineAsm {
+ asm_macro: _,
template: _,
template_strs: _,
operands,
diff --git a/compiler/rustc_ast/src/visit.rs b/compiler/rustc_ast/src/visit.rs
index 7b041768983e6..bae7ad93f90fa 100644
--- a/compiler/rustc_ast/src/visit.rs
+++ b/compiler/rustc_ast/src/visit.rs
@@ -976,6 +976,7 @@ pub fn walk_anon_const<'a, V: Visitor<'a>>(visitor: &mut V, constant: &'a AnonCo
pub fn walk_inline_asm<'a, V: Visitor<'a>>(visitor: &mut V, asm: &'a InlineAsm) -> V::Result {
let InlineAsm {
+ asm_macro: _,
template: _,
template_strs: _,
operands,
diff --git a/compiler/rustc_ast_lowering/src/asm.rs b/compiler/rustc_ast_lowering/src/asm.rs
index e077c54496586..a9d1ee5c9c13a 100644
--- a/compiler/rustc_ast_lowering/src/asm.rs
+++ b/compiler/rustc_ast_lowering/src/asm.rs
@@ -220,9 +220,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
let parent_def_id = self.current_def_id_parent;
let node_id = self.next_node_id();
// HACK(min_generic_const_args): see lower_anon_const
- if !self.tcx.features().const_arg_path
- || !expr.is_potential_trivial_const_arg()
- {
+ if !expr.is_potential_trivial_const_arg() {
self.create_def(
parent_def_id,
node_id,
@@ -474,8 +472,14 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
);
let line_spans =
self.arena.alloc_from_iter(asm.line_spans.iter().map(|span| self.lower_span(*span)));
- let hir_asm =
- hir::InlineAsm { template, template_strs, operands, options: asm.options, line_spans };
+ let hir_asm = hir::InlineAsm {
+ asm_macro: asm.asm_macro,
+ template,
+ template_strs,
+ operands,
+ options: asm.options,
+ line_spans,
+ };
self.arena.alloc(hir_asm)
}
}
diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs
index a6c7714a182bf..e105026ebd19d 100644
--- a/compiler/rustc_ast_lowering/src/expr.rs
+++ b/compiler/rustc_ast_lowering/src/expr.rs
@@ -387,7 +387,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
let node_id = self.next_node_id();
// HACK(min_generic_const_args): see lower_anon_const
- if !self.tcx.features().const_arg_path || !arg.is_potential_trivial_const_arg() {
+ if !arg.is_potential_trivial_const_arg() {
// Add a definition for the in-band const def.
self.create_def(parent_def_id, node_id, kw::Empty, DefKind::AnonConst, f.span);
}
@@ -1837,7 +1837,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
Safety::Default,
sym::allow,
sym::unreachable_code,
- self.lower_span(span),
+ try_span,
);
let attrs: AttrVec = thin_vec![attr];
diff --git a/compiler/rustc_ast_lowering/src/index.rs b/compiler/rustc_ast_lowering/src/index.rs
index 23729124e21a9..f90a0612db692 100644
--- a/compiler/rustc_ast_lowering/src/index.rs
+++ b/compiler/rustc_ast_lowering/src/index.rs
@@ -78,26 +78,24 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> {
// Make sure that the DepNode of some node coincides with the HirId
// owner of that node.
- if cfg!(debug_assertions) {
- if hir_id.owner != self.owner {
- span_bug!(
- span,
- "inconsistent HirId at `{:?}` for `{:?}`: \
+ if cfg!(debug_assertions) && hir_id.owner != self.owner {
+ span_bug!(
+ span,
+ "inconsistent HirId at `{:?}` for `{:?}`: \
current_dep_node_owner={} ({:?}), hir_id.owner={} ({:?})",
- self.tcx.sess.source_map().span_to_diagnostic_string(span),
- node,
- self.tcx
- .definitions_untracked()
- .def_path(self.owner.def_id)
- .to_string_no_crate_verbose(),
- self.owner,
- self.tcx
- .definitions_untracked()
- .def_path(hir_id.owner.def_id)
- .to_string_no_crate_verbose(),
- hir_id.owner,
- )
- }
+ self.tcx.sess.source_map().span_to_diagnostic_string(span),
+ node,
+ self.tcx
+ .definitions_untracked()
+ .def_path(self.owner.def_id)
+ .to_string_no_crate_verbose(),
+ self.owner,
+ self.tcx
+ .definitions_untracked()
+ .def_path(hir_id.owner.def_id)
+ .to_string_no_crate_verbose(),
+ hir_id.owner,
+ )
}
self.nodes[hir_id.local_id] = ParentedNode { parent: self.parent_node, node };
diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs
index c8ec8f308a8aa..73c604bf28a40 100644
--- a/compiler/rustc_ast_lowering/src/item.rs
+++ b/compiler/rustc_ast_lowering/src/item.rs
@@ -628,13 +628,11 @@ impl<'hir> LoweringContext<'_, 'hir> {
.map_or(Const::No, |attr| Const::Yes(attr.span)),
_ => Const::No,
}
+ } else if self.tcx.is_const_trait(def_id) {
+ // FIXME(effects) span
+ Const::Yes(self.tcx.def_ident_span(def_id).unwrap())
} else {
- if self.tcx.is_const_trait(def_id) {
- // FIXME(effects) span
- Const::Yes(self.tcx.def_ident_span(def_id).unwrap())
- } else {
- Const::No
- }
+ Const::No
}
} else {
Const::No
diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs
index 754fbae4d023f..efd3ae336afb8 100644
--- a/compiler/rustc_ast_lowering/src/lib.rs
+++ b/compiler/rustc_ast_lowering/src/lib.rs
@@ -2335,7 +2335,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
span: Span,
) -> &'hir hir::ConstArg<'hir> {
let ct_kind = match res {
- Res::Def(DefKind::ConstParam, _) if self.tcx.features().const_arg_path => {
+ Res::Def(DefKind::ConstParam, _) => {
let qpath = self.lower_qpath(
ty_id,
&None,
@@ -2410,8 +2410,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
self.resolver.get_partial_res(expr.id).and_then(|partial_res| partial_res.full_res());
debug!("res={:?}", maybe_res);
// FIXME(min_generic_const_args): for now we only lower params to ConstArgKind::Path
- if self.tcx.features().const_arg_path
- && let Some(res) = maybe_res
+ if let Some(res) = maybe_res
&& let Res::Def(DefKind::ConstParam, _) = res
&& let ExprKind::Path(qself, path) = &expr.kind
{
@@ -2442,7 +2441,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
/// See [`hir::ConstArg`] for when to use this function vs
/// [`Self::lower_anon_const_to_const_arg`].
fn lower_anon_const_to_anon_const(&mut self, c: &AnonConst) -> &'hir hir::AnonConst {
- if self.tcx.features().const_arg_path && c.value.is_potential_trivial_const_arg() {
+ if c.value.is_potential_trivial_const_arg() {
// HACK(min_generic_const_args): see DefCollector::visit_anon_const
// Over there, we guess if this is a bare param and only create a def if
// we think it's not. However we may can guess wrong (see there for example)
diff --git a/compiler/rustc_ast_passes/messages.ftl b/compiler/rustc_ast_passes/messages.ftl
index df5c639382f04..c361c35b723d8 100644
--- a/compiler/rustc_ast_passes/messages.ftl
+++ b/compiler/rustc_ast_passes/messages.ftl
@@ -40,15 +40,15 @@ ast_passes_body_in_extern = incorrect `{$kind}` inside `extern` block
ast_passes_bound_in_context = bounds on `type`s in {$ctx} have no effect
-ast_passes_const_and_async = functions cannot be both `const` and `async`
- .const = `const` because of this
- .async = `async` because of this
- .label = {""}
-
ast_passes_const_and_c_variadic = functions cannot be both `const` and C-variadic
.const = `const` because of this
.variadic = C-variadic because of this
+ast_passes_const_and_coroutine = functions cannot be both `const` and `{$coroutine_kind}`
+ .const = `const` because of this
+ .coroutine = `{$coroutine_kind}` because of this
+ .label = {""}
+
ast_passes_const_bound_trait_object = const trait bounds are not allowed in trait object types
ast_passes_const_without_body =
diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs
index ed9672a9e79b3..93881f5ed4261 100644
--- a/compiler/rustc_ast_passes/src/ast_validation.rs
+++ b/compiler/rustc_ast_passes/src/ast_validation.rs
@@ -447,13 +447,13 @@ impl<'a> AstValidator<'a> {
fn check_item_safety(&self, span: Span, safety: Safety) {
match self.extern_mod_safety {
Some(extern_safety) => {
- if matches!(safety, Safety::Unsafe(_) | Safety::Safe(_)) {
- if extern_safety == Safety::Default {
- self.dcx().emit_err(errors::InvalidSafetyOnExtern {
- item_span: span,
- block: Some(self.current_extern_span().shrink_to_lo()),
- });
- }
+ if matches!(safety, Safety::Unsafe(_) | Safety::Safe(_))
+ && extern_safety == Safety::Default
+ {
+ self.dcx().emit_err(errors::InvalidSafetyOnExtern {
+ item_span: span,
+ block: Some(self.current_extern_span().shrink_to_lo()),
+ });
}
}
None => {
@@ -1418,21 +1418,16 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
// Functions cannot both be `const async` or `const gen`
if let Some(&FnHeader {
- constness: Const::Yes(cspan),
+ constness: Const::Yes(const_span),
coroutine_kind: Some(coroutine_kind),
..
}) = fk.header()
{
- let aspan = match coroutine_kind {
- CoroutineKind::Async { span: aspan, .. }
- | CoroutineKind::Gen { span: aspan, .. }
- | CoroutineKind::AsyncGen { span: aspan, .. } => aspan,
- };
- // FIXME(gen_blocks): Report a different error for `const gen`
- self.dcx().emit_err(errors::ConstAndAsync {
- spans: vec![cspan, aspan],
- cspan,
- aspan,
+ self.dcx().emit_err(errors::ConstAndCoroutine {
+ spans: vec![coroutine_kind.span(), const_span],
+ const_span,
+ coroutine_span: coroutine_kind.span(),
+ coroutine_kind: coroutine_kind.as_str(),
span,
});
}
diff --git a/compiler/rustc_ast_passes/src/errors.rs b/compiler/rustc_ast_passes/src/errors.rs
index 67c0396333c4b..5cce47ce7bd21 100644
--- a/compiler/rustc_ast_passes/src/errors.rs
+++ b/compiler/rustc_ast_passes/src/errors.rs
@@ -657,16 +657,17 @@ pub(crate) enum TildeConstReason {
}
#[derive(Diagnostic)]
-#[diag(ast_passes_const_and_async)]
-pub(crate) struct ConstAndAsync {
+#[diag(ast_passes_const_and_coroutine)]
+pub(crate) struct ConstAndCoroutine {
#[primary_span]
pub spans: Vec,
#[label(ast_passes_const)]
- pub cspan: Span,
- #[label(ast_passes_async)]
- pub aspan: Span,
+ pub const_span: Span,
+ #[label(ast_passes_coroutine)]
+ pub coroutine_span: Span,
#[label]
pub span: Span,
+ pub coroutine_kind: &'static str,
}
#[derive(Diagnostic)]
diff --git a/compiler/rustc_attr/src/builtin.rs b/compiler/rustc_attr/src/builtin.rs
index e46dabc7a6e22..309049b98f0e2 100644
--- a/compiler/rustc_attr/src/builtin.rs
+++ b/compiler/rustc_attr/src/builtin.rs
@@ -1240,5 +1240,5 @@ pub fn parse_confusables(attr: &Attribute) -> Option> {
candidates.push(meta_lit.symbol);
}
- return Some(candidates);
+ Some(candidates)
}
diff --git a/compiler/rustc_borrowck/src/borrowck_errors.rs b/compiler/rustc_borrowck/src/borrowck_errors.rs
index 2c672dbf8c4ae..3a7e407f3e7a6 100644
--- a/compiler/rustc_borrowck/src/borrowck_errors.rs
+++ b/compiler/rustc_borrowck/src/borrowck_errors.rs
@@ -8,7 +8,7 @@ use rustc_middle::span_bug;
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_span::Span;
-impl<'infcx, 'tcx> crate::MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
+impl<'infcx, 'tcx> crate::MirBorrowckCtxt<'_, 'infcx, 'tcx> {
pub(crate) fn dcx(&self) -> DiagCtxtHandle<'infcx> {
self.infcx.dcx()
}
diff --git a/compiler/rustc_borrowck/src/constraints/graph.rs b/compiler/rustc_borrowck/src/constraints/graph.rs
index 0ae837898b9c0..9d500586f084c 100644
--- a/compiler/rustc_borrowck/src/constraints/graph.rs
+++ b/compiler/rustc_borrowck/src/constraints/graph.rs
@@ -97,11 +97,11 @@ impl ConstraintGraph {
/// Given the constraint set from which this graph was built
/// creates a region graph so that you can iterate over *regions*
/// and not constraints.
- pub(crate) fn region_graph<'rg, 'tcx>(
- &'rg self,
- set: &'rg OutlivesConstraintSet<'tcx>,
+ pub(crate) fn region_graph<'a, 'tcx>(
+ &'a self,
+ set: &'a OutlivesConstraintSet<'tcx>,
static_region: RegionVid,
- ) -> RegionGraph<'rg, 'tcx, D> {
+ ) -> RegionGraph<'a, 'tcx, D> {
RegionGraph::new(set, self, static_region)
}
@@ -130,15 +130,15 @@ impl ConstraintGraph {
}
}
-pub(crate) struct Edges<'s, 'tcx, D: ConstraintGraphDirection> {
- graph: &'s ConstraintGraph,
- constraints: &'s OutlivesConstraintSet<'tcx>,
+pub(crate) struct Edges<'a, 'tcx, D: ConstraintGraphDirection> {
+ graph: &'a ConstraintGraph,
+ constraints: &'a OutlivesConstraintSet<'tcx>,
pointer: Option,
next_static_idx: Option,
static_region: RegionVid,
}
-impl<'s, 'tcx, D: ConstraintGraphDirection> Iterator for Edges<'s, 'tcx, D> {
+impl<'a, 'tcx, D: ConstraintGraphDirection> Iterator for Edges<'a, 'tcx, D> {
type Item = OutlivesConstraint<'tcx>;
fn next(&mut self) -> Option {
@@ -171,20 +171,20 @@ impl<'s, 'tcx, D: ConstraintGraphDirection> Iterator for Edges<'s, 'tcx, D> {
/// This struct brings together a constraint set and a (normal, not
/// reverse) constraint graph. It implements the graph traits and is
/// usd for doing the SCC computation.
-pub(crate) struct RegionGraph<'s, 'tcx, D: ConstraintGraphDirection> {
- set: &'s OutlivesConstraintSet<'tcx>,
- constraint_graph: &'s ConstraintGraph,
+pub(crate) struct RegionGraph<'a, 'tcx, D: ConstraintGraphDirection> {
+ set: &'a OutlivesConstraintSet<'tcx>,
+ constraint_graph: &'a ConstraintGraph,
static_region: RegionVid,
}
-impl<'s, 'tcx, D: ConstraintGraphDirection> RegionGraph<'s, 'tcx, D> {
+impl<'a, 'tcx, D: ConstraintGraphDirection> RegionGraph<'a, 'tcx, D> {
/// Creates a "dependency graph" where each region constraint `R1:
/// R2` is treated as an edge `R1 -> R2`. We use this graph to
/// construct SCCs for region inference but also for error
/// reporting.
pub(crate) fn new(
- set: &'s OutlivesConstraintSet<'tcx>,
- constraint_graph: &'s ConstraintGraph,
+ set: &'a OutlivesConstraintSet<'tcx>,
+ constraint_graph: &'a ConstraintGraph,
static_region: RegionVid,
) -> Self {
Self { set, constraint_graph, static_region }
@@ -192,18 +192,18 @@ impl<'s, 'tcx, D: ConstraintGraphDirection> RegionGraph<'s, 'tcx, D> {
/// Given a region `R`, iterate over all regions `R1` such that
/// there exists a constraint `R: R1`.
- pub(crate) fn outgoing_regions(&self, region_sup: RegionVid) -> Successors<'s, 'tcx, D> {
+ pub(crate) fn outgoing_regions(&self, region_sup: RegionVid) -> Successors<'a, 'tcx, D> {
Successors {
edges: self.constraint_graph.outgoing_edges(region_sup, self.set, self.static_region),
}
}
}
-pub(crate) struct Successors<'s, 'tcx, D: ConstraintGraphDirection> {
- edges: Edges<'s, 'tcx, D>,
+pub(crate) struct Successors<'a, 'tcx, D: ConstraintGraphDirection> {
+ edges: Edges<'a, 'tcx, D>,
}
-impl<'s, 'tcx, D: ConstraintGraphDirection> Iterator for Successors<'s, 'tcx, D> {
+impl<'a, 'tcx, D: ConstraintGraphDirection> Iterator for Successors<'a, 'tcx, D> {
type Item = RegionVid;
fn next(&mut self) -> Option {
@@ -211,7 +211,7 @@ impl<'s, 'tcx, D: ConstraintGraphDirection> Iterator for Successors<'s, 'tcx, D>
}
}
-impl<'s, 'tcx, D: ConstraintGraphDirection> graph::DirectedGraph for RegionGraph<'s, 'tcx, D> {
+impl<'a, 'tcx, D: ConstraintGraphDirection> graph::DirectedGraph for RegionGraph<'a, 'tcx, D> {
type Node = RegionVid;
fn num_nodes(&self) -> usize {
@@ -219,7 +219,7 @@ impl<'s, 'tcx, D: ConstraintGraphDirection> graph::DirectedGraph for RegionGraph
}
}
-impl<'s, 'tcx, D: ConstraintGraphDirection> graph::Successors for RegionGraph<'s, 'tcx, D> {
+impl<'a, 'tcx, D: ConstraintGraphDirection> graph::Successors for RegionGraph<'a, 'tcx, D> {
fn successors(&self, node: Self::Node) -> impl Iterator
- {
self.outgoing_regions(node)
}
diff --git a/compiler/rustc_borrowck/src/dataflow.rs b/compiler/rustc_borrowck/src/dataflow.rs
index 9bb6109e66d95..5e1043ec81798 100644
--- a/compiler/rustc_borrowck/src/dataflow.rs
+++ b/compiler/rustc_borrowck/src/dataflow.rs
@@ -9,40 +9,39 @@ use rustc_middle::mir::{
use rustc_middle::ty::{RegionVid, TyCtxt};
use rustc_mir_dataflow::fmt::DebugWithContext;
use rustc_mir_dataflow::impls::{EverInitializedPlaces, MaybeUninitializedPlaces};
-use rustc_mir_dataflow::{Analysis, AnalysisDomain, GenKill, Results, ResultsVisitable};
+use rustc_mir_dataflow::{Analysis, AnalysisDomain, Forward, GenKill, Results, ResultsVisitable};
use tracing::debug;
use crate::{places_conflict, BorrowSet, PlaceConflictBias, PlaceExt, RegionInferenceContext};
/// The results of the dataflow analyses used by the borrow checker.
-pub(crate) struct BorrowckResults<'a, 'mir, 'tcx> {
- pub(crate) borrows: Results<'tcx, Borrows<'a, 'mir, 'tcx>>,
- pub(crate) uninits: Results<'tcx, MaybeUninitializedPlaces<'a, 'mir, 'tcx>>,
- pub(crate) ever_inits: Results<'tcx, EverInitializedPlaces<'a, 'mir, 'tcx>>,
+pub(crate) struct BorrowckResults<'a, 'tcx> {
+ pub(crate) borrows: Results<'tcx, Borrows<'a, 'tcx>>,
+ pub(crate) uninits: Results<'tcx, MaybeUninitializedPlaces<'a, 'tcx>>,
+ pub(crate) ever_inits: Results<'tcx, EverInitializedPlaces<'a, 'tcx>>,
}
/// The transient state of the dataflow analyses used by the borrow checker.
#[derive(Debug)]
-pub(crate) struct BorrowckFlowState<'a, 'mir, 'tcx> {
- pub(crate) borrows: as AnalysisDomain<'tcx>>::Domain,
- pub(crate) uninits: as AnalysisDomain<'tcx>>::Domain,
- pub(crate) ever_inits: as AnalysisDomain<'tcx>>::Domain,
+pub(crate) struct BorrowckDomain<'a, 'tcx> {
+ pub(crate) borrows: as AnalysisDomain<'tcx>>::Domain,
+ pub(crate) uninits: as AnalysisDomain<'tcx>>::Domain,
+ pub(crate) ever_inits: as AnalysisDomain<'tcx>>::Domain,
}
-impl<'a, 'mir, 'tcx> ResultsVisitable<'tcx> for BorrowckResults<'a, 'mir, 'tcx> {
- // All three analyses are forward, but we have to use just one here.
- type Direction = as AnalysisDomain<'tcx>>::Direction;
- type FlowState = BorrowckFlowState<'a, 'mir, 'tcx>;
+impl<'a, 'tcx> ResultsVisitable<'tcx> for BorrowckResults<'a, 'tcx> {
+ type Direction = Forward;
+ type Domain = BorrowckDomain<'a, 'tcx>;
- fn new_flow_state(&self, body: &mir::Body<'tcx>) -> Self::FlowState {
- BorrowckFlowState {
+ fn bottom_value(&self, body: &mir::Body<'tcx>) -> Self::Domain {
+ BorrowckDomain {
borrows: self.borrows.analysis.bottom_value(body),
uninits: self.uninits.analysis.bottom_value(body),
ever_inits: self.ever_inits.analysis.bottom_value(body),
}
}
- fn reset_to_block_entry(&self, state: &mut Self::FlowState, block: BasicBlock) {
+ fn reset_to_block_entry(&self, state: &mut Self::Domain, block: BasicBlock) {
state.borrows.clone_from(self.borrows.entry_set_for_block(block));
state.uninits.clone_from(self.uninits.entry_set_for_block(block));
state.ever_inits.clone_from(self.ever_inits.entry_set_for_block(block));
@@ -50,7 +49,7 @@ impl<'a, 'mir, 'tcx> ResultsVisitable<'tcx> for BorrowckResults<'a, 'mir, 'tcx>
fn reconstruct_before_statement_effect(
&mut self,
- state: &mut Self::FlowState,
+ state: &mut Self::Domain,
stmt: &mir::Statement<'tcx>,
loc: Location,
) {
@@ -61,7 +60,7 @@ impl<'a, 'mir, 'tcx> ResultsVisitable<'tcx> for BorrowckResults<'a, 'mir, 'tcx>
fn reconstruct_statement_effect(
&mut self,
- state: &mut Self::FlowState,
+ state: &mut Self::Domain,
stmt: &mir::Statement<'tcx>,
loc: Location,
) {
@@ -72,7 +71,7 @@ impl<'a, 'mir, 'tcx> ResultsVisitable<'tcx> for BorrowckResults<'a, 'mir, 'tcx>
fn reconstruct_before_terminator_effect(
&mut self,
- state: &mut Self::FlowState,
+ state: &mut Self::Domain,
term: &mir::Terminator<'tcx>,
loc: Location,
) {
@@ -83,7 +82,7 @@ impl<'a, 'mir, 'tcx> ResultsVisitable<'tcx> for BorrowckResults<'a, 'mir, 'tcx>
fn reconstruct_terminator_effect(
&mut self,
- state: &mut Self::FlowState,
+ state: &mut Self::Domain,
term: &mir::Terminator<'tcx>,
loc: Location,
) {
@@ -106,24 +105,23 @@ rustc_index::newtype_index! {
/// `BorrowIndex`, and maps each such index to a `BorrowData`
/// describing the borrow. These indexes are used for representing the
/// borrows in compact bitvectors.
-pub struct Borrows<'a, 'mir, 'tcx> {
+pub struct Borrows<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
- body: &'mir Body<'tcx>,
-
+ body: &'a Body<'tcx>,
borrow_set: &'a BorrowSet<'tcx>,
borrows_out_of_scope_at_location: FxIndexMap>,
}
-struct OutOfScopePrecomputer<'mir, 'tcx> {
+struct OutOfScopePrecomputer<'a, 'tcx> {
visited: BitSet,
visit_stack: Vec,
- body: &'mir Body<'tcx>,
- regioncx: &'mir RegionInferenceContext<'tcx>,
+ body: &'a Body<'tcx>,
+ regioncx: &'a RegionInferenceContext<'tcx>,
borrows_out_of_scope_at_location: FxIndexMap>,
}
-impl<'mir, 'tcx> OutOfScopePrecomputer<'mir, 'tcx> {
- fn new(body: &'mir Body<'tcx>, regioncx: &'mir RegionInferenceContext<'tcx>) -> Self {
+impl<'a, 'tcx> OutOfScopePrecomputer<'a, 'tcx> {
+ fn new(body: &'a Body<'tcx>, regioncx: &'a RegionInferenceContext<'tcx>) -> Self {
OutOfScopePrecomputer {
visited: BitSet::new_empty(body.basic_blocks.len()),
visit_stack: vec![],
@@ -226,17 +224,17 @@ pub fn calculate_borrows_out_of_scope_at_location<'tcx>(
prec.borrows_out_of_scope_at_location
}
-struct PoloniusOutOfScopePrecomputer<'mir, 'tcx> {
+struct PoloniusOutOfScopePrecomputer<'a, 'tcx> {
visited: BitSet,
visit_stack: Vec,
- body: &'mir Body<'tcx>,
- regioncx: &'mir RegionInferenceContext<'tcx>,
+ body: &'a Body<'tcx>,
+ regioncx: &'a RegionInferenceContext<'tcx>,
loans_out_of_scope_at_location: FxIndexMap>,
}
-impl<'mir, 'tcx> PoloniusOutOfScopePrecomputer<'mir, 'tcx> {
- fn new(body: &'mir Body<'tcx>, regioncx: &'mir RegionInferenceContext<'tcx>) -> Self {
+impl<'a, 'tcx> PoloniusOutOfScopePrecomputer<'a, 'tcx> {
+ fn new(body: &'a Body<'tcx>, regioncx: &'a RegionInferenceContext<'tcx>) -> Self {
Self {
visited: BitSet::new_empty(body.basic_blocks.len()),
visit_stack: vec![],
@@ -389,10 +387,10 @@ impl<'tcx> PoloniusOutOfScopePrecomputer<'_, 'tcx> {
}
}
-impl<'a, 'mir, 'tcx> Borrows<'a, 'mir, 'tcx> {
+impl<'a, 'tcx> Borrows<'a, 'tcx> {
pub fn new(
tcx: TyCtxt<'tcx>,
- body: &'mir Body<'tcx>,
+ body: &'a Body<'tcx>,
regioncx: &RegionInferenceContext<'tcx>,
borrow_set: &'a BorrowSet<'tcx>,
) -> Self {
@@ -494,7 +492,7 @@ impl<'a, 'mir, 'tcx> Borrows<'a, 'mir, 'tcx> {
}
}
-impl<'tcx> rustc_mir_dataflow::AnalysisDomain<'tcx> for Borrows<'_, '_, 'tcx> {
+impl<'tcx> rustc_mir_dataflow::AnalysisDomain<'tcx> for Borrows<'_, 'tcx> {
type Domain = BitSet;
const NAME: &'static str = "borrows";
@@ -517,7 +515,7 @@ impl<'tcx> rustc_mir_dataflow::AnalysisDomain<'tcx> for Borrows<'_, '_, 'tcx> {
/// region stops containing the CFG points reachable from the issuing location.
/// - we also kill loans of conflicting places when overwriting a shared path: e.g. borrows of
/// `a.b.c` when `a` is overwritten.
-impl<'tcx> rustc_mir_dataflow::GenKillAnalysis<'tcx> for Borrows<'_, '_, 'tcx> {
+impl<'tcx> rustc_mir_dataflow::GenKillAnalysis<'tcx> for Borrows<'_, 'tcx> {
type Idx = BorrowIndex;
fn domain_size(&self, _: &mir::Body<'tcx>) -> usize {
@@ -617,8 +615,8 @@ impl<'tcx> rustc_mir_dataflow::GenKillAnalysis<'tcx> for Borrows<'_, '_, 'tcx> {
}
}
-impl DebugWithContext> for BorrowIndex {
- fn fmt_with(&self, ctxt: &Borrows<'_, '_, '_>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+impl DebugWithContext> for BorrowIndex {
+ fn fmt_with(&self, ctxt: &Borrows<'_, '_>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", ctxt.location(*self))
}
}
diff --git a/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs
index 8a4e89d47bdc0..ee28e556cbc34 100644
--- a/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs
+++ b/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs
@@ -52,7 +52,7 @@ impl<'tcx> UniverseInfo<'tcx> {
pub(crate) fn report_error(
&self,
- mbcx: &mut MirBorrowckCtxt<'_, '_, '_, 'tcx>,
+ mbcx: &mut MirBorrowckCtxt<'_, '_, 'tcx>,
placeholder: ty::PlaceholderRegion,
error_element: RegionElement,
cause: ObligationCause<'tcx>,
@@ -151,7 +151,7 @@ trait TypeOpInfo<'tcx> {
fn nice_error<'infcx>(
&self,
- mbcx: &mut MirBorrowckCtxt<'_, '_, 'infcx, 'tcx>,
+ mbcx: &mut MirBorrowckCtxt<'_, 'infcx, 'tcx>,
cause: ObligationCause<'tcx>,
placeholder_region: ty::Region<'tcx>,
error_region: Option>,
@@ -160,7 +160,7 @@ trait TypeOpInfo<'tcx> {
#[instrument(level = "debug", skip(self, mbcx))]
fn report_error(
&self,
- mbcx: &mut MirBorrowckCtxt<'_, '_, '_, 'tcx>,
+ mbcx: &mut MirBorrowckCtxt<'_, '_, 'tcx>,
placeholder: ty::PlaceholderRegion,
error_element: RegionElement,
cause: ObligationCause<'tcx>,
@@ -233,7 +233,7 @@ impl<'tcx> TypeOpInfo<'tcx> for PredicateQuery<'tcx> {
fn nice_error<'infcx>(
&self,
- mbcx: &mut MirBorrowckCtxt<'_, '_, 'infcx, 'tcx>,
+ mbcx: &mut MirBorrowckCtxt<'_, 'infcx, 'tcx>,
cause: ObligationCause<'tcx>,
placeholder_region: ty::Region<'tcx>,
error_region: Option>,
@@ -277,7 +277,7 @@ where
fn nice_error<'infcx>(
&self,
- mbcx: &mut MirBorrowckCtxt<'_, '_, 'infcx, 'tcx>,
+ mbcx: &mut MirBorrowckCtxt<'_, 'infcx, 'tcx>,
cause: ObligationCause<'tcx>,
placeholder_region: ty::Region<'tcx>,
error_region: Option>,
@@ -324,7 +324,7 @@ impl<'tcx> TypeOpInfo<'tcx> for AscribeUserTypeQuery<'tcx> {
fn nice_error<'infcx>(
&self,
- mbcx: &mut MirBorrowckCtxt<'_, '_, 'infcx, 'tcx>,
+ mbcx: &mut MirBorrowckCtxt<'_, 'infcx, 'tcx>,
cause: ObligationCause<'tcx>,
placeholder_region: ty::Region<'tcx>,
error_region: Option>,
@@ -357,7 +357,7 @@ impl<'tcx> TypeOpInfo<'tcx> for crate::type_check::InstantiateOpaqueType<'tcx> {
fn nice_error<'infcx>(
&self,
- mbcx: &mut MirBorrowckCtxt<'_, '_, 'infcx, 'tcx>,
+ mbcx: &mut MirBorrowckCtxt<'_, 'infcx, 'tcx>,
_cause: ObligationCause<'tcx>,
placeholder_region: ty::Region<'tcx>,
error_region: Option>,
diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs
index c817b6fac7134..c7a5d516ad72d 100644
--- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs
+++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs
@@ -69,7 +69,7 @@ enum StorageDeadOrDrop<'tcx> {
Destructor(Ty<'tcx>),
}
-impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
+impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
pub(crate) fn report_use_of_moved_or_uninitialized(
&mut self,
location: Location,
@@ -1999,19 +1999,32 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
) {
let used_in_call = matches!(
explanation,
- BorrowExplanation::UsedLater(LaterUseKind::Call | LaterUseKind::Other, _call_span, _)
+ BorrowExplanation::UsedLater(
+ _,
+ LaterUseKind::Call | LaterUseKind::Other,
+ _call_span,
+ _
+ )
);
if !used_in_call {
debug!("not later used in call");
return;
}
+ if matches!(
+ self.body.local_decls[issued_borrow.borrowed_place.local].local_info(),
+ LocalInfo::IfThenRescopeTemp { .. }
+ ) {
+ // A better suggestion will be issued by the `if_let_rescope` lint
+ return;
+ }
- let use_span =
- if let BorrowExplanation::UsedLater(LaterUseKind::Other, use_span, _) = explanation {
- Some(use_span)
- } else {
- None
- };
+ let use_span = if let BorrowExplanation::UsedLater(_, LaterUseKind::Other, use_span, _) =
+ explanation
+ {
+ Some(use_span)
+ } else {
+ None
+ };
let outer_call_loc =
if let TwoPhaseActivation::ActivatedAt(loc) = issued_borrow.activation_location {
@@ -2574,33 +2587,31 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
}
impl<'hir> Visitor<'hir> for ExpressionFinder<'hir> {
fn visit_expr(&mut self, e: &'hir hir::Expr<'hir>) {
- if e.span.contains(self.capture_span) {
- if let hir::ExprKind::Closure(&hir::Closure {
+ if e.span.contains(self.capture_span)
+ && let hir::ExprKind::Closure(&hir::Closure {
kind: hir::ClosureKind::Closure,
body,
fn_arg_span,
fn_decl: hir::FnDecl { inputs, .. },
..
}) = e.kind
- && let hir::Node::Expr(body) = self.tcx.hir_node(body.hir_id)
- {
- self.suggest_arg = "this: &Self".to_string();
- if inputs.len() > 0 {
- self.suggest_arg.push_str(", ");
- }
- self.in_closure = true;
- self.closure_arg_span = fn_arg_span;
- self.visit_expr(body);
- self.in_closure = false;
+ && let hir::Node::Expr(body) = self.tcx.hir_node(body.hir_id)
+ {
+ self.suggest_arg = "this: &Self".to_string();
+ if inputs.len() > 0 {
+ self.suggest_arg.push_str(", ");
}
+ self.in_closure = true;
+ self.closure_arg_span = fn_arg_span;
+ self.visit_expr(body);
+ self.in_closure = false;
}
- if let hir::Expr { kind: hir::ExprKind::Path(path), .. } = e {
- if let hir::QPath::Resolved(_, hir::Path { segments: [seg], .. }) = path
- && seg.ident.name == kw::SelfLower
- && self.in_closure
- {
- self.closure_change_spans.push(e.span);
- }
+ if let hir::Expr { kind: hir::ExprKind::Path(path), .. } = e
+ && let hir::QPath::Resolved(_, hir::Path { segments: [seg], .. }) = path
+ && seg.ident.name == kw::SelfLower
+ && self.in_closure
+ {
+ self.closure_change_spans.push(e.span);
}
hir::intravisit::walk_expr(self, e);
}
@@ -2609,8 +2620,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
if let hir::Pat { kind: hir::PatKind::Binding(_, hir_id, _ident, _), .. } =
local.pat
&& let Some(init) = local.init
- {
- if let hir::Expr {
+ && let hir::Expr {
kind:
hir::ExprKind::Closure(&hir::Closure {
kind: hir::ClosureKind::Closure,
@@ -2618,11 +2628,11 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
}),
..
} = init
- && init.span.contains(self.capture_span)
- {
- self.closure_local_id = Some(*hir_id);
- }
+ && init.span.contains(self.capture_span)
+ {
+ self.closure_local_id = Some(*hir_id);
}
+
hir::intravisit::walk_local(self, local);
}
@@ -2862,7 +2872,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
// and `move` will not help here.
(
Some(name),
- BorrowExplanation::UsedLater(LaterUseKind::ClosureCapture, var_or_use_span, _),
+ BorrowExplanation::UsedLater(_, LaterUseKind::ClosureCapture, var_or_use_span, _),
) if borrow_spans.for_coroutine() || borrow_spans.for_closure() => self
.report_escaping_closure_capture(
borrow_spans,
@@ -3543,7 +3553,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
location: Location,
mpi: MovePathIndex,
) -> (Vec, Vec) {
- fn predecessor_locations<'tcx, 'a>(
+ fn predecessor_locations<'a, 'tcx>(
body: &'a mir::Body<'tcx>,
location: Location,
) -> impl Iterator
- + Captures<'tcx> + 'a {
@@ -3669,7 +3679,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
reinits.push(location);
return true;
}
- return false;
+ false
};
while let Some(location) = stack.pop() {
@@ -4358,11 +4368,7 @@ enum AnnotatedBorrowFnSignature<'tcx> {
impl<'tcx> AnnotatedBorrowFnSignature<'tcx> {
/// Annotate the provided diagnostic with information about borrow from the fn signature that
/// helps explain.
- pub(crate) fn emit(
- &self,
- cx: &MirBorrowckCtxt<'_, '_, '_, 'tcx>,
- diag: &mut Diag<'_>,
- ) -> String {
+ pub(crate) fn emit(&self, cx: &MirBorrowckCtxt<'_, '_, 'tcx>, diag: &mut Diag<'_>) -> String {
match self {
&AnnotatedBorrowFnSignature::Closure { argument_ty, argument_span } => {
diag.span_label(
diff --git a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs
index c720b0928feb0..d9b5fd8b5c182 100644
--- a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs
+++ b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs
@@ -30,7 +30,7 @@ use crate::{MirBorrowckCtxt, WriteKind};
#[derive(Debug)]
pub(crate) enum BorrowExplanation<'tcx> {
- UsedLater(LaterUseKind, Span, Option),
+ UsedLater(Local, LaterUseKind, Span, Option),
UsedLaterInLoop(LaterUseKind, Span, Option),
UsedLaterWhenDropped {
drop_loc: Location,
@@ -99,7 +99,12 @@ impl<'tcx> BorrowExplanation<'tcx> {
}
}
match *self {
- BorrowExplanation::UsedLater(later_use_kind, var_or_use_span, path_span) => {
+ BorrowExplanation::UsedLater(
+ dropped_local,
+ later_use_kind,
+ var_or_use_span,
+ path_span,
+ ) => {
let message = match later_use_kind {
LaterUseKind::TraitCapture => "captured here by trait object",
LaterUseKind::ClosureCapture => "captured here by closure",
@@ -107,9 +112,26 @@ impl<'tcx> BorrowExplanation<'tcx> {
LaterUseKind::FakeLetRead => "stored here",
LaterUseKind::Other => "used here",
};
- // We can use `var_or_use_span` if either `path_span` is not present, or both spans are the same
- if path_span.map(|path_span| path_span == var_or_use_span).unwrap_or(true) {
- if borrow_span.map(|sp| !sp.overlaps(var_or_use_span)).unwrap_or(true) {
+ let local_decl = &body.local_decls[dropped_local];
+
+ if let &LocalInfo::IfThenRescopeTemp { if_then } = local_decl.local_info()
+ && let Some((_, hir::Node::Expr(expr))) = tcx.hir().parent_iter(if_then).next()
+ && let hir::ExprKind::If(cond, conseq, alt) = expr.kind
+ && let hir::ExprKind::Let(&hir::LetExpr {
+ span: _,
+ pat,
+ init,
+ // FIXME(#101728): enable rewrite when type ascription is stabilized again
+ ty: None,
+ recovered: _,
+ }) = cond.kind
+ && pat.span.can_be_used_for_suggestions()
+ && let Ok(pat) = tcx.sess.source_map().span_to_snippet(pat.span)
+ {
+ suggest_rewrite_if_let(tcx, expr, &pat, init, conseq, alt, err);
+ } else if path_span.map_or(true, |path_span| path_span == var_or_use_span) {
+ // We can use `var_or_use_span` if either `path_span` is not present, or both spans are the same
+ if borrow_span.map_or(true, |sp| !sp.overlaps(var_or_use_span)) {
err.span_label(
var_or_use_span,
format!("{borrow_desc}borrow later {message}"),
@@ -255,6 +277,22 @@ impl<'tcx> BorrowExplanation<'tcx> {
Applicability::MaybeIncorrect,
);
};
+ } else if let &LocalInfo::IfThenRescopeTemp { if_then } =
+ local_decl.local_info()
+ && let hir::Node::Expr(expr) = tcx.hir_node(if_then)
+ && let hir::ExprKind::If(cond, conseq, alt) = expr.kind
+ && let hir::ExprKind::Let(&hir::LetExpr {
+ span: _,
+ pat,
+ init,
+ // FIXME(#101728): enable rewrite when type ascription is stabilized again
+ ty: None,
+ recovered: _,
+ }) = cond.kind
+ && pat.span.can_be_used_for_suggestions()
+ && let Ok(pat) = tcx.sess.source_map().span_to_snippet(pat.span)
+ {
+ suggest_rewrite_if_let(tcx, expr, &pat, init, conseq, alt, err);
}
}
}
@@ -390,7 +428,54 @@ impl<'tcx> BorrowExplanation<'tcx> {
}
}
-impl<'tcx> MirBorrowckCtxt<'_, '_, '_, 'tcx> {
+fn suggest_rewrite_if_let(
+ tcx: TyCtxt<'_>,
+ expr: &hir::Expr<'_>,
+ pat: &str,
+ init: &hir::Expr<'_>,
+ conseq: &hir::Expr<'_>,
+ alt: Option<&hir::Expr<'_>>,
+ err: &mut Diag<'_>,
+) {
+ let source_map = tcx.sess.source_map();
+ err.span_note(
+ source_map.end_point(conseq.span),
+ "lifetimes for temporaries generated in `if let`s have been shortened in Edition 2024 so that they are dropped here instead",
+ );
+ if expr.span.can_be_used_for_suggestions() && conseq.span.can_be_used_for_suggestions() {
+ let needs_block = if let Some(hir::Node::Expr(expr)) =
+ alt.and_then(|alt| tcx.hir().parent_iter(alt.hir_id).next()).map(|(_, node)| node)
+ {
+ matches!(expr.kind, hir::ExprKind::If(..))
+ } else {
+ false
+ };
+ let mut sugg = vec![
+ (
+ expr.span.shrink_to_lo().between(init.span),
+ if needs_block { "{ match ".into() } else { "match ".into() },
+ ),
+ (conseq.span.shrink_to_lo(), format!(" {{ {pat} => ")),
+ ];
+ let expr_end = expr.span.shrink_to_hi();
+ let mut expr_end_code;
+ if let Some(alt) = alt {
+ sugg.push((conseq.span.between(alt.span), " _ => ".into()));
+ expr_end_code = "}".to_string();
+ } else {
+ expr_end_code = " _ => {} }".into();
+ }
+ expr_end_code.push('}');
+ sugg.push((expr_end, expr_end_code));
+ err.multipart_suggestion(
+ "consider rewriting the `if` into `match` which preserves the extended lifetime",
+ sugg,
+ Applicability::MaybeIncorrect,
+ );
+ }
+}
+
+impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
fn free_region_constraint_info(
&self,
borrow_region: RegionVid,
@@ -465,14 +550,21 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, '_, 'tcx> {
.or_else(|| self.borrow_spans(span, location));
if use_in_later_iteration_of_loop {
- let later_use = self.later_use_kind(borrow, spans, use_location);
- BorrowExplanation::UsedLaterInLoop(later_use.0, later_use.1, later_use.2)
+ let (later_use_kind, var_or_use_span, path_span) =
+ self.later_use_kind(borrow, spans, use_location);
+ BorrowExplanation::UsedLaterInLoop(later_use_kind, var_or_use_span, path_span)
} else {
// Check if the location represents a `FakeRead`, and adapt the error
// message to the `FakeReadCause` it is from: in particular,
// the ones inserted in optimized `let var = ` patterns.
- let later_use = self.later_use_kind(borrow, spans, location);
- BorrowExplanation::UsedLater(later_use.0, later_use.1, later_use.2)
+ let (later_use_kind, var_or_use_span, path_span) =
+ self.later_use_kind(borrow, spans, location);
+ BorrowExplanation::UsedLater(
+ borrow.borrowed_place.local,
+ later_use_kind,
+ var_or_use_span,
+ path_span,
+ )
}
}
diff --git a/compiler/rustc_borrowck/src/diagnostics/find_use.rs b/compiler/rustc_borrowck/src/diagnostics/find_use.rs
index bea8d3bfdfbb1..d8fa5506a9919 100644
--- a/compiler/rustc_borrowck/src/diagnostics/find_use.rs
+++ b/compiler/rustc_borrowck/src/diagnostics/find_use.rs
@@ -21,15 +21,15 @@ pub(crate) fn find<'tcx>(
uf.find()
}
-struct UseFinder<'cx, 'tcx> {
- body: &'cx Body<'tcx>,
- regioncx: &'cx Rc>,
+struct UseFinder<'a, 'tcx> {
+ body: &'a Body<'tcx>,
+ regioncx: &'a Rc>,
tcx: TyCtxt<'tcx>,
region_vid: RegionVid,
start_point: Location,
}
-impl<'cx, 'tcx> UseFinder<'cx, 'tcx> {
+impl<'a, 'tcx> UseFinder<'a, 'tcx> {
fn find(&mut self) -> Option {
let mut queue = VecDeque::new();
let mut visited = FxIndexSet::default();
@@ -93,8 +93,8 @@ impl<'cx, 'tcx> UseFinder<'cx, 'tcx> {
}
}
-struct DefUseVisitor<'cx, 'tcx> {
- body: &'cx Body<'tcx>,
+struct DefUseVisitor<'a, 'tcx> {
+ body: &'a Body<'tcx>,
tcx: TyCtxt<'tcx>,
region_vid: RegionVid,
def_use_result: Option,
@@ -106,7 +106,7 @@ enum DefUseResult {
UseDrop { local: Local },
}
-impl<'cx, 'tcx> Visitor<'tcx> for DefUseVisitor<'cx, 'tcx> {
+impl<'a, 'tcx> Visitor<'tcx> for DefUseVisitor<'a, 'tcx> {
fn visit_local(&mut self, local: Local, context: PlaceContext, _: Location) {
let local_ty = self.body.local_decls[local].ty;
diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs
index 878ce6162e0f9..e52ddfa3eb543 100644
--- a/compiler/rustc_borrowck/src/diagnostics/mod.rs
+++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs
@@ -68,7 +68,7 @@ pub(super) struct DescribePlaceOpt {
pub(super) struct IncludingTupleField(pub(super) bool);
-impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
+impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
/// Adds a suggestion when a closure is invoked twice with a moved variable or when a closure
/// is moved after being invoked.
///
@@ -772,7 +772,7 @@ struct CapturedMessageOpt {
maybe_reinitialized_locations_is_empty: bool,
}
-impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
+impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
/// Finds the spans associated to a move or copy of move_place at location.
pub(super) fn move_spans(
&self,
diff --git a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs
index 3dab027bff057..5a9eba34d07f1 100644
--- a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs
+++ b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs
@@ -93,7 +93,7 @@ enum GroupedMoveError<'tcx> {
},
}
-impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
+impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
pub(crate) fn report_move_errors(&mut self) {
let grouped_errors = self.group_move_errors();
for error in grouped_errors {
diff --git a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs
index 337125f5ecc11..2bbafb0163ee0 100644
--- a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs
+++ b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs
@@ -32,7 +32,7 @@ pub(crate) enum AccessKind {
Mutate,
}
-impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
+impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
pub(crate) fn report_mutability_error(
&mut self,
access_place: Place<'tcx>,
@@ -558,7 +558,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
ty: Ty<'tcx>,
suggested: bool,
}
- impl<'a, 'cx, 'tcx> Visitor<'tcx> for SuggestIndexOperatorAlternativeVisitor<'a, 'cx, 'tcx> {
+ impl<'a, 'infcx, 'tcx> Visitor<'tcx> for SuggestIndexOperatorAlternativeVisitor<'a, 'infcx, 'tcx> {
fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) {
hir::intravisit::walk_stmt(self, stmt);
let expr = match stmt.kind {
diff --git a/compiler/rustc_borrowck/src/diagnostics/outlives_suggestion.rs b/compiler/rustc_borrowck/src/diagnostics/outlives_suggestion.rs
index b205dc9ff4922..bd0cf3578c2bb 100644
--- a/compiler/rustc_borrowck/src/diagnostics/outlives_suggestion.rs
+++ b/compiler/rustc_borrowck/src/diagnostics/outlives_suggestion.rs
@@ -76,7 +76,7 @@ impl OutlivesSuggestionBuilder {
/// Returns a name for the region if it is suggestable. See `region_name_is_suggestable`.
fn region_vid_to_name(
&self,
- mbcx: &MirBorrowckCtxt<'_, '_, '_, '_>,
+ mbcx: &MirBorrowckCtxt<'_, '_, '_>,
region: RegionVid,
) -> Option {
mbcx.give_region_a_name(region).filter(Self::region_name_is_suggestable)
@@ -85,7 +85,7 @@ impl OutlivesSuggestionBuilder {
/// Compiles a list of all suggestions to be printed in the final big suggestion.
fn compile_all_suggestions(
&self,
- mbcx: &MirBorrowckCtxt<'_, '_, '_, '_>,
+ mbcx: &MirBorrowckCtxt<'_, '_, '_>,
) -> SmallVec<[SuggestedConstraint; 2]> {
let mut suggested = SmallVec::new();
@@ -161,7 +161,7 @@ impl OutlivesSuggestionBuilder {
/// Emit an intermediate note on the given `Diag` if the involved regions are suggestable.
pub(crate) fn intermediate_suggestion(
&mut self,
- mbcx: &MirBorrowckCtxt<'_, '_, '_, '_>,
+ mbcx: &MirBorrowckCtxt<'_, '_, '_>,
errci: &ErrorConstraintInfo<'_>,
diag: &mut Diag<'_>,
) {
@@ -180,7 +180,7 @@ impl OutlivesSuggestionBuilder {
/// If there is a suggestion to emit, add a diagnostic to the buffer. This is the final
/// suggestion including all collected constraints.
- pub(crate) fn add_suggestion(&self, mbcx: &mut MirBorrowckCtxt<'_, '_, '_, '_>) {
+ pub(crate) fn add_suggestion(&self, mbcx: &mut MirBorrowckCtxt<'_, '_, '_>) {
// No constraints to add? Done.
if self.constraints_to_add.is_empty() {
debug!("No constraints to suggest.");
diff --git a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs
index d49d36dedafc1..57c3a0843a694 100644
--- a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs
+++ b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs
@@ -156,7 +156,7 @@ pub(crate) struct ErrorConstraintInfo<'tcx> {
pub(super) span: Span,
}
-impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
+impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
/// Converts a region inference variable into a `ty::Region` that
/// we can use for error reporting. If `r` is universally bound,
/// then we use the name that we have on record for it. If `r` is
diff --git a/compiler/rustc_borrowck/src/diagnostics/region_name.rs b/compiler/rustc_borrowck/src/diagnostics/region_name.rs
index cb05812ec7b5c..58fcda2571cc0 100644
--- a/compiler/rustc_borrowck/src/diagnostics/region_name.rs
+++ b/compiler/rustc_borrowck/src/diagnostics/region_name.rs
@@ -200,7 +200,7 @@ impl rustc_errors::IntoDiagArg for RegionName {
}
}
-impl<'tcx> MirBorrowckCtxt<'_, '_, '_, 'tcx> {
+impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
pub(crate) fn mir_def_id(&self) -> hir::def_id::LocalDefId {
self.body.source.def_id().expect_local()
}
diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs
index d40dcfa58054a..58e730307492e 100644
--- a/compiler/rustc_borrowck/src/lib.rs
+++ b/compiler/rustc_borrowck/src/lib.rs
@@ -83,7 +83,7 @@ mod util;
pub mod consumers;
use borrow_set::{BorrowData, BorrowSet};
-use dataflow::{BorrowIndex, BorrowckFlowState as Flows, BorrowckResults, Borrows};
+use dataflow::{BorrowIndex, BorrowckDomain, BorrowckResults, Borrows};
use nll::PoloniusOutput;
use place_ext::PlaceExt;
use places_conflict::{places_conflict, PlaceConflictBias};
@@ -304,11 +304,11 @@ fn do_mir_borrowck<'tcx>(
promoted_mbcx.report_move_errors();
diags = promoted_mbcx.diags;
- struct MoveVisitor<'a, 'b, 'mir, 'infcx, 'tcx> {
- ctxt: &'a mut MirBorrowckCtxt<'b, 'mir, 'infcx, 'tcx>,
+ struct MoveVisitor<'a, 'b, 'infcx, 'tcx> {
+ ctxt: &'a mut MirBorrowckCtxt<'b, 'infcx, 'tcx>,
}
- impl<'tcx> Visitor<'tcx> for MoveVisitor<'_, '_, '_, '_, 'tcx> {
+ impl<'tcx> Visitor<'tcx> for MoveVisitor<'_, '_, '_, 'tcx> {
fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
if let Operand::Move(place) = operand {
self.ctxt.check_movable_place(location, *place);
@@ -522,10 +522,10 @@ impl<'tcx> Deref for BorrowckInferCtxt<'tcx> {
}
}
-struct MirBorrowckCtxt<'a, 'mir, 'infcx, 'tcx> {
+struct MirBorrowckCtxt<'a, 'infcx, 'tcx> {
infcx: &'infcx BorrowckInferCtxt<'tcx>,
param_env: ParamEnv<'tcx>,
- body: &'mir Body<'tcx>,
+ body: &'a Body<'tcx>,
move_data: &'a MoveData<'tcx>,
/// Map from MIR `Location` to `LocationIndex`; created
@@ -599,28 +599,28 @@ struct MirBorrowckCtxt<'a, 'mir, 'infcx, 'tcx> {
// 2. loans made in overlapping scopes do not conflict
// 3. assignments do not affect things loaned out as immutable
// 4. moves do not affect things loaned out in any way
-impl<'a, 'mir, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'mir, 'tcx, R>
- for MirBorrowckCtxt<'a, 'mir, '_, 'tcx>
+impl<'a, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'a, 'tcx, R>
+ for MirBorrowckCtxt<'a, '_, 'tcx>
{
- type FlowState = Flows<'a, 'mir, 'tcx>;
+ type Domain = BorrowckDomain<'a, 'tcx>;
fn visit_statement_before_primary_effect(
&mut self,
_results: &mut R,
- flow_state: &Flows<'_, 'mir, 'tcx>,
- stmt: &'mir Statement<'tcx>,
+ state: &BorrowckDomain<'a, 'tcx>,
+ stmt: &'a Statement<'tcx>,
location: Location,
) {
- debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, flow_state);
+ debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, state);
let span = stmt.source_info.span;
- self.check_activations(location, span, flow_state);
+ self.check_activations(location, span, state);
match &stmt.kind {
StatementKind::Assign(box (lhs, rhs)) => {
- self.consume_rvalue(location, (rhs, span), flow_state);
+ self.consume_rvalue(location, (rhs, span), state);
- self.mutate_place(location, (*lhs, span), Shallow(None), flow_state);
+ self.mutate_place(location, (*lhs, span), Shallow(None), state);
}
StatementKind::FakeRead(box (_, place)) => {
// Read for match doesn't access any memory and is used to
@@ -637,11 +637,11 @@ impl<'a, 'mir, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'mir, 'tcx, R>
location,
InitializationRequiringAction::Use,
(place.as_ref(), span),
- flow_state,
+ state,
);
}
StatementKind::Intrinsic(box kind) => match kind {
- NonDivergingIntrinsic::Assume(op) => self.consume_operand(location, (op, span), flow_state),
+ NonDivergingIntrinsic::Assume(op) => self.consume_operand(location, (op, span), state),
NonDivergingIntrinsic::CopyNonOverlapping(..) => span_bug!(
span,
"Unexpected CopyNonOverlapping, should only appear after lower_intrinsics",
@@ -662,7 +662,7 @@ impl<'a, 'mir, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'mir, 'tcx, R>
(Place::from(*local), span),
(Shallow(None), Write(WriteKind::StorageDeadOrDrop)),
LocalMutationIsAllowed::Yes,
- flow_state,
+ state,
);
}
StatementKind::Nop
@@ -677,18 +677,18 @@ impl<'a, 'mir, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'mir, 'tcx, R>
fn visit_terminator_before_primary_effect(
&mut self,
_results: &mut R,
- flow_state: &Flows<'_, 'mir, 'tcx>,
- term: &'mir Terminator<'tcx>,
+ state: &BorrowckDomain<'a, 'tcx>,
+ term: &'a Terminator<'tcx>,
loc: Location,
) {
- debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, flow_state);
+ debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, state);
let span = term.source_info.span;
- self.check_activations(loc, span, flow_state);
+ self.check_activations(loc, span, state);
match &term.kind {
TerminatorKind::SwitchInt { discr, targets: _ } => {
- self.consume_operand(loc, (discr, span), flow_state);
+ self.consume_operand(loc, (discr, span), state);
}
TerminatorKind::Drop { place, target: _, unwind: _, replace } => {
debug!(
@@ -704,7 +704,7 @@ impl<'a, 'mir, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'mir, 'tcx, R>
(*place, span),
(AccessDepth::Drop, Write(write_kind)),
LocalMutationIsAllowed::Yes,
- flow_state,
+ state,
);
}
TerminatorKind::Call {
@@ -716,29 +716,29 @@ impl<'a, 'mir, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'mir, 'tcx, R>
call_source: _,
fn_span: _,
} => {
- self.consume_operand(loc, (func, span), flow_state);
+ self.consume_operand(loc, (func, span), state);
for arg in args {
- self.consume_operand(loc, (&arg.node, arg.span), flow_state);
+ self.consume_operand(loc, (&arg.node, arg.span), state);
}
- self.mutate_place(loc, (*destination, span), Deep, flow_state);
+ self.mutate_place(loc, (*destination, span), Deep, state);
}
TerminatorKind::TailCall { func, args, fn_span: _ } => {
- self.consume_operand(loc, (func, span), flow_state);
+ self.consume_operand(loc, (func, span), state);
for arg in args {
- self.consume_operand(loc, (&arg.node, arg.span), flow_state);
+ self.consume_operand(loc, (&arg.node, arg.span), state);
}
}
TerminatorKind::Assert { cond, expected: _, msg, target: _, unwind: _ } => {
- self.consume_operand(loc, (cond, span), flow_state);
+ self.consume_operand(loc, (cond, span), state);
if let AssertKind::BoundsCheck { len, index } = &**msg {
- self.consume_operand(loc, (len, span), flow_state);
- self.consume_operand(loc, (index, span), flow_state);
+ self.consume_operand(loc, (len, span), state);
+ self.consume_operand(loc, (index, span), state);
}
}
TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
- self.consume_operand(loc, (value, span), flow_state);
- self.mutate_place(loc, (*resume_arg, span), Deep, flow_state);
+ self.consume_operand(loc, (value, span), state);
+ self.mutate_place(loc, (*resume_arg, span), Deep, state);
}
TerminatorKind::InlineAsm {
@@ -752,22 +752,17 @@ impl<'a, 'mir, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'mir, 'tcx, R>
for op in operands {
match op {
InlineAsmOperand::In { reg: _, value } => {
- self.consume_operand(loc, (value, span), flow_state);
+ self.consume_operand(loc, (value, span), state);
}
InlineAsmOperand::Out { reg: _, late: _, place, .. } => {
if let Some(place) = place {
- self.mutate_place(loc, (*place, span), Shallow(None), flow_state);
+ self.mutate_place(loc, (*place, span), Shallow(None), state);
}
}
InlineAsmOperand::InOut { reg: _, late: _, in_value, out_place } => {
- self.consume_operand(loc, (in_value, span), flow_state);
+ self.consume_operand(loc, (in_value, span), state);
if let &Some(out_place) = out_place {
- self.mutate_place(
- loc,
- (out_place, span),
- Shallow(None),
- flow_state,
- );
+ self.mutate_place(loc, (out_place, span), Shallow(None), state);
}
}
InlineAsmOperand::Const { value: _ }
@@ -794,8 +789,8 @@ impl<'a, 'mir, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'mir, 'tcx, R>
fn visit_terminator_after_primary_effect(
&mut self,
_results: &mut R,
- flow_state: &Flows<'_, 'mir, 'tcx>,
- term: &'mir Terminator<'tcx>,
+ state: &BorrowckDomain<'a, 'tcx>,
+ term: &'a Terminator<'tcx>,
loc: Location,
) {
let span = term.source_info.span;
@@ -805,7 +800,7 @@ impl<'a, 'mir, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'mir, 'tcx, R>
if self.movable_coroutine {
// Look for any active borrows to locals
let borrow_set = self.borrow_set.clone();
- for i in flow_state.borrows.iter() {
+ for i in state.borrows.iter() {
let borrow = &borrow_set[i];
self.check_for_local_borrow(borrow, span);
}
@@ -821,7 +816,7 @@ impl<'a, 'mir, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'mir, 'tcx, R>
// StorageDead, but we don't always emit those (notably on unwind paths),
// so this "extra check" serves as a kind of backup.
let borrow_set = self.borrow_set.clone();
- for i in flow_state.borrows.iter() {
+ for i in state.borrows.iter() {
let borrow = &borrow_set[i];
self.check_for_invalidation_at_exit(loc, borrow, span);
}
@@ -972,8 +967,8 @@ impl InitializationRequiringAction {
}
}
-impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
- fn body(&self) -> &'mir Body<'tcx> {
+impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
+ fn body(&self) -> &'a Body<'tcx> {
self.body
}
@@ -989,7 +984,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
place_span: (Place<'tcx>, Span),
kind: (AccessDepth, ReadOrWrite),
is_local_mutation_allowed: LocalMutationIsAllowed,
- flow_state: &Flows<'_, 'mir, 'tcx>,
+ state: &BorrowckDomain<'a, 'tcx>,
) {
let (sd, rw) = kind;
@@ -1020,11 +1015,10 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
place_span,
rw,
is_local_mutation_allowed,
- flow_state,
+ state,
location,
);
- let conflict_error =
- self.check_access_for_conflict(location, place_span, sd, rw, flow_state);
+ let conflict_error = self.check_access_for_conflict(location, place_span, sd, rw, state);
if conflict_error || mutability_error {
debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind);
@@ -1032,14 +1026,14 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
}
}
- #[instrument(level = "debug", skip(self, flow_state))]
+ #[instrument(level = "debug", skip(self, state))]
fn check_access_for_conflict(
&mut self,
location: Location,
place_span: (Place<'tcx>, Span),
sd: AccessDepth,
rw: ReadOrWrite,
- flow_state: &Flows<'_, 'mir, 'tcx>,
+ state: &BorrowckDomain<'a, 'tcx>,
) -> bool {
let mut error_reported = false;
let borrow_set = Rc::clone(&self.borrow_set);
@@ -1054,7 +1048,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
}
&polonius_output
} else {
- &flow_state.borrows
+ &state.borrows
};
each_borrow_involving_path(
@@ -1180,25 +1174,25 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
location: Location,
place_span: (Place<'tcx>, Span),
kind: AccessDepth,
- flow_state: &Flows<'_, 'mir, 'tcx>,
+ state: &BorrowckDomain<'a, 'tcx>,
) {
// Write of P[i] or *P requires P init'd.
- self.check_if_assigned_path_is_moved(location, place_span, flow_state);
+ self.check_if_assigned_path_is_moved(location, place_span, state);
self.access_place(
location,
place_span,
(kind, Write(WriteKind::Mutate)),
LocalMutationIsAllowed::No,
- flow_state,
+ state,
);
}
fn consume_rvalue(
&mut self,
location: Location,
- (rvalue, span): (&'mir Rvalue<'tcx>, Span),
- flow_state: &Flows<'_, 'mir, 'tcx>,
+ (rvalue, span): (&'a Rvalue<'tcx>, Span),
+ state: &BorrowckDomain<'a, 'tcx>,
) {
match rvalue {
&Rvalue::Ref(_ /*rgn*/, bk, place) => {
@@ -1224,7 +1218,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
(place, span),
access_kind,
LocalMutationIsAllowed::No,
- flow_state,
+ state,
);
let action = if bk == BorrowKind::Fake(FakeBorrowKind::Shallow) {
@@ -1237,7 +1231,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
location,
action,
(place.as_ref(), span),
- flow_state,
+ state,
);
}
@@ -1257,14 +1251,14 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
(place, span),
access_kind,
LocalMutationIsAllowed::No,
- flow_state,
+ state,
);
self.check_if_path_or_subpath_is_moved(
location,
InitializationRequiringAction::Borrow,
(place.as_ref(), span),
- flow_state,
+ state,
);
}
@@ -1275,7 +1269,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
| Rvalue::UnaryOp(_ /*un_op*/, operand)
| Rvalue::Cast(_ /*cast_kind*/, operand, _ /*ty*/)
| Rvalue::ShallowInitBox(operand, _ /*ty*/) => {
- self.consume_operand(location, (operand, span), flow_state)
+ self.consume_operand(location, (operand, span), state)
}
&Rvalue::CopyForDeref(place) => {
@@ -1284,7 +1278,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
(place, span),
(Deep, Read(ReadKind::Copy)),
LocalMutationIsAllowed::No,
- flow_state,
+ state,
);
// Finally, check if path was already moved.
@@ -1292,7 +1286,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
location,
InitializationRequiringAction::Use,
(place.as_ref(), span),
- flow_state,
+ state,
);
}
@@ -1307,19 +1301,19 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
(place, span),
(Shallow(af), Read(ReadKind::Copy)),
LocalMutationIsAllowed::No,
- flow_state,
+ state,
);
self.check_if_path_or_subpath_is_moved(
location,
InitializationRequiringAction::Use,
(place.as_ref(), span),
- flow_state,
+ state,
);
}
Rvalue::BinaryOp(_bin_op, box (operand1, operand2)) => {
- self.consume_operand(location, (operand1, span), flow_state);
- self.consume_operand(location, (operand2, span), flow_state);
+ self.consume_operand(location, (operand1, span), state);
+ self.consume_operand(location, (operand2, span), state);
}
Rvalue::NullaryOp(_op, _ty) => {
@@ -1349,7 +1343,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
}
for operand in operands {
- self.consume_operand(location, (operand, span), flow_state);
+ self.consume_operand(location, (operand, span), state);
}
}
}
@@ -1455,8 +1449,8 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
fn consume_operand(
&mut self,
location: Location,
- (operand, span): (&'mir Operand<'tcx>, Span),
- flow_state: &Flows<'_, 'mir, 'tcx>,
+ (operand, span): (&'a Operand<'tcx>, Span),
+ state: &BorrowckDomain<'a, 'tcx>,
) {
match *operand {
Operand::Copy(place) => {
@@ -1467,7 +1461,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
(place, span),
(Deep, Read(ReadKind::Copy)),
LocalMutationIsAllowed::No,
- flow_state,
+ state,
);
// Finally, check if path was already moved.
@@ -1475,7 +1469,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
location,
InitializationRequiringAction::Use,
(place.as_ref(), span),
- flow_state,
+ state,
);
}
Operand::Move(place) => {
@@ -1488,7 +1482,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
(place, span),
(Deep, Write(WriteKind::Move)),
LocalMutationIsAllowed::Yes,
- flow_state,
+ state,
);
// Finally, check if path was already moved.
@@ -1496,7 +1490,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
location,
InitializationRequiringAction::Use,
(place.as_ref(), span),
- flow_state,
+ state,
);
}
Operand::Constant(_) => {}
@@ -1580,7 +1574,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
&mut self,
location: Location,
span: Span,
- flow_state: &Flows<'_, 'mir, 'tcx>,
+ state: &BorrowckDomain<'a, 'tcx>,
) {
// Two-phase borrow support: For each activation that is newly
// generated at this statement, check if it interferes with
@@ -1600,7 +1594,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
(borrow.borrowed_place, span),
(Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)),
LocalMutationIsAllowed::No,
- flow_state,
+ state,
);
// We do not need to call `check_if_path_or_subpath_is_moved`
// again, as we already called it when we made the
@@ -1744,9 +1738,9 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
location: Location,
desired_action: InitializationRequiringAction,
place_span: (PlaceRef<'tcx>, Span),
- flow_state: &Flows<'_, 'mir, 'tcx>,
+ state: &BorrowckDomain<'a, 'tcx>,
) {
- let maybe_uninits = &flow_state.uninits;
+ let maybe_uninits = &state.uninits;
// Bad scenarios:
//
@@ -1849,9 +1843,9 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
location: Location,
desired_action: InitializationRequiringAction,
place_span: (PlaceRef<'tcx>, Span),
- flow_state: &Flows<'_, 'mir, 'tcx>,
+ state: &BorrowckDomain<'a, 'tcx>,
) {
- let maybe_uninits = &flow_state.uninits;
+ let maybe_uninits = &state.uninits;
// Bad scenarios:
//
@@ -1868,7 +1862,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
// must have been initialized for the use to be sound.
// 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d`
- self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state);
+ self.check_if_full_path_is_moved(location, desired_action, place_span, state);
if let Some((place_base, ProjectionElem::Subslice { from, to, from_end: false })) =
place_span.0.last_projection()
@@ -1948,7 +1942,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
&mut self,
location: Location,
(place, span): (Place<'tcx>, Span),
- flow_state: &Flows<'_, 'mir, 'tcx>,
+ state: &BorrowckDomain<'a, 'tcx>,
) {
debug!("check_if_assigned_path_is_moved place: {:?}", place);
@@ -1970,7 +1964,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
ProjectionElem::Deref => {
self.check_if_full_path_is_moved(
location, InitializationRequiringAction::Use,
- (place_base, span), flow_state);
+ (place_base, span), state);
// (base initialized; no need to
// recur further)
break;
@@ -1990,7 +1984,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
ty::Adt(def, _) if def.has_dtor(tcx) => {
self.check_if_path_or_subpath_is_moved(
location, InitializationRequiringAction::Assignment,
- (place_base, span), flow_state);
+ (place_base, span), state);
// (base initialized; no need to
// recur further)
@@ -2000,7 +1994,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
// Once `let s; s.x = V; read(s.x);`,
// is allowed, remove this match arm.
ty::Adt(..) | ty::Tuple(..) => {
- check_parent_of_field(self, location, place_base, span, flow_state);
+ check_parent_of_field(self, location, place_base, span, state);
}
_ => {}
@@ -2009,12 +2003,12 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
}
}
- fn check_parent_of_field<'mir, 'tcx>(
- this: &mut MirBorrowckCtxt<'_, 'mir, '_, 'tcx>,
+ fn check_parent_of_field<'a, 'tcx>(
+ this: &mut MirBorrowckCtxt<'a, '_, 'tcx>,
location: Location,
base: PlaceRef<'tcx>,
span: Span,
- flow_state: &Flows<'_, 'mir, 'tcx>,
+ state: &BorrowckDomain<'a, 'tcx>,
) {
// rust-lang/rust#21232: Until Rust allows reads from the
// initialized parts of partially initialized structs, we
@@ -2047,7 +2041,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
// Shallow so that we'll stop at any dereference; we'll
// report errors about issues with such bases elsewhere.
- let maybe_uninits = &flow_state.uninits;
+ let maybe_uninits = &state.uninits;
// Find the shortest uninitialized prefix you can reach
// without going over a Deref.
@@ -2074,12 +2068,12 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
// no move out from an earlier location) then this is an attempt at initialization
// of the union - we should error in that case.
let tcx = this.infcx.tcx;
- if base.ty(this.body(), tcx).ty.is_union() {
- if this.move_data.path_map[mpi].iter().any(|moi| {
+ if base.ty(this.body(), tcx).ty.is_union()
+ && this.move_data.path_map[mpi].iter().any(|moi| {
this.move_data.moves[*moi].source.is_predecessor_of(location, this.body)
- }) {
- return;
- }
+ })
+ {
+ return;
}
this.report_use_of_moved_or_uninitialized(
@@ -2105,7 +2099,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
(place, span): (Place<'tcx>, Span),
kind: ReadOrWrite,
is_local_mutation_allowed: LocalMutationIsAllowed,
- flow_state: &Flows<'_, 'mir, 'tcx>,
+ state: &BorrowckDomain<'a, 'tcx>,
location: Location,
) -> bool {
debug!(
@@ -2129,7 +2123,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
};
match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
Ok(root_place) => {
- self.add_used_mut(root_place, flow_state);
+ self.add_used_mut(root_place, state);
return false;
}
Err(place_err) => {
@@ -2141,7 +2135,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => {
match self.is_mutable(place.as_ref(), is_local_mutation_allowed) {
Ok(root_place) => {
- self.add_used_mut(root_place, flow_state);
+ self.add_used_mut(root_place, state);
return false;
}
Err(place_err) => {
@@ -2199,7 +2193,7 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
// partial initialization, do not complain about mutability
// errors except for actual mutation (as opposed to an attempt
// to do a partial initialization).
- let previously_initialized = self.is_local_ever_initialized(place.local, flow_state);
+ let previously_initialized = self.is_local_ever_initialized(place.local, state);
// at this point, we have set up the error reporting state.
if let Some(init_index) = previously_initialized {
@@ -2221,22 +2215,22 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
fn is_local_ever_initialized(
&self,
local: Local,
- flow_state: &Flows<'_, 'mir, 'tcx>,
+ state: &BorrowckDomain<'a, 'tcx>,
) -> Option {
let mpi = self.move_data.rev_lookup.find_local(local)?;
let ii = &self.move_data.init_path_map[mpi];
- ii.into_iter().find(|&&index| flow_state.ever_inits.contains(index)).copied()
+ ii.into_iter().find(|&&index| state.ever_inits.contains(index)).copied()
}
/// Adds the place into the used mutable variables set
- fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, flow_state: &Flows<'_, 'mir, 'tcx>) {
+ fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, state: &BorrowckDomain<'a, 'tcx>) {
match root_place {
RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
// If the local may have been initialized, and it is now currently being
// mutated, then it is justified to be annotated with the `mut`
// keyword, since the mutation may be a possible reassignment.
if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
- && self.is_local_ever_initialized(local, flow_state).is_some()
+ && self.is_local_ever_initialized(local, state).is_some()
{
self.used_mut.insert(local);
}
@@ -2484,7 +2478,7 @@ mod diags {
}
}
- impl<'infcx, 'tcx> MirBorrowckCtxt<'_, '_, 'infcx, 'tcx> {
+ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
pub(crate) fn buffer_error(&mut self, diag: Diag<'infcx>) {
self.diags.buffer_error(diag);
}
diff --git a/compiler/rustc_borrowck/src/nll.rs b/compiler/rustc_borrowck/src/nll.rs
index 6525befc13b99..8575eb9e9a52d 100644
--- a/compiler/rustc_borrowck/src/nll.rs
+++ b/compiler/rustc_borrowck/src/nll.rs
@@ -75,14 +75,14 @@ pub(crate) fn replace_regions_in_mir<'tcx>(
/// Computes the (non-lexical) regions from the input MIR.
///
/// This may result in errors being reported.
-pub(crate) fn compute_regions<'cx, 'tcx>(
+pub(crate) fn compute_regions<'a, 'tcx>(
infcx: &BorrowckInferCtxt<'tcx>,
universal_regions: UniversalRegions<'tcx>,
body: &Body<'tcx>,
promoted: &IndexSlice>,
location_table: &LocationTable,
param_env: ty::ParamEnv<'tcx>,
- flow_inits: &mut ResultsCursor<'cx, 'tcx, MaybeInitializedPlaces<'_, 'cx, 'tcx>>,
+ flow_inits: &mut ResultsCursor<'a, 'tcx, MaybeInitializedPlaces<'a, 'tcx>>,
move_data: &MoveData<'tcx>,
borrow_set: &BorrowSet<'tcx>,
upvars: &[&ty::CapturedPlace<'tcx>],
@@ -301,13 +301,13 @@ pub(super) fn dump_nll_mir<'tcx>(
#[allow(rustc::diagnostic_outside_of_impl)]
#[allow(rustc::untranslatable_diagnostic)]
-pub(super) fn dump_annotation<'tcx, 'cx>(
- infcx: &'cx BorrowckInferCtxt<'tcx>,
+pub(super) fn dump_annotation<'tcx, 'infcx>(
+ infcx: &'infcx BorrowckInferCtxt<'tcx>,
body: &Body<'tcx>,
regioncx: &RegionInferenceContext<'tcx>,
closure_region_requirements: &Option>,
opaque_type_values: &FxIndexMap>,
- diags: &mut crate::diags::BorrowckDiags<'cx, 'tcx>,
+ diags: &mut crate::diags::BorrowckDiags<'infcx, 'tcx>,
) {
let tcx = infcx.tcx;
let base_def_id = tcx.typeck_root_def_id(body.source.def_id());
diff --git a/compiler/rustc_borrowck/src/polonius/loan_invalidations.rs b/compiler/rustc_borrowck/src/polonius/loan_invalidations.rs
index 0b9b8768b5600..afd811a0efb43 100644
--- a/compiler/rustc_borrowck/src/polonius/loan_invalidations.rs
+++ b/compiler/rustc_borrowck/src/polonius/loan_invalidations.rs
@@ -32,18 +32,18 @@ pub(super) fn emit_loan_invalidations<'tcx>(
visitor.visit_body(body);
}
-struct LoanInvalidationsGenerator<'cx, 'tcx> {
+struct LoanInvalidationsGenerator<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
- all_facts: &'cx mut AllFacts,
- location_table: &'cx LocationTable,
- body: &'cx Body<'tcx>,
- dominators: &'cx Dominators,
- borrow_set: &'cx BorrowSet<'tcx>,
+ all_facts: &'a mut AllFacts,
+ location_table: &'a LocationTable,
+ body: &'a Body<'tcx>,
+ dominators: &'a Dominators,
+ borrow_set: &'a BorrowSet<'tcx>,
}
/// Visits the whole MIR and generates `invalidates()` facts.
/// Most of the code implementing this was stolen from `borrow_check/mod.rs`.
-impl<'cx, 'tcx> Visitor<'tcx> for LoanInvalidationsGenerator<'cx, 'tcx> {
+impl<'a, 'tcx> Visitor<'tcx> for LoanInvalidationsGenerator<'a, 'tcx> {
fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
self.check_activations(location);
@@ -212,7 +212,7 @@ impl<'cx, 'tcx> Visitor<'tcx> for LoanInvalidationsGenerator<'cx, 'tcx> {
}
}
-impl<'cx, 'tcx> LoanInvalidationsGenerator<'cx, 'tcx> {
+impl<'a, 'tcx> LoanInvalidationsGenerator<'a, 'tcx> {
/// Simulates mutation of a place.
fn mutate_place(&mut self, location: Location, place: Place<'tcx>, kind: AccessDepth) {
self.access_place(
diff --git a/compiler/rustc_borrowck/src/polonius/loan_kills.rs b/compiler/rustc_borrowck/src/polonius/loan_kills.rs
index ed9f714e50062..68e0865ab82c9 100644
--- a/compiler/rustc_borrowck/src/polonius/loan_kills.rs
+++ b/compiler/rustc_borrowck/src/polonius/loan_kills.rs
@@ -25,15 +25,15 @@ pub(super) fn emit_loan_kills<'tcx>(
}
}
-struct LoanKillsGenerator<'cx, 'tcx> {
+struct LoanKillsGenerator<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
- all_facts: &'cx mut AllFacts,
- location_table: &'cx LocationTable,
- borrow_set: &'cx BorrowSet<'tcx>,
- body: &'cx Body<'tcx>,
+ all_facts: &'a mut AllFacts,
+ location_table: &'a LocationTable,
+ borrow_set: &'a BorrowSet<'tcx>,
+ body: &'a Body<'tcx>,
}
-impl<'cx, 'tcx> Visitor<'tcx> for LoanKillsGenerator<'cx, 'tcx> {
+impl<'a, 'tcx> Visitor<'tcx> for LoanKillsGenerator<'a, 'tcx> {
fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
// Also record CFG facts here.
self.all_facts.cfg_edge.push((
diff --git a/compiler/rustc_borrowck/src/prefixes.rs b/compiler/rustc_borrowck/src/prefixes.rs
index 39d831378cde6..aeb8a6c014a4f 100644
--- a/compiler/rustc_borrowck/src/prefixes.rs
+++ b/compiler/rustc_borrowck/src/prefixes.rs
@@ -34,7 +34,7 @@ pub(super) enum PrefixSet {
Shallow,
}
-impl<'tcx> MirBorrowckCtxt<'_, '_, '_, 'tcx> {
+impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
/// Returns an iterator over the prefixes of `place`
/// (inclusive) from longest to smallest, potentially
/// terminating the iteration early based on `kind`.
diff --git a/compiler/rustc_borrowck/src/region_infer/values.rs b/compiler/rustc_borrowck/src/region_infer/values.rs
index d62f2067729df..30dc062ae7cea 100644
--- a/compiler/rustc_borrowck/src/region_infer/values.rs
+++ b/compiler/rustc_borrowck/src/region_infer/values.rs
@@ -118,10 +118,8 @@ impl LivenessValues {
debug!("LivenessValues::add_location(region={:?}, location={:?})", region, location);
if let Some(points) = &mut self.points {
points.insert(region, point);
- } else {
- if self.elements.point_in_range(point) {
- self.live_regions.as_mut().unwrap().insert(region);
- }
+ } else if self.elements.point_in_range(point) {
+ self.live_regions.as_mut().unwrap().insert(region);
}
// When available, record the loans flowing into this region as live at the given point.
@@ -137,10 +135,8 @@ impl LivenessValues {
debug!("LivenessValues::add_points(region={:?}, points={:?})", region, points);
if let Some(this) = &mut self.points {
this.union_row(region, points);
- } else {
- if points.iter().any(|point| self.elements.point_in_range(point)) {
- self.live_regions.as_mut().unwrap().insert(region);
- }
+ } else if points.iter().any(|point| self.elements.point_in_range(point)) {
+ self.live_regions.as_mut().unwrap().insert(region);
}
// When available, record the loans flowing into this region as live at the given points.
diff --git a/compiler/rustc_borrowck/src/type_check/free_region_relations.rs b/compiler/rustc_borrowck/src/type_check/free_region_relations.rs
index 33cdb1b1f3774..c711190cb97ab 100644
--- a/compiler/rustc_borrowck/src/type_check/free_region_relations.rs
+++ b/compiler/rustc_borrowck/src/type_check/free_region_relations.rs
@@ -181,12 +181,12 @@ impl UniversalRegionRelations<'_> {
}
}
-struct UniversalRegionRelationsBuilder<'this, 'tcx> {
- infcx: &'this InferCtxt<'tcx>,
+struct UniversalRegionRelationsBuilder<'a, 'tcx> {
+ infcx: &'a InferCtxt<'tcx>,
param_env: ty::ParamEnv<'tcx>,
universal_regions: Rc>,
implicit_region_bound: ty::Region<'tcx>,
- constraints: &'this mut MirTypeckRegionConstraints<'tcx>,
+ constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
// outputs:
outlives: TransitiveRelationBuilder,
diff --git a/compiler/rustc_borrowck/src/type_check/liveness/mod.rs b/compiler/rustc_borrowck/src/type_check/liveness/mod.rs
index a24fd95e3e650..a73467824de5e 100644
--- a/compiler/rustc_borrowck/src/type_check/liveness/mod.rs
+++ b/compiler/rustc_borrowck/src/type_check/liveness/mod.rs
@@ -30,11 +30,11 @@ mod trace;
///
/// N.B., this computation requires normalization; therefore, it must be
/// performed before
-pub(super) fn generate<'mir, 'tcx>(
+pub(super) fn generate<'a, 'tcx>(
typeck: &mut TypeChecker<'_, 'tcx>,
body: &Body<'tcx>,
elements: &Rc,
- flow_inits: &mut ResultsCursor<'mir, 'tcx, MaybeInitializedPlaces<'_, 'mir, 'tcx>>,
+ flow_inits: &mut ResultsCursor<'a, 'tcx, MaybeInitializedPlaces<'a, 'tcx>>,
move_data: &MoveData<'tcx>,
) {
debug!("liveness::generate");
@@ -148,12 +148,12 @@ fn record_regular_live_regions<'tcx>(
}
/// Visitor looking for regions that should be live within rvalues or calls.
-struct LiveVariablesVisitor<'cx, 'tcx> {
+struct LiveVariablesVisitor<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
- liveness_constraints: &'cx mut LivenessValues,
+ liveness_constraints: &'a mut LivenessValues,
}
-impl<'cx, 'tcx> Visitor<'tcx> for LiveVariablesVisitor<'cx, 'tcx> {
+impl<'a, 'tcx> Visitor<'tcx> for LiveVariablesVisitor<'a, 'tcx> {
/// We sometimes have `args` within an rvalue, or within a
/// call. Make them live at the location where they appear.
fn visit_args(&mut self, args: &GenericArgsRef<'tcx>, location: Location) {
@@ -188,7 +188,7 @@ impl<'cx, 'tcx> Visitor<'tcx> for LiveVariablesVisitor<'cx, 'tcx> {
}
}
-impl<'cx, 'tcx> LiveVariablesVisitor<'cx, 'tcx> {
+impl<'a, 'tcx> LiveVariablesVisitor<'a, 'tcx> {
/// Some variable is "regular live" at `location` -- i.e., it may be used later. This means that
/// all regions appearing in the type of `value` must be live at `location`.
fn record_regions_live_at(&mut self, value: T, location: Location)
diff --git a/compiler/rustc_borrowck/src/type_check/liveness/polonius.rs b/compiler/rustc_borrowck/src/type_check/liveness/polonius.rs
index 7f6aabf8841dd..3a458731f2891 100644
--- a/compiler/rustc_borrowck/src/type_check/liveness/polonius.rs
+++ b/compiler/rustc_borrowck/src/type_check/liveness/polonius.rs
@@ -11,13 +11,13 @@ use crate::location::{LocationIndex, LocationTable};
type VarPointRelation = Vec<(Local, LocationIndex)>;
type PathPointRelation = Vec<(MovePathIndex, LocationIndex)>;
-struct UseFactsExtractor<'me, 'tcx> {
- var_defined_at: &'me mut VarPointRelation,
- var_used_at: &'me mut VarPointRelation,
- location_table: &'me LocationTable,
- var_dropped_at: &'me mut VarPointRelation,
- move_data: &'me MoveData<'tcx>,
- path_accessed_at_base: &'me mut PathPointRelation,
+struct UseFactsExtractor<'a, 'tcx> {
+ var_defined_at: &'a mut VarPointRelation,
+ var_used_at: &'a mut VarPointRelation,
+ location_table: &'a LocationTable,
+ var_dropped_at: &'a mut VarPointRelation,
+ move_data: &'a MoveData<'tcx>,
+ path_accessed_at_base: &'a mut PathPointRelation,
}
// A Visitor to walk through the MIR and extract point-wise facts
diff --git a/compiler/rustc_borrowck/src/type_check/liveness/trace.rs b/compiler/rustc_borrowck/src/type_check/liveness/trace.rs
index 6186904e5fbb6..1ac2757345390 100644
--- a/compiler/rustc_borrowck/src/type_check/liveness/trace.rs
+++ b/compiler/rustc_borrowck/src/type_check/liveness/trace.rs
@@ -37,11 +37,11 @@ use crate::type_check::{NormalizeLocation, TypeChecker};
/// DROP-LIVE set are to the liveness sets for regions found in the
/// `dropck_outlives` result of the variable's type (in particular,
/// this respects `#[may_dangle]` annotations).
-pub(super) fn trace<'mir, 'tcx>(
+pub(super) fn trace<'a, 'tcx>(
typeck: &mut TypeChecker<'_, 'tcx>,
body: &Body<'tcx>,
elements: &Rc,
- flow_inits: &mut ResultsCursor<'mir, 'tcx, MaybeInitializedPlaces<'_, 'mir, 'tcx>>,
+ flow_inits: &mut ResultsCursor<'a, 'tcx, MaybeInitializedPlaces<'a, 'tcx>>,
move_data: &MoveData<'tcx>,
relevant_live_locals: Vec,
boring_locals: Vec,
@@ -99,29 +99,29 @@ pub(super) fn trace<'mir, 'tcx>(
}
/// Contextual state for the type-liveness coroutine.
-struct LivenessContext<'a, 'me, 'typeck, 'flow, 'tcx> {
+struct LivenessContext<'a, 'typeck, 'b, 'tcx> {
/// Current type-checker, giving us our inference context etc.
- typeck: &'me mut TypeChecker<'typeck, 'tcx>,
+ typeck: &'a mut TypeChecker<'typeck, 'tcx>,
/// Defines the `PointIndex` mapping
- elements: &'me DenseLocationMap,
+ elements: &'a DenseLocationMap,
/// MIR we are analyzing.
- body: &'me Body<'tcx>,
+ body: &'a Body<'tcx>,
/// Mapping to/from the various indices used for initialization tracking.
- move_data: &'me MoveData<'tcx>,
+ move_data: &'a MoveData<'tcx>,
/// Cache for the results of `dropck_outlives` query.
drop_data: FxIndexMap, DropData<'tcx>>,
/// Results of dataflow tracking which variables (and paths) have been
/// initialized.
- flow_inits: &'me mut ResultsCursor<'flow, 'tcx, MaybeInitializedPlaces<'a, 'flow, 'tcx>>,
+ flow_inits: &'a mut ResultsCursor<'b, 'tcx, MaybeInitializedPlaces<'b, 'tcx>>,
/// Index indicating where each variable is assigned, used, or
/// dropped.
- local_use_map: &'me LocalUseMap,
+ local_use_map: &'a LocalUseMap,
}
struct DropData<'tcx> {
@@ -129,8 +129,8 @@ struct DropData<'tcx> {
region_constraint_data: Option<&'tcx QueryRegionConstraints<'tcx>>,
}
-struct LivenessResults<'a, 'me, 'typeck, 'flow, 'tcx> {
- cx: LivenessContext<'a, 'me, 'typeck, 'flow, 'tcx>,
+struct LivenessResults<'a, 'typeck, 'b, 'tcx> {
+ cx: LivenessContext<'a, 'typeck, 'b, 'tcx>,
/// Set of points that define the current local.
defs: BitSet,
@@ -151,8 +151,8 @@ struct LivenessResults<'a, 'me, 'typeck, 'flow, 'tcx> {
stack: Vec,
}
-impl<'a, 'me, 'typeck, 'flow, 'tcx> LivenessResults<'a, 'me, 'typeck, 'flow, 'tcx> {
- fn new(cx: LivenessContext<'a, 'me, 'typeck, 'flow, 'tcx>) -> Self {
+impl<'a, 'typeck, 'b, 'tcx> LivenessResults<'a, 'typeck, 'b, 'tcx> {
+ fn new(cx: LivenessContext<'a, 'typeck, 'b, 'tcx>) -> Self {
let num_points = cx.elements.num_points();
LivenessResults {
cx,
@@ -353,11 +353,11 @@ impl<'a, 'me, 'typeck, 'flow, 'tcx> LivenessResults<'a, 'me, 'typeck, 'flow, 'tc
let location = self.cx.elements.to_location(drop_point);
debug_assert_eq!(self.cx.body.terminator_loc(location.block), location,);
- if self.cx.initialized_at_terminator(location.block, mpi) {
- if self.drop_live_at.insert(drop_point) {
- self.drop_locations.push(location);
- self.stack.push(drop_point);
- }
+ if self.cx.initialized_at_terminator(location.block, mpi)
+ && self.drop_live_at.insert(drop_point)
+ {
+ self.drop_locations.push(location);
+ self.stack.push(drop_point);
}
}
@@ -505,7 +505,7 @@ impl<'a, 'me, 'typeck, 'flow, 'tcx> LivenessResults<'a, 'me, 'typeck, 'flow, 'tc
}
}
-impl<'tcx> LivenessContext<'_, '_, '_, '_, 'tcx> {
+impl<'tcx> LivenessContext<'_, '_, '_, 'tcx> {
/// Returns `true` if the local variable (or some part of it) is initialized at the current
/// cursor position. Callers should call one of the `seek` methods immediately before to point
/// the cursor to the desired location.
diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs
index 3c9a43883ad64..3e5a6ad85fa56 100644
--- a/compiler/rustc_borrowck/src/type_check/mod.rs
+++ b/compiler/rustc_borrowck/src/type_check/mod.rs
@@ -116,7 +116,7 @@ mod relate_tys;
/// - `flow_inits` -- results of a maybe-init dataflow analysis
/// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
/// - `elements` -- MIR region map
-pub(crate) fn type_check<'mir, 'tcx>(
+pub(crate) fn type_check<'a, 'tcx>(
infcx: &BorrowckInferCtxt<'tcx>,
param_env: ty::ParamEnv<'tcx>,
body: &Body<'tcx>,
@@ -125,7 +125,7 @@ pub(crate) fn type_check<'mir, 'tcx>(
location_table: &LocationTable,
borrow_set: &BorrowSet<'tcx>,
all_facts: &mut Option,
- flow_inits: &mut ResultsCursor<'mir, 'tcx, MaybeInitializedPlaces<'_, 'mir, 'tcx>>,
+ flow_inits: &mut ResultsCursor<'a, 'tcx, MaybeInitializedPlaces<'a, 'tcx>>,
move_data: &MoveData<'tcx>,
elements: &Rc,
upvars: &[&ty::CapturedPlace<'tcx>],
diff --git a/compiler/rustc_borrowck/src/type_check/relate_tys.rs b/compiler/rustc_borrowck/src/type_check/relate_tys.rs
index bb4a58930e1bb..71892a67ffcc7 100644
--- a/compiler/rustc_borrowck/src/type_check/relate_tys.rs
+++ b/compiler/rustc_borrowck/src/type_check/relate_tys.rs
@@ -58,8 +58,8 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
}
}
-struct NllTypeRelating<'me, 'bccx, 'tcx> {
- type_checker: &'me mut TypeChecker<'bccx, 'tcx>,
+struct NllTypeRelating<'a, 'b, 'tcx> {
+ type_checker: &'a mut TypeChecker<'b, 'tcx>,
/// Where (and why) is this relation taking place?
locations: Locations,
@@ -82,9 +82,9 @@ struct NllTypeRelating<'me, 'bccx, 'tcx> {
ambient_variance_info: ty::VarianceDiagInfo>,
}
-impl<'me, 'bccx, 'tcx> NllTypeRelating<'me, 'bccx, 'tcx> {
+impl<'a, 'b, 'tcx> NllTypeRelating<'a, 'b, 'tcx> {
fn new(
- type_checker: &'me mut TypeChecker<'bccx, 'tcx>,
+ type_checker: &'a mut TypeChecker<'b, 'tcx>,
locations: Locations,
category: ConstraintCategory<'tcx>,
universe_info: UniverseInfo<'tcx>,
@@ -214,7 +214,7 @@ impl<'me, 'bccx, 'tcx> NllTypeRelating<'me, 'bccx, 'tcx> {
let delegate = FnMutDelegate {
regions: &mut |br: ty::BoundRegion| {
if let Some(ex_reg_var) = reg_map.get(&br) {
- return *ex_reg_var;
+ *ex_reg_var
} else {
let ex_reg_var = self.next_existential_region_var(true, br.kind.get_name());
debug!(?ex_reg_var);
@@ -309,7 +309,7 @@ impl<'me, 'bccx, 'tcx> NllTypeRelating<'me, 'bccx, 'tcx> {
}
}
-impl<'bccx, 'tcx> TypeRelation> for NllTypeRelating<'_, 'bccx, 'tcx> {
+impl<'b, 'tcx> TypeRelation> for NllTypeRelating<'_, 'b, 'tcx> {
fn cx(&self) -> TyCtxt<'tcx> {
self.type_checker.infcx.tcx
}
@@ -520,7 +520,7 @@ impl<'bccx, 'tcx> TypeRelation> for NllTypeRelating<'_, 'bccx, 'tcx
}
}
-impl<'bccx, 'tcx> PredicateEmittingRelation> for NllTypeRelating<'_, 'bccx, 'tcx> {
+impl<'b, 'tcx> PredicateEmittingRelation> for NllTypeRelating<'_, 'b, 'tcx> {
fn span(&self) -> Span {
self.locations.span(self.type_checker.body)
}
diff --git a/compiler/rustc_borrowck/src/universal_regions.rs b/compiler/rustc_borrowck/src/universal_regions.rs
index 164be73f49296..c3edbcb50cc3d 100644
--- a/compiler/rustc_borrowck/src/universal_regions.rs
+++ b/compiler/rustc_borrowck/src/universal_regions.rs
@@ -423,8 +423,8 @@ impl<'tcx> UniversalRegions<'tcx> {
}
}
-struct UniversalRegionsBuilder<'cx, 'tcx> {
- infcx: &'cx BorrowckInferCtxt<'tcx>,
+struct UniversalRegionsBuilder<'infcx, 'tcx> {
+ infcx: &'infcx BorrowckInferCtxt<'tcx>,
mir_def: LocalDefId,
param_env: ty::ParamEnv<'tcx>,
}
diff --git a/compiler/rustc_borrowck/src/used_muts.rs b/compiler/rustc_borrowck/src/used_muts.rs
index 981e7daf6702e..bde07c05c0e16 100644
--- a/compiler/rustc_borrowck/src/used_muts.rs
+++ b/compiler/rustc_borrowck/src/used_muts.rs
@@ -7,7 +7,7 @@ use tracing::debug;
use crate::MirBorrowckCtxt;
-impl<'tcx> MirBorrowckCtxt<'_, '_, '_, 'tcx> {
+impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> {
/// Walks the MIR adding to the set of `used_mut` locals that will be ignored for the purposes
/// of the `unused_mut` lint.
///
@@ -46,13 +46,13 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, '_, 'tcx> {
/// MIR visitor for collecting used mutable variables.
/// The 'visit lifetime represents the duration of the MIR walk.
-struct GatherUsedMutsVisitor<'visit, 'a, 'mir, 'infcx, 'tcx> {
+struct GatherUsedMutsVisitor<'a, 'b, 'infcx, 'tcx> {
temporary_used_locals: FxIndexSet,
- never_initialized_mut_locals: &'visit mut FxIndexSet,
- mbcx: &'visit mut MirBorrowckCtxt<'a, 'mir, 'infcx, 'tcx>,
+ never_initialized_mut_locals: &'a mut FxIndexSet,
+ mbcx: &'a mut MirBorrowckCtxt<'b, 'infcx, 'tcx>,
}
-impl GatherUsedMutsVisitor<'_, '_, '_, '_, '_> {
+impl GatherUsedMutsVisitor<'_, '_, '_, '_> {
fn remove_never_initialized_mut_locals(&mut self, into: Place<'_>) {
// Remove any locals that we found were initialized from the
// `never_initialized_mut_locals` set. At the end, the only remaining locals will
@@ -64,7 +64,7 @@ impl GatherUsedMutsVisitor<'_, '_, '_, '_, '_> {
}
}
-impl<'tcx> Visitor<'tcx> for GatherUsedMutsVisitor<'_, '_, '_, '_, 'tcx> {
+impl<'tcx> Visitor<'tcx> for GatherUsedMutsVisitor<'_, '_, '_, 'tcx> {
fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
debug!("visit_terminator: terminator={:?}", terminator);
match &terminator.kind {
diff --git a/compiler/rustc_builtin_macros/src/asm.rs b/compiler/rustc_builtin_macros/src/asm.rs
index ae2627d693867..0e1ec3b3cad1b 100644
--- a/compiler/rustc_builtin_macros/src/asm.rs
+++ b/compiler/rustc_builtin_macros/src/asm.rs
@@ -3,6 +3,7 @@ use lint::BuiltinLintDiag;
use rustc_ast::ptr::P;
use rustc_ast::token::{self, Delimiter};
use rustc_ast::tokenstream::TokenStream;
+use rustc_ast::AsmMacro;
use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
use rustc_errors::PResult;
use rustc_expand::base::*;
@@ -234,13 +235,11 @@ pub fn parse_asm_args<'a>(
continue;
}
args.named_args.insert(name, slot);
- } else {
- if !args.named_args.is_empty() || !args.reg_args.is_empty() {
- let named = args.named_args.values().map(|p| args.operands[*p].1).collect();
- let explicit = args.reg_args.iter().map(|p| args.operands[p].1).collect();
+ } else if !args.named_args.is_empty() || !args.reg_args.is_empty() {
+ let named = args.named_args.values().map(|p| args.operands[*p].1).collect();
+ let explicit = args.reg_args.iter().map(|p| args.operands[p].1).collect();
- dcx.emit_err(errors::AsmPositionalAfter { span, named, explicit });
- }
+ dcx.emit_err(errors::AsmPositionalAfter { span, named, explicit });
}
}
@@ -484,6 +483,7 @@ fn parse_reg<'a>(
fn expand_preparsed_asm(
ecx: &mut ExtCtxt<'_>,
+ asm_macro: ast::AsmMacro,
args: AsmArgs,
) -> ExpandResult, ()> {
let mut template = vec![];
@@ -774,6 +774,7 @@ fn expand_preparsed_asm(
}
ExpandResult::Ready(Ok(ast::InlineAsm {
+ asm_macro,
template,
template_strs: template_strs.into_boxed_slice(),
operands: args.operands,
@@ -790,7 +791,7 @@ pub(super) fn expand_asm<'cx>(
) -> MacroExpanderResult<'cx> {
ExpandResult::Ready(match parse_args(ecx, sp, tts, false) {
Ok(args) => {
- let ExpandResult::Ready(mac) = expand_preparsed_asm(ecx, args) else {
+ let ExpandResult::Ready(mac) = expand_preparsed_asm(ecx, AsmMacro::Asm, args) else {
return ExpandResult::Retry(());
};
let expr = match mac {
@@ -812,6 +813,45 @@ pub(super) fn expand_asm<'cx>(
})
}
+pub(super) fn expand_naked_asm<'cx>(
+ ecx: &'cx mut ExtCtxt<'_>,
+ sp: Span,
+ tts: TokenStream,
+) -> MacroExpanderResult<'cx> {
+ ExpandResult::Ready(match parse_args(ecx, sp, tts, false) {
+ Ok(args) => {
+ let ExpandResult::Ready(mac) = expand_preparsed_asm(ecx, AsmMacro::NakedAsm, args)
+ else {
+ return ExpandResult::Retry(());
+ };
+ let expr = match mac {
+ Ok(mut inline_asm) => {
+ // for future compatibility, we always set the NORETURN option.
+ //
+ // When we turn `asm!` into `naked_asm!` with this implementation, we can drop
+ // the `options(noreturn)`, which makes the upgrade smooth when `naked_asm!`
+ // starts disallowing the `noreturn` option in the future
+ inline_asm.options |= ast::InlineAsmOptions::NORETURN;
+
+ P(ast::Expr {
+ id: ast::DUMMY_NODE_ID,
+ kind: ast::ExprKind::InlineAsm(P(inline_asm)),
+ span: sp,
+ attrs: ast::AttrVec::new(),
+ tokens: None,
+ })
+ }
+ Err(guar) => DummyResult::raw_expr(sp, Some(guar)),
+ };
+ MacEager::expr(expr)
+ }
+ Err(err) => {
+ let guar = err.emit();
+ DummyResult::any(sp, guar)
+ }
+ })
+}
+
pub(super) fn expand_global_asm<'cx>(
ecx: &'cx mut ExtCtxt<'_>,
sp: Span,
@@ -819,7 +859,8 @@ pub(super) fn expand_global_asm<'cx>(
) -> MacroExpanderResult<'cx> {
ExpandResult::Ready(match parse_args(ecx, sp, tts, true) {
Ok(args) => {
- let ExpandResult::Ready(mac) = expand_preparsed_asm(ecx, args) else {
+ let ExpandResult::Ready(mac) = expand_preparsed_asm(ecx, AsmMacro::GlobalAsm, args)
+ else {
return ExpandResult::Retry(());
};
match mac {
diff --git a/compiler/rustc_builtin_macros/src/global_allocator.rs b/compiler/rustc_builtin_macros/src/global_allocator.rs
index 734da318ac1bb..66df393b501a2 100644
--- a/compiler/rustc_builtin_macros/src/global_allocator.rs
+++ b/compiler/rustc_builtin_macros/src/global_allocator.rs
@@ -65,7 +65,7 @@ struct AllocFnFactory<'a, 'b> {
span: Span,
ty_span: Span,
global: Ident,
- cx: &'b ExtCtxt<'a>,
+ cx: &'a ExtCtxt<'b>,
}
impl AllocFnFactory<'_, '_> {
diff --git a/compiler/rustc_builtin_macros/src/lib.rs b/compiler/rustc_builtin_macros/src/lib.rs
index 30e1c8d262216..ebe5e2b544292 100644
--- a/compiler/rustc_builtin_macros/src/lib.rs
+++ b/compiler/rustc_builtin_macros/src/lib.rs
@@ -94,6 +94,7 @@ pub fn register_builtin_macros(resolver: &mut dyn ResolverExpand) {
line: source_util::expand_line,
log_syntax: log_syntax::expand_log_syntax,
module_path: source_util::expand_mod,
+ naked_asm: asm::expand_naked_asm,
option_env: env::expand_option_env,
pattern_type: pattern_type::expand,
std_panic: edition_panic::expand_panic,
diff --git a/compiler/rustc_builtin_macros/src/test.rs b/compiler/rustc_builtin_macros/src/test.rs
index 1b76a5f3234a2..40dc75339efd7 100644
--- a/compiler/rustc_builtin_macros/src/test.rs
+++ b/compiler/rustc_builtin_macros/src/test.rs
@@ -277,6 +277,8 @@ pub(crate) fn expand_test_or_bench(
cx.attr_nested_word(sym::cfg, sym::test, attr_sp),
// #[rustc_test_marker = "test_case_sort_key"]
cx.attr_name_value_str(sym::rustc_test_marker, test_path_symbol, attr_sp),
+ // #[doc(hidden)]
+ cx.attr_nested_word(sym::doc, sym::hidden, attr_sp),
],
// const $ident: test::TestDescAndFn =
ast::ItemKind::Const(
diff --git a/compiler/rustc_builtin_macros/src/test_harness.rs b/compiler/rustc_builtin_macros/src/test_harness.rs
index a9e4434581163..400557ca260b2 100644
--- a/compiler/rustc_builtin_macros/src/test_harness.rs
+++ b/compiler/rustc_builtin_macros/src/test_harness.rs
@@ -326,6 +326,8 @@ fn mk_main(cx: &mut TestCtxt<'_>) -> P {
let main_attr = ecx.attr_word(sym::rustc_main, sp);
// #[coverage(off)]
let coverage_attr = ecx.attr_nested_word(sym::coverage, sym::off, sp);
+ // #[doc(hidden)]
+ let doc_hidden_attr = ecx.attr_nested_word(sym::doc, sym::hidden, sp);
// pub fn main() { ... }
let main_ret_ty = ecx.ty(sp, ast::TyKind::Tup(ThinVec::new()));
@@ -355,7 +357,7 @@ fn mk_main(cx: &mut TestCtxt<'_>) -> P {
let main = P(ast::Item {
ident: main_id,
- attrs: thin_vec![main_attr, coverage_attr],
+ attrs: thin_vec![main_attr, coverage_attr, doc_hidden_attr],
id: ast::DUMMY_NODE_ID,
kind: main,
vis: ast::Visibility { span: sp, kind: ast::VisibilityKind::Public, tokens: None },
diff --git a/compiler/rustc_codegen_cranelift/Readme.md b/compiler/rustc_codegen_cranelift/Readme.md
index 6766e2f844d6d..18a840f8a50e0 100644
--- a/compiler/rustc_codegen_cranelift/Readme.md
+++ b/compiler/rustc_codegen_cranelift/Readme.md
@@ -70,7 +70,7 @@ For more docs on how to build and test see [build_system/usage.txt](build_system
|AIX|❌[^xcoff]|N/A|N/A|❌[^xcoff]|
|Other unixes|❓|❓|❓|❓|
|macOS|✅|✅|N/A|N/A|
-|Windows|✅[^no-rustup]|❌|N/A|N/A|
+|Windows|✅|❌|N/A|N/A|
✅: Fully supported and tested
❓: Maybe supported, not tested
diff --git a/compiler/rustc_codegen_cranelift/example/float-minmax-pass.rs b/compiler/rustc_codegen_cranelift/example/float-minmax-pass.rs
index c54574d801d3a..ad46e18c11c0d 100644
--- a/compiler/rustc_codegen_cranelift/example/float-minmax-pass.rs
+++ b/compiler/rustc_codegen_cranelift/example/float-minmax-pass.rs
@@ -9,13 +9,13 @@
#[repr(simd)]
#[derive(Copy, Clone, PartialEq, Debug)]
-struct f32x4(pub f32, pub f32, pub f32, pub f32);
+struct f32x4(pub [f32; 4]);
use std::intrinsics::simd::*;
fn main() {
- let x = f32x4(1.0, 2.0, 3.0, 4.0);
- let y = f32x4(2.0, 1.0, 4.0, 3.0);
+ let x = f32x4([1.0, 2.0, 3.0, 4.0]);
+ let y = f32x4([2.0, 1.0, 4.0, 3.0]);
#[cfg(not(any(target_arch = "mips", target_arch = "mips64")))]
let nan = f32::NAN;
@@ -24,13 +24,13 @@ fn main() {
#[cfg(any(target_arch = "mips", target_arch = "mips64"))]
let nan = f32::from_bits(f32::NAN.to_bits() - 1);
- let n = f32x4(nan, nan, nan, nan);
+ let n = f32x4([nan, nan, nan, nan]);
unsafe {
let min0 = simd_fmin(x, y);
let min1 = simd_fmin(y, x);
assert_eq!(min0, min1);
- let e = f32x4(1.0, 1.0, 3.0, 3.0);
+ let e = f32x4([1.0, 1.0, 3.0, 3.0]);
assert_eq!(min0, e);
let minn = simd_fmin(x, n);
assert_eq!(minn, x);
@@ -40,7 +40,7 @@ fn main() {
let max0 = simd_fmax(x, y);
let max1 = simd_fmax(y, x);
assert_eq!(max0, max1);
- let e = f32x4(2.0, 2.0, 4.0, 4.0);
+ let e = f32x4([2.0, 2.0, 4.0, 4.0]);
assert_eq!(max0, e);
let maxn = simd_fmax(x, n);
assert_eq!(maxn, x);
diff --git a/compiler/rustc_codegen_cranelift/example/std_example.rs b/compiler/rustc_codegen_cranelift/example/std_example.rs
index e99763e272233..f27d4ef57e0c0 100644
--- a/compiler/rustc_codegen_cranelift/example/std_example.rs
+++ b/compiler/rustc_codegen_cranelift/example/std_example.rs
@@ -166,7 +166,7 @@ fn main() {
enum Never {}
}
- foo(I64X2(0, 0));
+ foo(I64X2([0, 0]));
transmute_fat_pointer();
@@ -204,7 +204,7 @@ fn rust_call_abi() {
}
#[repr(simd)]
-struct I64X2(i64, i64);
+struct I64X2([i64; 2]);
#[allow(improper_ctypes_definitions)]
extern "C" fn foo(_a: I64X2) {}
diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs
index 604a88393fd95..a5621aec2444f 100644
--- a/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs
+++ b/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs
@@ -180,34 +180,20 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>(
return;
}
- // Make sure this is actually an array, since typeck only checks the length-suffixed
- // version of this intrinsic.
+ // Make sure this is actually a SIMD vector.
let idx_ty = fx.monomorphize(idx.node.ty(fx.mir, fx.tcx));
- let n: u16 = match idx_ty.kind() {
- ty::Array(ty, len) if matches!(ty.kind(), ty::Uint(ty::UintTy::U32)) => len
- .try_eval_target_usize(fx.tcx, ty::ParamEnv::reveal_all())
- .unwrap_or_else(|| {
- span_bug!(span, "could not evaluate shuffle index array length")
- })
- .try_into()
- .unwrap(),
- _ if idx_ty.is_simd()
- && matches!(
- idx_ty.simd_size_and_type(fx.tcx).1.kind(),
- ty::Uint(ty::UintTy::U32)
- ) =>
- {
- idx_ty.simd_size_and_type(fx.tcx).0.try_into().unwrap()
- }
- _ => {
- fx.tcx.dcx().span_err(
- span,
- format!("simd_shuffle index must be an array of `u32`, got `{}`", idx_ty),
- );
- // Prevent verifier error
- fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
- return;
- }
+ let n: u16 = if idx_ty.is_simd()
+ && matches!(idx_ty.simd_size_and_type(fx.tcx).1.kind(), ty::Uint(ty::UintTy::U32))
+ {
+ idx_ty.simd_size_and_type(fx.tcx).0.try_into().unwrap()
+ } else {
+ fx.tcx.dcx().span_err(
+ span,
+ format!("simd_shuffle index must be a SIMD vector of `u32`, got `{}`", idx_ty),
+ );
+ // Prevent verifier error
+ fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
+ return;
};
assert_eq!(x.layout(), y.layout());
diff --git a/compiler/rustc_codegen_gcc/Cargo.lock b/compiler/rustc_codegen_gcc/Cargo.lock
index 915229f7e7eef..0eb264f99eb08 100644
--- a/compiler/rustc_codegen_gcc/Cargo.lock
+++ b/compiler/rustc_codegen_gcc/Cargo.lock
@@ -11,63 +11,12 @@ dependencies = [
"memchr",
]
-[[package]]
-name = "bitflags"
-version = "1.3.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
-
-[[package]]
-name = "bitflags"
-version = "2.4.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b4682ae6287fcf752ecaabbfcc7b6f9b72aa33933dc23a554d853aea8eea8635"
-
[[package]]
name = "boml"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85fdb93f04c73bff54305fa437ffea5449c41edcaadfe882f35836206b166ac5"
-[[package]]
-name = "cc"
-version = "1.0.79"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f"
-
-[[package]]
-name = "cfg-if"
-version = "1.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
-
-[[package]]
-name = "errno"
-version = "0.3.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4bcfec3a70f97c962c307b2d2c56e358cf1d00b558d74262b5f929ee8cc7e73a"
-dependencies = [
- "errno-dragonfly",
- "libc",
- "windows-sys",
-]
-
-[[package]]
-name = "errno-dragonfly"
-version = "0.1.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf"
-dependencies = [
- "cc",
- "libc",
-]
-
-[[package]]
-name = "fastrand"
-version = "2.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6999dc1837253364c2ebb0704ba97994bd874e8f195d665c50b7548f6ea92764"
-
[[package]]
name = "fm"
version = "0.2.2"
@@ -132,12 +81,6 @@ version = "0.2.150"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89d92a4743f9a61002fae18374ed11e7973f530cb3a3255fb354818118b2203c"
-[[package]]
-name = "linux-raw-sys"
-version = "0.4.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "57bcfdad1b858c2db7c38303a6d2ad4dfaf5eb53dfeb0910128b2c26d6158503"
-
[[package]]
name = "memchr"
version = "2.5.0"
@@ -154,24 +97,6 @@ dependencies = [
"libc",
]
-[[package]]
-name = "object"
-version = "0.30.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "03b4680b86d9cfafba8fc491dc9b6df26b68cf40e9e6cd73909194759a63c385"
-dependencies = [
- "memchr",
-]
-
-[[package]]
-name = "redox_syscall"
-version = "0.3.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29"
-dependencies = [
- "bitflags 1.3.2",
-]
-
[[package]]
name = "regex"
version = "1.8.4"
@@ -196,22 +121,6 @@ dependencies = [
"boml",
"gccjit",
"lang_tester",
- "object",
- "smallvec",
- "tempfile",
-]
-
-[[package]]
-name = "rustix"
-version = "0.38.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "19ed4fa021d81c8392ce04db050a3da9a60299050b7ae1cf482d862b54a7218f"
-dependencies = [
- "bitflags 2.4.0",
- "errno",
- "libc",
- "linux-raw-sys",
- "windows-sys",
]
[[package]]
@@ -223,25 +132,6 @@ dependencies = [
"winapi-util",
]
-[[package]]
-name = "smallvec"
-version = "1.10.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0"
-
-[[package]]
-name = "tempfile"
-version = "3.7.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dc02fddf48964c42031a0b3fe0428320ecf3a73c401040fc0096f97794310651"
-dependencies = [
- "cfg-if",
- "fastrand",
- "redox_syscall",
- "rustix",
- "windows-sys",
-]
-
[[package]]
name = "termcolor"
version = "1.2.0"
@@ -315,69 +205,3 @@ name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
-
-[[package]]
-name = "windows-sys"
-version = "0.48.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
-dependencies = [
- "windows-targets",
-]
-
-[[package]]
-name = "windows-targets"
-version = "0.48.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "05d4b17490f70499f20b9e791dcf6a299785ce8af4d709018206dc5b4953e95f"
-dependencies = [
- "windows_aarch64_gnullvm",
- "windows_aarch64_msvc",
- "windows_i686_gnu",
- "windows_i686_msvc",
- "windows_x86_64_gnu",
- "windows_x86_64_gnullvm",
- "windows_x86_64_msvc",
-]
-
-[[package]]
-name = "windows_aarch64_gnullvm"
-version = "0.48.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc"
-
-[[package]]
-name = "windows_aarch64_msvc"
-version = "0.48.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3"
-
-[[package]]
-name = "windows_i686_gnu"
-version = "0.48.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241"
-
-[[package]]
-name = "windows_i686_msvc"
-version = "0.48.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00"
-
-[[package]]
-name = "windows_x86_64_gnu"
-version = "0.48.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1"
-
-[[package]]
-name = "windows_x86_64_gnullvm"
-version = "0.48.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953"
-
-[[package]]
-name = "windows_x86_64_msvc"
-version = "0.48.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a"
diff --git a/compiler/rustc_codegen_gcc/Cargo.toml b/compiler/rustc_codegen_gcc/Cargo.toml
index 5caca63f63480..44fb5eef04a57 100644
--- a/compiler/rustc_codegen_gcc/Cargo.toml
+++ b/compiler/rustc_codegen_gcc/Cargo.toml
@@ -23,21 +23,11 @@ default = ["master"]
[dependencies]
gccjit = "2.1"
-
# Local copy.
#gccjit = { path = "../gccjit.rs" }
-object = { version = "0.30.1", default-features = false, features = [
- "std",
- "read",
-] }
-smallvec = { version = "1.6.1", features = ["union", "may_dangle"] }
-# TODO(antoyo): make tempfile optional.
-tempfile = "3.7.1"
-
[dev-dependencies]
lang_tester = "0.8.0"
-tempfile = "3.1.0"
boml = "0.3.1"
[profile.dev]
diff --git a/compiler/rustc_codegen_gcc/src/back/lto.rs b/compiler/rustc_codegen_gcc/src/back/lto.rs
index 6b2dbbbed6771..c2adab7137f62 100644
--- a/compiler/rustc_codegen_gcc/src/back/lto.rs
+++ b/compiler/rustc_codegen_gcc/src/back/lto.rs
@@ -272,7 +272,6 @@ fn fat_lto(
}*/
}
};
- let mut serialized_bitcode = Vec::new();
{
info!("using {:?} as a base module", module.name);
@@ -317,7 +316,6 @@ fn fat_lto(
unimplemented!("from uncompressed file")
}
}
- serialized_bitcode.push(bc_decoded);
}
save_temp_bitcode(cgcx, &module, "lto.input");
@@ -337,7 +335,7 @@ fn fat_lto(
// of now.
module.module_llvm.temp_dir = Some(tmp_path);
- Ok(LtoModuleCodegen::Fat { module, _serialized_bitcode: serialized_bitcode })
+ Ok(LtoModuleCodegen::Fat(module))
}
pub struct ModuleBuffer(PathBuf);
diff --git a/compiler/rustc_codegen_gcc/src/builder.rs b/compiler/rustc_codegen_gcc/src/builder.rs
index 6ba678e2e7c65..31d778823e076 100644
--- a/compiler/rustc_codegen_gcc/src/builder.rs
+++ b/compiler/rustc_codegen_gcc/src/builder.rs
@@ -1939,33 +1939,18 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> {
self.int_type
};
- let mut mask_elements = if let Some(vector_type) = mask.get_type().dyncast_vector() {
- let mask_num_units = vector_type.get_num_units();
- let mut mask_elements = vec![];
- for i in 0..mask_num_units {
- let index = self.context.new_rvalue_from_long(self.cx.type_u32(), i as _);
- mask_elements.push(self.context.new_cast(
- self.location,
- self.extract_element(mask, index).to_rvalue(),
- mask_element_type,
- ));
- }
- mask_elements
- } else {
- let struct_type = mask.get_type().is_struct().expect("mask should be of struct type");
- let mask_num_units = struct_type.get_field_count();
- let mut mask_elements = vec![];
- for i in 0..mask_num_units {
- let field = struct_type.get_field(i as i32);
- mask_elements.push(self.context.new_cast(
- self.location,
- mask.access_field(self.location, field).to_rvalue(),
- mask_element_type,
- ));
- }
- mask_elements
- };
- let mask_num_units = mask_elements.len();
+ let vector_type =
+ mask.get_type().dyncast_vector().expect("simd_shuffle mask should be of vector type");
+ let mask_num_units = vector_type.get_num_units();
+ let mut mask_elements = vec![];
+ for i in 0..mask_num_units {
+ let index = self.context.new_rvalue_from_long(self.cx.type_u32(), i as _);
+ mask_elements.push(self.context.new_cast(
+ self.location,
+ self.extract_element(mask, index).to_rvalue(),
+ mask_element_type,
+ ));
+ }
// NOTE: the mask needs to be the same length as the input vectors, so add the missing
// elements in the mask if needed.
diff --git a/compiler/rustc_codegen_gcc/src/debuginfo.rs b/compiler/rustc_codegen_gcc/src/debuginfo.rs
index d770da5a8c44f..f2ae9f9c8a62e 100644
--- a/compiler/rustc_codegen_gcc/src/debuginfo.rs
+++ b/compiler/rustc_codegen_gcc/src/debuginfo.rs
@@ -48,6 +48,10 @@ impl<'a, 'gcc, 'tcx> DebugInfoBuilderMethods for Builder<'a, 'gcc, 'tcx> {
fn set_dbg_loc(&mut self, dbg_loc: Self::DILocation) {
self.location = Some(dbg_loc);
}
+
+ fn clear_dbg_loc(&mut self) {
+ self.location = None;
+ }
}
/// Generate the `debug_context` in an MIR Body.
diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs b/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs
index 96a833ccaf2b6..2eabc1430db5e 100644
--- a/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs
+++ b/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs
@@ -14,7 +14,6 @@ use rustc_codegen_ssa::traits::{BaseTypeMethods, BuilderMethods};
#[cfg(feature = "master")]
use rustc_hir as hir;
use rustc_middle::mir::BinOp;
-use rustc_middle::span_bug;
use rustc_middle::ty::layout::HasTyCtxt;
use rustc_middle::ty::{self, Ty};
use rustc_span::{sym, Span, Symbol};
@@ -353,24 +352,14 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>(
}
if name == sym::simd_shuffle {
- // Make sure this is actually an array or SIMD vector, since typeck only checks the length-suffixed
- // version of this intrinsic.
+ // Make sure this is actually a SIMD vector.
let idx_ty = args[2].layout.ty;
- let n: u64 = match idx_ty.kind() {
- ty::Array(ty, len) if matches!(*ty.kind(), ty::Uint(ty::UintTy::U32)) => {
- len.try_eval_target_usize(bx.cx.tcx, ty::ParamEnv::reveal_all()).unwrap_or_else(
- || span_bug!(span, "could not evaluate shuffle index array length"),
- )
- }
- _ if idx_ty.is_simd()
- && matches!(
- idx_ty.simd_size_and_type(bx.cx.tcx).1.kind(),
- ty::Uint(ty::UintTy::U32)
- ) =>
- {
- idx_ty.simd_size_and_type(bx.cx.tcx).0
- }
- _ => return_error!(InvalidMonomorphization::SimdShuffle { span, name, ty: idx_ty }),
+ let n: u64 = if idx_ty.is_simd()
+ && matches!(idx_ty.simd_size_and_type(bx.cx.tcx).1.kind(), ty::Uint(ty::UintTy::U32))
+ {
+ idx_ty.simd_size_and_type(bx.cx.tcx).0
+ } else {
+ return_error!(InvalidMonomorphization::SimdShuffle { span, name, ty: idx_ty })
};
require_simd!(ret_ty, InvalidMonomorphization::SimdReturn { span, name, ty: ret_ty });
diff --git a/compiler/rustc_codegen_gcc/src/lib.rs b/compiler/rustc_codegen_gcc/src/lib.rs
index 94f016234f921..4de671ac4a062 100644
--- a/compiler/rustc_codegen_gcc/src/lib.rs
+++ b/compiler/rustc_codegen_gcc/src/lib.rs
@@ -24,6 +24,14 @@
#![deny(clippy::pattern_type_mismatch)]
#![allow(clippy::needless_lifetimes)]
+// Some "regular" crates we want to share with rustc
+extern crate object;
+extern crate smallvec;
+extern crate tempfile;
+#[macro_use]
+extern crate tracing;
+
+// The rustc crates we need
extern crate rustc_apfloat;
extern crate rustc_ast;
extern crate rustc_attr;
@@ -42,8 +50,6 @@ extern crate rustc_middle;
extern crate rustc_session;
extern crate rustc_span;
extern crate rustc_target;
-#[macro_use]
-extern crate tracing;
// This prevents duplicating functions and statics that are already part of the host rustc process.
#[allow(unused_extern_crates)]
diff --git a/compiler/rustc_codegen_llvm/src/back/lto.rs b/compiler/rustc_codegen_llvm/src/back/lto.rs
index aa6842c75cec7..2ebe0be53aa11 100644
--- a/compiler/rustc_codegen_llvm/src/back/lto.rs
+++ b/compiler/rustc_codegen_llvm/src/back/lto.rs
@@ -92,11 +92,9 @@ fn prepare_lto(
dcx.emit_err(LtoDylib);
return Err(FatalError);
}
- } else if *crate_type == CrateType::ProcMacro {
- if !cgcx.opts.unstable_opts.dylib_lto {
- dcx.emit_err(LtoProcMacro);
- return Err(FatalError);
- }
+ } else if *crate_type == CrateType::ProcMacro && !cgcx.opts.unstable_opts.dylib_lto {
+ dcx.emit_err(LtoProcMacro);
+ return Err(FatalError);
}
}
@@ -314,7 +312,6 @@ fn fat_lto(
}
}
};
- let mut serialized_bitcode = Vec::new();
{
let (llcx, llmod) = {
let llvm = &module.module_llvm;
@@ -342,9 +339,7 @@ fn fat_lto(
serialized_modules.sort_by(|module1, module2| module1.1.cmp(&module2.1));
// For all serialized bitcode files we parse them and link them in as we did
- // above, this is all mostly handled in C++. Like above, though, we don't
- // know much about the memory management here so we err on the side of being
- // save and persist everything with the original module.
+ // above, this is all mostly handled in C++.
let mut linker = Linker::new(llmod);
for (bc_decoded, name) in serialized_modules {
let _timer = cgcx
@@ -355,7 +350,6 @@ fn fat_lto(
info!("linking {:?}", name);
let data = bc_decoded.data();
linker.add(data).map_err(|()| write::llvm_err(dcx, LlvmError::LoadBitcode { name }))?;
- serialized_bitcode.push(bc_decoded);
}
drop(linker);
save_temp_bitcode(cgcx, &module, "lto.input");
@@ -372,7 +366,7 @@ fn fat_lto(
}
}
- Ok(LtoModuleCodegen::Fat { module, _serialized_bitcode: serialized_bitcode })
+ Ok(LtoModuleCodegen::Fat(module))
}
pub(crate) struct Linker<'a>(&'a mut llvm::Linker<'a>);
diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs
index 01aae24ab56c2..73c2c15717fc1 100644
--- a/compiler/rustc_codegen_llvm/src/context.rs
+++ b/compiler/rustc_codegen_llvm/src/context.rs
@@ -27,7 +27,7 @@ use rustc_span::source_map::Spanned;
use rustc_span::{Span, DUMMY_SP};
use rustc_target::abi::call::FnAbi;
use rustc_target::abi::{HasDataLayout, TargetDataLayout, VariantIdx};
-use rustc_target::spec::{HasTargetSpec, RelocModel, Target, TlsModel};
+use rustc_target::spec::{HasTargetSpec, RelocModel, SmallDataThresholdSupport, Target, TlsModel};
use smallvec::SmallVec;
use crate::back::write::to_llvm_code_model;
@@ -387,6 +387,24 @@ pub(crate) unsafe fn create_module<'ll>(
}
}
+ match (sess.opts.unstable_opts.small_data_threshold, sess.target.small_data_threshold_support())
+ {
+ // Set up the small-data optimization limit for architectures that use
+ // an LLVM module flag to control this.
+ (Some(threshold), SmallDataThresholdSupport::LlvmModuleFlag(flag)) => {
+ let flag = SmallCStr::new(flag.as_ref());
+ unsafe {
+ llvm::LLVMRustAddModuleFlagU32(
+ llmod,
+ llvm::LLVMModFlagBehavior::Error,
+ flag.as_c_str().as_ptr(),
+ threshold as u32,
+ )
+ }
+ }
+ _ => (),
+ };
+
// Insert `llvm.ident` metadata.
//
// On the wasm targets it will get hooked up to the "producer" sections
diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs
index f5d6fc6f08073..842212ac05d4d 100644
--- a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs
+++ b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs
@@ -1,8 +1,8 @@
#![doc = include_str!("doc.md")]
use std::cell::{OnceCell, RefCell};
-use std::iter;
use std::ops::Range;
+use std::{iter, ptr};
use libc::c_uint;
use rustc_codegen_ssa::debuginfo::type_names;
@@ -209,6 +209,12 @@ impl<'ll> DebugInfoBuilderMethods for Builder<'_, 'll, '_> {
}
}
+ fn clear_dbg_loc(&mut self) {
+ unsafe {
+ llvm::LLVMSetCurrentDebugLocation2(self.llbuilder, ptr::null());
+ }
+ }
+
fn insert_reference_to_gdb_debug_scripts_section_global(&mut self) {
gdb::insert_reference_to_gdb_debug_scripts_section_global(self)
}
diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs
index 05fb77a193af3..9705dd506b97b 100644
--- a/compiler/rustc_codegen_llvm/src/intrinsic.rs
+++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs
@@ -573,6 +573,8 @@ impl<'ll, 'tcx> IntrinsicCallMethods<'tcx> for Builder<'_, 'll, 'tcx> {
span,
) {
Ok(llval) => llval,
+ // If there was an error, just skip this invocation... we'll abort compilation anyway,
+ // but we can keep codegen'ing to find more errors.
Err(()) => return Ok(()),
}
}
@@ -1290,24 +1292,14 @@ fn generic_simd_intrinsic<'ll, 'tcx>(
}
if name == sym::simd_shuffle {
- // Make sure this is actually an array or SIMD vector, since typeck only checks the length-suffixed
- // version of this intrinsic.
+ // Make sure this is actually a SIMD vector.
let idx_ty = args[2].layout.ty;
- let n: u64 = match idx_ty.kind() {
- ty::Array(ty, len) if matches!(ty.kind(), ty::Uint(ty::UintTy::U32)) => {
- len.try_eval_target_usize(bx.cx.tcx, ty::ParamEnv::reveal_all()).unwrap_or_else(
- || span_bug!(span, "could not evaluate shuffle index array length"),
- )
- }
- _ if idx_ty.is_simd()
- && matches!(
- idx_ty.simd_size_and_type(bx.cx.tcx).1.kind(),
- ty::Uint(ty::UintTy::U32)
- ) =>
- {
- idx_ty.simd_size_and_type(bx.cx.tcx).0
- }
- _ => return_error!(InvalidMonomorphization::SimdShuffle { span, name, ty: idx_ty }),
+ let n: u64 = if idx_ty.is_simd()
+ && matches!(idx_ty.simd_size_and_type(bx.cx.tcx).1.kind(), ty::Uint(ty::UintTy::U32))
+ {
+ idx_ty.simd_size_and_type(bx.cx.tcx).0
+ } else {
+ return_error!(InvalidMonomorphization::SimdShuffle { span, name, ty: idx_ty })
};
let (out_len, out_ty) = require_simd!(ret_ty, SimdReturn);
@@ -1322,38 +1314,24 @@ fn generic_simd_intrinsic<'ll, 'tcx>(
let total_len = u128::from(in_len) * 2;
- let vector = args[2].immediate();
-
- let indices: Option> = (0..n)
- .map(|i| {
- let arg_idx = i;
- let val = bx.const_get_elt(vector, i as u64);
- match bx.const_to_opt_u128(val, true) {
- None => {
- bug!("typeck should have already ensured that these are const")
- }
- Some(idx) if idx >= total_len => {
- bx.sess().dcx().emit_err(InvalidMonomorphization::SimdIndexOutOfBounds {
- span,
- name,
- arg_idx,
- total_len,
- });
- None
- }
- Some(idx) => Some(bx.const_i32(idx as i32)),
- }
- })
- .collect();
- let Some(indices) = indices else {
- return Ok(bx.const_null(llret_ty));
- };
+ // Check that the indices are in-bounds.
+ let indices = args[2].immediate();
+ for i in 0..n {
+ let val = bx.const_get_elt(indices, i as u64);
+ let idx = bx
+ .const_to_opt_u128(val, true)
+ .unwrap_or_else(|| bug!("typeck should have already ensured that these are const"));
+ if idx >= total_len {
+ return_error!(InvalidMonomorphization::SimdIndexOutOfBounds {
+ span,
+ name,
+ arg_idx: i,
+ total_len,
+ });
+ }
+ }
- return Ok(bx.shuffle_vector(
- args[0].immediate(),
- args[1].immediate(),
- bx.const_vector(&indices),
- ));
+ return Ok(bx.shuffle_vector(args[0].immediate(), args[1].immediate(), indices));
}
if name == sym::simd_insert {
@@ -1371,13 +1349,12 @@ fn generic_simd_intrinsic<'ll, 'tcx>(
.const_to_opt_u128(args[1].immediate(), false)
.expect("typeck should have ensure that this is a const");
if idx >= in_len.into() {
- bx.sess().dcx().emit_err(InvalidMonomorphization::SimdIndexOutOfBounds {
+ return_error!(InvalidMonomorphization::SimdIndexOutOfBounds {
span,
name,
arg_idx: 1,
total_len: in_len.into(),
});
- return Ok(bx.const_null(llret_ty));
}
return Ok(bx.insert_element(
args[0].immediate(),
@@ -1394,13 +1371,12 @@ fn generic_simd_intrinsic<'ll, 'tcx>(
.const_to_opt_u128(args[1].immediate(), false)
.expect("typeck should have ensure that this is a const");
if idx >= in_len.into() {
- bx.sess().dcx().emit_err(InvalidMonomorphization::SimdIndexOutOfBounds {
+ return_error!(InvalidMonomorphization::SimdIndexOutOfBounds {
span,
name,
arg_idx: 1,
total_len: in_len.into(),
});
- return Ok(bx.const_null(llret_ty));
}
return Ok(bx.extract_element(args[0].immediate(), bx.const_i32(idx as i32)));
}
diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs
index 3bf4d4964082f..e84ab0aa53889 100644
--- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs
+++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs
@@ -1041,7 +1041,7 @@ unsafe extern "C" {
pub fn LLVMDisposeBuilder<'a>(Builder: &'a mut Builder<'a>);
// Metadata
- pub fn LLVMSetCurrentDebugLocation2<'a>(Builder: &Builder<'a>, Loc: &'a Metadata);
+ pub fn LLVMSetCurrentDebugLocation2<'a>(Builder: &Builder<'a>, Loc: *const Metadata);
// Terminators
pub fn LLVMBuildRetVoid<'a>(B: &Builder<'a>) -> &'a Value;
diff --git a/compiler/rustc_codegen_llvm/src/llvm_util.rs b/compiler/rustc_codegen_llvm/src/llvm_util.rs
index d55220ba5c3a4..29afe6f6bfc7f 100644
--- a/compiler/rustc_codegen_llvm/src/llvm_util.rs
+++ b/compiler/rustc_codegen_llvm/src/llvm_util.rs
@@ -14,7 +14,7 @@ use rustc_middle::bug;
use rustc_session::config::{PrintKind, PrintRequest};
use rustc_session::Session;
use rustc_span::symbol::Symbol;
-use rustc_target::spec::{MergeFunctions, PanicStrategy};
+use rustc_target::spec::{MergeFunctions, PanicStrategy, SmallDataThresholdSupport};
use rustc_target::target_features::{RUSTC_SPECIAL_FEATURES, RUSTC_SPECIFIC_FEATURES};
use crate::back::write::create_informational_target_machine;
@@ -125,6 +125,18 @@ unsafe fn configure_llvm(sess: &Session) {
for arg in sess_args {
add(&(*arg), true);
}
+
+ match (
+ sess.opts.unstable_opts.small_data_threshold,
+ sess.target.small_data_threshold_support(),
+ ) {
+ // Set up the small-data optimization limit for architectures that use
+ // an LLVM argument to control this.
+ (Some(threshold), SmallDataThresholdSupport::LlvmArg(arg)) => {
+ add(&format!("--{arg}={threshold}"), false)
+ }
+ _ => (),
+ };
}
if sess.opts.unstable_opts.llvm_time_trace {
@@ -290,7 +302,7 @@ pub(crate) fn check_tied_features(
}
}
}
- return None;
+ None
}
/// Used to generate cfg variables and apply features
diff --git a/compiler/rustc_codegen_ssa/messages.ftl b/compiler/rustc_codegen_ssa/messages.ftl
index 8a6a2acd87d44..9091602d75b71 100644
--- a/compiler/rustc_codegen_ssa/messages.ftl
+++ b/compiler/rustc_codegen_ssa/messages.ftl
@@ -132,7 +132,7 @@ codegen_ssa_invalid_monomorphization_simd_return = invalid monomorphization of `
codegen_ssa_invalid_monomorphization_simd_second = invalid monomorphization of `{$name}` intrinsic: expected SIMD second type, found non-SIMD `{$ty}`
-codegen_ssa_invalid_monomorphization_simd_shuffle = invalid monomorphization of `{$name}` intrinsic: simd_shuffle index must be an array of `u32`, got `{$ty}`
+codegen_ssa_invalid_monomorphization_simd_shuffle = invalid monomorphization of `{$name}` intrinsic: simd_shuffle index must be a SIMD vector of `u32`, got `{$ty}`
codegen_ssa_invalid_monomorphization_simd_third = invalid monomorphization of `{$name}` intrinsic: expected SIMD third type, found non-SIMD `{$ty}`
diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs
index e8143b9a5f38f..8b855bd0dd568 100644
--- a/compiler/rustc_codegen_ssa/src/back/link.rs
+++ b/compiler/rustc_codegen_ssa/src/back/link.rs
@@ -281,12 +281,10 @@ pub fn each_linked_rlib(
let used_crate_source = &info.used_crate_source[&cnum];
if let Some((path, _)) = &used_crate_source.rlib {
f(cnum, path);
+ } else if used_crate_source.rmeta.is_some() {
+ return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name });
} else {
- if used_crate_source.rmeta.is_some() {
- return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name });
- } else {
- return Err(errors::LinkRlibError::NotFound { crate_name });
- }
+ return Err(errors::LinkRlibError::NotFound { crate_name });
}
}
Ok(())
@@ -438,7 +436,7 @@ fn link_rlib<'a>(
ab.add_file(&lib)
}
- return Ok(ab);
+ Ok(ab)
}
/// Extract all symbols defined in raw-dylib libraries, collated by library name.
@@ -628,12 +626,10 @@ fn link_staticlib(
let used_crate_source = &codegen_results.crate_info.used_crate_source[&cnum];
if let Some((path, _)) = &used_crate_source.dylib {
all_rust_dylibs.push(&**path);
+ } else if used_crate_source.rmeta.is_some() {
+ sess.dcx().emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name });
} else {
- if used_crate_source.rmeta.is_some() {
- sess.dcx().emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name });
- } else {
- sess.dcx().emit_fatal(errors::LinkRlibError::NotFound { crate_name });
- }
+ sess.dcx().emit_fatal(errors::LinkRlibError::NotFound { crate_name });
}
}
@@ -1319,7 +1315,7 @@ fn link_sanitizer_runtime(
fn find_sanitizer_runtime(sess: &Session, filename: &str) -> PathBuf {
let path = sess.target_tlib_path.dir.join(filename);
if path.exists() {
- return sess.target_tlib_path.dir.clone();
+ sess.target_tlib_path.dir.clone()
} else {
let default_sysroot =
filesearch::get_or_default_sysroot().expect("Failed finding sysroot");
@@ -1327,7 +1323,7 @@ fn link_sanitizer_runtime(
&default_sysroot,
sess.opts.target_triple.triple(),
);
- return default_tlib;
+ default_tlib
}
}
@@ -1972,10 +1968,8 @@ fn add_late_link_args(
if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
cmd.verbatim_args(args.iter().map(Deref::deref));
}
- } else {
- if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
- cmd.verbatim_args(args.iter().map(Deref::deref));
- }
+ } else if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
+ cmd.verbatim_args(args.iter().map(Deref::deref));
}
if let Some(args) = sess.target.late_link_args.get(&flavor) {
cmd.verbatim_args(args.iter().map(Deref::deref));
@@ -2635,10 +2629,8 @@ fn add_native_libs_from_crate(
if link_static {
cmd.link_staticlib_by_name(name, verbatim, false);
}
- } else {
- if link_dynamic {
- cmd.link_dylib_by_name(name, verbatim, true);
- }
+ } else if link_dynamic {
+ cmd.link_dylib_by_name(name, verbatim, true);
}
}
NativeLibKind::Framework { as_needed } => {
@@ -3052,7 +3044,7 @@ fn get_apple_sdk_root(sdk_name: &str) -> Result {
}
- "macosx10.15"
+ "macosx"
if sdkroot.contains("iPhoneOS.platform")
|| sdkroot.contains("iPhoneSimulator.platform") => {}
"watchos"
diff --git a/compiler/rustc_codegen_ssa/src/back/linker.rs b/compiler/rustc_codegen_ssa/src/back/linker.rs
index cb266247e0dde..7f5f9f0386809 100644
--- a/compiler/rustc_codegen_ssa/src/back/linker.rs
+++ b/compiler/rustc_codegen_ssa/src/back/linker.rs
@@ -791,14 +791,12 @@ impl<'a> Linker for GccLinker<'a> {
self.link_arg("-exported_symbols_list").link_arg(path);
} else if self.sess.target.is_like_solaris {
self.link_arg("-M").link_arg(path);
+ } else if is_windows {
+ self.link_arg(path);
} else {
- if is_windows {
- self.link_arg(path);
- } else {
- let mut arg = OsString::from("--version-script=");
- arg.push(path);
- self.link_arg(arg).link_arg("--no-undefined-version");
- }
+ let mut arg = OsString::from("--version-script=");
+ arg.push(path);
+ self.link_arg(arg).link_arg("--no-undefined-version");
}
}
@@ -1484,7 +1482,6 @@ impl<'a> Linker for L4Bender<'a> {
fn export_symbols(&mut self, _: &Path, _: CrateType, _: &[String]) {
// ToDo, not implemented, copy from GCC
self.sess.dcx().emit_warn(errors::L4BenderExportingSymbolsUnimplemented);
- return;
}
fn subsystem(&mut self, subsystem: &str) {
diff --git a/compiler/rustc_codegen_ssa/src/back/lto.rs b/compiler/rustc_codegen_ssa/src/back/lto.rs
index 8b6f6b5a220a4..1e1e039882be0 100644
--- a/compiler/rustc_codegen_ssa/src/back/lto.rs
+++ b/compiler/rustc_codegen_ssa/src/back/lto.rs
@@ -41,18 +41,14 @@ pub struct ThinShared {
}
pub enum LtoModuleCodegen {
- Fat {
- module: ModuleCodegen,
- _serialized_bitcode: Vec>,
- },
-
+ Fat(ModuleCodegen),
Thin(ThinModule),
}
impl LtoModuleCodegen {
pub fn name(&self) -> &str {
match *self {
- LtoModuleCodegen::Fat { .. } => "everything",
+ LtoModuleCodegen::Fat(_) => "everything",
LtoModuleCodegen::Thin(ref m) => m.name(),
}
}
@@ -68,7 +64,7 @@ impl LtoModuleCodegen {
cgcx: &CodegenContext,
) -> Result, FatalError> {
match self {
- LtoModuleCodegen::Fat { mut module, .. } => {
+ LtoModuleCodegen::Fat(mut module) => {
B::optimize_fat(cgcx, &mut module)?;
Ok(module)
}
@@ -81,7 +77,7 @@ impl LtoModuleCodegen {
pub fn cost(&self) -> u64 {
match *self {
// Only one module with fat LTO, so the cost doesn't matter.
- LtoModuleCodegen::Fat { .. } => 0,
+ LtoModuleCodegen::Fat(_) => 0,
LtoModuleCodegen::Thin(ref m) => m.cost(),
}
}
diff --git a/compiler/rustc_codegen_ssa/src/back/metadata.rs b/compiler/rustc_codegen_ssa/src/back/metadata.rs
index 0fd9d7fffe8f9..6215616e51000 100644
--- a/compiler/rustc_codegen_ssa/src/back/metadata.rs
+++ b/compiler/rustc_codegen_ssa/src/back/metadata.rs
@@ -171,10 +171,10 @@ pub(super) fn get_metadata_xcoff<'a>(path: &Path, data: &'a [u8]) -> Result<&'a
"Metadata at offset {offset} with size {len} is beyond .info section"
));
}
- return Ok(&info_data[offset..(offset + len)]);
+ Ok(&info_data[offset..(offset + len)])
} else {
- return Err(format!("Unable to find symbol {AIX_METADATA_SYMBOL_NAME}"));
- };
+ Err(format!("Unable to find symbol {AIX_METADATA_SYMBOL_NAME}"))
+ }
}
pub(crate) fn create_object_file(sess: &Session) -> Option> {
@@ -413,7 +413,7 @@ fn macho_object_build_version_for_target(target: &Target) -> object::write::Mach
/// Is Apple's CPU subtype `arm64e`s
fn macho_is_arm64e(target: &Target) -> bool {
- return target.llvm_target.starts_with("arm64e");
+ target.llvm_target.starts_with("arm64e")
}
pub enum MetadataPosition {
diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs
index 4ab20c154ccd0..9149c60229668 100644
--- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs
+++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs
@@ -617,32 +617,29 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
// purpose functions as they wouldn't have the right target features
// enabled. For that reason we also forbid #[inline(always)] as it can't be
// respected.
- if !codegen_fn_attrs.target_features.is_empty() {
- if codegen_fn_attrs.inline == InlineAttr::Always {
- if let Some(span) = inline_span {
- tcx.dcx().span_err(
- span,
- "cannot use `#[inline(always)]` with \
+ if !codegen_fn_attrs.target_features.is_empty() && codegen_fn_attrs.inline == InlineAttr::Always
+ {
+ if let Some(span) = inline_span {
+ tcx.dcx().span_err(
+ span,
+ "cannot use `#[inline(always)]` with \
`#[target_feature]`",
- );
- }
+ );
}
}
- if !codegen_fn_attrs.no_sanitize.is_empty() {
- if codegen_fn_attrs.inline == InlineAttr::Always {
- if let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) {
- let hir_id = tcx.local_def_id_to_hir_id(did);
- tcx.node_span_lint(
- lint::builtin::INLINE_NO_SANITIZE,
- hir_id,
- no_sanitize_span,
- |lint| {
- lint.primary_message("`no_sanitize` will have no effect after inlining");
- lint.span_note(inline_span, "inlining requested here");
- },
- )
- }
+ if !codegen_fn_attrs.no_sanitize.is_empty() && codegen_fn_attrs.inline == InlineAttr::Always {
+ if let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) {
+ let hir_id = tcx.local_def_id_to_hir_id(did);
+ tcx.node_span_lint(
+ lint::builtin::INLINE_NO_SANITIZE,
+ hir_id,
+ no_sanitize_span,
+ |lint| {
+ lint.primary_message("`no_sanitize` will have no effect after inlining");
+ lint.span_note(inline_span, "inlining requested here");
+ },
+ )
}
}
diff --git a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs
index 5103b2f31582b..e34fbfe3f7614 100644
--- a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs
+++ b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs
@@ -236,15 +236,13 @@ fn push_debuginfo_type_name<'tcx>(
let has_enclosing_parens = if cpp_like_debuginfo {
output.push_str("dyn$<");
false
+ } else if trait_data.len() > 1 && auto_traits.len() != 0 {
+ // We need enclosing parens because there is more than one trait
+ output.push_str("(dyn ");
+ true
} else {
- if trait_data.len() > 1 && auto_traits.len() != 0 {
- // We need enclosing parens because there is more than one trait
- output.push_str("(dyn ");
- true
- } else {
- output.push_str("dyn ");
- false
- }
+ output.push_str("dyn ");
+ false
};
if let Some(principal) = trait_data.principal() {
diff --git a/compiler/rustc_codegen_ssa/src/mir/block.rs b/compiler/rustc_codegen_ssa/src/mir/block.rs
index 817e2ca72ec12..8f96c46224098 100644
--- a/compiler/rustc_codegen_ssa/src/mir/block.rs
+++ b/compiler/rustc_codegen_ssa/src/mir/block.rs
@@ -915,32 +915,8 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
}
};
- let args: Vec<_> = args
- .iter()
- .enumerate()
- .map(|(i, arg)| {
- // The indices passed to simd_shuffle in the
- // third argument must be constant. This is
- // checked by the type-checker.
- if i == 2 && intrinsic.name == sym::simd_shuffle {
- // FIXME: the simd_shuffle argument is actually an array,
- // not a vector, so we need this special hack to make sure
- // it is passed as an immediate. We should pass the
- // shuffle indices as a vector instead to avoid this hack.
- if let mir::Operand::Constant(constant) = &arg.node {
- let (llval, ty) = self.immediate_const_vector(bx, constant);
- return OperandRef {
- val: Immediate(llval),
- layout: bx.layout_of(ty),
- };
- } else {
- span_bug!(span, "shuffle indices must be constant");
- }
- }
-
- self.codegen_operand(bx, &arg.node)
- })
- .collect();
+ let args: Vec<_> =
+ args.iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect();
if matches!(intrinsic, ty::IntrinsicDef { name: sym::caller_location, .. }) {
let location = self
diff --git a/compiler/rustc_codegen_ssa/src/mir/constant.rs b/compiler/rustc_codegen_ssa/src/mir/constant.rs
index 0aa85b8203825..8254fb3d8661e 100644
--- a/compiler/rustc_codegen_ssa/src/mir/constant.rs
+++ b/compiler/rustc_codegen_ssa/src/mir/constant.rs
@@ -1,6 +1,6 @@
use rustc_middle::mir::interpret::ErrorHandled;
use rustc_middle::ty::layout::HasTyCtxt;
-use rustc_middle::ty::{self, Ty, ValTree};
+use rustc_middle::ty::{self, Ty};
use rustc_middle::{bug, mir, span_bug};
use rustc_target::abi::Abi;
@@ -66,15 +66,8 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
constant: &mir::ConstOperand<'tcx>,
) -> (Bx::Value, Ty<'tcx>) {
let ty = self.monomorphize(constant.ty());
- let ty_is_simd = ty.is_simd();
- // FIXME: ideally we'd assert that this is a SIMD type, but simd_shuffle
- // in its current form relies on a regular array being passed as an
- // immediate argument. This hack can be removed once that is fixed.
- let field_ty = if ty_is_simd {
- ty.simd_size_and_type(bx.tcx()).1
- } else {
- ty.builtin_index().unwrap()
- };
+ assert!(ty.is_simd());
+ let field_ty = ty.simd_size_and_type(bx.tcx()).1;
let val = self
.eval_unevaluated_mir_constant_to_valtree(constant)
@@ -82,19 +75,13 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
.map(|x| x.ok())
.flatten()
.map(|val| {
- // Depending on whether this is a SIMD type with an array field
- // or a type with many fields (one for each elements), the valtree
- // is either a single branch with N children, or a root node
- // with exactly one child which then in turn has many children.
- // So we look at the first child to determine whether it is a
- // leaf or whether we have to go one more layer down.
- let branch_or_leaf = val.unwrap_branch();
- let first = branch_or_leaf.get(0).unwrap();
- let field_iter = match first {
- ValTree::Branch(_) => first.unwrap_branch().iter(),
- ValTree::Leaf(_) => branch_or_leaf.iter(),
- };
- let values: Vec<_> = field_iter
+ // A SIMD type has a single field, which is an array.
+ let fields = val.unwrap_branch();
+ assert_eq!(fields.len(), 1);
+ let array = fields[0].unwrap_branch();
+ // Iterate over the array elements to obtain the values in the vector.
+ let values: Vec<_> = array
+ .iter()
.map(|field| {
if let Some(prim) = field.try_to_scalar() {
let layout = bx.layout_of(field_ty);
@@ -107,7 +94,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
}
})
.collect();
- if ty_is_simd { bx.const_vector(&values) } else { bx.const_struct(&values, false) }
+ bx.const_vector(&values)
})
.unwrap_or_else(|| {
bx.tcx().dcx().emit_err(errors::ShuffleIndicesEvaluation { span: constant.span });
diff --git a/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs b/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs
index 75692540c0345..ab08ef72a697b 100644
--- a/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs
+++ b/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs
@@ -547,6 +547,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
self.set_debug_loc(bx, var.source_info);
let base =
Self::spill_operand_to_stack(operand, Some(var.name.to_string()), bx);
+ bx.clear_dbg_loc();
bx.dbg_var_addr(
dbg_var,
diff --git a/compiler/rustc_codegen_ssa/src/traits/debuginfo.rs b/compiler/rustc_codegen_ssa/src/traits/debuginfo.rs
index 31104e5749b30..5fbe97214fb00 100644
--- a/compiler/rustc_codegen_ssa/src/traits/debuginfo.rs
+++ b/compiler/rustc_codegen_ssa/src/traits/debuginfo.rs
@@ -80,6 +80,7 @@ pub trait DebugInfoBuilderMethods: BackendTypes {
fragment: Option>,
);
fn set_dbg_loc(&mut self, dbg_loc: Self::DILocation);
+ fn clear_dbg_loc(&mut self);
fn insert_reference_to_gdb_debug_scripts_section_global(&mut self);
fn set_var_name(&mut self, value: Self::Value, name: &str);
}
diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs
index 8be327a8b5647..0517ce24a412a 100644
--- a/compiler/rustc_const_eval/src/check_consts/check.rs
+++ b/compiler/rustc_const_eval/src/check_consts/check.rs
@@ -166,12 +166,12 @@ impl<'mir, 'tcx> Qualifs<'mir, 'tcx> {
}
}
-struct LocalReturnTyVisitor<'ck, 'mir, 'tcx> {
+struct LocalReturnTyVisitor<'a, 'mir, 'tcx> {
kind: LocalKind,
- checker: &'ck mut Checker<'mir, 'tcx>,
+ checker: &'a mut Checker<'mir, 'tcx>,
}
-impl<'ck, 'mir, 'tcx> TypeVisitor> for LocalReturnTyVisitor<'ck, 'mir, 'tcx> {
+impl<'a, 'mir, 'tcx> TypeVisitor> for LocalReturnTyVisitor<'a, 'mir, 'tcx> {
fn visit_ty(&mut self, t: Ty<'tcx>) {
match t.kind() {
ty::FnPtr(..) => {}
diff --git a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs
index 96b3ec6f18728..da4173f903296 100644
--- a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs
+++ b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs
@@ -75,12 +75,7 @@ fn eval_body_using_ecx<'tcx, R: InterpretationResult<'tcx>>(
// This can't use `init_stack_frame` since `body` is not a function,
// so computing its ABI would fail. It's also not worth it since there are no arguments to pass.
- ecx.push_stack_frame_raw(
- cid.instance,
- body,
- &ret.clone().into(),
- StackPopCleanup::Root { cleanup: false },
- )?;
+ ecx.push_stack_frame_raw(cid.instance, body, &ret, StackPopCleanup::Root { cleanup: false })?;
ecx.storage_live_for_always_live_locals()?;
// The main interpreter loop.
@@ -94,7 +89,7 @@ fn eval_body_using_ecx<'tcx, R: InterpretationResult<'tcx>>(
let intern_result = intern_const_alloc_recursive(ecx, intern_kind, &ret);
// Since evaluation had no errors, validate the resulting constant.
- const_validate_mplace(&ecx, &ret, cid)?;
+ const_validate_mplace(ecx, &ret, cid)?;
// Only report this after validation, as validaiton produces much better diagnostics.
// FIXME: ensure validation always reports this and stop making interning care about it.
@@ -391,7 +386,7 @@ fn eval_in_interpreter<'tcx, R: InterpretationResult<'tcx>>(
#[inline(always)]
fn const_validate_mplace<'tcx>(
- ecx: &InterpCx<'tcx, CompileTimeMachine<'tcx>>,
+ ecx: &mut InterpCx<'tcx, CompileTimeMachine<'tcx>>,
mplace: &MPlaceTy<'tcx>,
cid: GlobalId<'tcx>,
) -> Result<(), ErrorHandled> {
diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs
index 9c1fef095f552..7405ca09342da 100644
--- a/compiler/rustc_const_eval/src/const_eval/machine.rs
+++ b/compiler/rustc_const_eval/src/const_eval/machine.rs
@@ -1,16 +1,16 @@
-use std::borrow::Borrow;
+use std::borrow::{Borrow, Cow};
use std::fmt;
use std::hash::Hash;
use std::ops::ControlFlow;
use rustc_ast::Mutability;
-use rustc_data_structures::fx::{FxIndexMap, IndexEntry};
+use rustc_data_structures::fx::{FxHashMap, FxIndexMap, IndexEntry};
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::{self as hir, LangItem, CRATE_HIR_ID};
use rustc_middle::mir::AssertMessage;
use rustc_middle::query::TyCtxtAt;
use rustc_middle::ty::layout::{FnAbiOf, TyAndLayout};
-use rustc_middle::ty::{self, TyCtxt};
+use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_middle::{bug, mir};
use rustc_span::symbol::{sym, Symbol};
use rustc_span::Span;
@@ -24,8 +24,8 @@ use crate::fluent_generated as fluent;
use crate::interpret::{
self, compile_time_machine, err_ub, throw_exhaust, throw_inval, throw_ub_custom, throw_unsup,
throw_unsup_format, AllocId, AllocRange, ConstAllocation, CtfeProvenance, FnArg, Frame,
- GlobalAlloc, ImmTy, InterpCx, InterpResult, MPlaceTy, OpTy, Pointer, PointerArithmetic, Scalar,
- StackPopCleanup,
+ GlobalAlloc, ImmTy, InterpCx, InterpResult, MPlaceTy, OpTy, Pointer, PointerArithmetic,
+ RangeSet, Scalar, StackPopCleanup,
};
/// When hitting this many interpreted terminators we emit a deny by default lint
@@ -65,6 +65,9 @@ pub struct CompileTimeMachine<'tcx> {
/// storing the result in the given `AllocId`.
/// Used to prevent reads from a static's base allocation, as that may allow for self-initialization loops.
pub(crate) static_root_ids: Option<(AllocId, LocalDefId)>,
+
+ /// A cache of "data range" computations for unions (i.e., the offsets of non-padding bytes).
+ union_data_ranges: FxHashMap, RangeSet>,
}
#[derive(Copy, Clone)]
@@ -99,6 +102,7 @@ impl<'tcx> CompileTimeMachine<'tcx> {
can_access_mut_global,
check_alignment,
static_root_ids: None,
+ union_data_ranges: FxHashMap::default(),
}
}
}
@@ -766,6 +770,19 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> {
}
Ok(())
}
+
+ fn cached_union_data_range<'e>(
+ ecx: &'e mut InterpCx<'tcx, Self>,
+ ty: Ty<'tcx>,
+ compute_range: impl FnOnce() -> RangeSet,
+ ) -> Cow<'e, RangeSet> {
+ if ecx.tcx.sess.opts.unstable_opts.extra_const_ub_checks {
+ Cow::Borrowed(ecx.machine.union_data_ranges.entry(ty).or_insert_with(compute_range))
+ } else {
+ // Don't bother caching, we're only doing one validation at the end anyway.
+ Cow::Owned(compute_range())
+ }
+ }
}
// Please do not add any code below the above `Machine` trait impl. I (oli-obk) plan more cleanups
diff --git a/compiler/rustc_const_eval/src/interpret/call.rs b/compiler/rustc_const_eval/src/interpret/call.rs
index 568a9a3a637be..0f2b22f035bc8 100644
--- a/compiler/rustc_const_eval/src/interpret/call.rs
+++ b/compiler/rustc_const_eval/src/interpret/call.rs
@@ -235,13 +235,13 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
if self.layout_compat(caller_abi.layout, callee_abi.layout)? {
// Ensure that our checks imply actual ABI compatibility for this concrete call.
assert!(caller_abi.eq_abi(callee_abi));
- return Ok(true);
+ Ok(true)
} else {
trace!(
"check_argument_compat: incompatible ABIs:\ncaller: {:?}\ncallee: {:?}",
caller_abi, callee_abi
);
- return Ok(false);
+ Ok(false)
}
}
@@ -823,7 +823,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
(Abi::Rust, fn_abi),
&[FnArg::Copy(arg.into())],
false,
- &ret.into(),
+ &ret,
Some(target),
unwind,
)
diff --git a/compiler/rustc_const_eval/src/interpret/discriminant.rs b/compiler/rustc_const_eval/src/interpret/discriminant.rs
index 0008a15722bde..de93ed85704b5 100644
--- a/compiler/rustc_const_eval/src/interpret/discriminant.rs
+++ b/compiler/rustc_const_eval/src/interpret/discriminant.rs
@@ -7,7 +7,7 @@ use rustc_target::abi::{self, TagEncoding, VariantIdx, Variants};
use tracing::{instrument, trace};
use super::{
- err_ub, throw_ub, ImmTy, InterpCx, InterpResult, Machine, Readable, Scalar, Writeable,
+ err_ub, throw_ub, ImmTy, InterpCx, InterpResult, Machine, Projectable, Scalar, Writeable,
};
impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
@@ -60,7 +60,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
#[instrument(skip(self), level = "trace")]
pub fn read_discriminant(
&self,
- op: &impl Readable<'tcx, M::Provenance>,
+ op: &impl Projectable<'tcx, M::Provenance>,
) -> InterpResult<'tcx, VariantIdx> {
let ty = op.layout().ty;
trace!("read_discriminant_value {:#?}", op.layout());
diff --git a/compiler/rustc_const_eval/src/interpret/eval_context.rs b/compiler/rustc_const_eval/src/interpret/eval_context.rs
index dd744c51f23be..16d40fcceb6bb 100644
--- a/compiler/rustc_const_eval/src/interpret/eval_context.rs
+++ b/compiler/rustc_const_eval/src/interpret/eval_context.rs
@@ -16,7 +16,7 @@ use rustc_span::Span;
use rustc_target::abi::call::FnAbi;
use rustc_target::abi::{Align, HasDataLayout, Size, TargetDataLayout};
use rustc_trait_selection::traits::ObligationCtxt;
-use tracing::{debug, trace};
+use tracing::{debug, instrument, trace};
use super::{
err_inval, throw_inval, throw_ub, throw_ub_custom, Frame, FrameInfo, GlobalId, InterpErrorInfo,
@@ -315,6 +315,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
/// Check if the two things are equal in the current param_env, using an infctx to get proper
/// equality checks.
+ #[instrument(level = "trace", skip(self), ret)]
pub(super) fn eq_in_param_env(&self, a: T, b: T) -> bool
where
T: PartialEq + TypeFoldable> + ToTrace<'tcx>,
@@ -330,13 +331,20 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
// equate the two trait refs after normalization
let a = ocx.normalize(&cause, self.param_env, a);
let b = ocx.normalize(&cause, self.param_env, b);
- if ocx.eq(&cause, self.param_env, a, b).is_ok() {
- if ocx.select_all_or_error().is_empty() {
- // All good.
- return true;
- }
+
+ if let Err(terr) = ocx.eq(&cause, self.param_env, a, b) {
+ trace!(?terr);
+ return false;
+ }
+
+ let errors = ocx.select_all_or_error();
+ if !errors.is_empty() {
+ trace!(?errors);
+ return false;
}
- return false;
+
+ // All good.
+ true
}
/// Walks up the callstack from the intrinsic's callsite, searching for the first callsite in a
diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs
index bedc56de0da25..8a07f90c95104 100644
--- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs
+++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs
@@ -384,8 +384,8 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
sym::simd_insert => {
let index = u64::from(self.read_scalar(&args[1])?.to_u32()?);
let elem = &args[2];
- let (input, input_len) = self.operand_to_simd(&args[0])?;
- let (dest, dest_len) = self.mplace_to_simd(dest)?;
+ let (input, input_len) = self.project_to_simd(&args[0])?;
+ let (dest, dest_len) = self.project_to_simd(dest)?;
assert_eq!(input_len, dest_len, "Return vector length must match input length");
// Bounds are not checked by typeck so we have to do it ourselves.
if index >= input_len {
@@ -406,7 +406,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
}
sym::simd_extract => {
let index = u64::from(self.read_scalar(&args[1])?.to_u32()?);
- let (input, input_len) = self.operand_to_simd(&args[0])?;
+ let (input, input_len) = self.project_to_simd(&args[0])?;
// Bounds are not checked by typeck so we have to do it ourselves.
if index >= input_len {
throw_ub_format!(
diff --git a/compiler/rustc_const_eval/src/interpret/machine.rs b/compiler/rustc_const_eval/src/interpret/machine.rs
index 6cfd7be48e624..8cab3c34eedfb 100644
--- a/compiler/rustc_const_eval/src/interpret/machine.rs
+++ b/compiler/rustc_const_eval/src/interpret/machine.rs
@@ -10,6 +10,7 @@ use rustc_apfloat::{Float, FloatConvert};
use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
use rustc_middle::query::TyCtxtAt;
use rustc_middle::ty::layout::TyAndLayout;
+use rustc_middle::ty::Ty;
use rustc_middle::{mir, ty};
use rustc_span::def_id::DefId;
use rustc_span::Span;
@@ -19,7 +20,7 @@ use rustc_target::spec::abi::Abi as CallAbi;
use super::{
throw_unsup, throw_unsup_format, AllocBytes, AllocId, AllocKind, AllocRange, Allocation,
ConstAllocation, CtfeProvenance, FnArg, Frame, ImmTy, InterpCx, InterpResult, MPlaceTy,
- MemoryKind, Misalignment, OpTy, PlaceTy, Pointer, Provenance, CTFE_ALLOC_SALT,
+ MemoryKind, Misalignment, OpTy, PlaceTy, Pointer, Provenance, RangeSet, CTFE_ALLOC_SALT,
};
/// Data returned by [`Machine::after_stack_pop`], and consumed by
@@ -578,6 +579,15 @@ pub trait Machine<'tcx>: Sized {
ecx: &InterpCx<'tcx, Self>,
instance: Option>,
) -> usize;
+
+ fn cached_union_data_range<'e>(
+ _ecx: &'e mut InterpCx<'tcx, Self>,
+ _ty: Ty<'tcx>,
+ compute_range: impl FnOnce() -> RangeSet,
+ ) -> Cow<'e, RangeSet> {
+ // Default to no caching.
+ Cow::Owned(compute_range())
+ }
}
/// A lot of the flexibility above is just needed for `Miri`, but all "compile-time" machines
diff --git a/compiler/rustc_const_eval/src/interpret/memory.rs b/compiler/rustc_const_eval/src/interpret/memory.rs
index 45a5eb9bd52fc..23c76038b0bb4 100644
--- a/compiler/rustc_const_eval/src/interpret/memory.rs
+++ b/compiler/rustc_const_eval/src/interpret/memory.rs
@@ -8,9 +8,8 @@
use std::assert_matches::assert_matches;
use std::borrow::Cow;
-use std::cell::Cell;
use std::collections::VecDeque;
-use std::{fmt, ptr};
+use std::{fmt, mem, ptr};
use rustc_ast::Mutability;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
@@ -118,7 +117,7 @@ pub struct Memory<'tcx, M: Machine<'tcx>> {
/// This stores whether we are currently doing reads purely for the purpose of validation.
/// Those reads do not trigger the machine's hooks for memory reads.
/// Needless to say, this must only be set with great care!
- validation_in_progress: Cell,
+ validation_in_progress: bool,
}
/// A reference to some allocation that was already bounds-checked for the given region
@@ -145,7 +144,7 @@ impl<'tcx, M: Machine<'tcx>> Memory<'tcx, M> {
alloc_map: M::MemoryMap::default(),
extra_fn_ptr_map: FxIndexMap::default(),
dead_alloc_map: FxIndexMap::default(),
- validation_in_progress: Cell::new(false),
+ validation_in_progress: false,
}
}
@@ -682,7 +681,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
// We want to call the hook on *all* accesses that involve an AllocId, including zero-sized
// accesses. That means we cannot rely on the closure above or the `Some` branch below. We
// do this after `check_and_deref_ptr` to ensure some basic sanity has already been checked.
- if !self.memory.validation_in_progress.get() {
+ if !self.memory.validation_in_progress {
if let Ok((alloc_id, ..)) = self.ptr_try_get_alloc_id(ptr, size_i64) {
M::before_alloc_read(self, alloc_id)?;
}
@@ -690,7 +689,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
if let Some((alloc_id, offset, prov, alloc)) = ptr_and_alloc {
let range = alloc_range(offset, size);
- if !self.memory.validation_in_progress.get() {
+ if !self.memory.validation_in_progress {
M::before_memory_read(
self.tcx,
&self.machine,
@@ -766,11 +765,14 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
let parts = self.get_ptr_access(ptr, size)?;
if let Some((alloc_id, offset, prov)) = parts {
let tcx = self.tcx;
+ let validation_in_progress = self.memory.validation_in_progress;
// FIXME: can we somehow avoid looking up the allocation twice here?
// We cannot call `get_raw_mut` inside `check_and_deref_ptr` as that would duplicate `&mut self`.
let (alloc, machine) = self.get_alloc_raw_mut(alloc_id)?;
let range = alloc_range(offset, size);
- M::before_memory_write(tcx, machine, &mut alloc.extra, (alloc_id, prov), range)?;
+ if !validation_in_progress {
+ M::before_memory_write(tcx, machine, &mut alloc.extra, (alloc_id, prov), range)?;
+ }
Ok(Some(AllocRefMut { alloc, range, tcx: *tcx, alloc_id }))
} else {
Ok(None)
@@ -1014,16 +1016,16 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
///
/// We do this so Miri's allocation access tracking does not show the validation
/// reads as spurious accesses.
- pub fn run_for_validation(&self, f: impl FnOnce() -> R) -> R {
+ pub fn run_for_validation(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
// This deliberately uses `==` on `bool` to follow the pattern
// `assert!(val.replace(new) == old)`.
assert!(
- self.memory.validation_in_progress.replace(true) == false,
+ mem::replace(&mut self.memory.validation_in_progress, true) == false,
"`validation_in_progress` was already set"
);
- let res = f();
+ let res = f(self);
assert!(
- self.memory.validation_in_progress.replace(false) == true,
+ mem::replace(&mut self.memory.validation_in_progress, false) == true,
"`validation_in_progress` was unset by someone else"
);
res
@@ -1112,9 +1114,13 @@ impl<'a, 'tcx, M: Machine<'tcx>> std::fmt::Debug for DumpAllocs<'a, 'tcx, M> {
}
/// Reading and writing.
-impl<'tcx, 'a, Prov: Provenance, Extra, Bytes: AllocBytes>
+impl<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes>
AllocRefMut<'a, 'tcx, Prov, Extra, Bytes>
{
+ pub fn as_ref<'b>(&'b self) -> AllocRef<'b, 'tcx, Prov, Extra, Bytes> {
+ AllocRef { alloc: self.alloc, range: self.range, tcx: self.tcx, alloc_id: self.alloc_id }
+ }
+
/// `range` is relative to this allocation reference, not the base of the allocation.
pub fn write_scalar(&mut self, range: AllocRange, val: Scalar) -> InterpResult<'tcx> {
let range = self.range.subrange(range);
@@ -1130,16 +1136,33 @@ impl<'tcx, 'a, Prov: Provenance, Extra, Bytes: AllocBytes>
self.write_scalar(alloc_range(offset, self.tcx.data_layout().pointer_size), val)
}
+ /// Mark the given sub-range (relative to this allocation reference) as uninitialized.
+ pub fn write_uninit(&mut self, range: AllocRange) -> InterpResult<'tcx> {
+ let range = self.range.subrange(range);
+ Ok(self
+ .alloc
+ .write_uninit(&self.tcx, range)
+ .map_err(|e| e.to_interp_error(self.alloc_id))?)
+ }
+
/// Mark the entire referenced range as uninitialized
- pub fn write_uninit(&mut self) -> InterpResult<'tcx> {
+ pub fn write_uninit_full(&mut self) -> InterpResult<'tcx> {
Ok(self
.alloc
.write_uninit(&self.tcx, self.range)
.map_err(|e| e.to_interp_error(self.alloc_id))?)
}
+
+ /// Remove all provenance in the reference range.
+ pub fn clear_provenance(&mut self) -> InterpResult<'tcx> {
+ Ok(self
+ .alloc
+ .clear_provenance(&self.tcx, self.range)
+ .map_err(|e| e.to_interp_error(self.alloc_id))?)
+ }
}
-impl<'tcx, 'a, Prov: Provenance, Extra, Bytes: AllocBytes> AllocRef<'a, 'tcx, Prov, Extra, Bytes> {
+impl<'a, 'tcx, Prov: Provenance, Extra, Bytes: AllocBytes> AllocRef<'a, 'tcx, Prov, Extra, Bytes> {
/// `range` is relative to this allocation reference, not the base of the allocation.
pub fn read_scalar(
&self,
@@ -1278,7 +1301,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
};
let src_alloc = self.get_alloc_raw(src_alloc_id)?;
let src_range = alloc_range(src_offset, size);
- assert!(!self.memory.validation_in_progress.get(), "we can't be copying during validation");
+ assert!(!self.memory.validation_in_progress, "we can't be copying during validation");
M::before_memory_read(
tcx,
&self.machine,
diff --git a/compiler/rustc_const_eval/src/interpret/mod.rs b/compiler/rustc_const_eval/src/interpret/mod.rs
index 511756e3f86c9..561d681f804a1 100644
--- a/compiler/rustc_const_eval/src/interpret/mod.rs
+++ b/compiler/rustc_const_eval/src/interpret/mod.rs
@@ -33,11 +33,11 @@ pub(crate) use self::intrinsics::eval_nullary_intrinsic;
pub use self::machine::{compile_time_machine, AllocMap, Machine, MayLeak, ReturnAction};
pub use self::memory::{AllocKind, AllocRef, AllocRefMut, FnVal, Memory, MemoryKind};
use self::operand::Operand;
-pub use self::operand::{ImmTy, Immediate, OpTy, Readable};
+pub use self::operand::{ImmTy, Immediate, OpTy};
pub use self::place::{MPlaceTy, MemPlaceMeta, PlaceTy, Writeable};
use self::place::{MemPlace, Place};
pub use self::projection::{OffsetMode, Projectable};
pub use self::stack::{Frame, FrameInfo, LocalState, StackPopCleanup, StackPopInfo};
pub(crate) use self::util::create_static_alloc;
-pub use self::validity::{CtfeValidationMode, RefTracking};
+pub use self::validity::{CtfeValidationMode, RangeSet, RefTracking};
pub use self::visitor::ValueVisitor;
diff --git a/compiler/rustc_const_eval/src/interpret/operand.rs b/compiler/rustc_const_eval/src/interpret/operand.rs
index 9a8ccaa7cc5ca..2e02d1001c859 100644
--- a/compiler/rustc_const_eval/src/interpret/operand.rs
+++ b/compiler/rustc_const_eval/src/interpret/operand.rs
@@ -111,6 +111,46 @@ impl Immediate {
Immediate::Uninit => bug!("Got uninit where a scalar or scalar pair was expected"),
}
}
+
+ /// Assert that this immediate is a valid value for the given ABI.
+ pub fn assert_matches_abi(self, abi: Abi, cx: &impl HasDataLayout) {
+ match (self, abi) {
+ (Immediate::Scalar(scalar), Abi::Scalar(s)) => {
+ assert_eq!(scalar.size(), s.size(cx));
+ if !matches!(s.primitive(), abi::Pointer(..)) {
+ assert!(matches!(scalar, Scalar::Int(..)));
+ }
+ }
+ (Immediate::ScalarPair(a_val, b_val), Abi::ScalarPair(a, b)) => {
+ assert_eq!(a_val.size(), a.size(cx));
+ if !matches!(a.primitive(), abi::Pointer(..)) {
+ assert!(matches!(a_val, Scalar::Int(..)));
+ }
+ assert_eq!(b_val.size(), b.size(cx));
+ if !matches!(b.primitive(), abi::Pointer(..)) {
+ assert!(matches!(b_val, Scalar::Int(..)));
+ }
+ }
+ (Immediate::Uninit, _) => {}
+ _ => {
+ bug!("value {self:?} does not match ABI {abi:?})",)
+ }
+ }
+ }
+
+ pub fn clear_provenance<'tcx>(&mut self) -> InterpResult<'tcx> {
+ match self {
+ Immediate::Scalar(s) => {
+ s.clear_provenance()?;
+ }
+ Immediate::ScalarPair(a, b) => {
+ a.clear_provenance()?;
+ b.clear_provenance()?;
+ }
+ Immediate::Uninit => {}
+ }
+ Ok(())
+ }
}
// ScalarPair needs a type to interpret, so we often have an immediate and a type together
@@ -393,6 +433,7 @@ impl<'tcx, Prov: Provenance> Projectable<'tcx, Prov> for ImmTy<'tcx, Prov> {
Ok(self.offset_(offset, layout, ecx))
}
+ #[inline(always)]
fn to_op>(
&self,
_ecx: &InterpCx<'tcx, M>,
@@ -482,6 +523,7 @@ impl<'tcx, Prov: Provenance> Projectable<'tcx, Prov> for OpTy<'tcx, Prov> {
}
}
+ #[inline(always)]
fn to_op>(
&self,
_ecx: &InterpCx<'tcx, M>,
@@ -490,32 +532,6 @@ impl<'tcx, Prov: Provenance> Projectable<'tcx, Prov> for OpTy<'tcx, Prov> {
}
}
-/// The `Readable` trait describes interpreter values that one can read from.
-pub trait Readable<'tcx, Prov: Provenance>: Projectable<'tcx, Prov> {
- fn as_mplace_or_imm(&self) -> Either, ImmTy<'tcx, Prov>>;
-}
-
-impl<'tcx, Prov: Provenance> Readable<'tcx, Prov> for OpTy<'tcx, Prov> {
- #[inline(always)]
- fn as_mplace_or_imm(&self) -> Either, ImmTy<'tcx, Prov>> {
- self.as_mplace_or_imm()
- }
-}
-
-impl<'tcx, Prov: Provenance> Readable<'tcx, Prov> for MPlaceTy<'tcx, Prov> {
- #[inline(always)]
- fn as_mplace_or_imm(&self) -> Either, ImmTy<'tcx, Prov>> {
- Left(self.clone())
- }
-}
-
-impl<'tcx, Prov: Provenance> Readable<'tcx, Prov> for ImmTy<'tcx, Prov> {
- #[inline(always)]
- fn as_mplace_or_imm(&self) -> Either, ImmTy<'tcx, Prov>> {
- Right(self.clone())
- }
-}
-
impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
/// Try reading an immediate in memory; this is interesting particularly for `ScalarPair`.
/// Returns `None` if the layout does not permit loading this as a value.
@@ -588,9 +604,9 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
/// ConstProp needs it, though.
pub fn read_immediate_raw(
&self,
- src: &impl Readable<'tcx, M::Provenance>,
+ src: &impl Projectable<'tcx, M::Provenance>,
) -> InterpResult<'tcx, Either, ImmTy<'tcx, M::Provenance>>> {
- Ok(match src.as_mplace_or_imm() {
+ Ok(match src.to_op(self)?.as_mplace_or_imm() {
Left(ref mplace) => {
if let Some(val) = self.read_immediate_from_mplace_raw(mplace)? {
Right(val)
@@ -608,7 +624,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
#[inline(always)]
pub fn read_immediate(
&self,
- op: &impl Readable<'tcx, M::Provenance>,
+ op: &impl Projectable<'tcx, M::Provenance>,
) -> InterpResult<'tcx, ImmTy<'tcx, M::Provenance>> {
if !matches!(
op.layout().abi,
@@ -627,7 +643,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
/// Read a scalar from a place
pub fn read_scalar(
&self,
- op: &impl Readable<'tcx, M::Provenance>,
+ op: &impl Projectable<'tcx, M::Provenance>,
) -> InterpResult<'tcx, Scalar> {
Ok(self.read_immediate(op)?.to_scalar())
}
@@ -638,21 +654,21 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
/// Read a pointer from a place.
pub fn read_pointer(
&self,
- op: &impl Readable<'tcx, M::Provenance>,
+ op: &impl Projectable<'tcx, M::Provenance>,
) -> InterpResult<'tcx, Pointer