312 Commits

Author SHA1 Message Date
Kazu Hirata
b7a66d0fae [llvm] Use SmallString::operator std::string (NFC) 2024-01-19 18:54:11 -08:00
Teresa Johnson
329ba523cc
[LTO][NFC] Free the GlobalResolutions map after final use (#76780)
The GlobalResolutions map was found to contribute ~9% of the peak
memory of a large thin link. However, we are essentially done with it
when we are about to compute cross module imports, which itself adds to
the peak memory due to the import and export lists (there is one use
just after importing but it can easily be moved before importing).

Move the last use up above importing, and free the GlobalResolutions
map after that (and before importing). To help guard against future
inadvertent use after it has been released, change it to a
std::optional.
2024-01-03 07:19:56 -08:00
Martin Storsjö
89efffd463
[LTO] [LLD] Don't alias the __imp_func and func symbol resolutions (#71376)
Commit b963c0b658cc54b370832df4f5a3d63fd69da334 fixed LTO compilation of
cases where one translation unit is calling a function with the
dllimport attribute, and another translation unit provides this function
locally within the same linked module (i.e. not actually dllimported);
see https://github.com/llvm/llvm-project/issues/37453 or
https://bugs.llvm.org/show_bug.cgi?id=38105 for full context.

This was fixed by aliasing their GlobalResolution structs, for the
`__imp_` prefixed and non prefixed symbols.

I believe this fix to be wrong.

This patch reverts that fix, and fixes the same issue differently,
within LLD instead.

The fix assumed that one can treat the `__imp_` prefixed and unprefixed
symbols as equal, referencing SVN r240620
(d766653534e0cff702e42a43b44d3057b6094fea). However that referenced
commit had mistaken how this logic works, which was corrected later in
SVN r240622 (88e0f9206b4dccb56dee931adab08f89ff80525a); those symbols
aren't direct aliases for each other - but if there's a need for the
`__imp_` prefixed one and the other one exists, the `__imp_` prefixed
one is created, as a pointer to the other one.

However this fix only works if both translation units are compiled as
LTO; if the caller is compiled as a regular object file and the callee
is compiled as LTO, the fix fails, as the LTO compilation doesn't know
that the unprefixed symbol is needed.

The only level that knows of the potential relationship between the
`__imp_` prefixed and unprefixed symbol, across regular and bitcode
object files, is LLD itself.

Therefore, revert the original fix from
b963c0b658cc54b370832df4f5a3d63fd69da334, and fix the issue differently
- when concluding that we can fulfill an undefined symbol starting with
`__imp_`, mark the corresponding non prefixed symbol as used in a
regular object for the LTO compilation, to make sure that this non
prefixed symbol exists after the LTO compilation, to let LLD do the
fixup of the local import.

Extend the testcase to test a regular object file calling an LTO object
file, which previously failed.

This change also fixes another issue; an object file can provide both
unprefixed and prefixed versions of the same symbol, like this:

    void importedFunc(void) { 
    }
    void (*__imp_importedFunc)(void) = importedFunc;

That allows the function to be called both with and without dllimport
markings. (The concept of automatically resolving a reference to
`__imp_func` to a locally defined `func` only is done in MSVC style
linkers, but not in GNU ld, therefore MinGW mode code often uses this
construct.)

Previously, the aliasing of global resolutions at the LTO level would
trigger a failed assert with "Multiple prevailing defs are not allowed"
for this case, as both `importedFunc` and `__imp_importedFunc` could be
prevailing. Add a case to the existing LLD test case lto-imp-prefix.ll
to test this as well.

This change (together with previous change in
3ab6209a3f93bdbeec8e9b9fcc00a9a4980915ff) completes LLD to work with
mingw-w64-crt files (the base glue code for a mingw-w64 toolchain) built
with LTO.
2023-11-21 15:06:00 +02:00
Youngsuk Kim
876236023c
[llvm] Remove no-op ptr-to-ptr bitcasts (NFC) (#72133)
Opaque ptr cleanup effort (NFC).
2023-11-13 13:05:27 -05:00
Fangrui Song
2d854dd3e7 Move global namespace cl::opt inside llvm:: or internalize them 2023-10-10 19:58:03 -07:00
modimo
272bd6f9cc [WPD][LLD] Add option to validate RTTI is enabled on all native types and prevent devirtualization on types with native RTTI
Discussion about this approach: https://discourse.llvm.org/t/rfc-safer-whole-program-class-hierarchy-analysis/65144/18

When enabling WPD in an environment where native binaries are present, types we want to optimize can be derived from inside these native files and devirtualizing them can lead to correctness issues. RTTI can be used as a way to determine all such types in native files and exclude them from WPD providing a safe checked way to enable WPD.

The approach is:
1. In the linker, identify if RTTI is available for all native types. If not, under `--lto-validate-all-vtables-have-type-infos` `--lto-whole-program-visibility` is automatically disabled. This is done by examining all .symtab symbols in object files and .dynsym symbols in DSOs for vtable (_ZTV) and typeinfo (_ZTI) symbols and ensuring there's always a match for every vtable symbol.
2. During thinlink, if `--lto-validate-all-vtables-have-type-infos` is set and RTTI is available for all native types, identify all typename (_ZTS) symbols via their corresponding typeinfo (_ZTI) symbols that are used natively or outside of our summary and exclude them from WPD.

Testing:
ninja check-all
large Meta service that uses boost, glog and libstdc++.so runs successfully with WPD via --lto-whole-program-visibility. Previously, native types in boost caused incorrect devirtualization that led to crashes.

Reviewed By: MaskRay, tejohnson

Differential Revision: https://reviews.llvm.org/D155659
2023-09-18 15:51:49 -07:00
Arthur Eubanks
0a1aa6cda2
[NFC][CodeGen] Change CodeGenOpt::Level/CodeGenFileType into enum classes (#66295)
This will make it easy for callers to see issues with and fix up calls
to createTargetMachine after a future change to the params of
TargetMachine.

This matches other nearby enums.

For downstream users, this should be a fairly straightforward
replacement,
e.g. s/CodeGenOpt::Aggressive/CodeGenOptLevel::Aggressive
or s/CGFT_/CodeGenFileType::
2023-09-14 14:10:14 -07:00
Teresa Johnson
bbe8cd1333 [LTO] Remove module id from summary index
The module paths string table mapped to both an id sequentially assigned
during LTO linking, and the module hash. The former is leftover from
before the module hash was added for caching and subsequently replaced
use of the module id when renaming promoted symbols (to avoid affects
due to link order changes). The sequentially assigned module id was not
removed, however, as it was still a convenience when serializing to/from
bitcode and assembly.

This patch removes the module id from this table, since it isn't
strictly needed and can lead to confusion on when it is appropriate to
use (e.g. see fix in D156525). It also takes a (likely not significant)
amount of overhead. Where an integer module id is needed (e.g. bitcode
writing), one is assigned on the fly.

There are a couple of test changes since the paths are now sorted
alphanumerically when assigning ids on the fly during assembly writing,
in order to ensure deterministic behavior.

Differential Revision: https://reviews.llvm.org/D156730
2023-09-01 13:43:08 -07:00
Fangrui Song
02054d3ae9 [LTO] Simplify internalize logic. NFC
D151965 removed incorrect internalization for {linkonce,weak}{,_odr} when
the prevailing copy is in native code. The multiple conditions are based
on negative conditions, which can be simplified to be based on positive cases:

* an object with an external linkage (must be prevailing) can be internalized
* a prevailing object with a {linkonce,weak}{,_odr} or common linkage can be internalized.

Further, the lengthy comment is a bit misleading, as it doesn't say that
objects with an external/linkonce/weak linkage can be internalized.
Clarify it.

Reviewed By: tejohnson

Differential Revision: https://reviews.llvm.org/D158949
2023-08-28 10:02:51 -07:00
Teresa Johnson
65e57bbed0 [FunctionImport] Reduce string duplication (NFC)
The import/export maps, and the ModuleToDefinedGVSummaries map, are all
indexed by module paths, which are StringRef obtained from the module
summary index, which already has a data structure than owns these
strings (the ModulePathStringTable). Because these other maps are also
StringMap, which makes a copy of the string key, we were keeping
multiple extra copies of the module paths, leading to memory overhead.

Change these to DenseMap keyed by StringRef, and document that the
strings are owned by the index.

The only exception is the llvm-link tool which synthesizes an import list
from command line options, and I have added a string cache to maintain
ownership there.

I measured around 5% memory reduction in the thin link of a large
binary.

Differential Revision: https://reviews.llvm.org/D156580
2023-08-04 14:43:11 -07:00
Nikita Popov
279c297195 [ThinLTO] Use module hash instead of module ID for cache key
This is a followup to D151165. Instead of using the module ID, use
the module hash for sorting the import list. The module hash is what
will actually be included in the hash.

This has the advantage of being independent of the module order,
which is something that Rust relies on.

A caveat here is that the test doesn't quite work for linkonce_odr
functions, because the function may be imported from two different
modules, and the first one on the llvm-lto2 command line gets picked
(rather than, say, the prevailing copy). This doesn't really matter
for Rust's purposes (because it does not use linkonce_odr linkage),
but may still be worth addressing. For now I'm using a variant of
the test using internal instead of linkonce_odr functions.

Differential Revision: https://reviews.llvm.org/D156525
2023-07-28 16:39:44 +02:00
Matthew Voss
a1ca3af31e [llvm] A Unified LTO Bitcode Frontend
Here's a high level summary of the changes in this patch. For more
information on rational, see the RFC.
(https://discourse.llvm.org/t/rfc-a-unified-lto-bitcode-frontend/61774).

  - Add config parameter to LTO backend, specifying which LTO mode is
    desired when using unified LTO.
  - Add unified LTO flag to the summary index for efficiency. Unified
    LTO modules can be detected without parsing the module.
  - Make sure that the ModuleID is generated by incorporating more types
    of symbols.

Differential Revision: https://reviews.llvm.org/D123803
2023-07-05 14:53:14 -07:00
Arnold Schwaighofer
98eb8abff6 Add a type_checked_load_relative to support relative function pointer tables
This adds a type_checked_load_relative intrinsic whose semantics it is to
load a relative function pointer.

A relative function pointer is a pointer to a 32bit value that when
added to its address yields the address of the function.

Differential Revision: https://reviews.llvm.org/D143204
2023-06-29 08:33:45 -07:00
Teresa Johnson
200cc952a2 [LTO][GlobalDCE] Use pass parameter instead of module flag for LTO phase
D63932 added a module flag to indicate that we are executing the regular
LTO post merge pipeline, so that GlobalDCE could perform more aggressive
optimization for Dead Virtual Function Elimination. This caused issues
trying to reuse bitcode that had already been through the LTO pipeline
(see context in D139816).

Instead support this by passing down a parameter flag to the
GlobalDCEPass constructor, which is the more usual way for indicating
this information.

Most test changes are to remove incidental uses of this flag. Of the 2
real uses, llvm/test/LTO/ARM/lto-linking-metadata.ll is now obsolete and
removed in this patch, and the virtual-functions-visibility-post-lto.ll
test is updated to use the regular LTO default pipeline where this
parameter is set to true.

Differential Revision: https://reviews.llvm.org/D153655
2023-06-23 17:05:07 -07:00
Teresa Johnson
456468a08a [ThinLTO] Fix internalization decisions for weak/linkonce ODR
This fixes a runtime error that occurred due to incorrect
internalization of linkonce_odr functions where function pointer
equality was broken. This was hit because the prevailing copy was in a
native object, so the IR copies were not exported, and the existing code
internalized all of the IR copies. It could be fixed by guarding this
internalization on whether the defs are (local_)unnamed_addr, meaning
that their address is not significant (which we have in the summary
currently for linkonce_odr via the CanAutoHide flag). Or we can
propagate reference attributes as we do when determining whether a
global variable is read or write-only (reference edges are annotated
with whether they are read-only, write-only, or neither, and taking the
address of a function would result in a reference edge to the function
that is not read or write-only).

However, this exposed a larger issue with the internalization handling.
Looking at test cases, it appears the intent is to internalize when
there is a single definition of a linkonce/weak ODR symbol (that isn't
exported). This makes sense in the case of functions, because the
inliner can apply its last call to static heuristic when appropriate. In
the case where there is no prevailing copy in IR, internalizing all of
the IR copies of a linkonce_odr, even if legal, just increases binary
size. In that case it is better to fall back to the normal handling of
converting all non-prevailing copies to available_externally so that
they are eliminated after inlining.

In the case of variables, the existing code was attempting to
internalize the non-exported linkonce/weak ODR variables if they were
read or write-only. While this is legal (we propagate reference
attributes to determine this information), we don't even need to
internalize these here as there is later separate handling that
internalizes read and write-only variables when we process the module at
the start of the ThinLTO backend (processGlobalForThinLTO). Instead, we
can also internalize any non-exported variable when there is only one
(IR) definition, which is prevailing. And in that case, we don't need to
require that it is read or write-only, since we are guaranteed that all
uses must use that single definition.

In the new LTO API, if there are multiple defs of a linkonce or weak ODR
it will be marked exported, but it isn't clear that this will always be
true for the legacy LTO API. Therefore, require that there is only a
single (non-local) def, and that it is prevailing.

The test cases changes are both to reflect the change in the handling of
linkonce_odr IR copies where the prevailing def is not in IR (the main
correctness bug fix here), and to reflect the more aggressive
internalization of variables when there is only a single def, it is in
IR, and not exported.

I've also added some additional testing via the new LTO API.

Differential Revision: https://reviews.llvm.org/D151965
2023-06-02 15:34:14 -07:00
Teresa Johnson
06bb94832d [ThinLTO] Restructure promotion / internalization decisions (NFC)
Restructures the combined index based promotion and internalization
decision code so that it is a bit easier to follow. This is in
preparation for a bugfix to this code that will modify one part of the
logic.
2023-06-01 09:08:43 -07:00
Argyrios Kyrtzidis
bacb45eb9a [ThinLTO] Make the cache key independent of the module identifier paths
Otherwise there are cache misses just from changing the name of a path, even though the input modules did not change.

rdar://109672225

Differential Revision: https://reviews.llvm.org/D151165
2023-05-22 21:41:01 -07:00
Teresa Johnson
1768898680 [MemProf] Control availability of hot/cold operator new from LTO link
Adds an LTO option to indicate that whether we are linking with an
allocator that supports hot/cold operator new interfaces. If not,
at the start of the LTO backends any existing memprof hot/cold
attributes are removed from the IR, and we also remove memprof metadata
so that post-LTO inlining doesn't add any new attributes.

This is done via setting a new flag in the module summary index. It is
important to communicate via the index to the LTO backends so that
distributed ThinLTO handles this correctly, as they are invoked by
separate clang processes and the combined index is how we communicate
information from the LTO link. Specifically, for distributed ThinLTO the
LTO related processes look like:
```
   # Thin link:
   $ lld --thinlto-index-only obj1.o ... objN.o -llib ...
   # ThinLTO backends:
   $ clang -x ir obj1.o -fthinlto-index=obj1.o.thinlto.bc -c -O2
   ...
   $ clang -x ir objN.o -fthinlto-index=objN.o.thinlto.bc -c -O2
```

It is during the thin link (lld --thinlto-index-only) that we have
visibility into linker dependences and want to be able to pass the new
option via -Wl,-supports-hot-cold-new. This will be recorded in the
summary indexes created for the distributed backend processes
(*.thinlto.bc) and queried from there, so that we don't need to know
during those individual clang backends what allocation library was
linked. Since in-process ThinLTO and regular LTO also use a combined
index, for consistency we query the flag out of the index in all LTO
backends.

Additionally, when the LTO option is disabled, exit early from the
MemProfContextDisambiguation handling performed during LTO, as this is
unnecessary.

Depends on D149117 and D149192.

Differential Revision: https://reviews.llvm.org/D149215
2023-05-08 08:02:21 -07:00
Fangrui Song
71cb689661 [LTO] Change getThinLTOOutputFile to take StringRef 2023-04-26 20:43:11 -07:00
Shraiysh Vaishay
7021182d6b [nfc][llvm] Replace pointer cast functions in PointerUnion by llvm casting functions.
This patch replaces the uses of PointerUnion.is function by llvm::isa,
PointerUnion.get function by llvm::cast, and PointerUnion.dyn_cast by
llvm::dyn_cast_if_present. This is according to the FIXME in
the definition of the class PointerUnion.

This patch does not remove them as they are being used in other
subprojects.

Reviewed By: mehdi_amini

Differential Revision: https://reviews.llvm.org/D148449
2023-04-17 13:40:51 -05:00
Ivan Tadeu Ferreira Antunes Filho
73fd9d310f [lld] Support separate native object file path in --thinlto-prefix-replace
Currently, the --thinlto-prefix-replace="oldpath;newpath" option is used during
distributed ThinLTO thin links to specify the mapping of the input bitcode object
files' directory tree (oldpath) to the directory tree (newpath) used for both:

1) the output files of the thin link itself (the .thinlto.bc index files and the
optional .imports files)
2) the specified object file paths written to the response file given in the
--thinlto-index-only=${response} option, which is used by the final native
link and must match the paths of the native object files that will be
produced by ThinLTO backend compiles.
This patch expands the --thinlto-prefix-replace option to allow a separate directory
tree mapping to be specified for the object file paths written to the response file
(number 2 above). This is important to support builds and build systems where the
same output directory may not be written by multiple build actions (e.g. the thin link
and the ThinLTO backend compiles).

The new format is: --thinlto-prefix-replace="origpath;outpath[;objpath]"

This replaces the origpath directory tree of the thin link input files with
outpath when writing the thin link index and imports outputs (number 1
above). If objpath is specified it replaces origpath of the input files with
objpath when writing the response file (number 2 above), otherwise it
falls back to the old behavior of using outpath for this as well.

Reviewed By: tejohnson, MaskRay

Differential Revision: https://reviews.llvm.org/D144596
2023-04-04 11:24:51 -07:00
Shoaib Meenai
377e1311d5 [ThinLTO] Only import for non-prevailing interposable global variables
This logic was added in https://reviews.llvm.org/D95943 specifically to
handle an issue for non-prevailing global variables. It turns out that
it adds a new issue for prevailing glboal variables, since those could
be replaced by an available_externally definition and hence incorrectly
omitted from the output object file. Limit the import to non-prevailing
global variables to fix this, as suggested by @tejohnson.

The bulk of the diff is mechanical changes to thread isPrevailing
through to where it's needed and ensure it's available before the
relevant calls; the actual logic change itself is straightforward.

Fixes https://github.com/llvm/llvm-project/issues/61677

Reviewed By: tejohnson

Differential Revision: https://reviews.llvm.org/D146876
2023-03-25 21:37:42 -07:00
Teresa Johnson
fe27495be2 [MemProf] Context disambiguation cloning pass [patch 1b/3]
Adds support for building the graph in ThinLTO from MemProf summaries.

Follow-on patches will contain the support for cloning on the graph and
in the IR.

Depends on D140908.

Differential Revision: https://reviews.llvm.org/D145836
2023-03-22 14:57:53 -07:00
Jez Ng
8be84e1e31 [LTO] Add debug logging for module ID <-> path mapping
It's helpful

Reviewed By: MaskRay

Differential Revision: https://reviews.llvm.org/D145541
2023-03-09 13:25:48 -08:00
Guillaume Chatelet
ffc1205bde [reland][NFC] Transition GlobalObject alignment from MaybeAlign to Align
This is a follow up on https://reviews.llvm.org/D142459#4081179.
This first patch adds an overload to `GlobalObject::setAlignment` that accepts an `Align` type.
This already handles most of the calls.

This patch also converts a few call sites to the new type when this is safe.

Here is the list of the remaining call sites:

 - [clang/lib/CodeGen/CodeGenModule.cpp:1688](e195e6bad6/clang/lib/CodeGen/CodeGenModule.cpp (L1688))
 - [llvm/lib/AsmParser/LLParser.cpp:1309](e195e6bad6/llvm/lib/AsmParser/LLParser.cpp (L1309))
 - [llvm/lib/AsmParser/LLParser.cpp:6050](e195e6bad6/llvm/lib/AsmParser/LLParser.cpp (L6050))
 - [llvm/lib/Bitcode/Reader/BitcodeReader.cpp:3871](e195e6bad6/llvm/lib/Bitcode/Reader/BitcodeReader.cpp (L3871))
 - [llvm/lib/Bitcode/Reader/BitcodeReader.cpp:4030](e195e6bad6/llvm/lib/Bitcode/Reader/BitcodeReader.cpp (L4030))
 - [llvm/lib/IR/Core.cpp:2018](e195e6bad6/llvm/lib/IR/Core.cpp (L2018))
 - [llvm/lib/IR/Globals.cpp:141](e195e6bad6/llvm/lib/IR/Globals.cpp (L141))
 - [llvm/lib/Linker/IRMover.cpp:660](e195e6bad6/llvm/lib/Linker/IRMover.cpp (L660))
 - [llvm/lib/Linker/LinkModules.cpp:361](e195e6bad6/llvm/lib/Linker/LinkModules.cpp (L361))
 - [llvm/lib/Linker/LinkModules.cpp:362](e195e6bad6/llvm/lib/Linker/LinkModules.cpp (L362))
 - [llvm/lib/Transforms/IPO/MergeFunctions.cpp:782](e195e6bad6/llvm/lib/Transforms/IPO/MergeFunctions.cpp (L782))
 - [llvm/lib/Transforms/IPO/MergeFunctions.cpp:840](e195e6bad6/llvm/lib/Transforms/IPO/MergeFunctions.cpp (L840))
 - [llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp:1813](e195e6bad6/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp (L1813))
 - [llvm/tools/llvm-reduce/deltas/ReduceGlobalObjects.cpp:27](e195e6bad6/llvm/tools/llvm-reduce/deltas/ReduceGlobalObjects.cpp (L27))

Differential Revision: https://reviews.llvm.org/D142708
2023-01-31 15:09:10 +00:00
Guillaume Chatelet
e098ee726e Revert D142708 "[NFC] Transition GlobalObject alignment from MaybeAlign to Align"
This is breaking the build bots. e.g.,
https://lab.llvm.org/buildbot/#/builders/121/builds/27549

This reverts commit 6717efe74da825214cb4d307ad35e5fbda353301.
2023-01-31 14:12:51 +00:00
Guillaume Chatelet
6717efe74d [NFC] Transition GlobalObject alignment from MaybeAlign to Align
This is a follow up on https://reviews.llvm.org/D142459#4081179.
This first patch adds an overload to `GlobalObject::setAlignment` that accepts an `Align` type.
This already handles most of the calls.

This patch also converts a few call sites to the new type when this is safe.

Here is the list of the remaining call sites:

 - [clang/lib/CodeGen/CodeGenModule.cpp:1688](e195e6bad6/clang/lib/CodeGen/CodeGenModule.cpp (L1688))
 - [llvm/lib/AsmParser/LLParser.cpp:1309](e195e6bad6/llvm/lib/AsmParser/LLParser.cpp (L1309))
 - [llvm/lib/AsmParser/LLParser.cpp:6050](e195e6bad6/llvm/lib/AsmParser/LLParser.cpp (L6050))
 - [llvm/lib/Bitcode/Reader/BitcodeReader.cpp:3871](e195e6bad6/llvm/lib/Bitcode/Reader/BitcodeReader.cpp (L3871))
 - [llvm/lib/Bitcode/Reader/BitcodeReader.cpp:4030](e195e6bad6/llvm/lib/Bitcode/Reader/BitcodeReader.cpp (L4030))
 - [llvm/lib/IR/Core.cpp:2018](e195e6bad6/llvm/lib/IR/Core.cpp (L2018))
 - [llvm/lib/IR/Globals.cpp:141](e195e6bad6/llvm/lib/IR/Globals.cpp (L141))
 - [llvm/lib/Linker/IRMover.cpp:660](e195e6bad6/llvm/lib/Linker/IRMover.cpp (L660))
 - [llvm/lib/Linker/LinkModules.cpp:361](e195e6bad6/llvm/lib/Linker/LinkModules.cpp (L361))
 - [llvm/lib/Linker/LinkModules.cpp:362](e195e6bad6/llvm/lib/Linker/LinkModules.cpp (L362))
 - [llvm/lib/Transforms/IPO/MergeFunctions.cpp:782](e195e6bad6/llvm/lib/Transforms/IPO/MergeFunctions.cpp (L782))
 - [llvm/lib/Transforms/IPO/MergeFunctions.cpp:840](e195e6bad6/llvm/lib/Transforms/IPO/MergeFunctions.cpp (L840))
 - [llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp:1813](e195e6bad6/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp (L1813))
 - [llvm/tools/llvm-reduce/deltas/ReduceGlobalObjects.cpp:27](e195e6bad6/llvm/tools/llvm-reduce/deltas/ReduceGlobalObjects.cpp (L27))

Differential Revision: https://reviews.llvm.org/D142708
2023-01-31 13:59:58 +00:00
serge-sans-paille
38818b60c5
Move from llvm::makeArrayRef to ArrayRef deduction guides - llvm/ part
Use deduction guides instead of helper functions.

The only non-automatic changes have been:

1. ArrayRef(some_uint8_pointer, 0) needs to be changed into ArrayRef(some_uint8_pointer, (size_t)0) to avoid an ambiguous call with ArrayRef((uint8_t*), (uint8_t*))
2. CVSymbol sym(makeArrayRef(symStorage)); needed to be rewritten as CVSymbol sym{ArrayRef(symStorage)}; otherwise the compiler is confused and thinks we have a (bad) function prototype. There was a few similar situation across the codebase.
3. ADL doesn't seem to work the same for deduction-guides and functions, so at some point the llvm namespace must be explicitly stated.
4. The "reference mode" of makeArrayRef(ArrayRef<T> &) that acts as no-op is not supported (a constructor cannot achieve that).

Per reviewers' comment, some useless makeArrayRef have been removed in the process.

This is a follow-up to https://reviews.llvm.org/D140896 that introduced
the deduction guides.

Differential Revision: https://reviews.llvm.org/D140955
2023-01-05 14:11:08 +01:00
Fangrui Song
7d43c3ba51 IR: HotnessThreshold llvm::Optional => std::optional 2022-12-04 19:06:47 +00:00
Bjorn Pettersson
99c47d9e31 Remove TargetMachine::adjustPassManager
Since opt no longer supports to run default (O0/O1/O2/O3/Os/Oz)
pipelines using the legacy PM, there are no in-tree uses of
TargetMachine::adjustPassManager remaining. This patch removes the
no longer used adjustPassManager functions.

Reviewed By: aeubanks

Differential Revision: https://reviews.llvm.org/D137796
2022-11-28 10:24:16 +01:00
Kazu Hirata
b68a38a960 [LTO] Use std::optional in LTO.cpp (NFC)
This is part of an effort to migrate from llvm::Optional to
std::optional:

https://discourse.llvm.org/t/deprecating-llvm-optional-x-hasvalue-getvalue-getvalueor/63716
2022-11-26 15:29:30 -08:00
Fangrui Song
5f759beaae [LTO] Move cl::opt inside llvm:: after D53294 2022-11-23 23:22:26 -08:00
Zequan Wu
84be92d26f Reland "[LTO][COFF] Use bitcode file names in lto native object file names."
This reverts commit 34108082947c964ae9bbfcd9808f2fd31c0d672f with fixes.
2022-11-22 13:46:42 -08:00
Roman Lebedev
3410808294
Revert "Reland "[LTO][COFF] Use bitcode file names in lto native object file names.""
Breaks build of LLVMgold here:
```
/repositories/llvm-project/llvm/tools/gold/gold-plugin.cpp:1108:19: error: no matching function for call to 'localCache'
    Cache = check(localCache("ThinLTO", "Thin", options::cache_dir, AddBuffer));
                  ^~~~~~~~~~
/repositories/llvm-project/llvm/include/llvm/Support/Caching.h:72:21: note: candidate function not viable: no known conversion from '(lambda at /repositories/llvm-project/llvm/tools/gold/gold-plugin.cpp:1102:20)' to 'llvm::AddBufferFn' (aka 'function<void (unsigned int, const llvm::Twine &, std::unique_ptr<MemoryBuffer>)>') for 4th argument
Expected<FileCache> localCache(
                    ^
/repositories/llvm-project/llvm/tools/gold/gold-plugin.cpp:1110:18: error: no viable conversion from '(lambda at /repositories/llvm-project/llvm/tools/gold/gold-plugin.cpp:1094:20)' to 'llvm::AddStreamFn' (aka 'function<Expected<std::unique_ptr<CachedFileStream>> (unsigned int, const llvm::Twine &)>')
  check(Lto->run(AddStream, Cache));
                 ^~~~~~~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../include/c++/12/bits/std_function.h:375:7: note: candidate constructor not viable: no known conversion from '(lambda at /repositories/llvm-project/llvm/tools/gold/gold-plugin.cpp:1094:20)' to 'std::nullptr_t' for 1st argument
      function(nullptr_t) noexcept
      ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../include/c++/12/bits/std_function.h:386:7: note: candidate constructor not viable: no known conversion from '(lambda at /repositories/llvm-project/llvm/tools/gold/gold-plugin.cpp:1094:20)' to 'const std::function<llvm::Expected<std::unique_ptr<llvm::CachedFileStream>> (unsigned int, const llvm::Twine &)> &' for 1st argument
      function(const function& __x)
      ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../include/c++/12/bits/std_function.h:404:7: note: candidate constructor not viable: no known conversion from '(lambda at /repositories/llvm-project/llvm/tools/gold/gold-plugin.cpp:1094:20)' to 'std::function<llvm::Expected<std::unique_ptr<llvm::CachedFileStream>> (unsigned int, const llvm::Twine &)> &&' for 1st argument
      function(function&& __x) noexcept
      ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/12/../../../../include/c++/12/bits/std_function.h:435:2: note: candidate template ignored: requirement '_Callable<(lambda at /repositories/llvm-project/llvm/tools/gold/gold-plugin.cpp:1094:20) &, (lambda at /repositories/llvm-project/llvm/tools/gold/gold-plugin.cpp:1094:20), std::__invoke_result<(lambda at /repositories/llvm-project/llvm/tools/gold/gold-plugin.cpp:1094:20) &, unsigned int, const llvm::Twine &>>::value' was not satisfied [with _Functor = (lambda at /repositories/llvm-project/llvm/tools/gold/gold-plugin.cpp:1094:20) &]
        function(_Functor&& __f)
        ^
/repositories/llvm-project/llvm/include/llvm/LTO/LTO.h:278:25: note: passing argument to parameter 'AddStream' here
  Error run(AddStreamFn AddStream, FileCache Cache = nullptr);
                        ^

```

This reverts commit 387620aa8cea33174b6c1fb80c1af713fee732ac.
2022-11-23 00:40:12 +03:00
Zequan Wu
387620aa8c Reland "[LTO][COFF] Use bitcode file names in lto native object file names."
This reverts commit eef5405f74ae208e3e2eb7daacecac923d7338f2.
2022-11-22 11:26:18 -08:00
Zequan Wu
eef5405f74 Revert "[LTO][COFF] Use bitcode file names in lto native object file names."
This reverts commit 531ed6d5aa65f41c6dfe2e74905d5c6c88fc95a7.
2022-11-22 10:55:05 -08:00
Zequan Wu
531ed6d5aa [LTO][COFF] Use bitcode file names in lto native object file names.
Currently the lto native object files have names like main.exe.lto.1.obj. In
PDB, those names are used as names for each compiland. Microsoft’s tool
SizeBench uses those names to present to users the size of each object files.
So, names like main.exe.lto.1.obj is not user friendly.

This patch makes the lto native object file names more readable by using
the bitcode file names as part of the file names. For example, if the input
bitcode file has path like "path/to/foo.obj", its corresponding lto native
object file path would be "path/to/main.exe.lto.foo.obj". Since the lto native
object file name only bothers PDB, this patch only changes the lld-linker's
behavior.

Reviewed By: tejohnson, MaskRay, #lld-macho

Differential Revision: https://reviews.llvm.org/D137217
2022-11-22 10:19:58 -08:00
Fangrui Song
12050a3fb7 [LTO] Make local linkage GlobalValue in non-prevailing COMDAT available_externally
For a local linkage GlobalObject in a non-prevailing COMDAT, it remains defined while its
leader has been made available_externally. This violates the COMDAT rule that
its members must be retained or discarded as a unit.

To fix this, update the regular LTO change D34803 to track local linkage
GlobalValues, and port the code to ThinLTO (GlobalAliases are not handled.)

This fixes two problems.

(a) `__cxx_global_var_init` in a non-prevailing COMDAT group used to
linger around (unreferenced, hence benign), and is now correctly discarded.
```
int foo();
inline int v = foo();
```

(b) Fix https://github.com/llvm/llvm-project/issues/58215:
as a size optimization, we place private `__profd_` in a COMDAT with a
`__profc_` key. When FuncImport.cpp makes `__profc_` available_externally due to
a non-prevailing COMDAT, `__profd_` incorrectly remains private. This change
makes the `__profd_` available_externally.

```
cat > c.h <<'eof'
extern void bar();
inline __attribute__((noinline)) void foo() {}
eof
cat > m1.cc <<'eof'
#include "c.h"
int main() {
  bar();
  foo();
}
eof
cat > m2.cc <<'eof'
#include "c.h"
__attribute__((noinline)) void bar() {
  foo();
}
eof

clang -O2 -fprofile-generate=./t m1.cc m2.cc -flto -fuse-ld=lld -o t_gen
rm -fr t && ./t_gen && llvm-profdata show -function=foo t/default_*.profraw

clang -O2 -fprofile-generate=./t m1.cc m2.cc -flto=thin -fuse-ld=lld -o t_gen
rm -fr t && ./t_gen && llvm-profdata show -function=foo t/default_*.profraw
```

If a GlobalAlias references a GlobalValue which is just changed to
available_externally, change the GlobalAlias as well (e.g. C5/D5 comdats due to
cc1 -mconstructor-aliases). The GlobalAlias may be referenced by other
available_externally functions, so it cannot easily be removed.

Depends on D137441: we use available_externally to mark a GlobalAlias in a
non-prevailing COMDAT, similar to how we handle GlobalVariable/Function.
GlobalAlias may refer to a ConstantExpr, not changing GlobalAlias to
GlobalVariable gives flexibility for future extensions (the use case is niche.
For simplicity we don't handle it yet). In addition, available_externally
GlobalAlias is the most straightforward implementation and retains the aliasee
information to help optimizers.

See windows-vftable.ll: Windows vftable uses an alias pointing to a
private constant where the alias is the COMDAT leader. The COMDAT use case
is skeptical and ThinLTO does not discard the alias in the non-prevailing COMDAT.
This patch retains the behavior.

See new tests ctor-dtor-alias2.ll: depending on whether the complete object
destructor emitted, when ctor/dtor aliases are used, we may see D0/D2 COMDATs in
one TU and D0/D1/D2 in a D5 COMDAT in another TU.
Allow such a mix-and-match with `if (GO->getComdat()->getName() == GO->getName()) NonPrevailingComdats.insert(GO->getComdat());`

GlobalAlias handling in ThinLTO is still weird, but this patch should hopefully
improve the situation for at least all cases I can think of.

Reviewed By: tejohnson

Differential Revision: https://reviews.llvm.org/D135427
2022-11-16 22:13:22 -08:00
Fangrui Song
2c239da691 Revert D135427 "[LTO] Make local linkage GlobalValue in non-prevailing COMDAT available_externally"
This reverts commit 8901635423cbea4324059a5127657126d2e00ce1.

This change broke the following example and we need to check `if (GO->getComdat()->getName() == GO->getName())`
before `NonPrevailingComdats.insert(GO->getComdat());`
Revert for clarify.

```
// a.cc
template <typename T>
struct A final { virtual ~A() {} };
extern "C" void aa() { A<int> a; }
// b.cc
template <typename T>
struct A final { virtual ~A() {} };
template struct A<int>;
extern "C" void bb(A<int> *a) { delete a; }

clang -c -fpic -O0 -flto=thin a.cc && ld.lld -shared a.o b.o
```
2022-11-16 21:43:50 -08:00
Teresa Johnson
9eacbba290 Restore "[MemProf] ThinLTO summary support" with more fixes
This restores commit 98ed423361de2f9dc0113a31be2aa04524489ca9 and
follow on fix 00c22351ba697dbddb4b5bf0ad94e4bcea4b316b, which were
reverted in 5d938eb6f79b16f55266dd23d5df831f552ea082 due to an
MSVC bot failure. I've included a fix for that failure.

Differential Revision: https://reviews.llvm.org/D135714
2022-11-16 09:42:41 -08:00
Jeremy Morse
5d938eb6f7 Revert "Restore "[MemProf] ThinLTO summary support" with fixes"
This reverts commit 00c22351ba697dbddb4b5bf0ad94e4bcea4b316b.
This reverts commit 98ed423361de2f9dc0113a31be2aa04524489ca9.

Seemingly MSVC has some kind of issue with this patch, in terms of linking:

  https://lab.llvm.org/buildbot/#/builders/123/builds/14137

I'll post more detail on D135714 momentarily.
2022-11-16 11:21:02 +00:00
Teresa Johnson
98ed423361 Restore "[MemProf] ThinLTO summary support" with fixes
This restores 47459455009db4790ffc3765a2ec0f8b4934c2a4, which was
reverted in commit 452a14efc84edf808d1e2953dad2c694972b312f, along with
fixes for a couple of bot failures.
2022-11-15 08:55:17 -08:00
Teresa Johnson
452a14efc8 Revert "[MemProf] ThinLTO summary support"
This reverts commit 47459455009db4790ffc3765a2ec0f8b4934c2a4.

Revert while I try to fix a couple of non-Linux build failures.
2022-11-15 07:39:40 -08:00
Teresa Johnson
4745945500 [MemProf] ThinLTO summary support
Implements the ThinLTO summary support for memprof related metadata.

This includes support for the assembly format, and for building the
summary from IR during ModuleSummaryAnalysis.

To reduce space in both the bitcode format and the in memory index,
we do 2 things:
1. We keep a single vector of all uniq stack id hashes, and record the
   index into this vector in the callsite and allocation memprof
   summaries.
2. When building the combined index during the LTO link, the callsite
   and allocation memprof summaries are only kept on the FunctionSummary
   of the prevailing copy.

Differential Revision: https://reviews.llvm.org/D135714
2022-11-15 06:45:12 -08:00
Fangrui Song
8901635423 [LTO] Make local linkage GlobalValue in non-prevailing COMDAT available_externally
For a local linkage GlobalObject in a non-prevailing COMDAT, it remains defined while its
leader has been made available_externally. This violates the COMDAT rule that
its members must be retained or discarded as a unit.

To fix this, update the regular LTO change D34803 to track local linkage
GlobalValues, and port the code to ThinLTO (GlobalAliases are not handled.)

This fixes two problems.

(a) `__cxx_global_var_init` in a non-prevailing COMDAT group used to
linger around (unreferenced, hence benign), and is now correctly discarded.
```
int foo();
inline int v = foo();
```

(b) Fix https://github.com/llvm/llvm-project/issues/58215:
as a size optimization, we place private `__profd_` in a COMDAT with a
`__profc_` key. When FuncImport.cpp makes `__profc_` available_externally due to
a non-prevailing COMDAT, `__profd_` incorrectly remains private. This change
makes the `__profd_` available_externally.

```
cat > c.h <<'eof'
extern void bar();
inline __attribute__((noinline)) void foo() {}
eof
cat > m1.cc <<'eof'
#include "c.h"
int main() {
  bar();
  foo();
}
eof
cat > m2.cc <<'eof'
#include "c.h"
__attribute__((noinline)) void bar() {
  foo();
}
eof

clang -O2 -fprofile-generate=./t m1.cc m2.cc -flto -fuse-ld=lld -o t_gen
rm -fr t && ./t_gen && llvm-profdata show -function=foo t/default_*.profraw

clang -O2 -fprofile-generate=./t m1.cc m2.cc -flto=thin -fuse-ld=lld -o t_gen
rm -fr t && ./t_gen && llvm-profdata show -function=foo t/default_*.profraw
```

If a GlobalAlias references a GlobalValue which is just changed to
available_externally, change the GlobalAlias as well (e.g. C5/D5 comdats due to
cc1 -mconstructor-aliases). The GlobalAlias may be referenced by other
available_externally functions, so it cannot easily be removed.

Depends on D137441: we use available_externally to mark a GlobalAlias in a
non-prevailing COMDAT, similar to how we handle GlobalVariable/Function.
GlobalAlias may refer to a ConstantExpr, not changing GlobalAlias to
GlobalVariable gives flexibility for future extensions (the use case is niche.
For simplicity we don't handle it yet). In addition, available_externally
GlobalAlias is the most straightforward implementation and retains the aliasee
information to help optimizers.

See windows-vftable.ll: Windows vftable uses an alias pointing to a
private constant where the alias is the COMDAT leader. The COMDAT use case
is skeptical and ThinLTO does not discard the alias in the non-prevailing COMDAT.
This patch retains the behavior.

Reviewed By: tejohnson

Differential Revision: https://reviews.llvm.org/D135427
2022-11-10 21:54:43 -08:00
Alan Zhao
885e6105b4 Revert "[LTO] Make local linkage GlobalValue in non-prevailing COMDAT available_externally"
This reverts commit 89ddcff1d2d6e9f4de78f3a563a8b1987bf7ea8f.

Reason: This breaks bootstrapping builds of LLVM on Windows using
ThinLTO; see https://crbug.com/1382839
2022-11-10 17:48:18 -08:00
Fangrui Song
89ddcff1d2 [LTO] Make local linkage GlobalValue in non-prevailing COMDAT available_externally
For a local linkage GlobalObject in a non-prevailing COMDAT, it remains defined while its
leader has been made available_externally. This violates the COMDAT rule that
its members must be retained or discarded as a unit.

To fix this, update the regular LTO change D34803 to track local linkage
GlobalValues, and port the code to ThinLTO (GlobalAliases are not handled.)

This fixes two problems.

(a) `__cxx_global_var_init` in a non-prevailing COMDAT group used to
linger around (unreferenced, hence benign), and is now correctly discarded.
```
int foo();
inline int v = foo();
```

(b) Fix https://github.com/llvm/llvm-project/issues/58215:
as a size optimization, we place private `__profd_` in a COMDAT with a
`__profc_` key. When FuncImport.cpp makes `__profc_` available_externally due to
a non-prevailing COMDAT, `__profd_` incorrectly remains private. This change
makes the `__profd_` available_externally.

```
cat > c.h <<'eof'
extern void bar();
inline __attribute__((noinline)) void foo() {}
eof
cat > m1.cc <<'eof'
#include "c.h"
int main() {
  bar();
  foo();
}
eof
cat > m2.cc <<'eof'
#include "c.h"
__attribute__((noinline)) void bar() {
  foo();
}
eof

clang -O2 -fprofile-generate=./t m1.cc m2.cc -flto -fuse-ld=lld -o t_gen
rm -fr t && ./t_gen && llvm-profdata show -function=foo t/default_*.profraw

clang -O2 -fprofile-generate=./t m1.cc m2.cc -flto=thin -fuse-ld=lld -o t_gen
rm -fr t && ./t_gen && llvm-profdata show -function=foo t/default_*.profraw
```

If a GlobalAlias references a GlobalValue which is just changed to
available_externally, change the GlobalAlias as well (e.g. C5/D5 comdats due to
cc1 -mconstructor-aliases). The GlobalAlias may be referenced by other
available_externally functions, so it cannot easily be removed.

Depends on D137441: we use available_externally to mark a GlobalAlias in a
non-prevailing COMDAT, similar to how we handle GlobalVariable/Function.
GlobalAlias may refer to a ConstantExpr, not changing GlobalAlias to
GlobalVariable gives flexibility for future extensions (the use case is niche.
For simplicity we don't handle it yet). In addition, available_externally
GlobalAlias is the most straightforward implementation and retains the aliasee
information to help optimizers.

Reviewed By: tejohnson

Differential Revision: https://reviews.llvm.org/D135427
2022-11-07 10:07:10 -08:00
Fangrui Song
c80b12d352 Revert D135427 "[LTO] Make local linkage GlobalValue in non-prevailing COMDAT available_externally"
This reverts commit 8ef3fd8d59ba0100bc6e83350ab1e978536aa531.

I mentioned that GlobalAlias was not handled. It turns out GlobalAlias has to be handled in the same patch (as opposed to in a follow-up),
as otherwise clang codegen of C5/D5 constructor/destructor would regress (https://reviews.llvm.org/D135427#3869003).
2022-10-19 11:24:12 -07:00
serge-sans-paille
232e0a011e
[lto] Do not try to internalize symbols with escaped name
Because of LLVM mangling escape sequence (through '\01' prefix), it is possible
for a single symbols two have two different IR representations.

For instance, consider @symbol and @"\01_symbol". On OSX, because of the system
mangling rules, these two IR names point are converted in the same final symbol
upon linkage.

LTO doesn't model this behavior, which may result in symbols being incorrectly
internalized (if all reference use the escaping sequence while the definition
doesn't).

The proper approach is probably to use the mangled name to compute GUID to
avoid the dual representation, but we can also avoid discarding symbols that are
bound to two different IR names. This is an approximation, but it's less
intrusive on the codebase.

Fix #57864

Differential Revision: https://reviews.llvm.org/D135710
2022-10-14 22:34:17 +02:00
Fangrui Song
8ef3fd8d59 [LTO] Make local linkage GlobalValue in non-prevailing COMDAT available_externally
For a local linkage GlobalObject in a non-prevailing COMDAT, it remains defined while its
leader has been made available_externally. This violates the COMDAT rule that
its members must be retained or discarded as a unit.

To fix this, update the regular LTO change D34803 to track local linkage
GlobalValues, and port the code to ThinLTO (GlobalAliases are not handled.)

This fixes two problems.

(a) `__cxx_global_var_init` in a non-prevailing COMDAT group used to
linger around (unreferenced, hence benign), and is now correctly discarded.
```
int foo();
inline int v = foo();
```

(b) Fix https://github.com/llvm/llvm-project/issues/58215:
as a size optimization, we place private `__profd_` in a COMDAT with a
`__profc_` key. When FuncImport.cpp makes `__profc_` available_externally due to
a non-prevailing COMDAT, `__profd_` incorrectly remains private. This change
makes the `__profd_` available_externally.

```
cat > c.h <<'eof'
extern void bar();
inline __attribute__((noinline)) void foo() {}
eof
cat > m1.cc <<'eof'
int main() {
  bar();
  foo();
}
eof
cat > m2.cc <<'eof'
__attribute__((noinline)) void bar() {
  foo();
}
eof

clang -O2 -fprofile-generate=./t m1.cc m2.cc -flto -fuse-ld=lld -o t_gen
rm -fr t && ./t_gen && llvm-profdata show -function=foo t/default_*.profraw

clang -O2 -fprofile-generate=./t m1.cc m2.cc -flto=thin -fuse-ld=lld -o t_gen
rm -fr t && ./t_gen && llvm-profdata show -function=foo t/default_*.profraw
```

Reviewed By: tejohnson

Differential Revision: https://reviews.llvm.org/D135427
2022-10-11 15:30:07 -07:00