xref: /llvm-project-15.0.7/lld/ELF/LTO.cpp (revision 1c16d1b5)
1 //===- LTO.cpp ------------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "LTO.h"
11 #include "Config.h"
12 #include "Driver.h"
13 #include "Error.h"
14 #include "InputFiles.h"
15 #include "Symbols.h"
16 #include "llvm/Analysis/AliasAnalysis.h"
17 #include "llvm/Analysis/CGSCCPassManager.h"
18 #include "llvm/Analysis/LoopPassManager.h"
19 #include "llvm/Analysis/TargetLibraryInfo.h"
20 #include "llvm/Analysis/TargetTransformInfo.h"
21 #include "llvm/Bitcode/ReaderWriter.h"
22 #include "llvm/CodeGen/CommandFlags.h"
23 #include "llvm/CodeGen/ParallelCG.h"
24 #include "llvm/IR/AutoUpgrade.h"
25 #include "llvm/IR/LegacyPassManager.h"
26 #include "llvm/IR/PassManager.h"
27 #include "llvm/IR/Verifier.h"
28 #include "llvm/LTO/legacy/UpdateCompilerUsed.h"
29 #include "llvm/Linker/IRMover.h"
30 #include "llvm/Passes/PassBuilder.h"
31 #include "llvm/Support/StringSaver.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Transforms/IPO.h"
35 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
36 #include "llvm/Transforms/Utils/ModuleUtils.h"
37 
38 using namespace llvm;
39 using namespace llvm::object;
40 using namespace llvm::ELF;
41 
42 using namespace lld;
43 using namespace lld::elf;
44 
45 // This is for use when debugging LTO.
46 static void saveBuffer(StringRef Buffer, const Twine &Path) {
47   std::error_code EC;
48   raw_fd_ostream OS(Path.str(), EC, sys::fs::OpenFlags::F_None);
49   if (EC)
50     error(EC, "cannot create " + Path);
51   OS << Buffer;
52 }
53 
54 // This is for use when debugging LTO.
55 static void saveBCFile(Module &M, const Twine &Path) {
56   std::error_code EC;
57   raw_fd_ostream OS(Path.str(), EC, sys::fs::OpenFlags::F_None);
58   if (EC)
59     error(EC, "cannot create " + Path);
60   WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ true);
61 }
62 
63 static void runNewCustomLtoPasses(Module &M, TargetMachine &TM) {
64   PassBuilder PB(&TM);
65 
66   AAManager AA;
67 
68   // Parse a custom AA pipeline if asked to.
69   if (!PB.parseAAPipeline(AA, Config->LtoAAPipeline)) {
70     error("Unable to parse AA pipeline description: " + Config->LtoAAPipeline);
71     return;
72   }
73 
74   LoopAnalysisManager LAM;
75   FunctionAnalysisManager FAM;
76   CGSCCAnalysisManager CGAM;
77   ModuleAnalysisManager MAM;
78 
79   // Register the AA manager first so that our version is the one used.
80   FAM.registerPass([&] { return std::move(AA); });
81 
82   // Register all the basic analyses with the managers.
83   PB.registerModuleAnalyses(MAM);
84   PB.registerCGSCCAnalyses(CGAM);
85   PB.registerFunctionAnalyses(FAM);
86   PB.registerLoopAnalyses(LAM);
87   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
88 
89   ModulePassManager MPM;
90   if (!Config->DisableVerify)
91     MPM.addPass(VerifierPass());
92 
93   // Now, add all the passes we've been requested to.
94   if (!PB.parsePassPipeline(MPM, Config->LtoNewPmPasses)) {
95     error("unable to parse pass pipeline description: " +
96           Config->LtoNewPmPasses);
97     return;
98   }
99 
100   if (!Config->DisableVerify)
101     MPM.addPass(VerifierPass());
102   MPM.run(M, MAM);
103 }
104 
105 static void runOldLtoPasses(Module &M, TargetMachine &TM) {
106   // Note that the gold plugin has a similar piece of code, so
107   // it is probably better to move this code to a common place.
108   legacy::PassManager LtoPasses;
109   LtoPasses.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
110   PassManagerBuilder PMB;
111   PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM.getTargetTriple()));
112   PMB.Inliner = createFunctionInliningPass();
113   PMB.VerifyInput = PMB.VerifyOutput = !Config->DisableVerify;
114   PMB.LoopVectorize = true;
115   PMB.SLPVectorize = true;
116   PMB.OptLevel = Config->LtoO;
117   PMB.populateLTOPassManager(LtoPasses);
118   LtoPasses.run(M);
119 }
120 
121 static void runLTOPasses(Module &M, TargetMachine &TM) {
122   if (!Config->LtoNewPmPasses.empty()) {
123     // The user explicitly asked for a set of passes to be run.
124     // This needs the new PM to work as there's no clean way to
125     // pass a set of passes to run in the legacy PM.
126     runNewCustomLtoPasses(M, TM);
127     if (HasError)
128       return;
129   } else {
130     // Run the 'default' set of LTO passes. This code still uses
131     // the legacy PM as the new one is not the default.
132     runOldLtoPasses(M, TM);
133   }
134 
135   if (Config->SaveTemps)
136     saveBCFile(M, Config->OutputFile + ".lto.opt.bc");
137 }
138 
139 static bool shouldInternalize(const SmallPtrSet<GlobalValue *, 8> &Used,
140                               Symbol *S, GlobalValue *GV) {
141   if (S->IsUsedInRegularObj || Used.count(GV))
142     return false;
143   return !S->includeInDynsym();
144 }
145 
146 BitcodeCompiler::BitcodeCompiler()
147     : Combined(new Module("ld-temp.o", Driver->Context)) {}
148 
149 static void undefine(Symbol *S) {
150   replaceBody<Undefined>(S, S->body()->getName(), STV_DEFAULT, S->body()->Type,
151                          nullptr);
152 }
153 
154 static void handleUndefinedAsmRefs(const BasicSymbolRef &Sym, GlobalValue *GV,
155                                    StringSet<> &AsmUndefinedRefs) {
156   // GV associated => not an assembly symbol, bail out.
157   if (GV)
158     return;
159 
160   // This is an undefined reference to a symbol in asm. We put that in
161   // compiler.used, so that we can preserve it from being dropped from
162   // the output, without necessarily preventing its internalization.
163   SmallString<64> Name;
164   raw_svector_ostream OS(Name);
165   Sym.printName(OS);
166   AsmUndefinedRefs.insert(Name.str());
167 }
168 
169 void BitcodeCompiler::add(BitcodeFile &F) {
170   std::unique_ptr<IRObjectFile> Obj = std::move(F.Obj);
171   std::vector<GlobalValue *> Keep;
172   unsigned BodyIndex = 0;
173   ArrayRef<Symbol *> Syms = F.getSymbols();
174 
175   Module &M = Obj->getModule();
176   if (M.getDataLayoutStr().empty())
177     fatal("invalid bitcode file: " + F.getName() + " has no datalayout");
178 
179   // Discard non-compatible debug infos if necessary.
180   M.materializeMetadata();
181   UpgradeDebugInfo(M);
182 
183   // If a symbol appears in @llvm.used, the linker is required
184   // to treat the symbol as there is a reference to the symbol
185   // that it cannot see. Therefore, we can't internalize.
186   SmallPtrSet<GlobalValue *, 8> Used;
187   collectUsedGlobalVariables(M, Used, /* CompilerUsed */ false);
188 
189   for (const BasicSymbolRef &Sym : Obj->symbols()) {
190     uint32_t Flags = Sym.getFlags();
191     GlobalValue *GV = Obj->getSymbolGV(Sym.getRawDataRefImpl());
192     if (GV && GV->hasAppendingLinkage())
193       Keep.push_back(GV);
194     if (BitcodeFile::shouldSkip(Flags))
195       continue;
196     Symbol *S = Syms[BodyIndex++];
197     if (GV)
198       GV->setUnnamedAddr(S->HasUnnamedAddr ? GlobalValue::UnnamedAddr::Global
199                                            : GlobalValue::UnnamedAddr::None);
200     if (Flags & BasicSymbolRef::SF_Undefined) {
201       handleUndefinedAsmRefs(Sym, GV, AsmUndefinedRefs);
202       continue;
203     }
204     SymbolBody *B = S->body();
205     if (B->File != &F)
206       continue;
207 
208     // We collect the set of symbols we want to internalize here
209     // and change the linkage after the IRMover executed, i.e. after
210     // we imported the symbols and satisfied undefined references
211     // to it. We can't just change linkage here because otherwise
212     // the IRMover will just rename the symbol.
213     if (GV && shouldInternalize(Used, S, GV))
214       InternalizedSyms.insert(GV->getName());
215 
216     // At this point we know that either the combined LTO object will provide a
217     // definition of a symbol, or we will internalize it. In either case, we
218     // need to undefine the symbol. In the former case, the real definition
219     // needs to be able to replace the original definition without conflicting.
220     // In the latter case, we need to allow the combined LTO object to provide a
221     // definition with the same name, for example when doing parallel codegen.
222     if (auto *C = dyn_cast<DefinedCommon>(B)) {
223       if (auto *GO = dyn_cast<GlobalObject>(GV))
224         GO->setAlignment(C->Alignment);
225     } else {
226       undefine(S);
227     }
228 
229     if (!GV)
230       // Module asm symbol.
231       continue;
232 
233     switch (GV->getLinkage()) {
234     default:
235       break;
236     case GlobalValue::LinkOnceAnyLinkage:
237       GV->setLinkage(GlobalValue::WeakAnyLinkage);
238       break;
239     case GlobalValue::LinkOnceODRLinkage:
240       GV->setLinkage(GlobalValue::WeakODRLinkage);
241       break;
242     }
243 
244     Keep.push_back(GV);
245   }
246 
247   IRMover Mover(*Combined);
248   if (Error E = Mover.move(Obj->takeModule(), Keep,
249                            [](GlobalValue &, IRMover::ValueAdder) {})) {
250     handleAllErrors(std::move(E), [&](const ErrorInfoBase &EIB) {
251       fatal("failed to link module " + F.getName() + ": " + EIB.message());
252     });
253   }
254 }
255 
256 static void internalize(GlobalValue &GV) {
257   assert(!GV.hasLocalLinkage() &&
258          "Trying to internalize a symbol with local linkage!");
259   GV.setLinkage(GlobalValue::InternalLinkage);
260 }
261 
262 std::vector<InputFile *> BitcodeCompiler::runSplitCodegen(
263     const std::function<std::unique_ptr<TargetMachine>()> &TMFactory) {
264   unsigned NumThreads = Config->LtoJobs;
265   OwningData.resize(NumThreads);
266 
267   std::list<raw_svector_ostream> OSs;
268   std::vector<raw_pwrite_stream *> OSPtrs;
269   for (SmallString<0> &Obj : OwningData) {
270     OSs.emplace_back(Obj);
271     OSPtrs.push_back(&OSs.back());
272   }
273 
274   splitCodeGen(std::move(Combined), OSPtrs, {}, TMFactory);
275 
276   std::vector<InputFile *> ObjFiles;
277   for (SmallString<0> &Obj : OwningData)
278     ObjFiles.push_back(createObjectFile(
279         MemoryBufferRef(Obj, "LLD-INTERNAL-combined-lto-object")));
280 
281   // If -save-temps is given, we need to save temporary objects to files.
282   // This is for debugging.
283   if (Config->SaveTemps) {
284     if (NumThreads == 1) {
285       saveBuffer(OwningData[0], Config->OutputFile + ".lto.o");
286     } else {
287       for (unsigned I = 0; I < NumThreads; ++I)
288         saveBuffer(OwningData[I], Config->OutputFile + Twine(I) + ".lto.o");
289     }
290   }
291 
292   return ObjFiles;
293 }
294 
295 // Merge all the bitcode files we have seen, codegen the result
296 // and return the resulting ObjectFile.
297 std::vector<InputFile *> BitcodeCompiler::compile() {
298   for (const auto &Name : InternalizedSyms) {
299     GlobalValue *GV = Combined->getNamedValue(Name.first());
300     assert(GV);
301     internalize(*GV);
302   }
303 
304   std::string TheTriple = Combined->getTargetTriple();
305   std::string Msg;
306   const Target *T = TargetRegistry::lookupTarget(TheTriple, Msg);
307   if (!T)
308     fatal("target not found: " + Msg);
309 
310   // LLD supports the new relocations.
311   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
312   Options.RelaxELFRelocations = true;
313 
314   auto CreateTargetMachine = [&]() {
315     return std::unique_ptr<TargetMachine>(T->createTargetMachine(
316         TheTriple, "", "", Options, Config->Pic ? Reloc::PIC_ : Reloc::Static));
317   };
318 
319   std::unique_ptr<TargetMachine> TM = CreateTargetMachine();
320 
321   // Update llvm.compiler.used so that optimizations won't strip
322   // off AsmUndefinedReferences.
323   updateCompilerUsed(*Combined, *TM, AsmUndefinedRefs);
324 
325   if (Config->SaveTemps)
326     saveBCFile(*Combined, Config->OutputFile + ".lto.bc");
327 
328   runLTOPasses(*Combined, *TM);
329   if (HasError)
330     return {};
331 
332   return runSplitCodegen(CreateTargetMachine);
333 }
334