Commit Graph

131 Commits

Author SHA1 Message Date
bors 22a7a19f93 Auto merge of #98112 - saethlin:mir-alignment-checks, r=oli-obk
Insert alignment checks for pointer dereferences when debug assertions are enabled

Closes https://github.com/rust-lang/rust/issues/54915

- [x] Jake tells me this sounds like a place to use `MirPatch`, but I can't figure out how to insert a new basic block with a new terminator in the middle of an existing basic block, using `MirPatch`. (if nobody else backs up this point I'm checking this as "not actually a good idea" because the code looks pretty clean to me after rearranging it a bit)
- [x] Using `CastKind::PointerExposeAddress` is definitely wrong, we don't want to expose. Calling a function to get the pointer address seems quite excessive. ~I'll see if I can add a new `CastKind`.~ `CastKind::Transmute` to the rescue!
- [x] Implement a more helpful panic message like slice bounds checking.

r? `@oli-obk`
2023-03-31 08:50:35 +00:00
Dylan DPC a3eb2f0f22
Rollup merge of #109664 - m-ou-se:format-args-placeholder-span, r=oli-obk
Use span of placeholders in format_args!() expansion.

`format_args!("{}", x)` expands to something that contains `Argument::new_display(&x)`. That entire expression was generated with the span of `x`.

After this PR, `&x` uses the span of `x`, but the `new_display` call uses the span of the `{}` placeholder within the format string. If an implicitly captured argument was used like in `format_args!("{x}")`, both use the span of the `{x}` placeholder.

This fixes https://github.com/rust-lang/rust/issues/109576, and also allows for more improvements to similar diagnostics in the future, since the usage of `x` can now be traced to the exact `{}` placeholder that required it to be `Display` (or `Debug` etc.)
2023-03-29 14:07:28 +05:30
Scott McMurray f20af8d43d Simplify transmutes in MIR InstCombine
Thanks to the combination of #108246 and #108442 it could already remove identity transmutes.

With this PR, it can also simplify them to `IntToInt` casts, `Discriminant` reads, or `Field` projections.
2023-03-28 18:18:10 -07:00
Mara Bos 769886cc35 Bless mir-opt tests.
(Only the lifetime spans changed.)
2023-03-27 14:57:02 +02:00
bors 2420bd34ba Auto merge of #106428 - saethlin:inline-diverging-functions, r=cjgillot
Permit the MIR inliner to inline diverging functions

This heuristic prevents inlining of `hint::unreachable_unchecked`, which in turn makes `Option/Result::unwrap_unchecked` a bad inlining candidate. I looked through the changes to `core`, `alloc`, `std`, and `hashbrown` by hand and they all seem reasonable. Let's see how this looks in perf...

---

Based on rustc-perf it looks like this regresses ctfe-stress, and the cachegrind diff indicates that this regression is in `InterpCx::statement`. I don't know how to do any deeper analysis because that function is _enormous_ in the try toolchain, which has no debuginfo in it. And a local build produces significantly different codegen for that function, even with LTO.
2023-03-26 05:55:32 +00:00
Ben Kimock b932751984 Ignore the unwrap_unchecked test on wasm32-unknown-unknown 2023-03-25 19:33:19 -04:00
Ben Kimock 8ccf53332e A MIR transform that checks pointers are aligned 2023-03-23 18:23:06 -04:00
bors e216300876 Auto merge of #108442 - scottmcm:mir-transmute, r=oli-obk
Add `CastKind::Transmute` to MIR

~~Nothing actually produces it in this commit, so I don't know how to test it, but it also means it shouldn't be possible for it to break anything.~~

Includes lowering `transmute` calls to it, so it's used.

Zulip Conversation: <https://rust-lang.zulipchat.com/#narrow/stream/189540-t-compiler.2Fwg-mir-opt/topic/Good.20first.20isssue/near/321849610>
2023-03-23 18:43:04 +00:00
Matthias Krüger 7afed92749
Rollup merge of #109475 - scottmcm:simpler-shifts, r=WaffleLapkin
Simpler checked shifts in MIR building

