Commit graph

560 commits

Author SHA1 Message Date
bors
a1411de9de Auto merge of #86267 - ZuseZ4:master, r=nagisa
Allow loading of llvm plugins on nightly

Based on a discussion in  #82734 / with `@wsmoses.`
Mainly moves [this](0149bc4e7e) behind a -Z flag, so it can only be used on nightly,
as requested by `@nagisa` in https://github.com/rust-lang/rust/issues/82734#issuecomment-835863940

This change allows loading of llvm plugins like Enzyme.
Right now it also requires a shared library LLVM build of rustc for symbol resolution.

```rust
// test.rs
extern { fn __enzyme_autodiff(_: usize, ...) -> f64; }

fn square(x : f64) -> f64 {
   return x * x;
}

fn main() {
   unsafe {
      println!("Hello, world {} {}!", square(3.0), __enzyme_autodiff(square as usize, 3.0));
   }
}
```
```
./rustc test.rs -Z llvm-plugins="./LLVMEnzyme-12.so" -C passes="enzyme"
./test
Hello, world 9 6!
```

I will try to figure out how to simplify the usage and get this into stable in a later iteration,
but having this on nightly will already help testing further steps.
2021-06-26 19:20:41 +00:00
Manuel Drehwald
abdd24a040 Remove dropping of loaded plugins and better debug info 2021-06-26 19:30:09 +02:00
Josh Triplett
aadbf75283 rustc_codegen_llvm: Remove unused dependency rustc_incremental
Unused since commit f141acf067
("Move finalize_session_directory call out of cg_llvm").
2021-06-25 01:12:59 -07:00
Josh Triplett
e37d6a9bae rustc_codegen_llvm: Remove unused dependency rustc_feature
Unused since commit 622c48e4f1
("Allow making `RUSTC_BOOTSTRAP` conditional on the crate name").
2021-06-25 01:12:59 -07:00
Smitty
bdfcb88e8b Use HTTPS links where possible 2021-06-23 16:26:46 -04:00
Manuel Drehwald
f454aab3d6 Add missing use 2021-06-23 04:26:14 +02:00
Manuel Drehwald
9f406ce2c7 addressing feedback 2021-06-21 01:38:25 +02:00
Manuel Drehwald
4dbdcd1c5c allow loading of llvm plugins on nightly 2021-06-13 18:23:01 +02:00
bors
1f949e94e8 Auto merge of #86020 - nagisa:nagisa/outliner, r=pnkfelix
Disable the machine outliner by default

This addresses a codegen-issue that needs to be fixed upstream in LLVM.
While we wait for the fix, we can disable it.

Verified manually that the outliner is no longer run when
`-Copt-level=z` is specified, and also that you can override this with
`-Cllvm-args=-enable-machine-outliner` if you need it anyway.

A regression test is not really feasible in this instance, given that we
do not have any minimal reproducers.

Fixes #85351

cc `@pnkfelix`
2021-06-10 15:11:01 +00:00
bors
1639a16ebf Auto merge of #85910 - cjgillot:no-meta-version, r=Aaron1011
Drop metadata_encoding_version.

Part of #85153

r? `@Aaron1011`
2021-06-10 00:39:25 +00:00
bors
cc9610bf5a Auto merge of #85810 - bjorn3:further_driver_cleanup, r=varkor
Driver improvements

This PR contains a couple of cleanups for the driver and a few small improvements for the custom codegen backend interface. It also implements `--version` and `-Cpasses=list` support for custom codegen backends.
2021-06-07 02:30:24 +00:00
bors
9a576175cc Auto merge of #84171 - ricobbe:raw-dylib-via-llvm, r=petrochenkov
Partial support for raw-dylib linkage

First cut of functionality for issue #58713: add support for `#[link(kind = "raw-dylib")]` on `extern` blocks in lib crates compiled to .rlib files.  Does not yet support `#[link_name]` attributes on functions, or the `#[link_ordinal]` attribute, or `#[link(kind = "raw-dylib")]` on `extern` blocks in bin crates; I intend to publish subsequent PRs to fill those gaps.  It's also not yet clear whether this works for functions in `extern "stdcall"` blocks; I also intend to investigate that shortly and make any necessary changes as a follow-on PR.

This implementation calls out to an LLVM function to construct the actual `.idata` sections as temporary `.lib` files on disk and then links those into the generated .rlib.
2021-06-06 03:59:17 +00:00
bors
f434217aab Auto merge of #79608 - alessandrod:bpf, r=nagisa
BPF target support

This adds `bpfel-unknown-none` and `bpfeb-unknown-none`, two new no_std targets that generate little and big endian BPF. The approach taken is very similar to the cuda target, where `TargetOptions::obj_is_bitcode` is enabled and code generation is done by the linker.

I added the targets to `dist-various-2`. There are [some tests](https://github.com/alessandrod/bpf-linker/tree/main/tests/assembly) in bpf-linker and I'm planning to add more. Those are currently not ran as part of rust CI.
2021-06-06 01:02:32 +00:00
Simonas Kazlauskas
c63a1c0a1b Disable the machine outliner by default
This addresses a codegen-issue that needs to be fixed upstream in LLVM.
While we wait for the fix, we can disable it.

Verified manually that the outliner is no longer run when
`-Copt-level=z` is specified, and also that you can override this with
`-Cllvm-args=-enable-machine-outliner` if you need it anyway.

A regression test is not really feasible in this instance, given that we
do not have any minimal reproducers.

Fixes #85351
2021-06-05 14:57:28 +03:00
Richard Cobbe
6aa45b71b1 Add first cut of functionality for #58713: support for #[link(kind = "raw-dylib")].
This does not yet support #[link_name] attributes on functions, the #[link_ordinal]
attribute, #[link(kind = "raw-dylib")] on extern blocks in bin crates, or
stdcall functions on 32-bit x86.
2021-06-04 18:01:35 -07:00
bors
c79419af07 Auto merge of #84449 - alexcrichton:metadata-in-object, r=nagisa
rustc: Store metadata-in-rlibs in object files

This commit updates how rustc compiler metadata is stored in rlibs.
Previously metadata was stored as a raw file that has the same format as
`--emit metadata`. After this commit, however, the metadata is encoded
into a small object file which has one section which is the contents of
the metadata.

The motivation for this commit is to fix a common case where #83730
arises. The problem is that when rustc crates a `dylib` crate type it
needs to include entire rlib files into the dylib, so it passes
`--whole-archive` (or the equivalent) to the linker. The problem with
this, though, is that the linker will attempt to read all files in the
archive. If the metadata file were left as-is (today) then the linker
would generate an error saying it can't read the file. The previous
solution was to alter the rlib just before linking, creating a new
archive in a temporary directory which has the metadata file removed.

This problem from before this commit is now removed if the metadata file
is stored in an object file that the linker can read. The only caveat we
have to take care of is to ensure that the linker never actually
includes the contents of the object file into the final output. We apply
similar tricks as the `.llvmbc` bytecode sections to do this.

This involved changing the metadata loading code a bit, namely updating
some of the LLVM C APIs used to use non-deprecated ones and fiddling
with the lifetimes a bit to get everything to work out. Otherwise though
this isn't intended to be a functional change really, only that metadata
is stored differently in archives now.

This should end up fixing #83730 because by default dylibs will no
longer have their rlib dependencies "altered" meaning that
split-debuginfo will continue to have valid paths pointing at the
original rlibs. (note that we still "alter" rlibs if LTO is enabled to
remove Rust object files and we also "alter" for the #[link(cfg)]
feature, but that's rarely used).

Closes #83730
2021-06-04 19:29:50 +00:00
Alex Crichton
0e0338744d rustc: Store metadata-in-rlibs in object files
This commit updates how rustc compiler metadata is stored in rlibs.
Previously metadata was stored as a raw file that has the same format as
`--emit metadata`. After this commit, however, the metadata is encoded
into a small object file which has one section which is the contents of
the metadata.

The motivation for this commit is to fix a common case where #83730
arises. The problem is that when rustc crates a `dylib` crate type it
needs to include entire rlib files into the dylib, so it passes
`--whole-archive` (or the equivalent) to the linker. The problem with
this, though, is that the linker will attempt to read all files in the
archive. If the metadata file were left as-is (today) then the linker
would generate an error saying it can't read the file. The previous
solution was to alter the rlib just before linking, creating a new
archive in a temporary directory which has the metadata file removed.

This problem from before this commit is now removed if the metadata file
is stored in an object file that the linker can read. The only caveat we
have to take care of is to ensure that the linker never actually
includes the contents of the object file into the final output. We apply
similar tricks as the `.llvmbc` bytecode sections to do this.

This involved changing the metadata loading code a bit, namely updating
some of the LLVM C APIs used to use non-deprecated ones and fiddling
with the lifetimes a bit to get everything to work out. Otherwise though
this isn't intended to be a functional change really, only that metadata
is stored differently in archives now.

This should end up fixing #83730 because by default dylibs will no
longer have their rlib dependencies "altered" meaning that
split-debuginfo will continue to have valid paths pointing at the
original rlibs. (note that we still "alter" rlibs if LTO is enabled to
remove Rust object files and we also "alter" for the #[link(cfg)]
feature, but that's rarely used).

Closes #83730
2021-06-04 10:05:20 -07:00
bjorn3
e30490d5b2 Move crate_name field from OngoingCodegen to CrateInfo 2021-06-04 13:20:05 +02:00
bjorn3
f8ed66be6b Remove unused imports 2021-06-04 13:20:04 +02:00
bjorn3
f04a2d308e Provide default MetadataLoader 2021-06-04 13:20:04 +02:00
bjorn3
092bc2b744 Provide a default provide* implementation for CodegenBackend
Both cg_llvm and cg_clif don't override it. cg_spirv does override it,
so it needs to be preserved.
2021-06-04 13:20:04 +02:00
Wesley Wiser
3127419e2b Respond to review feedback 2021-06-02 10:23:12 -04:00
Wesley Wiser
ef053fd6f0 Change the type name from _enum<..> to enum$<..>
This makes the type name inline with the proposed standard in #85269.
2021-06-02 10:23:12 -04:00
Wesley Wiser
d2d6fa852d Respond to review feedback 2021-06-02 10:23:11 -04:00
Wesley Wiser
d650091117 Make tidy happy 2021-06-02 10:23:11 -04:00
Wesley Wiser
141546c355 Generate better debuginfo for niche-layout enums
Previously, we would generate a single struct with the layout of the
dataful variant plus an extra field whose name contained the value of
the niche (this would only really work for things like `Option<&_>`
where we can determine that the `None` case maps to `0` but for enums
that have multiple tag only variants, this doesn't work).

Now, we generate a union of two structs, one which is the layout of the
dataful variant and one which just has a way of reading the
discriminant. We also generate an enum which maps the discriminant value
to the tag only variants.

We also encode information about the range of values which correspond to
the dataful variant in the type name and then use natvis to determine
which union field we should display to the user.

As a result of this change, all niche-layout enums render correctly in
WinDbg and Visual Studio!
2021-06-02 10:23:10 -04:00
Wesley Wiser
2a025c1a76 Remove fallback for containing scopes
This wasn't necessary for msvc and caused issues where different types
with the same name such as different instantiations of `Option<T>` would
have colliding debuginfo. This confused the debugger which would pick
one of the type definitions and use for all types with that name even
though they had different layout.
2021-06-02 10:23:10 -04:00
Wesley Wiser
b644f06326 Resolve EnumTagInfo FIXME 2021-06-02 10:23:10 -04:00
Wesley Wiser
f353cbf1a1 Generate better debuginfo for directly tagged enums 2021-06-02 10:23:09 -04:00
Tomasz Miąsko
c1f6495b8e Miscellaneous inlining improvements 2021-06-02 08:49:58 +02:00
Camille GILLOT
202d39a96b Drop metadata_encoding_version. 2021-06-01 21:12:27 +02:00
Camille Gillot
0f0f3138cb
Revert "Reduce the amount of untracked state in TyCtxt" 2021-06-01 09:05:22 +02:00
Camille GILLOT
2543028161 Drop metadata_encoding_version. 2021-05-30 20:05:46 +02:00
Boris-Chengbiao Zhou
4a76934aa7 Fix static relocation model for PowerPC64
We now also use `should_assume_dso_local()` for declarations and port two
additional cases from clang:
- Exclude PPC64 [1]
- Exclude thread-local variables [2]

[1]: 033138ea45/clang/lib/CodeGen/CodeGenModule.cpp (L1038-L1040)
[2]: 033138ea45/clang/lib/CodeGen/CodeGenModule.cpp (L1048-L1050)
2021-05-28 03:48:39 +02:00
Pietro Albini
9e22b844dd remove cfg(bootstrap) 2021-05-24 11:07:48 -04:00
Alessandro Decina
b2a6967114 Add support for BPF inline assembly 2021-05-23 18:03:27 +10:00
bors
8a57820bca Auto merge of #84665 - adamgemmell:aarch64-features, r=Amanieu
Update list of allowed aarch64 features

I recently added these features to std_detect for aarch64 linux, pending [review](https://github.com/rust-lang/stdarch/pull/1146).

I have commented any features not supported by LLVM 9, the current minimum version for Rust. Some (PAuth at least) were renamed between 9 & 12 and I've left them disabled. TME, however, is not in LLVM 9 but I've left it enabled.

See https://github.com/rust-lang/stdarch/issues/993
2021-05-20 13:07:35 +00:00
Adam Gemmell
c71e58d432 Rename fptoint to frintts 2021-05-19 16:12:30 +01:00
Adam Gemmell
523b4d1499 Remove LSE2 2021-05-19 16:11:11 +01:00
bors
be8450eec8 Auto merge of #85276 - Bobo1239:more_dso_local, r=nagisa
Set dso_local for more items

Related to https://github.com/rust-lang/rust/pull/83592. (cc `@nagisa)`

Noticed that on x86_64 with `relocation-model: static` `R_X86_64_GOTPCREL` relocations were still generated in some cases. (related: https://github.com/Rust-for-Linux/linux/issues/135; Rust-for-Linux needs these fixes to successfully build)

First time doing anything with LLVM so not sure whether this is correct but the following are some of the things I've tried to convince myself.

## C equivalent

Example from clang which also sets `dso_local` in these cases:
`clang-12 -fno-PIC -S -emit-llvm test.c`
```C
extern int A;

int* a() {
    return &A;
}

int B;

int* b() {
    return &B;
}
```
```
; ModuleID = 'test.c'
source_filename = "test.c"
target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-unknown-linux-gnu"

`@A` = external dso_local global i32, align 4
`@B` = dso_local global i32 0, align 4

; Function Attrs: noinline nounwind optnone uwtable
define dso_local i32* `@a()` #0 {
  ret i32* `@A`
}

; Function Attrs: noinline nounwind optnone uwtable
define dso_local i32* `@b()` #0 {
  ret i32* `@B`
}

attributes #0 = { noinline nounwind optnone uwtable "disable-tail-calls"="false" "frame-pointer"="all" "less-precise-fpmad"="false" "min-legal-vector-width"="0" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "tune-cpu"="generic" "unsafe-fp-math"="false" "use-soft-float"="false" }

!llvm.module.flags = !{!0}
!llvm.ident = !{!1}

!0 = !{i32 1, !"wchar_size", i32 4}
!1 = !{!"clang version 12.0.0 (https://github.com/llvm/llvm-project/ b978a93635b584db380274d7c8963c73989944a1)"}
```
`clang-12 -fno-PIC -c test.c`
`objdump test.o -r`:
```
test.o:     file format elf64-x86-64

RELOCATION RECORDS FOR [.text]:
OFFSET           TYPE              VALUE
0000000000000006 R_X86_64_64       A
0000000000000016 R_X86_64_64       B

RELOCATION RECORDS FOR [.eh_frame]:
OFFSET           TYPE              VALUE
0000000000000020 R_X86_64_PC32     .text
0000000000000040 R_X86_64_PC32     .text+0x0000000000000010
```

## Comparison to pre-LLVM 12 output

`rustc --emit=obj,llvm-ir --target=x86_64-unknown-none-linuxkernel --crate-type rlib test.rs`
```Rust
#![feature(no_core, lang_items)]
#![no_core]

#[lang="sized"]
trait Sized {}

#[lang="sync"]
trait Sync {}

#[lang = "drop_in_place"]
pub unsafe fn drop_in_place<T: ?Sized>(_: *mut T) {}

impl Sync for i32 {}

pub static STATIC: i32 = 32;

extern {
    pub static EXT_STATIC: i32;
}

pub fn a() -> &'static i32 {
    &STATIC
}
pub fn b() -> &'static i32 {
    unsafe {&EXT_STATIC}
}
```
`objdump test.o -r`
nightly-2021-02-20 (rustc target is `x86_64-linux-kernel`):
```
RELOCATION RECORDS FOR [.text._ZN4test1a17h1024ba65f3424175E]:
OFFSET           TYPE              VALUE
0000000000000007 R_X86_64_32S      _ZN4test6STATIC17h3adc41a83746c9ffE

RELOCATION RECORDS FOR [.text._ZN4test1b17h86a6a80c1190ac8dE]:
OFFSET           TYPE              VALUE
0000000000000007 R_X86_64_32S      EXT_STATIC
```
nightly-2021-05-10:
```
RELOCATION RECORDS FOR [.text._ZN4test1a17he846f03bf37b2d20E]:
OFFSET           TYPE              VALUE
0000000000000007 R_X86_64_GOTPCREL  _ZN4test6STATIC17h5a059515bf3d4968E-0x0000000000000004

RELOCATION RECORDS FOR [.text._ZN4test1b17h7e0f7f80fbd91125E]:
OFFSET           TYPE              VALUE
0000000000000007 R_X86_64_GOTPCREL  EXT_STATIC-0x0000000000000004
```
This PR:
```
RELOCATION RECORDS FOR [.text._ZN4test1a17he846f03bf37b2d20E]:
OFFSET           TYPE              VALUE
0000000000000007 R_X86_64_32S      _ZN4test6STATIC17h5a059515bf3d4968E

RELOCATION RECORDS FOR [.text._ZN4test1b17h7e0f7f80fbd91125E]:
OFFSET           TYPE              VALUE
0000000000000007 R_X86_64_32S      EXT_STATIC
```
2021-05-19 07:25:17 +00:00
Boris-Chengbiao Zhou
f7ed4a799a Set dso_local for more items 2021-05-18 20:13:24 +02:00
Joshua Nelson
e48b6b4599 Stabilize extended_key_value_attributes
# Stabilization report

 ## Summary

This stabilizes using macro expansion in key-value attributes, like so:

 ```rust
 #[doc = include_str!("my_doc.md")]
 struct S;

 #[path = concat!(env!("OUT_DIR"), "/generated.rs")]
 mod m;
 ```

See the changes to the reference for details on what macros are allowed;
see Petrochenkov's excellent blog post [on internals](https://internals.rust-lang.org/t/macro-expansion-points-in-attributes/11455)
for alternatives that were considered and rejected ("why accept no more
and no less?")

This has been available on nightly since 1.50 with no major issues.

 ## Notes

 ### Accepted syntax

The parser accepts arbitrary Rust expressions in this position, but any expression other than a macro invocation will ultimately lead to an error because it is not expected by the built-in expression forms (e.g., `#[doc]`).  Note that decorators and the like may be able to observe other expression forms.

 ### Expansion ordering

Expansion of macro expressions in "inert" attributes occurs after decorators have executed, analogously to macro expressions appearing in the function body or other parts of decorator input.

There is currently no way for decorators to accept macros in key-value position if macro expansion must be performed before the decorator executes (if the macro can simply be copied into the output for later expansion, that can work).

 ## Test cases

 - https://github.com/rust-lang/rust/blob/master/src/test/ui/attributes/key-value-expansion-on-mac.rs
 - https://github.com/rust-lang/rust/blob/master/src/test/rustdoc/external-doc.rs

The feature has also been dogfooded extensively in the compiler and
standard library:

- https://github.com/rust-lang/rust/pull/83329
- https://github.com/rust-lang/rust/pull/83230
- https://github.com/rust-lang/rust/pull/82641
- https://github.com/rust-lang/rust/pull/80534

 ## Implementation history

- Initial proposal: https://github.com/rust-lang/rust/issues/55414#issuecomment-554005412
- Experiment to see how much code it would break: https://github.com/rust-lang/rust/pull/67121
- Preliminary work to restrict expansion that would conflict with this
feature: https://github.com/rust-lang/rust/pull/77271
- Initial implementation: https://github.com/rust-lang/rust/pull/78837
- Fix for an ICE: https://github.com/rust-lang/rust/pull/80563

 ## Unresolved Questions

~~https://github.com/rust-lang/rust/pull/83366#issuecomment-805180738 listed some concerns, but they have been resolved as of this final report.~~

 ## Additional Information

 There are two workarounds that have a similar effect for `#[doc]`
attributes on nightly. One is to emulate this behavior by using a limited version of this feature that was stabilized for historical reasons:

```rust
macro_rules! forward_inner_docs {
    ($e:expr => $i:item) => {
        #[doc = $e]
        $i
    };
}

forward_inner_docs!(include_str!("lib.rs") => struct S {});
```

This also works for other attributes (like `#[path = concat!(...)]`).
The other is to use `doc(include)`:

```rust
 #![feature(external_doc)]
 #[doc(include = "lib.rs")]
 struct S {}
```

The first works, but is non-trivial for people to discover, and
difficult to read and maintain. The second is a strange special-case for
a particular use of the macro. This generalizes it to work for any use
case, not just including files.

I plan to remove `doc(include)` when this is stabilized. The
`forward_inner_docs` workaround will still compile without warnings, but
I expect it to be used less once it's no longer necessary.
2021-05-18 01:01:36 -04:00
bors
3396a383bb Auto merge of #85178 - cjgillot:local-crate, r=oli-obk
Remove CrateNum parameter for queries that only work on local crate

The pervasive `CrateNum` parameter is a remnant of the multi-crate rustc idea.

Using `()` as query key in those cases avoids having to worry about the validity of the query key.
2021-05-17 01:42:03 +00:00
Eduard-Mihai Burtescu
0fcaf11455 rustc_codegen_ssa: append blocks to functions w/o creating a builder. 2021-05-17 00:04:09 +03:00
Eduard-Mihai Burtescu
402e9efc56 rustc_codegen_ssa: only create backend BasicBlocks as-needed. 2021-05-17 00:04:09 +03:00
bors
e78bccfbc0 Auto merge of #85279 - DrChat:asm_powerpc64, r=Amanieu
Add asm!() support for PowerPC64

I was anticipating this to be difficult so I didn't do it as part of #84732... but this was pretty easy to do 👀
2021-05-16 04:47:52 +00:00
bors
75da570d78 Auto merge of #83640 - bjorn3:shared_metadata_reader, r=nagisa
Use the object crate for metadata reading

This allows sharing the metadata reader between cg_llvm, cg_clif and other codegen backends.

This is not currently useful for rlib reading with cg_spirv ([rust-gpu](https://github.com/EmbarkStudios/rust-gpu/)) as it uses tar rather than ar as .rlib format, but it is useful for dylib reading required for loading proc macros. (cc `@eddyb)`

The object crate is already trusted as dependency of libstd through backtrace. As far as I know it supports reading all object file formats used by targets for which we support rust dylibs with crate metadata, but I am not certain. If this happens to not be the case, I could keep using LLVM for reading dylib metadata.

Marked as WIP for a perf run and as it is based on #83637.
2021-05-14 12:58:58 +00:00
Dr. Chat
69acee3ffe Add asm!() support for PowerPC64 2021-05-13 22:31:47 -05:00
Amanieu d'Antras
5918ee4317 Add support for const operands and options to global_asm!
On x86, the default syntax is also switched to Intel to match asm!
2021-05-13 22:31:57 +01:00
bors
72d07257ed Auto merge of #84732 - DrChat:asm_powerpc, r=Amanieu
Add asm!() support for PowerPC

This includes GPRs and FPRs only.
Note that this does not include PowerPC64.

For my reference, this was mostly duplicated from PR #73214.
2021-05-13 05:40:55 +00:00
Camille GILLOT
0bde3b1f80 Use () for codegen queries. 2021-05-12 13:58:46 +02:00
Camille GILLOT
75f4f6ee4f Use () for mir_keys. 2021-05-12 13:58:43 +02:00
Camille GILLOT
829a9d33a9 Use () for entry_fn. 2021-05-12 13:58:42 +02:00
bors
e1ff91f439 Auto merge of #83813 - cbeuw:remap-std, r=michaelwoerister
Fix `--remap-path-prefix` not correctly remapping `rust-src` component paths and unify handling of path mapping with virtualized paths

This PR fixes #73167 ("Binaries end up containing path to the rust-src component despite `--remap-path-prefix`") by preventing real local filesystem paths from reaching compilation output if the path is supposed to be remapped.

`RealFileName::Named` introduced in #72767 is now renamed as `LocalPath`, because this variant wraps a (most likely) valid local filesystem path.

`RealFileName::Devirtualized` is renamed as `Remapped` to be used for remapped path from a real path via `--remap-path-prefix` argument, as well as real path inferred from a virtualized (during compiler bootstrapping) `/rustc/...` path. The `local_path` field is now an `Option<PathBuf>`, as it will be set to `None` before serialisation, so it never reaches any build output. Attempting to serialise a non-`None` `local_path` will cause an assertion faliure.

When a path is remapped, a `RealFileName::Remapped` variant is created. The original path is preserved in `local_path` field and the remapped path is saved in `virtual_name` field. Previously, the `local_path` is directly modified which goes against its purpose of "suitable for reading from the file system on the local host".

`rustc_span::SourceFile`'s fields `unmapped_path` (introduced by #44940) and `name_was_remapped` (introduced by #41508 when `--remap-path-prefix` feature originally added) are removed, as these two pieces of information can be inferred from the `name` field: if it's anything other than a `FileName::Real(_)`, or if it is a `FileName::Real(RealFileName::LocalPath(_))`, then clearly `name_was_remapped` would've been false and `unmapped_path` would've been `None`. If it is a `FileName::Real(RealFileName::Remapped{local_path, virtual_name})`, then `name_was_remapped` would've been true and `unmapped_path` would've been `Some(local_path)`.

cc `@eddyb` who implemented `/rustc/...` path devirtualisation
2021-05-12 11:05:56 +00:00
bors
ac923d94f8 Auto merge of #83610 - bjorn3:driver_cleanup, r=cjgillot
rustc_driver cleanup

Best reviewed one commit at a time.
2021-05-12 08:38:03 +00:00
Dr. Chat
b1bb5d662c Add initial asm!() support for PowerPC
This includes GPRs and FPRs only
2021-05-11 19:04:16 -05:00
bjorn3
537e814d9c Add link to historic note 2021-05-10 10:49:45 +02:00
Nikita Popov
c2b15a6b64 Support -C passes in NewPM
And report an error if parsing the additional pass pipeline fails.
Threading through the error accounts for most of the changes here.
2021-05-08 10:58:08 +02:00
Nikita Popov
5519cbfe33 Don't force -O1 with ThinLTO
This doesn't seem to be necessary anymore, although I don't know
at which point or why that changed.

Forcing -O1 makes some tests fail under NewPM, because NewPM also
performs inlining at -O1, so it ends up performing much more
optimization in practice than before.
2021-05-08 10:58:08 +02:00
Nikita Popov
db140de8f2 Explicitly register GCOV profiling pass as well 2021-05-08 10:58:08 +02:00
Nikita Popov
5ecbe7fcf8 Explicitly register instrprof pass
Don't use "passes" for this purpose, explicitly insert it into
the correct place in the pipeline instead.
2021-05-08 10:58:08 +02:00
Nikita Popov
0318883cd6 Make -Z new-llvm-pass-manager an Option<bool>
To allow it to have an LLVM version dependent default.
2021-05-08 10:58:08 +02:00
bjorn3
f5d388302b Remove cg_llvm::metadata module 2021-05-07 18:48:58 +02:00
bjorn3
267d55d44a Use the object crate for metadata reading 2021-05-07 18:48:58 +02:00
Dylan DPC
a3fbde4240
Rollup merge of #84991 - alexcrichton:target-feature-remap, r=nagisa
rustc: Support Rust-specific features in -Ctarget-feature

Since the beginning of time the `-Ctarget-feature` flag on the command
line has largely been passed unmodified to LLVM. Afterwards, though, the
`#[target_feature]` attribute was stabilized and some of the names in
this attribute do not match the corresponding LLVM name. This is because
Rust doesn't always want to stabilize the exact feature name in LLVM for
the equivalent functionality in Rust. This creates a situation, however,
where in Rust you'd write:

    #[target_feature(enable = "pclmulqdq")]
    unsafe fn foo() {
        // ...
    }

but on the command line you would write:

    RUSTFLAGS="-Ctarget-feature=+pclmul" cargo build --release

This difference is somewhat odd to deal with if you're a newcomer and
the situation may be made worse with upcoming features like [WebAssembly
SIMD](https://github.com/rust-lang/rust/issues/74372) which may be more
prevalent.

This commit implements a mapping to translate requests via
`-Ctarget-feature` through the same name-mapping functionality that's
present for attributes in Rust going to LLVM. This means that
`+pclmulqdq` will work on x86 targets where as previously it did not.

I've attempted to keep this backwards-compatible where the compiler will
just opportunistically attempt to remap features found in
`-Ctarget-feature`, but if there's something it doesn't understand it
gets passed unmodified to LLVM just as it was before.
2021-05-07 16:19:22 +02:00
Yuki Okushi
b088318985
Rollup merge of #84875 - richkadel:no-coverage-dont-check-unused, r=tmandry
Removes unneeded check of `#[no_coverage]` in mapgen

There is an anticipated feature request to support a compiler flag that
only adds coverage for specific files (or perhaps mods). As I thought
about where that change would need to be supported, I realized that
checking the attribute in mapgen (for unused functions) was unnecessary.
The unused functions are only synthesized if they have MIR coverage, and
functions with the `no_coverage` attribute will not have been
instrumented with MIR coverage statements in the first place.

New tests confirm this.

Also, while adding tests, I updated resolved comments and FIXMEs in
other tests, and expanded comments and tests on one remaining issue that
is still not resolved.

r? `@tmandry`
cc: `@wesleywiser`
2021-05-07 15:20:25 +09:00
Yuki Okushi
283ef86784
Rollup merge of #84815 - richkadel:coverage-docs-update-2021-05, r=tmandry
Update coverage docs and command line help

r? `@tmandry`
cc: `@wesleywiser`
2021-05-07 15:20:24 +09:00
Rich Kadel
cd3a8c1b7f Removes unneeded check of #[no_coverage] in mapgen
And adds tests to validate it still works.

There is an anticipated feature request to support a compiler flag that
only adds coverage for specific files (or perhaps mods). As I thought
about where that change would need to be supported, I realized that
checking the attribute in mapgen (for unused functions) was unnecessary.
The unused functions are only synthesized if they have MIR coverage, and
functions with the `no_coverage` attribute will not have been
instrumented with MIR coverage statements in the first place.

New tests confirm this.

Also, while adding tests, I updated resolved comments and FIXMEs in
other tests.
2021-05-06 12:44:49 -07:00
Rich Kadel
f58a362d18 Update coverage docs and command line help 2021-05-06 12:20:31 -07:00
Alex Crichton
97658e58f0 rustc: Support Rust-specific features in -Ctarget-feature
Since the beginning of time the `-Ctarget-feature` flag on the command
line has largely been passed unmodified to LLVM. Afterwards, though, the
`#[target_feature]` attribute was stabilized and some of the names in
this attribute do not match the corresponding LLVM name. This is because
Rust doesn't always want to stabilize the exact feature name in LLVM for
the equivalent functionality in Rust. This creates a situation, however,
where in Rust you'd write:

    #[target_feature(enable = "pclmulqdq")]
    unsafe fn foo() {
        // ...
    }

but on the command line you would write:

    RUSTFLAGS="-Ctarget-feature=+pclmul" cargo build --release

This difference is somewhat odd to deal with if you're a newcomer and
the situation may be made worse with upcoming features like [WebAssembly
SIMD](https://github.com/rust-lang/rust/issues/74372) which may be more
prevalent.

This commit implements a mapping to translate requests via
`-Ctarget-feature` through the same name-mapping functionality that's
present for attributes in Rust going to LLVM. This means that
`+pclmulqdq` will work on x86 targets where as previously it did not.

I've attempted to keep this backwards-compatible where the compiler will
just opportunistically attempt to remap features found in
`-Ctarget-feature`, but if there's something it doesn't understand it
gets passed unmodified to LLVM just as it was before.
2021-05-06 08:52:03 -07:00
Luqman Aden
db555e1284 Implement RFC 2951: Native link modifiers
This commit implements both the native linking modifiers infrastructure
as well as an initial attempt at the individual modifiers from the RFC.
It also introduces a feature flag for the general syntax along with
individual feature flags for each modifier.
2021-05-05 16:04:25 -07:00
Andy Wang
5417b45c26
Use local and remapped paths where appropriate 2021-05-05 15:31:28 +01:00
Andy Wang
fb4f6439f6
Revamp RealFileName public methods 2021-05-05 15:31:03 +01:00
Andy Wang
0407919083
Use RealFileName for Session::working_dir as it may also be remapped 2021-05-05 15:10:57 +01:00
Brent Kerby
6679f5ceb1 Change 'NULL' to 'null' 2021-05-02 17:46:00 -06:00
bjorn3
c47eeac612 Move wasm_import_module_map provider to cg_ssa 2021-05-02 18:00:20 +02:00
bjorn3
808090eb07 Pass target_cpu to LinkerInfo::new instead of link_binary
This is one step towards separating the linking code from codegen backends
2021-05-02 18:00:20 +02:00
Dylan DPC
2553053828
Rollup merge of #84752 - lrh2000:generator-debuginfo, r=tmandry
Fix debuginfo for generators

First, all fields except the discriminant (including `outer_fields`) should be put into structures inside the variant part, which gives an equivalent layout but offers us much better integration with debuggers.

Second, artificial flags in generator variants should be removed.
 - Literally, variants are not artificial. We have `yield` statements, upvars and inner variables in the source code.
 - Functionally, we don't want debuggers to suppress the variants. It contains the state of the generator, which is useful when debugging. So they shouldn't be marked artificial.
 - Debuggers may use artificial flags to find the active variant. In this case, marking variants artificial will make debuggers not work properly.

Fixes #62572.
Fixes #79009.

And refer https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Debuginfo.20for.20generators.
2021-05-02 17:00:23 +02:00
lrh2000
5bf989ece9 Remove artificial flag from generator variants
- Literally, variants are not artificial. We have `yield` statements,
   upvars and inner variables in the source code.
 - Functionally, we don't want debuggers to suppress the variants. It
   contains the state of the generator, which is useful when debugging.
   So they shouldn't be marked artificial.
 - Debuggers may use artificial flags to find the active variant. In
   this case, marking variants artificial will make debuggers not work
   properly.

Fixes #79009.
2021-04-30 22:36:08 +08:00
lrh2000
060deec4b1 Move outer fields of enums into variant parts in debuginfo
All fields except the discriminant (including `outer_fields`)
should be put into structures inside the variant part, which gives
an equivalent layout but offers us much better integration with
debuggers.
2021-04-30 16:30:25 +08:00
bors
bcd696d722 Auto merge of #84401 - crlf0710:impl_main_by_path, r=petrochenkov
Implement RFC 1260 with feature_name `imported_main`.

This is the second extraction part of #84062 plus additional adjustments.
This (mostly) implements RFC 1260.

However there's still one test case failure in the extern crate case. Maybe `LocalDefId` doesn't work here? I'm not sure.

cc https://github.com/rust-lang/rust/issues/28937
r? `@petrochenkov`
2021-04-30 06:59:37 +00:00
Charles Lew
d261df4a72 Implement RFC 1260 with feature_name imported_main. 2021-04-29 08:35:08 +08:00
Adam Gemmell
3f5f54cd8b Update list of allowed aarch64 features
These features were recently added to std_detect. Features not supported
by LLVM 9, the current minimum version for Rust, are commented.
2021-04-28 17:54:44 +01:00
Rich Kadel
888d0b4c96 Derived Eq no longer shows uncovered
The Eq trait has a special hidden function. MIR `InstrumentCoverage`
would add this function to the coverage map, but it is never called, so
the `Eq` trait would always appear uncovered.

Fixes: #83601

The fix required creating a new function attribute `no_coverage` to mark
functions that should be ignored by `InstrumentCoverage` and the
coverage `mapgen` (during codegen).

While testing, I also noticed two other issues:

* spanview debug file output ICEd on a function with no body. The
workaround for this is included in this PR.
* `assert_*!()` macro coverage can appear covered if followed by another
`assert_*!()` macro. Normally they appear uncovered. I submitted a new
Issue #84561, and added a coverage test to demonstrate this issue.
2021-04-27 11:11:56 -07:00
Alex Crichton
35ae752231 Disable LLVM's new fptoint intrinsics on riscv64
Looks like this platform still isn't quite working yet due to
https://bugs.llvm.org/show_bug.cgi?id=50083
2021-04-23 07:45:23 -07:00
Alex Crichton
de2a4601ab rustc: Use LLVM's new saturating float-to-int intrinsics
This commit updates rustc, with an applicable LLVM version, to use
LLVM's new `llvm.fpto{u,s}i.sat.*.*` intrinsics to implement saturating
floating-point-to-int conversions. This results in a little bit tighter
codegen for x86/x86_64, but the main purpose of this is to prepare for
upcoming changes to the WebAssembly backend in LLVM where wasm's
saturating float-to-int instructions will now be implemented with these
intrinsics.

This change allows simplifying a good deal of surrounding code, namely
removing a lot of wasm-specific behavior. WebAssembly no longer has any
special-casing of saturating arithmetic instructions and the need for
`fptoint_may_trap` is gone and all handling code for that is now
removed. This means that the only wasm-specific logic is in the
`fpto{s,u}i` instructions which only get used for "out of bounds is
undefined behavior". This does mean that for the WebAssembly target
specifically the Rust compiler will no longer be 100% compatible with
pre-LLVM 12 versions, but it seems like that's unlikely to be relied on
by too many folks.

Note that this change does immediately regress the codegen of saturating
float-to-int casts on WebAssembly due to the specialization of the LLVM
intrinsic not being present in our LLVM fork just yet. I'll be following
up with an LLVM update to pull in those patches, but affects a few other
SIMD things in flight for WebAssembly so I wanted to separate this change.

Eventually the entire `cast_float_to_int` function can be removed when
LLVM 12 is the minimum version, but that will require sinking the
complexity of it into other backends such as Cranelfit.
2021-04-21 07:15:53 -07:00
Simonas Kazlauskas
487e27350a Don't set fast(-math) for certain simd ops
`fast-math` implies things like functions not being able to accept as an
argument or return as a result, say, `inf` which made these functions
confusingly named or behaving incorrectly, depending on how you
interpret it. Since the time when these intrinsics have been implemented
the intrinsics user's (stdsimd) approach has changed significantly and
so now it is required that these intrinsics operate normally rather than
in "whatever" way.

Fixes #84268
2021-04-17 23:33:10 +03:00
Jubilee Young
003b8eadd7 Add more SIMD math.h intrinsics
LLVM supports many functions from math.h in its IR. Many of these have
single-instruction variants on various platforms. So, let's add them so
std::arch can use them.

Yes, exact comparison is intentional: rounding must always return a
valid integer-equal value, except for inf/NAN.
2021-04-14 15:25:06 -07:00
bors
dae9d6ac3e Auto merge of #84004 - mattico:print-target-features-improvements, r=petrochenkov
Categorize and explain target features support

There are 3 different uses of the `-C target-feature` args passed to rustc:
1. All of the features are passed to LLVM, which uses them to configure code-generation. This is sort-of stabilized since 1.0 though LLVM does change/add/remove target features regularly.
2. Target features which are in [the compiler's allowlist](69e1d22ddb/compiler/rustc_codegen_ssa/src/target_features.rs (L12-L34)) can be used in `cfg!(target_feature)` etc. These may have different names than in LLVM and are renamed before passing them to LLVM.
3. Target features which are in the allowlist and which are stabilized or feature-gate-enabled can be used in `#[target_feature]`.

It can be confusing that `rustc --print target-features` just prints out the LLVM features without separating out the rustc features or even mentioning that the dichotomy exists.

This improves the situation by separating out the rustc and LLVM target features and adding a brief explanation about the difference.

Abbreviated Example Output:
```
$ rustc --print target-features
Features supported by rustc for this target:
    adx                         - Support ADX instructions.
    aes                         - Enable AES instructions.
...
    xsaves                      - Support xsaves instructions.
    crt-static                  - Enables libraries with C Run-time Libraries(CRT) to be statically linked.

Code-generation features supported by LLVM for this target:
    16bit-mode                  - 16-bit mode (i8086).
    32bit-mode                  - 32-bit mode (80386).
...
    x87                         - Enable X87 float instructions.
    xop                         - Enable XOP instructions.

Use +feature to enable a feature, or -feature to disable it.
For example, rustc -C target-cpu=mycpu -C target-feature=+feature1,-feature2

Code-generation features cannot be used in cfg or #[target_feature],
and may be renamed or removed in a future version of LLVM or rustc.

```

Motivated by #83975.
CC https://github.com/rust-lang/rust/issues/49653
2021-04-09 21:14:50 +00:00
Matt Ickstadt
e258a5ba6e Categorize and explain target features support 2021-04-09 10:16:04 -05:00
Alex Crichton
482a3d06c3 rustc: Add a new wasm ABI
This commit implements the idea of a new ABI for the WebAssembly target,
one called `"wasm"`. This ABI is entirely of my own invention
and has no current precedent, but I think that the addition of this ABI
might help solve a number of issues with the WebAssembly targets.

When `wasm32-unknown-unknown` was first added to Rust I naively
"implemented an abi" for the target. I then went to write `wasm-bindgen`
which accidentally relied on details of this ABI. Turns out the ABI
definition didn't match C, which is causing issues for C/Rust interop.
Currently the compiler has a "wasm32 bindgen compat" ABI which is the
original implementation I added, and it's purely there for, well,
`wasm-bindgen`.

Another issue with the WebAssembly target is that it's not clear to me
when and if the default C ABI will change to account for WebAssembly's
multi-value feature (a feature that allows functions to return multiple
values). Even if this does happen, though, it seems like the C ABI will
be guided based on the performance of WebAssembly code and will likely
not match even what the current wasm-bindgen-compat ABI is today. This
leaves a hole in Rust's expressivity in binding WebAssembly where given
a particular import type, Rust may not be able to import that signature
with an updated C ABI for multi-value.

To fix these issues I had the idea of a new ABI for WebAssembly, one
called `wasm`. The definition of this ABI is "what you write
maps straight to wasm". The goal here is that whatever you write down in
the parameter list or in the return values goes straight into the
function's signature in the WebAssembly file. This special ABI is for
intentionally matching the ABI of an imported function from the
environment or exporting a function with the right signature.

With the addition of a new ABI, this enables rustc to:

* Eventually remove the "wasm-bindgen compat hack". Once this
  ABI is stable wasm-bindgen can switch to using it everywhere.
  Afterwards the wasm32-unknown-unknown target can have its default ABI
  updated to match C.

* Expose the ability to precisely match an ABI signature for a
  WebAssembly function, regardless of what the C ABI that clang chooses
  turns out to be.

* Continue to evolve the definition of the default C ABI to match what
  clang does on all targets, since the purpose of that ABI will be
  explicitly matching C rather than generating particular function
  imports/exports.

Naturally this is implemented as an unstable feature initially, but it
would be nice for this to get stabilized (if it works) in the near-ish
future to remove the wasm32-unknown-unknown incompatibility with the C
ABI. Doing this, however, requires the feature to be on stable because
wasm-bindgen works with stable Rust.
2021-04-08 08:03:18 -07:00
bors
a6e7a5aa5d Auto merge of #81234 - repnop:fn-alignment, r=lcnr
Allow specifying alignment for functions

Fixes #75072

This allows the user to specify alignment for functions, which can be useful for low level work where functions need to necessarily be aligned to a specific value.

I believe the error cases not covered in the match are caught earlier based on my testing so I had them just return `None`.
2021-04-06 04:35:26 +00:00
bors
0c7d4effd7 Auto merge of #83592 - nagisa:nagisa/dso_local, r=davidtwco
Set dso_local for hidden, private and local items

This should probably have no real effect in most cases, as e.g. `hidden`
visibility already implies `dso_local` (or at least LLVM IR does not
preserve the `dso_local` setting if the item is already `hidden`), but
it should fix `-Crelocation-model=static` and improve codegen in
executables.

Note that this PR does not exhaustively port the logic in [clang], only the
portion that is necessary to fix a regression from LLVM 12 that relates to
`-Crelocation_model=static`.

Fixes #83335

[clang]: 3001d080c8/clang/lib/CodeGen/CodeGenModule.cpp (L945-L1039)
2021-04-06 02:09:01 +00:00
Wesley Norris
448d07683a Allow specifying alignment for functions 2021-04-05 17:36:51 -04:00
Dylan DPC
e64dbb1f46
Rollup merge of #82483 - tmiasko:option-from-str, r=matthewjasper
Use FromStr trait for number option parsing

Replace `parse_uint` with generic `parse_number` based on `FromStr`.
Use it for parsing inlining threshold to avoid casting later.
2021-04-05 13:03:37 +02:00
Dylan DPC
f8709ec962
Rollup merge of #83841 - Amanieu:asm_clobber_feature, r=nagisa
Allow clobbering unsupported registers in asm!

Previously registers could only be marked as clobbered if the target feature for that register was enabled. This restriction is now removed.

cc #81092

r? ``@nagisa``
2021-04-05 00:24:34 +02:00
Dylan DPC
0d12422f2d
Rollup merge of #80525 - devsnek:wasm64, r=nagisa
wasm64 support

There is still some upstream llvm work needed before this can land.
2021-04-05 00:24:23 +02:00
Gus Caplan
da66a31572
wasm64 2021-04-04 11:29:34 -05:00
Amanieu d'Antras
ddc53f809b Allow clobbering unsupported registers in asm!
Previously registers could only be marked as clobbered if the target feature for that register was enabled. This restriction is now removed.
2021-04-04 10:42:32 +01:00
bors
836c317426 Auto merge of #83774 - richkadel:zero-based-counters, r=tmandry
Translate counters from Rust 1-based to LLVM 0-based counter ids

A colleague contacted me and asked why Rust's counters start at 1, when
Clangs appear to start at 0. There is a reason why Rust's internal
counters start at 1 (see the docs), and I tried to keep them consistent
when codegenned to LLVM's coverage mapping format. LLVM should be
tolerant of missing counters, but as my colleague pointed out,
`llvm-cov` will silently fail to generate a coverage report for a
function based on LLVM's assumption that the counters are 0-based.

See:
https://github.com/llvm/llvm-project/blob/main/llvm/lib/ProfileData/Coverage/CoverageMapping.cpp#L170

Apparently, if, for example, a function has no branches, it would have
exactly 1 counter. `CounterValues.size()` would be 1, and (with the
1-based index), the counter ID would be 1. This would fail the check
and abort reporting coverage for the function.

It turns out that by correcting for this during coverage map generation,
by subtracting 1 from the Rust Counter ID (both when generating the
counter increment intrinsic call, and when adding counters to the map),
some uncovered functions (including in tests) now appear covered! This
corrects the coverage for a few tests!

r? `@tmandry`
FYI: `@wesleywiser`
2021-04-03 06:27:03 +00:00
Rich Kadel
7ceff6835a Translate counters from Rust 1-based to LLVM 0-based counter ids
A colleague contacted me and asked why Rust's counters start at 1, when
Clangs appear to start at 0. There is a reason why Rust's internal
counters start at 1 (see the docs), and I tried to keep them consistent
when codegenned to LLVM's coverage mapping format. LLVM should be
tolerant of missing counters, but as my colleague pointed out,
`llvm-cov` will silently fail to generate a coverage report for a
function based on LLVM's assumption that the counters are 0-based.

See:
https://github.com/llvm/llvm-project/blob/main/llvm/lib/ProfileData/Coverage/CoverageMapping.cpp#L170

Apparently, if, for example, a function has no branches, it would have
exactly 1 counter. `CounterValues.size()` would be 1, and (with the
1-based index), the counter ID would be 1. This would fail the check
and abort reporting coverage for the function.

It turns out that by correcting for this during coverage map generation,
by subtracting 1 from the Rust Counter ID (both when generating the
counter increment intrinsic call, and when adding counters to the map),
some uncovered functions (including in tests) now appear covered! This
corrects the coverage for a few tests!
2021-04-02 17:16:36 -07:00
Simonas Kazlauskas
64af7eae1e Move SanitizerSet to rustc_target 2021-04-03 00:37:49 +03:00
Simonas Kazlauskas
2f000a78bf Manually set dso_local when its valid to do so
This should have no real effect in most cases, as e.g. `hidden`
visibility already implies `dso_local` (or at least LLVM IR does not
preserve the `dso_local` setting if the item is already `hidden`), but
it should fix `-Crelocation-model=static` and improve codegen in
executables.

Note that this PR does not exhaustively port the logic in [clang]. Only
the obviously correct portion and what is necessary to fix a regression
from LLVM 12 that relates to `-Crelocation_model=static`.

Fixes #83335

[clang]: 3001d080c8/clang/lib/CodeGen/CodeGenModule.cpp (L945-L1039)
2021-04-03 00:00:29 +03:00
bors
6ff482bde5 Auto merge of #83666 - Amanieu:instrprof-order, r=tmandry
Run LLVM coverage instrumentation passes before optimization passes

This matches the behavior of Clang and allows us to remove several
hacks which were needed to ensure functions weren't optimized away
before reaching the instrumentation pass.

Fixes #83429

cc `@richkadel`

r? `@tmandry`
2021-03-31 03:20:33 +00:00
Amanieu d'Antras
cad9b6b695 Apply review feedback 2021-03-30 07:03:41 +01:00
Amanieu d'Antras
26d260bfa4 Run LLVM coverage instrumentation passes before optimization passes
This matches the behavior of Clang and allows us to remove several
hacks which were needed to ensure functions weren't optimized away
before reaching the instrumentation pass.
2021-03-30 02:10:28 +01:00
Joshua Nelson
de0fda9558 Address review comments
- Add back `HirIdVec`, with a comment that it will soon be used.
- Add back `*_region` functions, with a comment they may soon be used.
- Remove `-Z borrowck_stats` completely. It didn't do anything.
- Remove `make_nop` completely.
- Add back `current_loc`, which is used by an out-of-tree tool.
- Fix style nits
- Remove `AtomicCell` with `cfg(parallel_compiler)` for consistency.
2021-03-27 22:16:34 -04:00
Joshua Nelson
441dc3640a Remove (lots of) dead code
Found with https://github.com/est31/warnalyzer.

Dubious changes:
- Is anyone else using rustc_apfloat? I feel weird completely deleting
  x87 support.
- Maybe some of the dead code in rustc_data_structures, in case someone
  wants to use it in the future?
- Don't change rustc_serialize

  I plan to scrap most of the json module in the near future (see
  https://github.com/rust-lang/compiler-team/issues/418) and fixing the
  tests needed more work than I expected.

TODO: check if any of the comments on the deleted code should be kept.
2021-03-27 22:16:33 -04:00
Josh Stone
72ebebe474 Use iter::zip in compiler/ 2021-03-26 09:32:31 -07:00
bors
e423058751 Auto merge of #82980 - tmiasko:import-cold-multiplier, r=michaelwoerister
Import small cold functions

The Rust code is often written under an assumption that for generic
methods inline attribute is mostly unnecessary, since for optimized
builds using ThinLTO, a method will be code generated in at least one
CGU and available for import.

For example, deref implementations for Box, Vec, MutexGuard, and
MutexGuard are not currently marked as inline, neither is identity
implementation of From trait.

In PGO builds, when functions are determined to be cold, the default
multiplier of zero will stop the import, no matter how trivial the
implementation.

Increase slightly the default multiplier from 0 to 0.1.

r? `@ghost`
2021-03-26 11:57:44 +00:00
bors
6e17a5c5fd Auto merge of #83387 - cuviper:min-llvm-10, r=nagisa
Update the minimum external LLVM to 10

r? `@nikic`
2021-03-25 13:11:18 +00:00
bors
dbc37a97dc Auto merge of #83307 - richkadel:cov-unused-functions-1.1, r=tmandry
coverage bug fixes and optimization support

Adjusted LLVM codegen for code compiled with `-Zinstrument-coverage` to
address multiple, somewhat related issues.

Fixed a significant flaw in prior coverage solution: Every counter
generated a new counter variable, but there should have only been one
counter variable per function. This appears to have bloated .profraw
files significantly. (For a small program, it increased the size by
about 40%. I have not tested large programs, but there is anecdotal
evidence that profraw files were way too large. This is a good fix,
regardless, but hopefully it also addresses related issues.

Fixes: #82144

Invalid LLVM coverage data produced when compiled with -C opt-level=1

Existing tests now work up to at least `opt-level=3`. This required a
detailed analysis of the LLVM IR, comparisons with Clang C++ LLVM IR
when compiled with coverage, and a lot of trial and error with codegen
adjustments.

The biggest hurdle was figuring out how to continue to support coverage
results for unused functions and generics. Rust's coverage results have
three advantages over Clang's coverage results:

1. Rust's coverage map does not include any overlapping code regions,
   making coverage counting unambiguous.
2. Rust generates coverage results (showing zero counts) for all unused
   functions, including generics. (Clang does not generate coverage for
   uninstantiated template functions.)
3. Rust's unused functions produce minimal stubbed functions in LLVM IR,
   sufficient for including in the coverage results; while Clang must
   generate the complete LLVM IR for each unused function, even though
   it will never be called.

This PR removes the previous hack of attempting to inject coverage into
some other existing function instance, and generates dedicated instances
for each unused function. This change, and a few other adjustments
(similar to what is required for `-C link-dead-code`, but with lower
impact), makes it possible to support LLVM optimizations.

Fixes: #79651

Coverage report: "Unexecuted instantiation:..." for a generic function
from multiple crates

Fixed by removing the aforementioned hack. Some "Unexecuted
instantiation" notices are unavoidable, as explained in the
`used_crate.rs` test, but `-Zinstrument-coverage` has new options to
back off support for either unused generics, or all unused functions,
which avoids the notice, at the cost of less coverage of unused
functions.

Fixes: #82875

Invalid LLVM coverage data produced with crate brotli_decompressor

Fixed by disabling the LLVM function attribute that forces inlining, if
`-Z instrument-coverage` is enabled. This attribute is applied to
Rust functions with `#[inline(always)], and in some cases, the forced
inlining breaks coverage instrumentation and reports.

FYI: `@wesleywiser`

r? `@tmandry`
2021-03-25 05:07:34 +00:00
Rich Kadel
0859cec652 Changes from review comments 2021-03-23 17:02:10 -07:00
Rich Kadel
94a3454b03 Change def_id filter to use requires_monomorphization()
Per @wesleywiser's comment: https://github.com/rust-lang/rust/pull/83307#discussion_r599223342
2021-03-23 00:33:57 -07:00
bors
5d04957a4b Auto merge of #79278 - mark-i-m:stabilize-or-pattern, r=nikomatsakis
Stabilize or_patterns (RFC 2535, 2530, 2175)

closes #54883

This PR stabilizes the or_patterns feature in Rust 1.53.

This is blocked on the following (in order):
- [x] The crater run in https://github.com/rust-lang/rust/pull/78935#issuecomment-731564021
- [x] The resolution of the unresolved questions and a second crater run (https://github.com/rust-lang/rust/pull/78935#issuecomment-735412705)
    - It looks like we will need to pursue some sort of edition-based transition for `:pat`.
- [x] Nomination and discussion by T-lang
- [x] Implement new behavior for `:pat` based on consensus (https://github.com/rust-lang/rust/pull/80100).
- [ ] An FCP on stabilization

EDIT: Stabilization report is in https://github.com/rust-lang/rust/pull/79278#issuecomment-772815177
2021-03-22 19:48:27 +00:00
Josh Stone
7d872f538e Update the minimum external LLVM to 10 2021-03-22 11:33:43 -07:00
Dylan DPC
85f16fb4bc
Rollup merge of #83329 - camelid:debuginfo-doc-cleanup, r=davidtwco
Cleanup LLVM debuginfo module docs

- Move debuginfo docs from `doc.rs` module to `doc.md` file
- Cleanup LLVM debuginfo module docs
2021-03-22 02:20:31 +01:00
Nikita Popov
39ed64399e Enable mutable noalias by default for LLVM 12
We don't have any known noalias bugs for LLVM 12 ... yet.
2021-03-21 20:10:54 +01:00
Nikita Popov
08c5ffd4a3 Convert -Z mutable-noalias to Optional<bool>
The default value will dependend on the LLVM version in the future,
so don't specify one to start with.
2021-03-21 20:10:53 +01:00
Nikita Popov
dfc4cafe8e Move decision aboute noalias into codegen_llvm
The frontend shouldn't be deciding whether or not to use mutable
noalias attributes, as this is a pure LLVM concern. Only provide
the necessary information and do the actual decision in
codegen_llvm.
2021-03-21 20:10:53 +01:00
Camelid
dc240faed5 Cleanup LLVM debuginfo module docs
* Use Markdown list syntax and unindent a bit to prevent Markdown
  interpreting the nested lists as code blocks
* A few more small typographical cleanups
2021-03-20 14:38:49 -07:00
Camelid
a2e9374048 Move debuginfo docs from doc.rs module to doc.md file
And use `#[doc = include_str!("doc.md")]` in `mod.rs` so the docs are
rendered as if they were inline in the root module.
2021-03-20 14:38:49 -07:00
Rich Kadel
5a484a1aed gave unused_fn WeakAnyLinkage; moved create_pgo_func_name_var
The sample json5format tests produce coverage results again (and work
with opt-level 3!)
2021-03-19 20:46:15 -07:00
mark
db5629adcb stabilize or_patterns 2021-03-19 19:45:32 -05:00
Rich Kadel
bcf755562a coverage bug fixes and optimization support
Adjusted LLVM codegen for code compiled with `-Zinstrument-coverage` to
address multiple, somewhat related issues.

Fixed a significant flaw in prior coverage solution: Every counter
generated a new counter variable, but there should have only been one
counter variable per function. This appears to have bloated .profraw
files significantly. (For a small program, it increased the size by
about 40%. I have not tested large programs, but there is anecdotal
evidence that profraw files were way too large. This is a good fix,
regardless, but hopefully it also addresses related issues.

Fixes: #82144

Invalid LLVM coverage data produced when compiled with -C opt-level=1

Existing tests now work up to at least `opt-level=3`. This required a
detailed analysis of the LLVM IR, comparisons with Clang C++ LLVM IR
when compiled with coverage, and a lot of trial and error with codegen
adjustments.

The biggest hurdle was figuring out how to continue to support coverage
results for unused functions and generics. Rust's coverage results have
three advantages over Clang's coverage results:

1. Rust's coverage map does not include any overlapping code regions,
   making coverage counting unambiguous.
2. Rust generates coverage results (showing zero counts) for all unused
   functions, including generics. (Clang does not generate coverage for
   uninstantiated template functions.)
3. Rust's unused functions produce minimal stubbed functions in LLVM IR,
   sufficient for including in the coverage results; while Clang must
   generate the complete LLVM IR for each unused function, even though
   it will never be called.

This PR removes the previous hack of attempting to inject coverage into
some other existing function instance, and generates dedicated instances
for each unused function. This change, and a few other adjustments
(similar to what is required for `-C link-dead-code`, but with lower
impact), makes it possible to support LLVM optimizations.

Fixes: #79651

Coverage report: "Unexecuted instantiation:..." for a generic function
from multiple crates

Fixed by removing the aforementioned hack. Some "Unexecuted
instantiation" notices are unavoidable, as explained in the
`used_crate.rs` test, but `-Zinstrument-coverage` has new options to
back off support for either unused generics, or all unused functions,
which avoids the notice, at the cost of less coverage of unused
functions.

Fixes: #82875

Invalid LLVM coverage data produced with crate brotli_decompressor

Fixed by disabling the LLVM function attribute that forces inlining, if
`-Z instrument-coverage` is enabled. This attribute is applied to
Rust functions with `#[inline(always)], and in some cases, the forced
inlining breaks coverage instrumentation and reports.
2021-03-19 17:11:50 -07:00
SparrowLii
b93590e5d8 correct macro names 2021-03-19 03:47:13 +08:00
SparrowLii
0fa158b38f Add simd_neg platform intrinsic 2021-03-19 02:16:21 +08:00
Dylan DPC
b688b694d0
Rollup merge of #83080 - tmiasko:inline-coverage, r=wesleywiser
Make source-based code coverage compatible with MIR inlining

When codegenning code coverage use the instance that coverage data was
originally generated for, to ensure basic level of compatibility with
MIR inlining.

Fixes #83061
2021-03-18 00:28:09 +01:00
bors
0c341226ad Auto merge of #83084 - nagisa:nagisa/features-native, r=petrochenkov
Adjust `-Ctarget-cpu=native` handling in cg_llvm

When cg_llvm encounters the `-Ctarget-cpu=native` it computes an
explciit set of features that applies to the target in order to
correctly compile code for the host CPU (because e.g. `skylake` alone is
not sufficient to tell if some of the instructions are available or
not).

However there were a couple of issues with how we did this. Firstly, the
order in which features were overriden wasn't quite right – conceptually
you'd expect `-Ctarget-cpu=native` option to override the features that
are implicitly set by the target definition. However due to how other
`-Ctarget-cpu` values are handled we must adopt the following order
of priority:

* Features from -Ctarget-cpu=*; are overriden by
* Features implied by --target; are overriden by
* Features from -Ctarget-feature; are overriden by
* function specific features.

Another problem was in that the function level `target-features`
attribute would overwrite the entire set of the globally enabled
features, rather than just the features the
`#[target_feature(enable/disable)]` specified. With something like
`-Ctarget-cpu=native` we'd end up in a situation wherein a function
without `#[target_feature(enable)]` annotation would have a broader
set of features compared to a function with one such attribute. This
turned out to be a cause of heavy run-time regressions in some code
using these function-level attributes in conjunction with
`-Ctarget-cpu=native`, for example.

With this PR rustc is more careful about specifying the entire set of
features for functions that use `#[target_feature(enable/disable)]` or
`#[instruction_set]` attributes.

Sadly testing the original reproducer for this behaviour is quite
impossible – we cannot rely on `-Ctarget-cpu=native` to be anything in
particular on developer or CI machines.

cc https://github.com/rust-lang/rust/issues/83027 `@BurntSushi`
2021-03-17 05:46:08 +00:00
Simonas Kazlauskas
72fb4379d5 Adjust -Ctarget-cpu=native handling in cg_llvm
When cg_llvm encounters the `-Ctarget-cpu=native` it computes an
explciit set of features that applies to the target in order to
correctly compile code for the host CPU (because e.g. `skylake` alone is
not sufficient to tell if some of the instructions are available or
not).

However there were a couple of issues with how we did this. Firstly, the
order in which features were overriden wasn't quite right – conceptually
you'd expect `-Ctarget-cpu=native` option to override the features that
are implicitly set by the target definition. However due to how other
`-Ctarget-cpu` values are handled we must adopt the following order
of priority:

* Features from -Ctarget-cpu=*; are overriden by
* Features implied by --target; are overriden by
* Features from -Ctarget-feature; are overriden by
* function specific features.

Another problem was in that the function level `target-features`
attribute would overwrite the entire set of the globally enabled
features, rather than just the features the
`#[target_feature(enable/disable)]` specified. With something like
`-Ctarget-cpu=native` we'd end up in a situation wherein a function
without `#[target_feature(enable)]` annotation would have a broader
set of features compared to a function with one such attribute. This
turned out to be a cause of heavy run-time regressions in some code
using these function-level attributes in conjunction with
`-Ctarget-cpu=native`, for example.

With this PR rustc is more careful about specifying the entire set of
features for functions that use `#[target_feature(enable/disable)]` or
`#[instruction_set]` attributes.

Sadly testing the original reproducer for this behaviour is quite
impossible – we cannot rely on `-Ctarget-cpu=native` to be anything in
particular on developer or CI machines.
2021-03-16 21:32:55 +02:00
bors
f24ce9b014 Auto merge of #82838 - Amanieu:rustdoc_asm, r=nagisa
Allow rustdoc to handle asm! of foreign architectures

This allows rustdoc to process code containing `asm!` for architectures other than the current one. Since this never reaches codegen, we just replace target-specific registers and register classes with a dummy one.

Fixes #82869
2021-03-16 10:05:46 +00:00
Tomasz Miąsko
5a9538acb5 Functions inlined into reachable functions are reachable
Consider functions to be reachable for code coverage purposes, either
when they reach the code generation directly, or indirectly as inlined
part of another function.
2021-03-15 23:26:03 +01:00
Tomasz Miąsko
1796cc0e6c Make source-based code coverage compatible with MIR inlining
When codegenning code coverage use the instance that coverage data was
originally generated for, to ensure basic level of compatibility with
MIR inlining.
2021-03-15 23:26:03 +01:00
Amanieu d'Antras
fa3694fada Always lower asm! to valid HIR 2021-03-13 20:49:32 +00:00
Hiroki Noda
8357e57346 Add support for storing code model to LLVM module IR
This patch avoids undefined behavior by linking different object files.
Also this would it could be propagated properly to LTO.

See https://reviews.llvm.org/D52322 and https://reviews.llvm.org/D52323.

This patch is based on https://github.com/rust-lang/rust/pull/74002
2021-03-12 11:02:25 +09:00
Tomasz Miąsko
1aee8083be Import small cold functions
The Rust code is often written under an assumption that for generic
methods inline attribute is mostly unnecessary, since for optimized
builds using ThinLTO, a method will be generated in at least one CGU and
available for import.

For example, deref implementations for Box, Vec, MutexGuard, and
MutexGuard are not currently marked as inline, neither is identity
implementation of From trait.

In PGO builds, when functions are determined to be cold, the default
multiplier of zero will stop the import, even for completely trivial
functions.

Increase slightly the default multiplier from 0 to 0.1 to import them
regardless.
2021-03-11 00:00:00 +00:00
Simonas Kazlauskas
0517acd543 Remove the -Zinsert-sideeffect
This removes all of the code we had in place to work-around LLVM's
handling of forward progress. From this removal excluded is a workaround
where we'd insert a `sideeffect` into clearly infinite loops such as
`loop {}`. This code remains conditionally effective when the LLVM
version is earlier than 12.0, which fixed the forward progress related
miscompilations at their root.
2021-03-10 12:21:43 +02:00
Tomasz Miąsko
1ec905766d Use FromStr trait for number option parsing
Replace `parse_uint` with generic `parse_number` based on `FromStr`.
Use it for parsing inlining threshold to avoid casting later.
2021-03-09 14:49:04 +01:00
bors
234781afe3 Auto merge of #82285 - nhwn:nonzero-debug, r=nagisa
Use u32 over Option<u32> in DebugLoc

~~Changes `Option<u32>` fields in `DebugLoc` to `Option<NonZeroU32>`. Since the respective fields (`line` and `col`) are guaranteed to be 1-based, this layout optimization is a freebie.~~

EDIT: Changes `Option<u32>` fields in `DebugLoc` to `u32`. As `@bugadani` pointed out, an `Option<NonZeroU32>` is probably an unnecessary layer of abstraction since the `None` variant is always used as `UNKNOWN_LINE_NUMBER` (which is just `0`).  Also, `SourceInfo` in `metadata.rs` already uses a `u32` instead of an `Option<u32>` to encode the same information, so I think this change is warranted.

Since `@jyn514` raised some concerns over measuring performance in a similar PR (#82255), does this need a perf run?
2021-03-07 20:23:23 +00:00
bors
409920873c Auto merge of #81451 - nikic:llvm-12, r=nagisa
Upgrade to LLVM 12

This implements the necessary adjustments to make rustc work with LLVM 12. I didn't encounter any major issues so far.

r? `@cuviper`
2021-03-04 15:16:44 +00:00
Nikita Popov
bc96516a28 Mark pure asm as willreturn 2021-03-01 23:35:35 +01:00
Nikita Popov
1d280b012d Don't directly expose coverage::CounterMappingRegion via FFI
The definition of this struct changes in LLVM 12 due to the addition
of branch coverage support. To avoid future mismatches, declare our
own struct and then convert between them.
2021-03-01 23:35:35 +01:00
Dániel Buga
b97eb23cd0 Box generator-related Body fields 2021-03-01 08:32:49 +01:00
Nikita Popov
55f345f325 Support LLVM 12 in rustc 2021-02-28 10:19:44 +01:00
Dylan DPC
6d288c65df
Rollup merge of #82537 - wesleywiser:update_measureme, r=oli-obk
Update measureme dependency to the latest version

This version adds the ability to use `rdpmc` hardware-based performance
counters instead of wall-clock time for measuring duration. This also
introduces a dependency on the `perf-event-open-sys` crate on Linux
which is used when using hardware counters.

r? ```@oli-obk```
2021-02-27 21:56:20 +01:00
Dylan DPC
cabe97272d
Rollup merge of #82057 - upsuper-forks:cstr, r=davidtwco,wesleywiser
Replace const_cstr with cstr crate

This PR replaces the `const_cstr` macro inside `rustc_data_structures` with `cstr` macro from [cstr](https://crates.io/crates/cstr) crate.

The two macros basically serve the same purpose, which is to generate `&'static CStr` from a string literal. `cstr` is better because it validates the literal at compile time, while the existing `const_cstr` does it at runtime when `debug_assertions` is enabled. In addition, the value `cstr` generates can be used in constant context (which is seemingly not needed anywhere currently, though).
2021-02-27 02:34:21 +01:00
Guillaume Gomez
039b1b62ac
Rollup merge of #82456 - klensy:or-else, r=estebank
Replaced some unwrap_or and map_or with lazy variants

Replaced some `unwrap_or` and `map_or` with `unwrap_or_else` and `map_or_else`.
2021-02-26 15:52:31 +01:00
Wesley Wiser
e130e9cf77 Update measureme dependency to the latest version
This version adds the ability to use `rdpmc` hardware-based performance
counters instead of wall-clock time for measuring duration. This also
introduces a dependency on the `perf-event-open-sys` crate on Linux
which is used when using hardware counters.
2021-02-25 18:25:38 -05:00
Dylan DPC
00aa3e6880
Rollup merge of #82214 - est31:no_to_string, r=oli-obk
Remove redundant to_string calls
2021-02-25 14:33:59 +01:00
Dylan DPC
199095afc6
Rollup merge of #82213 - est31:slices_for_vecs, r=jyn514
Slices for vecs
2021-02-25 14:33:58 +01:00
klensy
08b1e8004b fix review 2021-02-25 04:21:12 +03:00
klensy
c75c4a579b replaced some map_or with map_or_else 2021-02-24 02:43:35 +03:00
bors
446d4533e8 Auto merge of #82102 - nagisa:nagisa/fix-dwo-name, r=davidtwco
Set path of the compile unit to the source directory

As part of the effort to implement split dwarf debug info, we ended up
setting the compile unit location to the output directory rather than
the source directory. Furthermore, it seems like we failed to remap the
prefixes for this as well!

The desired behaviour is to instead set the `DW_AT_GNU_dwo_name` to a
path relative to compiler's working directory. This still allows
debuggers to find the split dwarf files, while not changing the
behaviour of the code that is compiling with regular debug info, and not
changing the compiler's behaviour with regards to reproducibility.

Fixes #82074

cc `@alexcrichton` `@davidtwco`
2021-02-23 10:02:16 +00:00
Nathan Nguyen
408d4027d0 nhwn: use plain u32 in DebugLoc 2021-02-20 11:46:58 -06:00
Nathan Nguyen
f5aa1bceb9 nhwn: use Option<NonZeroU32> in DebugLoc 2021-02-20 11:46:50 -06:00
Guillaume Gomez
7292d5ff60
Rollup merge of #82105 - nagisa:nagisa/ensure-removed, r=petrochenkov
Don't fail to remove files if they are missing

In the backend we may want to remove certain temporary files, but in
certain other situations these files might not be produced in the first
place. We don't exactly care about that, and the intent is really that
these files are gone after a certain point in the backend.

Here we unify the backend file removing calls to use `ensure_removed`
which will attempt to delete a file, but will not fail if it does not
exist (anymore).

The tradeoff to this approach is, of course, that we may miss instances
were we are attempting to remove files at wrong paths due to some bug –
compilation would silently succeed but the temporary files would remain
there somewhere.
2021-02-17 20:37:57 +01:00
est31
003670748f Remove redundant to_string calls 2021-02-17 11:25:55 +01:00
est31
c5b9264929 Replace vec![] calls with slice literals
There is no need to create vec's here
2021-02-17 10:37:47 +01:00
Johnathan Van Why
fd21eb18e9 32-bit ARM: Emit lr instead of r14 when specified as an asm! output register.
On 32-bit ARM platforms, the register `r14` has the alias `lr`. When used as an output register in `asm!`, rustc canonicalizes the name to `r14`. LLVM only knows the register by the name `lr`, and rejects it. This changes rustc's LLVM code generation to output `lr` instead.
2021-02-14 23:41:10 -08:00
Simonas Kazlauskas
fa3621b468 Don't fail to remove files if they are missing
In the backend we may want to remove certain temporary files, but in
certain other situations these files might not be produced in the first
place. We don't exactly care about that, and the intent is really that
these files are gone after a certain point in the backend.

Here we unify the backend file removing calls to use `ensure_removed`
which will attempt to delete a file, but will not fail if it does not
exist (anymore).

The tradeoff to this approach is, of course, that we may miss instances
were we are attempting to remove files at wrong paths due to some bug –
compilation would silently succeed but the temporary files would remain
there somewhere.
2021-02-14 18:31:57 +02:00
Simonas Kazlauskas
16c71886c9 Set path of the compile unit to the source directory
As part of the effort to implement split dwarf debug info, we ended up
setting the compile unit location to the output directory rather than
the source directory. Furthermore, it seems like we failed to remap the
prefixes for this as well!

The desired behaviour is to instead set the `DW_AT_GNU_dwo_name` to a
path relative to compiler's working directory. This still allows
debuggers to find the split dwarf files, while not changing the
behaviour of the code that is compiling with regular debug info, and not
changing the compiler's behaviour with regards to reproducibility.

Fixes #82074
2021-02-14 17:12:14 +02:00
klensy
93c8ebe022 bumped smallvec deps 2021-02-14 18:03:11 +03:00
Xidorn Quan
38e4233a32 Replace const_cstr with cstr crate 2021-02-14 09:45:35 +11:00
Tri Vo
c7d9bffe76 HWASan support 2021-02-07 23:48:58 -08:00
bors
bb587b1a17 Auto merge of #80652 - calebzulawski:simd-lanes, r=nagisa
Improve SIMD type element count validation

Resolves rust-lang/stdsimd#53.

These changes are motivated by `stdsimd` moving in the direction of const generic vectors, e.g.:
```rust
#[repr(simd)]
struct SimdF32<const N: usize>([f32; N]);
```

This makes a few changes:
* Establishes a maximum SIMD lane count of 2^16 (65536).  This value is arbitrary, but attempts to validate lane count before hitting potential errors in the backend.  It's not clear what LLVM's maximum lane count is, but cranelift's appears to be much less than `usize::MAX`, at least.
* Expands some SIMD intrinsics to support arbitrary lane counts.  This resolves the ICE in the linked issue.
* Attempts to catch invalid-sized vectors during typeck when possible.

Unresolved questions:
* Generic-length vectors can't be validated in typeck and are only validated after monomorphization while computing layout.  This "works", but the errors simply bail out with no context beyond the name of the type.  Should these errors instead return `LayoutError` or otherwise provide context in some way?  As it stands, users of `stdsimd` could trivially produce monomorphization errors by making zero-length vectors.

cc `@bjorn3`
2021-02-07 22:25:14 +00:00
Mara Bos
add80c9d4b
Rollup merge of #81664 - bjorn3:no_codegen_hir, r=lcnr
Avoid a hir access inside get_static

Together with #81056 this ensures that the codegen unit DepNode doesn't have a direct dependency on any part of the hir.
2021-02-06 00:14:13 +01:00
bjorn3
da536554a0 Use is_local instead of as_local 2021-02-04 11:17:01 +01:00
bors
b593389edb Auto merge of #81346 - hug-dev:nonsecure-call-abi, r=jonas-schievink
Add a new ABI to support cmse_nonsecure_call

This adds support for the `cmse_nonsecure_call` feature to be able to perform non-secure function call.

See the discussion on Zulip [here](https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Support.20for.20callsite.20attributes/near/223054928).

This is a followup to #75810 which added `cmse_nonsecure_entry`. As for that PR, I assume that the changes are small enough to not have to go through a RFC but I don't mind doing one if needed 😃
I did not yet create a tracking issue, but if most of it is fine, I can create one and update the various files accordingly (they refer to the other tracking issue now).

On the Zulip chat, I believe `@jonas-schievink` volunteered to be a reviewer 💯
2021-02-03 06:00:43 +00:00
Jack Huey
399c0a8e52
Rollup merge of #81455 - Amanieu:aarch64_ilp32, r=sanxiyn
Add AArch64 big-endian and ILP32 targets

This PR adds 3 new AArch64 targets:
- `aarch64_be-unknown-linux-gnu`
- `aarch64-unknown-linux-gnu_ilp32`
- `aarch64_be-unknown-linux-gnu_ilp32`

It also fixes some ABI issues on big-endian ARM and AArch64.
2021-02-02 16:01:35 -05:00
bjorn3
fbe109a2fc Avoid a hir access inside get_static 2021-02-02 16:36:54 +01:00
Hugues de Valon
ce9818f2b7 Add a new ABI to support cmse_nonsecure_call
This commit adds a new ABI to be selected via `extern
"C-cmse-nonsecure-call"` on function pointers in order for the compiler to
apply the corresponding cmse_nonsecure_call callsite attribute.
For Armv8-M targets supporting TrustZone-M, this will perform a
non-secure function call by saving, clearing and calling a non-secure
function pointer using the BLXNS instruction.

See the page on the unstable book for details.

Signed-off-by: Hugues de Valon <hugues.devalon@arm.com>
2021-02-02 13:04:31 +00:00
Yuki Okushi
d9e56f48c5
Rollup merge of #79570 - alexcrichton:split-debuginfo, r=bjorn3
rustc: Stabilize `-Zrun-dsymutil` as `-Csplit-debuginfo`

This commit adds a new stable codegen option to rustc,
`-Csplit-debuginfo`. The old `-Zrun-dsymutil` flag is deleted and now
subsumed by this stable flag. Additionally `-Zsplit-dwarf` is also
subsumed by this flag but still requires `-Zunstable-options` to
actually activate. The `-Csplit-debuginfo` flag takes one of
three values:

* `off` - This indicates that split-debuginfo from the final artifact is
  not desired. This is not supported on Windows and is the default on
  Unix platforms except macOS. On macOS this means that `dsymutil` is
  not executed.

* `packed` - This means that debuginfo is desired in one location
  separate from the main executable. This is the default on Windows
  (`*.pdb`) and macOS (`*.dSYM`). On other Unix platforms this subsumes
  `-Zsplit-dwarf=single` and produces a `*.dwp` file.

* `unpacked` - This means that debuginfo will be roughly equivalent to
  object files, meaning that it's throughout the build directory
  rather than in one location (often the fastest for local development).
  This is not the default on any platform and is not supported on Windows.

Each target can indicate its own default preference for how debuginfo is
handled. Almost all platforms default to `off` except for Windows and
macOS which default to `packed` for historical reasons.

Some equivalencies for previous unstable flags with the new flags are:

* `-Zrun-dsymutil=yes` -> `-Csplit-debuginfo=packed`
* `-Zrun-dsymutil=no` -> `-Csplit-debuginfo=unpacked`
* `-Zsplit-dwarf=single` -> `-Csplit-debuginfo=packed`
* `-Zsplit-dwarf=split` -> `-Csplit-debuginfo=unpacked`

Note that `-Csplit-debuginfo` still requires `-Zunstable-options` for
non-macOS platforms since split-dwarf support was *just* implemented in
rustc.

There's some more rationale listed on #79361, but the main gist of the
motivation for this commit is that `dsymutil` can take quite a long time
to execute in debug builds and provides little benefit. This means that
incremental compile times appear that much worse on macOS because the
compiler is constantly running `dsymutil` over every single binary it
produces during `cargo build` (even build scripts!). Ideally rustc would
switch to not running `dsymutil` by default, but that's a problem left
to get tackled another day.

Closes #79361
2021-01-29 09:17:20 +09:00
Alex Crichton
a124043fb0 rustc: Stabilize -Zrun-dsymutil as -Csplit-debuginfo
This commit adds a new stable codegen option to rustc,
`-Csplit-debuginfo`. The old `-Zrun-dsymutil` flag is deleted and now
subsumed by this stable flag. Additionally `-Zsplit-dwarf` is also
subsumed by this flag but still requires `-Zunstable-options` to
actually activate. The `-Csplit-debuginfo` flag takes one of
three values:

* `off` - This indicates that split-debuginfo from the final artifact is
  not desired. This is not supported on Windows and is the default on
  Unix platforms except macOS. On macOS this means that `dsymutil` is
  not executed.

* `packed` - This means that debuginfo is desired in one location
  separate from the main executable. This is the default on Windows
  (`*.pdb`) and macOS (`*.dSYM`). On other Unix platforms this subsumes
  `-Zsplit-dwarf=single` and produces a `*.dwp` file.

* `unpacked` - This means that debuginfo will be roughly equivalent to
  object files, meaning that it's throughout the build directory
  rather than in one location (often the fastest for local development).
  This is not the default on any platform and is not supported on Windows.

Each target can indicate its own default preference for how debuginfo is
handled. Almost all platforms default to `off` except for Windows and
macOS which default to `packed` for historical reasons.

Some equivalencies for previous unstable flags with the new flags are:

* `-Zrun-dsymutil=yes` -> `-Csplit-debuginfo=packed`
* `-Zrun-dsymutil=no` -> `-Csplit-debuginfo=unpacked`
* `-Zsplit-dwarf=single` -> `-Csplit-debuginfo=packed`
* `-Zsplit-dwarf=split` -> `-Csplit-debuginfo=unpacked`

Note that `-Csplit-debuginfo` still requires `-Zunstable-options` for
non-macOS platforms since split-dwarf support was *just* implemented in
rustc.

There's some more rationale listed on #79361, but the main gist of the
motivation for this commit is that `dsymutil` can take quite a long time
to execute in debug builds and provides little benefit. This means that
incremental compile times appear that much worse on macOS because the
compiler is constantly running `dsymutil` over every single binary it
produces during `cargo build` (even build scripts!). Ideally rustc would
switch to not running `dsymutil` by default, but that's a problem left
to get tackled another day.

Closes #79361
2021-01-28 08:51:11 -08:00
Yuki Okushi
446edd1e1a
Rollup merge of #79951 - LeSeulArtichaut:ty-ir, r=nikomatsakis
Refractor a few more types to `rustc_type_ir`

In the continuation of #79169, ~~blocked on that PR~~.

This PR:
 - moves `IntVarValue`, `FloatVarValue`, `InferTy` (and friends) and `Variance`
 - creates the `IntTy`, `UintTy` and `FloatTy` enums in `rustc_type_ir`, based on their `ast` and `chalk_ir` equilavents, and uses them for types in the rest of the compiler.

~~I will split up that commit to make this easier to review and to have a better commit history.~~
EDIT: done, I split the PR in commits of 200-ish lines each

r? `````@nikomatsakis````` cc `````@jackh726`````
2021-01-28 15:09:02 +09:00
Amanieu d'Antras
8afe59893a Add big-endian support for AArch64 va_arg 2021-01-27 22:47:56 +00:00
bors
72c7b70267 Auto merge of #80838 - nagisa:nagisa/stack-probe-type, r=cuviper
Target stack-probe support configurable finely

This adds capability to configure the target's stack probe support in a
more precise manner than just on/off. In particular now we allow
choosing between always inline-asm, always call or either one of those
depending on the LLVM version.

Note that this removes the ability to turn off the generation of the
stack-probe attribute. This is valid to replace it with inline-asm for all targets because
`probe-stack="inline-asm"` will not generate any machine code on targets
that do not currently support stack probes. This makes support for stack
probes on targets that don't have any right now automatic with LLVM
upgrades in the future.

(This is valid to do based on the fact that clang unconditionally sets
this attribute when `-fstack-clash-protection` is used, AFAICT)

cc #77885
r? `@cuviper`
2021-01-24 09:44:42 +00:00
Caleb Zulawski
4d72ed61ee Make declare_cfn more flexible 2021-01-23 17:19:49 -05:00
LeSeulArtichaut
50e1ae15e9 Use ty::{IntTy,UintTy,FloatTy} in rustc 2021-01-18 21:09:30 +01:00
Mara Bos
7e2425ab73
Rollup merge of #81095 - LingMan:unwrap, r=oli-obk
Use Option::unwrap_or instead of open-coding it

r? ```@oli-obk``` Noticed this while we were talking about the other PR just now 😆
```@rustbot``` modify labels +C-cleanup +T-compiler
2021-01-17 12:24:59 +00:00
LingMan
5a706cfc49 Use Option::unwrap_or instead of open-coding it 2021-01-16 20:13:06 +01:00
LingMan
76003f31f1 Use Option::map instead of open-coding it 2021-01-16 20:05:02 +01:00
Simonas Kazlauskas
007080b607 Target stack-probe support configurable finely
This adds capability to configure the target's stack probe support in a
more precise manner than just on/off. In particular now we allow
choosing between always inline-asm, always call or either one of those
depending on the LLVM version on a per-target basis.
2021-01-16 12:38:02 +02:00
bors
635ccfe01c Auto merge of #77885 - erikdesjardins:probeasm, r=cuviper
Use probe-stack=inline-asm in LLVM 11+

Fixes (?) #74405, related to #43241

r? `@cuviper`
2021-01-16 03:10:52 +00:00
Yuki Okushi
ce06df2e4a
Rollup merge of #81008 - tmiasko:generator-layout-err, r=tmandry
Don't ICE when computing a layout of a generator tainted by errors

Fixes #80998.
2021-01-15 18:26:16 +09:00
Yuki Okushi
a584d87417
Rollup merge of #80944 - LingMan:map_or, r=nagisa
Use Option::map_or instead of `.map(..).unwrap_or(..)`

``@rustbot`` modify labels +C-cleanup +T-compiler
2021-01-15 18:26:14 +09:00
Erik Desjardins
cd25807223 Use probe-stack=inline-asm in LLVM 11+ 2021-01-14 22:49:16 -05:00
LingMan
a56bffb4f9 Use Option::map_or instead of .map(..).unwrap_or(..) 2021-01-14 19:23:59 +01:00
Tomasz Miąsko
5ea1d0e865 Don't ICE when computing a layout of a generator tainted by errors 2021-01-14 13:13:13 +01:00
Josh Stone
0342fd16ff Remove the unused context from CreateDebugLocation
This went unused in commit 88d874de63, part of #68965.
2021-01-13 11:55:49 -08:00
bors
fc9944fe84 Auto merge of #80499 - matthiaskrgr:red_clos, r=estebank
remove redundant closures (clippy::redundant_closure)
2021-01-12 11:20:47 +00:00
bors
c87ef0a2fc Auto merge of #80749 - as-com:target-cpu-actually-native, r=nagisa
Make target-cpu=native detect individual features

This PR makes target-cpu=native check for and enable/disable individual features instead of detecting and targeting a CPU by name. This brings the flag's behavior more in line with clang and gcc and ensures that the host actually supports each feature that we are compiling for.

This should resolve issues with miscompilations on e.g. "Haswell" Pentiums and Celerons that lack support for AVX, and also enable support for `aes` on Broadwell processors that support it. It should also resolve issues with failing to detect feature support in newer CPUs that aren't yet known by LLVM (see: #80633).

Fixes #54688
Fixes #48464
Fixes #38218
2021-01-09 04:36:24 +00:00
Andrew Sun
80ca198212 Check if the pointer is null/string is not utf8 2021-01-08 11:50:21 -05:00
Andrew Sun
bc4c5bac40 Use LLVMGetHostCPUFeatures instead of stdsimd 2021-01-07 23:25:19 -05:00
Lzu Tao
fa4d8bc878 Prefer enum Endian in rustc_target::Target 2021-01-06 13:34:19 +00:00
Andrew Sun
bf80159050 Make target-cpu=native detect individual features 2021-01-06 03:23:54 -05:00
Matthias Krüger
e2272cdffc remove redundant closures (clippy::redundant_closure) 2021-01-03 13:34:24 +01:00
Caleb Zulawski
07db2bfe39 Implement floating point SIMD intrinsics over all vector widths, and limit SIMD vector lengths. 2021-01-03 01:06:54 -05:00
Dylan DPC
55cfcd596f
Rollup merge of #80323 - camelid:codegen-base-docs, r=nagisa
Update and improve `rustc_codegen_{llvm,ssa}` docs

Fixes #75342.

These docs were very out of date and misleading. They even said that
they codegen'd the *AST*!

For some reason, the `rustc_codegen_ssa::base` docs were exactly
identical to the `rustc_codegen_llvm::base` docs. They didn't really
make sense, because they had LLVM-specific information even though
`rustc_codegen_ssa` is supposed to be somewhat generic. So I removed
them as they were misleading.

r? ``@pnkfelix`` maybe?
2020-12-31 22:20:43 +01:00
Matthias Krüger
e5ead5fc58 remove unused return types such as empty Results or Options that would always be Some(..)
remove unused return type of dropck::check_drop_obligations()
don't wrap return type in Option in get_macro_by_def_id() since we would always return Some(..)
remove redundant return type of back::write::optimize()
don't Option-wrap return type of compute_type_parameters() since we always return Some(..)
don't return empty Result in assemble_generator_candidates()
don't return empty Result in assemble_closure_candidates()
don't return empty result in assemble_fn_pointer_candidates()
don't return empty result in assemble_candidates_from_impls()
don't return empty result in assemble_candidates_from_auto_impls()
don't return emtpy result in assemble_candidates_for_trait_alias()
don't return empty result in assemble_builtin_bound_candidates()
don't return empty results in assemble_extension_candidates_for_traits_in_scope() and assemble_extension_candidates_for_trait()
remove redundant wrapping of return type of StripItem::strip() since it always returns Some(..)
remove unused return type of assemble_extension_candidates_for_all_traits()
2020-12-30 13:15:40 +01:00
Dylan DPC
98d80bda01
Rollup merge of #79662 - bjorn3:move_more_code_out_of_codegen_backend, r=oli-obk
Move some more code out of CodegenBackend::{codegen_crate,link}

Kind of a follow up to #77795
2020-12-28 14:12:59 +01:00
Camelid
5b32ab671a Update and improve rustc_codegen_{llvm,ssa} docs
These docs were very out of date and misleading. They even said that
they codegen'd the *AST*!

For some reason, the `rustc_codegen_ssa::base` docs were exactly
identical to the `rustc_codegen_llvm::base` docs. They didn't really
make sense, because they had LLVM-specific information even though
`rustc_codegen_ssa` is supposed to be somewhat generic. So I removed
them as they were misleading.
2020-12-22 19:42:23 -08:00
David Wood
88dc58fc9b
Revert "cg_llvm: fewer_names in uncached_llvm_type"
This reverts commit fa01ce802f.
2020-12-17 16:40:47 +00:00
bjorn3
2c0dccb7f2 Move some code out of CodegenBackend::{codegen_crate,link} 2020-12-17 10:02:06 +01:00
David Wood
ee073b5ec5
cg_llvm: split dwarf filename and comp dir
llvm-dwp concatenates `DW_AT_comp_dir` with `DW_AT_GNU_dwo_name` (only
when `DW_AT_comp_dir` exists), which can result in it failing to find
the DWARF object files.

In earlier testing, `DW_AT_comp_dir` wasn't present in the final
object and the current directory was the output directory.

When running tests through compiletest, the working directory of the
compilation is different from output directory and that resulted in
`DW_AT_comp_dir` being in the object file (and set to the current
working directory, rather than the output directory), and
`DW_AT_GNU_dwo_name` being set to the full path (rather than just
the filename), so llvm-dwp was failing.

This commit changes the compilation directory provided to LLVM to match
the output directory, where DWARF objects are output; and ensures that
only the filename is used for `DW_AT_GNU_dwo_name`.

Signed-off-by: David Wood <david@davidtw.co>
2020-12-16 10:33:52 +00:00
David Wood
e3fdae9d81
cg_llvm: implement split dwarf support
This commit implements Split DWARF support, wiring up the flag (added in
earlier commits) to the modified FFI wrapper (also from earlier
commits).

Signed-off-by: David Wood <david@davidtw.co>
2020-12-16 10:33:47 +00:00
David Wood
6890312ea3
cg_ssa: introduce TargetMachineFactoryFn alias
This commit removes the `TargetMachineFactory` struct and adds a
`TargetMachineFactoryFn` type alias which is used everywhere that the
previous, long type was used.

Signed-off-by: David Wood <david@davidtw.co>
2020-12-16 10:33:43 +00:00
David Wood
341aa97adb
llvm: update ffi bindings for split dwarf
This commit modifies the FFI bindings to LLVM required for Split DWARF
support in rustc. In particular:

- `addPassesToEmitFile`'s wrapper, `LLVMRustWriteOutputFile` now takes
  a `DwoPath` `const char*`. When disabled, `nullptr` should be provided
  which will preserve existing behaviour. When enabled, the path to the
  `.dwo` file should be provided.
- `createCompileUnit`'s wrapper, `LLVMRustDIBuilderCreateCompileUnit`
  now has two additional arguments, for the `DWOId` and to enable
  `SplitDebugInlining`. `DWOId` should always be zero.
- `createTargetMachine`'s wrapper, `LLVMRustCreateTargetMachine` has an
  additional argument which should be provided the path to the `.dwo`
  when enabled.

Signed-off-by: David Wood <david@davidtw.co>
2020-12-16 10:31:42 +00:00
bors
e99a89c7c0 Auto merge of #73210 - wesleywiser:consts_in_debuginfo, r=oli-obk
[mir-opt] Allow debuginfo to be generated for a constant or a Place

Prior to this commit, debuginfo was always generated by mapping a name
to a Place. This has the side-effect that `SimplifyLocals` cannot remove
locals that are only used for debuginfo because their other uses have
been const-propagated.

To allow these locals to be removed, we now allow debuginfo to point to
a constant value. The `ConstProp` pass detects when debuginfo points to
a local with a known constant value and replaces it with the value. This
allows the later `SimplifyLocals` pass to remove the local.
2020-12-15 08:46:00 +00:00
Matthias Krüger
5c8de1cf49 use strip_prefix over slicing (clippy::manual_strip) 2020-12-11 23:02:17 +01:00
Rich Kadel
95c268f64d Fixes to Rust coverage
Fixes: #79725

Some macros can create a situation where `fn_sig_span` and `body_span`
map to different files.

New documentation on coverage tests incorrectly assumed multiple test
binaries could just be listed at the end of the `llvm-cov` command,
but it turns out each binary needs a `--object` prefix.

This PR fixes the bug and updates the documentation to correct that
issue. It also fixes a few other minor issues in internal implementation
comments, and adds documentation on getting coverage results for doc
tests.
2020-12-07 17:56:19 -08:00
Wesley Wiser
01aec8d185 [mir-opt] Allow debuginfo to be generated for a constant or a Place
Prior to this commit, debuginfo was always generated by mapping a name
to a Place. This has the side-effect that `SimplifyLocals` cannot remove
locals that are only used for debuginfo because their other uses have
been const-propagated.

To allow these locals to be removed, we now allow debuginfo to point to
a constant value. The `ConstProp` pass detects when debuginfo points to
a local with a known constant value and replaces it with the value. This
allows the later `SimplifyLocals` pass to remove the local.
2020-12-06 20:48:25 -05:00
Rich Kadel
d96f351fa3 Addressed feedback from 2020-12-01
Added one more test (two files) showing coverage of generics and unused
functions across crates.

Created and referenced new Issues, as requested.

Added comments.

Added a note about the possible effects of compiler options on LLVM
coverage maps.
2020-12-03 09:50:10 -08:00
Rich Kadel
def932ca86 Combination of commits
Fixes multiple issue with counters, with simplification

  Includes a change to the implicit else span in ast_lowering, so coverage
  of the implicit else no longer spans the `then` block.

  Adds coverage for unused closures and async function bodies.

  Fixes: #78542

Adding unreachable regions for known MIR missing from coverage map

Cleaned up PR commits, and removed link-dead-code requirement and tests

  Coverage no longer depends on Issue #76038 (`-C link-dead-code` is
  no longer needed or enforced, so MSVC can use the same tests as
  Linux and MacOS now)

Restrict adding unreachable regions to covered files

  Improved the code that adds coverage for uncalled functions (with MIR
  but not-codegenned) to avoid generating coverage in files not already
  included in the files with covered functions.

Resolved last known issue requiring --emit llvm-ir workaround

  Fixed bugs in how unreachable code spans were added.
2020-12-03 09:50:10 -08:00
bors
6645da366e Auto merge of #78684 - devsnek:inline-asm-wasm, r=Amanieu
Add wasm32 support to inline asm

There is some contention around inline asm and wasm, and I really only made this to figure out the process of hacking on rustc, but I figured as long as the code existed, it was worth uploading.

cc `@Amanieu`
2020-12-01 20:23:06 +00:00
Gus Caplan
d9f237caa6
Add wasm32 support to inline asm 2020-12-01 12:18:21 -06:00
bors
760430e6fd Auto merge of #78863 - KodrAus:feat/simd-array, r=oli-obk
Support repr(simd) on ADTs containing a single array field

This is a squash and rebase of `@gnzlbg's` #63531

I've never actually written code in the compiler before so just fumbled my way around until it would build 😅

I imagine there'll be some work we need to do in `rustc_codegen_cranelift` too for this now, but might need some input from `@bjorn3` to know what that is.

cc `@rust-lang/project-portable-simd`

-----

This PR allows using `#[repr(simd)]` on ADTs containing a single array field:

```rust
 #[repr(simd)] struct S0([f32; 4]);
 #[repr(simd)] struct S1<const N: usize>([f32; N]);
 #[repr(simd)] struct S2<T, const N: usize>([T; N]);
```

This should allow experimenting with portable packed SIMD abstractions on nightly that make use of const generics.
2020-11-29 09:28:09 +00:00
Jonas Schievink
0ae653a531
Rollup merge of #79365 - richkadel:llvm-cov-map-version-4, r=wesleywiser
Upgrades the coverage map to Version 4

Changes the coverage map injected into binaries compiled with
`-Zinstrument-coverage` to LLVM Coverage Mapping Format, Version 4 (from
Version 3). Note, binaries compiled with this version will require LLVM
tools from at least LLVM Version 11.

r? ``@wesleywiser``
2020-11-26 13:39:09 +01:00
Rich Kadel
d334f589c4
Update compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs 2020-11-25 11:41:23 -08:00
Rich Kadel
b1df6c0e63
replace assert with condition and fatal error 2020-11-25 11:38:09 -08:00
Rich Kadel
b4668ecb73 Improved version check 2020-11-25 09:45:33 -08:00
Rich Kadel
b5fef37d23
Apply suggestions from code review
Co-authored-by: Wesley Wiser <wwiser@gmail.com>
2020-11-24 18:34:10 -08:00
Rich Kadel
51268d2735 Check for LLVM 11+ when using -Z instrument-coverage
* `rustc` should now compile under LLVM 9 or 10
* Compiler generates an error if `-Z instrument-coverage` is specified
  but LLVM version is less than 11
* Coverage tests that require `-Z instrument-coverage` and run codegen
  should be skipped if LLVM version is less than 11
2020-11-24 11:50:24 -08:00
Rich Kadel
5d5dc4c9d8 Updated links to LLVM 11 docs and types 2020-11-23 19:15:10 -08:00
Dario Nieuwenhuis
7b62e09b03 Allow disabling TrapUnreachable via -Ztrap-unreachable=no
This is useful for embedded targets where small code size is desired.
For example, on my project (thumbv7em-none-eabi) this yields a 0.6% code size reduction.
2020-11-24 01:08:27 +01:00
Rich Kadel
1d8c381c01 Upgrades the coverage map to Version 4
Changes the coverage map injected into binaries compiled with
`-Zinstrument-coverage` to LLVM Coverage Mapping Format, Version 4 (from
Version 3). Note, binaries compiled with this version will require LLVM
tools from at least LLVM Version 11.
2020-11-23 15:14:47 -08:00
LingMan
cd8973250d Use Option::map instead of open coding it 2020-11-23 04:58:21 +01:00
bjorn3
6a5f537fb9 Rename prefix_chunk to prefix_chunk_size 2020-11-21 19:22:31 +01:00
bjorn3
39b8b2b623 Remove StructRet arg attr
It is applied exactly when the return value has an indirect pass mode.
Except for InReg on x86 fastcall, arg attrs are now only used for
optimization purposes and thus are fine to ignore.
2020-11-21 19:22:31 +01:00
bjorn3
42b0b8080d Replace ByVal attribute with on_stack field for Indirect
This makes it clearer that only PassMode::Indirect allows ByVal
2020-11-21 19:22:30 +01:00
bjorn3
967a228208 Replace ZExt and SExt flags with ArgExtension enum
Both flags are mutually exclusive
2020-11-21 19:07:38 +01:00
Tomasz Miąsko
c2fb99984c Never inline naked functions
The `#[naked]` attribute disabled prologue / epilogue emission for the
function and it is responsibility of a developer to provide them. The
compiler is no position to inline such functions correctly.

Disable inlining of naked functions at LLVM and MIR level.
2020-11-20 00:00:00 +00:00
bors
675f114d95 Auto merge of #79106 - tmiasko:inline-hint, r=nagisa,eddyb
Fix setting inline hint based on `InstanceDef::requires_inline`

For instances where `InstanceDef::requires_inline` is true, an attempt
is made to set an inline hint though a call to the `inline` function.
The attempt is ineffective, since all attributes will be usually removed
by the second call.

Fix the issue by applying the attributes only once, with user provided
attributes having a priority when provided.

Closes #79108.
2020-11-18 23:44:54 +00:00
Mara Bos
c7e9029b80
Rollup merge of #78361 - DevJPM:master, r=workingjubilee
Updated the list of white-listed target features for x86

This PR both adds in-source documentation on what to look out for when adding a new (X86) feature set and [adds all that are detectable at run-time in Rust stable as of 1.27.0](https://github.com/rust-lang/stdarch/blob/master/crates/std_detect/src/detect/arch/x86.rs).

This should only enable the use of the corresponding LLVM intrinsics.
Actual intrinsics need to be added separately in rust-lang/stdarch.

It also re-orders the run-time-detect test statements to be more consistent
with the actual list of intrinsics whitelisted and removes underscores not present
in the actual names (which might be mistaken as being part of the name)

The reference for LLVM's feature names used is [this file](https://github.com/llvm/llvm-project/blob/master/llvm/include/llvm/Support/X86TargetParser.def).

This PR was motivated as the compiler end's part for allowing #67329 to be adressed over on rust-lang/stdarch
2020-11-18 15:46:19 +01:00
Mara Bos
fa45fce0d3
Rollup merge of #78702 - wesleywiser:self_profile_cgu_sizes, r=Mark-Simulacrum
[self-profiling] Include the estimated size of each cgu in the profile

This is helpful when looking for CGUs where the size estimate isn't a
good indicator of compilation time.

I verified that moving the profiling timer call doesn't affect the
results.

Results:

<img width="297" alt="Screen Shot 2020-11-03 at 7 25 04 AM" src="https://user-images.githubusercontent.com/831192/97985503-5901d100-1da6-11eb-9f10-f3e399702952.png">

`measureme` doesn't have support for custom arg names yet so `arg0` is the CGU name and `arg1` is the estimated size.
2020-11-17 16:13:49 +01:00
Tomasz Miąsko
4ea25da237 Fix setting inline hint based on InstanceDef::requires_inline
For instances where `InstanceDef::requires_inline` is true, an attempt
is made to set an inline hint though a call to the `inline` function.
The attempt is ineffective, since all attributes will be usually removed
by the second call.

Fix the issue by applying the attributes only once, with user provided
attributes having a priority when provided.
2020-11-17 00:00:00 +00:00
Bastian Kauschke
2bf93bd852 compiler: fold by value 2020-11-16 22:34:57 +01:00
Jonas Schievink
8825942e86
Rollup merge of #77802 - jyn514:bootstrap-specific, r=nikomatsakis
Allow making `RUSTC_BOOTSTRAP` conditional on the crate name

Motivation: This came up in the [Zulip stream](https://rust-lang.zulipchat.com/#narrow/stream/233931-t-compiler.2Fmajor-changes/topic/Require.20users.20to.20confirm.20they.20know.20RUSTC_.E2.80.A6.20compiler-team.23350/near/208403962) for https://github.com/rust-lang/compiler-team/issues/350.
See also https://github.com/rust-lang/cargo/pull/6608#issuecomment-458546258; this implements https://github.com/rust-lang/cargo/issues/6627.
The goal is for this to eventually allow prohibiting setting `RUSTC_BOOTSTRAP` in build.rs (https://github.com/rust-lang/cargo/issues/7088).

## User-facing changes

- `RUSTC_BOOTSTRAP=1` still works; there is no current plan to remove this.
- Things like `RUSTC_BOOTSTRAP=0` no longer activate nightly features. In practice this shouldn't be a big deal, since `RUSTC_BOOTSTRAP` is the opposite of stable and everyone uses `RUSTC_BOOTSTRAP=1` anyway.
- `RUSTC_BOOTSTRAP=x` will enable nightly features only for crate `x`.
- `RUSTC_BOOTSTRAP=x,y` will enable nightly features only for crates `x` and `y`.

## Implementation changes

The main change is that `UnstableOptions::from_environment` now requires
an (optional) crate name. If the crate name is unknown (`None`), then the new feature is not available and you still have to use `RUSTC_BOOTSTRAP=1`. In practice this means the feature is only available for `--crate-name`, not for `#![crate_name]`; I'm interested in supporting the second but I'm not sure how.

Other major changes:

- Added `Session::is_nightly_build()`, which uses the `crate_name` of
the session
- Added `nightly_options::match_is_nightly_build`, a convenience method
for looking up `--crate-name` from CLI arguments.
`Session::is_nightly_build()`should be preferred where possible, since
it will take into account `#![crate_name]` (I think).
- Added `unstable_features` to `rustdoc::RenderOptions`

I'm not sure whether this counts as T-compiler or T-lang; _technically_ RUSTC_BOOTSTRAP is an implementation detail, but it's been used so much it seems like this counts as a language change too.

r? `@joshtriplett`
cc `@Mark-Simulacrum` `@hsivonen`
2020-11-15 13:39:43 +01:00
Dylan DPC
ae7020fcb4
Rollup merge of #78848 - DevJPM:ci-llvm-9, r=nikic
Bump minimal supported LLVM version to 9

This bumps the minimal tested llvm version to 9.
This should enable supporting newer LLVM features (and CPU extensions).

This was motived by #78361 having to drop features because of LLVM 8 not supporting certain CPU extensions yet.
This was declared relatively uncontroversial on [Zulip](https://rust-lang.zulipchat.com/#narrow/stream/182449-t-compiler.2Fhelp/topic/Min.20Supported.20LLVM.20Upgrade.20Process.3F/near/215957859).

Paging ````@eddyb```` because there was a comment in the [dockerfile](https://github.com/rust-lang/rust/blob/master/src/ci/docker/host-x86_64/x86_64-gnu-llvm-8/Dockerfile#L42) describing a hack (which I don't quite understand) which was also blocked by not having LLVM 9.
2020-11-15 03:02:39 +01:00
bors
66c1309446 Auto merge of #78959 - petrochenkov:likeuefi, r=nagisa
rustc_target: Mark UEFI targets as `is_like_windows`/`is_like_msvc`

And document what `is_like_windows` and `is_like_msvc` actually mean in more detail.

Addresses FIXMEs left from https://github.com/rust-lang/rust/pull/71030.
r? `@nagisa`
2020-11-14 09:11:25 +00:00
Ashley Mannix
045105b1a2 remove internal simd_size_and_ty from llvm backend 2020-11-13 14:43:45 +10:00
Mara Bos
76fa5f25ab
Rollup merge of #78950 - khyperia:spirv-asm, r=Amanieu
Add asm register information for SPIR-V

As discussed in [zulip](https://rust-lang.zulipchat.com/#narrow/stream/182449-t-compiler.2Fhelp/topic/Defining.20asm!.20for.20new.20architecture), we at [rust-gpu](https://github.com/EmbarkStudios/rust-gpu) would like to support `asm!` for our SPIR-V backend. However, we cannot do so purely without frontend support: [this match](d4ea0b3e46/compiler/rustc_target/src/asm/mod.rs (L185)) fails and so `asm!` is not supported ([error reported here](d4ea0b3e46/compiler/rustc_ast_lowering/src/expr.rs (L1095))). To resolve this, we need to stub out register information for SPIR-V to support getting the `asm!` content all the way to [`AsmBuilderMethods::codegen_inline_asm`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_codegen_ssa/traits/trait.AsmBuilderMethods.html#tymethod.codegen_inline_asm), at which point the rust-gpu backend can do all the parsing and codegen that is needed.

This is a pretty weird PR - adding support for a backend that isn't in-tree feels pretty gross to me, but I don't see an easy way around this. ``@Amanieu`` said I should submit it anyway, so, here we are! Let me know if this needs to go through a more formal process (MCP?) and what I should do to help this along.

I based this off the [wasm asm PR](https://github.com/rust-lang/rust/pull/78684), which unfortunately this PR conflicts with that one quite a bit, sorry for any merge conflict pain :(

---

Some open questions:

- What do we call the register class? Some context, SPIR-V is an SSA-based IR, there are "instructions" that create IDs (referred to as `<id>` in the spec), which can be referenced by other instructions. So, `reg` isn't exactly accurate, they're SSA IDs, not re-assignable registers.
- What happens when a SPIR-V register gets to the LLVM backend? Right now it's a `bug!`, but should that be a `sess.fatal()`? I'm not sure if it's even possible to reach that point, maybe there's a check that prevents the `spirv` target from even reaching that codepath.
2020-11-12 19:46:14 +01:00
Vadim Petrochenkov
04d41e1f40 rustc_target: Mark UEFI targets as is_like_windows/is_like_msvc
Document what `is_like_windows` and `is_like_msvc` mean in more detail.
2020-11-12 19:40:41 +03:00
DevJPM
86193ca91c fixed a re-format due to removed chain call 2020-11-12 14:40:41 +01:00
DevJPM
7e443c4282 Dropped Support for Bidirectional Custom Target Definition Emulation
as requested in the review and argued that this is only consistent with later LLVM upgrades
2020-11-12 14:39:47 +01:00
DevJPM
8236830209 Removed an unused function now that LLVM 9 is the minimal supported version
The function was only used in LLVM 8 compatibility code
and was found and flagged by dead code detection and now removed.
2020-11-12 14:39:47 +01:00
DevJPM
b51bcc72d9 fully exploited the dropped support of LLVM 8
This commit grepped for LLVM_VERSION_GE, LLVM_VERSION_LT, get_major_version and
min-llvm-version and statically evaluated every expression possible
(and sensible) assuming that the LLVM version is >=9 now
2020-11-12 14:39:47 +01:00
khyperia
0e34b73996 Change capitalization of Spirv to SpirV
This matches the capitalization of RiscV
2020-11-11 19:18:06 +01:00
khyperia
f3441348e0 Add asm register information for SPIR-V 2020-11-11 17:38:02 +01:00
Nicholas-Baron
261ca04c92 Changed unwrap_or to unwrap_or_else in some places.
The discussion seems to have resolved that this lint is a bit "noisy" in
that applying it in all places would result in a reduction in
readability.

A few of the trivial functions (like `Path::new`) are fine to leave
outside of closures.

The general rule seems to be that anything that is obviously an
allocation (`Box`, `Vec`, `vec![]`) should be in a closure, even if it
is a 0-sized allocation.
2020-11-10 20:07:47 -08:00
Vadim Petrochenkov
dc004d4809 rustc_target: Rename some target options to avoid tautology
`target.target_endian` -> `target.endian`
`target.target_c_int_width` -> `target.c_int_width`
`target.target_os` -> `target.os`
`target.target_env` -> `target.env`
`target.target_vendor` -> `target.vendor`
`target.target_family` -> `target.os_family`
`target.target_mcount` -> `target.mcount`
2020-11-08 17:29:13 +03:00