Doing masking to check unsigned shift amounts is overcomplicated; just comparing the shift directly saves a statement and a temporary, as well as is much easier to read as a human.  And shifting by unsigned is the canonical case -- notably, all the library shifting methods (that don't support every type) take shift RHSs as `u32` -- so we might as well make that simpler since it's easy to do so.

This PR also changes *signed* shift amounts to `IntToInt` casts and then uses the same check as for unsigned.  The bit-masking is a nice trick, but for example LLVM actually canonicalizes it to an unsigned comparison anyway <https://rust.godbolt.org/z/8h59fMGT4> so I don't think it's worth the effort and the extra `Constant`.  (If MIR's `assert` was `assert_nz` then the masking might make sense, but when the `!=` uses another statement I think the comparison is better.)

To review, I suggest looking at 2ee0468c49 first -- that's the interesting code change and has a MIR diff.

My favourite part of the diff:
```diff
-        _20 = BitAnd(_19, const 340282366920938463463374607431768211448_u128); // scope 0 at $DIR/shifts.rs:+2:34: +2:44
-        _21 = Ne(move _20, const 0_u128); // scope 0 at $DIR/shifts.rs:+2:34: +2:44
-        assert(!move _21, "attempt to shift right by `{}`, which would overflow", _19) -> [success: bb3, unwind: bb7]; // scope 0 at $DIR/shifts.rs:+2:34: +2:44
+        _18 = Lt(_17, const 8_u128);     // scope 0 at $DIR/shifts.rs:+2:34: +2:44
+        assert(move _18, "attempt to shift right by `{}`, which would overflow", _17) -> [success: bb3, unwind: bb7]; // scope 0 at $DIR/shifts.rs:+2:34: +2:44
```
2023-03-23 08:35:35 +01:00
Scott McMurray 64cce5fc7d Add `CastKind::Transmute` to MIR
Updates `interpret`, `codegen_ssa`, and `codegen_cranelift` to consume the new cast instead of the intrinsic.

Includes `CastTransmute` for custom MIR building, to be able to test the extra UB.
2023-03-22 15:15:41 -07:00
bors 8859fde21f Auto merge of #109497 - matthiaskrgr:rollup-6txuxm0, r=matthiaskrgr
Rollup of 10 pull requests

Successful merges:

 - #109373 (Set LLVM `LLVM_UNREACHABLE_OPTIMIZE` to `OFF`)
 - #109392 (Custom MIR: Allow optional RET type annotation)
 - #109394 (adapt tests/codegen/vec-shrink-panik for LLVM 17)
 - #109412 (rustdoc: Add GUI test for "Auto-hide item contents for large items" setting)
 - #109452 (Ignore the vendor directory for tidy tests.)
 - #109457 (Remove comment about reusing rib allocations)
 - #109461 (rustdoc: remove redundant `.content` prefix from span/a colors)
 - #109477 (`HirId` to `LocalDefId` cleanup)
 - #109489 (More general captures)
 - #109494 (Do not feed param_env for RPITITs impl side)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2023-03-22 21:35:02 +00:00
Scott McMurray b537e6bc53 Generate simpler MIR for shifts 2023-03-22 13:32:12 -07:00
Matthias Krüger 9545ab8e12
Rollup merge of #109392 - cbeuw:composite-ret, r=JakobDegen
Custom MIR: Allow optional RET type annotation

This currently doesn't compile because the type of `RET` is inferred, which fails if RET is a composite type and fields are initialised separately.
```rust
#![feature(custom_mir, core_intrinsics)]
extern crate core;
use core::intrinsics::mir::*;
#[custom_mir(dialect = "runtime", phase = "optimized")]
fn fn0() -> (i32, bool) {
    mir! ({
        RET.0 = 0;
        RET.1 = true;
        Return()
    })
}
```
```
error[E0282]: type annotations needed
 --> src/lib.rs:8:9
  |
8 |         RET.0 = 0;
  |         ^^^ cannot infer type

For more information about this error, try `rustc --explain E0282`.
```

This PR allows the user to manually specify the return type with `type RET = ...;` if required:

```rust
#[custom_mir(dialect = "runtime", phase = "optimized")]
fn fn0() -> (i32, bool) {
    mir! (
        type RET = (i32, bool);
        {
            RET.0 = 0;
            RET.1 = true;
            Return()
        }
    )
}
```

The syntax is not optimal, I'm happy to see other suggestions. Ideally I wanted it to be a normal type annotation like `let RET: ...;`, but this runs into the multiple parsing options error during macro expansion, as it can be parsed as a normal `let` declaration as well.

r? ```@oli-obk``` or ```@tmiasko``` or ```@JakobDegen```
2023-03-22 20:08:01 +01:00
Dylan DPC 14d06467f0
Rollup merge of #109179 - llogiq:intrinsically-option-as-slice, r=eholk
move Option::as_slice to intrinsic

````@scottmcm```` suggested on #109095 I use a direct approach of unpacking the operation in MIR lowering, so here's the implementation.

cc ````@nikic```` as this should hopefully unblock #107224 (though perhaps other changes to the prior implementation, which I left for bootstrapping, are needed).
2023-03-23 00:00:31 +05:30
Scott McMurray ec25f08748 Demonstration test for MIR building of checked shift operators 2023-03-22 01:37:11 -07:00
Andy Wang 8e4e55e524
Support aggregate expressions 2023-03-20 15:25:11 +01:00
Andy Wang 9da1da94ef
Allow optional RET type annotation 2023-03-20 12:21:19 +01:00
Ben Kimock a98ddb6de1 Enable inlining of diverging functions 2023-03-18 14:29:13 -04:00
Ben Kimock 2a628bd99c Remove duplicate switch targets 2023-03-18 14:29:13 -04:00
Ben Kimock 41eda69516 Remove duplicate unreachable blocks 2023-03-18 14:29:04 -04:00
Andre Bogus 27e9ee9bae move Option::as_slice to intrinsic 2023-03-18 07:15:15 +01:00
bors 2d64f229a0 Auto merge of #109085 - tmiasko:index-based, r=WaffleLapkin
Use index based drop loop for slices and arrays

Instead of building two kinds of drop pair loops, of which only one will be eventually used at runtime in a given monomorphization, always use index based loop.
2023-03-17 08:17:21 +00:00
bors 511364e787 Auto merge of #108944 - cjgillot:clear-local-info, r=oli-obk
Wrap the whole LocalInfo in ClearCrossCrate.

MIR contains a lot of information about locals. The primary purpose of this information is the quality of borrowck diagnostics.

This PR aims to drop this information after MIR analyses are finished, ie. starting from post-cleanup runtime MIR.
2023-03-16 19:59:56 +00:00
bors e386217dd9 Auto merge of #107270 - cjgillot:remove-zst, r=oli-obk
Replace ZST operands and debuginfo by constants.

This is work that ConstProp will not have to do.
Split from https://github.com/rust-lang/rust/pull/107267
2023-03-16 16:40:53 +00:00
bors c90eb4825a Auto merge of #108282 - cjgillot:mir-checked-sh, r=tmiasko
Implement checked Shl/Shr at MIR building.

This does not require any special handling by codegen backends,
as the overflow behaviour is entirely determined by the rhs (shift amount).

This allows MIR ConstProp to remove the overflow check for constant shifts.

~There is an existing different behaviour between cg_llvm and cg_clif (cc `@bjorn3).`
I took cg_llvm's one as reference: overflow if `rhs < 0 || rhs > number_of_bits_in_lhs_ty`.~

EDIT: `cg_llvm` and `cg_clif` implement the overflow check differently. This PR uses `cg_llvm`'s implementation based on a `BitAnd` instead of `cg_clif`'s one based on an unsigned comparison.
2023-03-15 21:31:06 +00:00
bors e4b9f86054 Auto merge of #109035 - scottmcm:ptr-read-should-know-undef, r=WaffleLapkin,JakobDegen
Ensure `ptr::read` gets all the same LLVM `load` metadata that dereferencing does

I was looking into `array::IntoIter` optimization, and noticed that it wasn't annotating the loads with `noundef` for simple things like `array::IntoIter<i32, N>`.  Trying to narrow it down, it seems that was because `MaybeUninit::assume_init_read` isn't marking the load as initialized (<https://rust.godbolt.org/z/Mxd8TPTnv>), which is unfortunate since that's basically its reason to exist.

The root cause is that `ptr::read` is currently implemented via the *untyped* `copy_nonoverlapping`, and thus the `load` doesn't get any type-aware metadata: no `noundef`, no `!range`.  This PR solves that by lowering `ptr::read(p)` to `copy *p` in MIR, for which the backends already do the right thing.

Fortuitiously, this also improves the IR we give to LLVM for things like `mem::replace`, and fixes a couple of long-standing bugs where `ptr::read` on `Copy` types was worse than `*`ing them.

Zulip conversation: <https://rust-lang.zulipchat.com/#narrow/stream/219381-t-libs/topic/Move.20array.3A.3AIntoIter.20to.20ManuallyDrop/near/341189936>

cc `@erikdesjardins` `@JakobDegen` `@workingjubilee` `@the8472`

Fixes #106369
Fixes #73258
2023-03-15 11:44:12 +00:00
Scott McMurray e7c6ad89cf Improved implementation and comments after code review feedback 2023-03-14 22:24:28 -07:00
Tomasz Miąsko cf0e78bd3b Use index based drop loop for slices and arrays
Instead of building two kinds of drop pair loops, of which only one will
be eventually used at runtime in a given monomorphization, always use
index based loop.
2023-03-14 21:29:32 +01:00
Camille GILLOT bcb161def7 Wrap the whole LocalInfo in ClearCrossCrate. 2023-03-14 20:52:42 +01:00
bors 669e751639 Auto merge of #104833 - Swatinem:async-identity-future, r=compiler-errors
Remove `identity_future` indirection

This was previously needed because the indirection used to hide some unexplained lifetime errors, which it turned out were related to the `min_choice` algorithm.

Removing the indirection also solves a couple of cycle errors, large moves and makes async blocks support the `#[track_caller]`annotation.

Fixes https://github.com/rust-lang/rust/issues/104826.
2023-03-14 10:12:58 +00:00
Camille GILLOT 19a8bb16c8 Generalize operation. 2023-03-13 18:22:55 +00:00
Camille GILLOT 9e3f091f2b Replace ZST operands and debuginfo by constants. 2023-03-13 18:19:57 +00:00
bors f1b1ed7e18 Auto merge of #108471 - clubby789:unbox-the-syntax, r=Nilstrieb,est31
Remove `box_syntax`

r? `@Nilstrieb`

This removes the feature `box_syntax`, which allows the use of `box <expr>` to create a Box, and finalises removing use of the feature from the compiler. `box_patterns` (allowing the use of `box <pat>` in a pattern) is unaffected.
It also removes `ast::ExprKind::Box` - the only way to create a 'box' expression now is with the rustc-internal `#[rustc_box]` attribute.
As a temporary measure to help users move away, `box <expr>` now parses the inner expression, and emits a `MachineApplicable` lint to replace it with `Box::new`

Closes #49733
2023-03-13 10:41:50 +00:00
bors b05bb29008 Auto merge of #108872 - cjgillot:simp-const-prop, r=oli-obk
Strengthen state tracking in const-prop

Some/many of the changes are replicated between both the const-prop lint and the const-prop optimization.

Behaviour changes:
- const-prop opt does not give a span to propagated values. This was useless as that span's primary purpose is to diagnose evaluation failure in codegen.
- we remove the `OnlyPropagateInto` mode. It was only used for function arguments, which are better modeled by a write before entry.
- the tracking of assignments and discriminants make clearer that we do nothing in `NoPropagation` mode or on indirect places.
2023-03-12 23:27:52 +00:00
clubby789 dd7df04e16 Remove uses of `box_syntax` in rustc and tools 2023-03-12 13:19:46 +00:00
Scott McMurray b2c717fa33 `MaybeUninit::assume_init_read` should have `noundef` load metadata
I was looking into `array::IntoIter` optimization, and noticed that it wasn't annotating the loads with `noundef` for simple things like `array::IntoIter<i32, N>`.

Turned out to be a more general problem as `MaybeUninit::assume_init_read` isn't marking the load as initialized (<https://rust.godbolt.org/z/Mxd8TPTnv>), which is unfortunate since that's basically its reason to exist.

This PR lowers `ptr::read(p)` to `copy *p` in MIR, which fortuitiously also improves the IR we give to LLVM for things like `mem::replace`.
2023-03-11 17:44:43 -08:00
Camille GILLOT 4462bb54e3 Introduce a no-op PlaceMention statement for `let _ =`. 2023-03-09 17:45:13 +00:00
bors 39f2657d11 Auto merge of #108920 - matthiaskrgr:rollup-qrr9a0u, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #108754 (Retry `pred_known_to_hold_modulo_regions` with fulfillment if ambiguous)
 - #108759 (1.41.1 supported 32-bit Apple targets)
 - #108839 (Canonicalize root var when making response from new solver)
 - #108856 (Remove DropAndReplace terminator)
 - #108882 (Tweak E0740)
 - #108898 (Set `LIBC_CHECK_CFG=1` when building Rust code in bootstrap)
 - #108911 (Improve rustdoc-gui/tester.js code a bit)
 - #108916 (Remove an unused return value in `rustc_hir_typeck`)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2023-03-09 08:21:17 +00:00
bors 66a2d62210 Auto merge of #108178 - cjgillot:ssa-deref, r=oli-obk
Do not consider `&mut *x` as mutating `x` in `CopyProp`

This PR removes an unfortunate overly cautious case from the current implementation.

Found by https://github.com/rust-lang/rust/pull/105274 cc `@saethlin`
2023-03-09 04:50:38 +00:00
Matthias Krüger 4e84fbf8a0
Rollup merge of #108856 - Zeegomo:remove-drop-and-rep, r=tmiasko
Remove DropAndReplace terminator

#107844 made DropAndReplace unused, let's remove it completely from the codebase.
2023-03-08 21:26:51 +01:00
Camille GILLOT d94ec3091e Bless 32bit. 2023-03-08 14:40:38 +00:00
Camille GILLOT 9928d0e566 Remove OnlyPropagateInto. 2023-03-08 14:40:37 +00:00
Camille GILLOT 0e64ce7c5e Do not track span in ConstProp. 2023-03-08 14:40:37 +00:00
Arpad Borsos 9f03cfc207
Remove `identity_future` indirection
This was previously needed because the indirection used to hide some unexplained lifetime errors, which it turned out were related to the `min_choice` algorithm.

Removing the indirection also solves a couple of cycle errors, large moves and makes async blocks support the `#[track_caller]` annotation.
2023-03-08 15:37:14 +01:00
Yuki Okushi fddd861a7d
Rollup merge of #108855 - cbeuw:mir-cast, r=tmiasko
Custom MIR: Support `as` casts

Small changes to support this low hanging fruit

r? `@oli-obk` or `@tmiasko` or `@JakobDegen`
2023-03-07 23:06:25 +09:00
Giacomo Pasini c5d4e4d907
Remove DropAndReplace terminator
PR 107844 made DropAndReplace unused, let's remove it completely
from the codebase.
2023-03-07 14:25:22 +01:00
Andy Wang 7281cd0c21
Custom MIR: Support as casts 2023-03-07 11:42:34 +01:00
bors ac4379fea9 Auto merge of #108787 - cjgillot:sroa-lifetime, r=compiler-errors
Erase regions even when failing to normalize type in MIR opts

The first commit just moves the tests around.

Fixes https://github.com/rust-lang/rust/issues/108720

cc `@saethlin`
2023-03-06 08:31:28 +00:00
Camille GILLOT 708536bb47 Remove -Zverbose. 2023-03-05 19:18:58 +00:00
Camille GILLOT fc1a861558 Erase lifetimes in SROA. 2023-03-05 18:35:30 +00:00