Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/LTO/LTOBackend.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-LTOBackend.cpp - LLVM Link Time Optimizer Backend -------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file implements the "backend" phase of LTO, i.e. it performs
10
// optimization and code generation on a loaded module. It is generally used
11
// internally by the LTO class but can also be used independently, for example
12
// to implement a standalone ThinLTO backend.
13
//
14
//===----------------------------------------------------------------------===//
15
16
#include "llvm/LTO/LTOBackend.h"
17
#include "llvm/Analysis/AliasAnalysis.h"
18
#include "llvm/Analysis/CGSCCPassManager.h"
19
#include "llvm/Analysis/TargetLibraryInfo.h"
20
#include "llvm/Analysis/TargetTransformInfo.h"
21
#include "llvm/Bitcode/BitcodeReader.h"
22
#include "llvm/Bitcode/BitcodeWriter.h"
23
#include "llvm/IR/LegacyPassManager.h"
24
#include "llvm/IR/PassManager.h"
25
#include "llvm/IR/RemarkStreamer.h"
26
#include "llvm/IR/Verifier.h"
27
#include "llvm/LTO/LTO.h"
28
#include "llvm/MC/SubtargetFeature.h"
29
#include "llvm/Object/ModuleSymbolTable.h"
30
#include "llvm/Passes/PassBuilder.h"
31
#include "llvm/Support/Error.h"
32
#include "llvm/Support/FileSystem.h"
33
#include "llvm/Support/MemoryBuffer.h"
34
#include "llvm/Support/Path.h"
35
#include "llvm/Support/Program.h"
36
#include "llvm/Support/TargetRegistry.h"
37
#include "llvm/Support/ThreadPool.h"
38
#include "llvm/Support/raw_ostream.h"
39
#include "llvm/Target/TargetMachine.h"
40
#include "llvm/Transforms/IPO.h"
41
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
42
#include "llvm/Transforms/Scalar/LoopPassManager.h"
43
#include "llvm/Transforms/Utils/FunctionImportUtils.h"
44
#include "llvm/Transforms/Utils/SplitModule.h"
45
46
using namespace llvm;
47
using namespace lto;
48
49
0
LLVM_ATTRIBUTE_NORETURN static void reportOpenError(StringRef Path, Twine Msg) {
50
0
  errs() << "failed to open " << Path << ": " << Msg << '\n';
51
0
  errs().flush();
52
0
  exit(1);
53
0
}
54
55
Error Config::addSaveTemps(std::string OutputFileName,
56
174
                           bool UseInputModulePath) {
57
174
  ShouldDiscardValueNames = false;
58
174
59
174
  std::error_code EC;
60
174
  ResolutionFile = llvm::make_unique<raw_fd_ostream>(
61
174
      OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::F_Text);
62
174
  if (EC)
63
0
    return errorCodeToError(EC);
64
174
65
1.04k
  
auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) 174
{
66
1.04k
    // Keep track of the hook provided by the linker, which also needs to run.
67
1.04k
    ModuleHookFn LinkerHook = Hook;
68
1.51k
    Hook = [=](unsigned Task, const Module &M) {
69
1.51k
      // If the linker's hook returned false, we need to pass that result
70
1.51k
      // through.
71
1.51k
      if (LinkerHook && 
!LinkerHook(Task, M)0
)
72
0
        return false;
73
1.51k
74
1.51k
      std::string PathPrefix;
75
1.51k
      // If this is the combined module (not a ThinLTO backend compile) or the
76
1.51k
      // user hasn't requested using the input module's path, emit to a file
77
1.51k
      // named from the provided OutputFileName with the Task ID appended.
78
1.51k
      if (M.getModuleIdentifier() == "ld-temp.o" || 
!UseInputModulePath837
) {
79
1.40k
        PathPrefix = OutputFileName;
80
1.40k
        if (Task != (unsigned)-1)
81
1.37k
          PathPrefix += utostr(Task) + ".";
82
1.40k
      } else
83
119
        PathPrefix = M.getModuleIdentifier() + ".";
84
1.51k
      std::string Path = PathPrefix + PathSuffix + ".bc";
85
1.51k
      std::error_code EC;
86
1.51k
      raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
87
1.51k
      // Because -save-temps is a debugging feature, we report the error
88
1.51k
      // directly and exit.
89
1.51k
      if (EC)
90
0
        reportOpenError(Path, EC.message());
91
1.51k
      WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false);
92
1.51k
      return true;
93
1.51k
    };
94
1.04k
  };
95
174
96
174
  setHook("0.preopt", PreOptModuleHook);
97
174
  setHook("1.promote", PostPromoteModuleHook);
98
174
  setHook("2.internalize", PostInternalizeModuleHook);
99
174
  setHook("3.import", PostImportModuleHook);
100
174
  setHook("4.opt", PostOptModuleHook);
101
174
  setHook("5.precodegen", PreCodeGenModuleHook);
102
174
103
174
  CombinedIndexHook = [=](const ModuleSummaryIndex &Index) {
104
84
    std::string Path = OutputFileName + "index.bc";
105
84
    std::error_code EC;
106
84
    raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::F_None);
107
84
    // Because -save-temps is a debugging feature, we report the error
108
84
    // directly and exit.
109
84
    if (EC)
110
0
      reportOpenError(Path, EC.message());
111
84
    WriteIndexToFile(Index, OS);
112
84
113
84
    Path = OutputFileName + "index.dot";
114
84
    raw_fd_ostream OSDot(Path, EC, sys::fs::OpenFlags::F_None);
115
84
    if (EC)
116
0
      reportOpenError(Path, EC.message());
117
84
    Index.exportToDot(OSDot);
118
84
    return true;
119
84
  };
120
174
121
174
  return Error::success();
122
174
}
123
124
namespace {
125
126
std::unique_ptr<TargetMachine>
127
723
createTargetMachine(Config &Conf, const Target *TheTarget, Module &M) {
128
723
  StringRef TheTriple = M.getTargetTriple();
129
723
  SubtargetFeatures Features;
130
723
  Features.getDefaultSubtargetFeatures(Triple(TheTriple));
131
723
  for (const std::string &A : Conf.MAttrs)
132
191
    Features.AddFeature(A);
133
723
134
723
  Reloc::Model RelocModel;
135
723
  if (Conf.RelocModel)
136
722
    RelocModel = *Conf.RelocModel;
137
1
  else
138
1
    RelocModel =
139
18.4E
        M.getPICLevel() == PICLevel::NotPIC ? 
Reloc::Static18
: Reloc::PIC_;
140
723
141
723
  Optional<CodeModel::Model> CodeModel;
142
723
  if (Conf.CodeModel)
143
4
    CodeModel = *Conf.CodeModel;
144
719
  else
145
719
    CodeModel = M.getCodeModel();
146
723
147
723
  return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
148
723
      TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
149
723
      CodeModel, Conf.CGOptLevel));
150
723
}
151
152
static void runNewPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
153
                           unsigned OptLevel, bool IsThinLTO,
154
                           ModuleSummaryIndex *ExportSummary,
155
29
                           const ModuleSummaryIndex *ImportSummary) {
156
29
  Optional<PGOOptions> PGOOpt;
157
29
  if (!Conf.SampleProfile.empty())
158
3
    PGOOpt = PGOOptions(Conf.SampleProfile, "", Conf.ProfileRemapping,
159
3
                        PGOOptions::SampleUse, PGOOptions::NoCSAction, true);
160
26
  else if (Conf.RunCSIRInstr) {
161
1
    PGOOpt = PGOOptions("", Conf.CSIRProfile, Conf.ProfileRemapping,
162
1
                        PGOOptions::IRUse, PGOOptions::CSIRInstr);
163
25
  } else if (!Conf.CSIRProfile.empty()) {
164
1
    PGOOpt = PGOOptions(Conf.CSIRProfile, "", Conf.ProfileRemapping,
165
1
                        PGOOptions::IRUse, PGOOptions::CSIRUse);
166
1
  }
167
29
168
29
  PassBuilder PB(TM, PipelineTuningOptions(), PGOOpt);
169
29
  AAManager AA;
170
29
171
29
  // Parse a custom AA pipeline if asked to.
172
29
  if (auto Err = PB.parseAAPipeline(AA, "default"))
173
0
    report_fatal_error("Error parsing default AA pipeline");
174
29
175
29
  LoopAnalysisManager LAM(Conf.DebugPassManager);
176
29
  FunctionAnalysisManager FAM(Conf.DebugPassManager);
177
29
  CGSCCAnalysisManager CGAM(Conf.DebugPassManager);
178
29
  ModuleAnalysisManager MAM(Conf.DebugPassManager);
179
29
180
29
  // Register the AA manager first so that our version is the one used.
181
29
  FAM.registerPass([&] { return std::move(AA); });
182
29
183
29
  // Register all the basic analyses with the managers.
184
29
  PB.registerModuleAnalyses(MAM);
185
29
  PB.registerCGSCCAnalyses(CGAM);
186
29
  PB.registerFunctionAnalyses(FAM);
187
29
  PB.registerLoopAnalyses(LAM);
188
29
  PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
189
29
190
29
  ModulePassManager MPM(Conf.DebugPassManager);
191
29
  // FIXME (davide): verify the input.
192
29
193
29
  PassBuilder::OptimizationLevel OL;
194
29
195
29
  switch (OptLevel) {
196
29
  default:
197
0
    llvm_unreachable("Invalid optimization level");
198
29
  case 0:
199
1
    OL = PassBuilder::O0;
200
1
    break;
201
29
  case 1:
202
0
    OL = PassBuilder::O1;
203
0
    break;
204
29
  case 2:
205
28
    OL = PassBuilder::O2;
206
28
    break;
207
29
  case 3:
208
0
    OL = PassBuilder::O3;
209
0
    break;
210
29
  }
211
29
212
29
  if (IsThinLTO)
213
15
    MPM = PB.buildThinLTODefaultPipeline(OL, Conf.DebugPassManager,
214
15
                                         ImportSummary);
215
14
  else
216
14
    MPM = PB.buildLTODefaultPipeline(OL, Conf.DebugPassManager, ExportSummary);
217
29
  MPM.run(Mod, MAM);
218
29
219
29
  // FIXME (davide): verify the output.
220
29
}
221
222
static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
223
                                 std::string PipelineDesc,
224
                                 std::string AAPipelineDesc,
225
9
                                 bool DisableVerify) {
226
9
  PassBuilder PB(TM);
227
9
  AAManager AA;
228
9
229
9
  // Parse a custom AA pipeline if asked to.
230
9
  if (!AAPipelineDesc.empty())
231
4
    if (auto Err = PB.parseAAPipeline(AA, AAPipelineDesc))
232
2
      report_fatal_error("unable to parse AA pipeline description '" +
233
2
                         AAPipelineDesc + "': " + toString(std::move(Err)));
234
7
235
7
  LoopAnalysisManager LAM;
236
7
  FunctionAnalysisManager FAM;
237
7
  CGSCCAnalysisManager CGAM;
238
7
  ModuleAnalysisManager MAM;
239
7
240
7
  // Register the AA manager first so that our version is the one used.
241
7
  FAM.registerPass([&] { return std::move(AA); });
242
7
243
7
  // Register all the basic analyses with the managers.
244
7
  PB.registerModuleAnalyses(MAM);
245
7
  PB.registerCGSCCAnalyses(CGAM);
246
7
  PB.registerFunctionAnalyses(FAM);
247
7
  PB.registerLoopAnalyses(LAM);
248
7
  PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
249
7
250
7
  ModulePassManager MPM;
251
7
252
7
  // Always verify the input.
253
7
  MPM.addPass(VerifierPass());
254
7
255
7
  // Now, add all the passes we've been requested to.
256
7
  if (auto Err = PB.parsePassPipeline(MPM, PipelineDesc))
257
2
    report_fatal_error("unable to parse pass pipeline description '" +
258
2
                       PipelineDesc + "': " + toString(std::move(Err)));
259
5
260
5
  if (!DisableVerify)
261
5
    MPM.addPass(VerifierPass());
262
5
  MPM.run(Mod, MAM);
263
5
}
264
265
static void runOldPMPasses(Config &Conf, Module &Mod, TargetMachine *TM,
266
                           bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
267
696
                           const ModuleSummaryIndex *ImportSummary) {
268
696
  legacy::PassManager passes;
269
696
  passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
270
696
271
696
  PassManagerBuilder PMB;
272
696
  PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
273
696
  PMB.Inliner = createFunctionInliningPass();
274
696
  PMB.ExportSummary = ExportSummary;
275
696
  PMB.ImportSummary = ImportSummary;
276
696
  // Unconditionally verify input since it is not verified before this
277
696
  // point and has unknown origin.
278
696
  PMB.VerifyInput = true;
279
696
  PMB.VerifyOutput = !Conf.DisableVerify;
280
696
  PMB.LoopVectorize = true;
281
696
  PMB.SLPVectorize = true;
282
696
  PMB.OptLevel = Conf.OptLevel;
283
696
  PMB.PGOSampleUse = Conf.SampleProfile;
284
696
  PMB.EnablePGOCSInstrGen = Conf.RunCSIRInstr;
285
696
  if (!Conf.RunCSIRInstr && 
!Conf.CSIRProfile.empty()694
) {
286
4
    PMB.EnablePGOCSInstrUse = true;
287
4
    PMB.PGOInstrUse = Conf.CSIRProfile;
288
4
  }
289
696
  if (IsThinLTO)
290
272
    PMB.populateThinLTOPassManager(passes);
291
424
  else
292
424
    PMB.populateLTOPassManager(passes);
293
696
  passes.run(Mod);
294
696
}
295
296
bool opt(Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
297
         bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
298
733
         const ModuleSummaryIndex *ImportSummary) {
299
733
  // FIXME: Plumb the combined index into the new pass manager.
300
733
  if (!Conf.OptPipeline.empty())
301
9
    runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
302
9
                         Conf.DisableVerify);
303
724
  else if (Conf.UseNewPM)
304
29
    runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
305
29
                   ImportSummary);
306
695
  else
307
695
    runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
308
733
  return !Conf.PostOptModuleHook || 
Conf.PostOptModuleHook(Task, Mod)308
;
309
733
}
310
311
void codegen(Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
312
738
             unsigned Task, Module &Mod) {
313
738
  if (Conf.PreCodeGenModuleHook && 
!Conf.PreCodeGenModuleHook(Task, Mod)323
)
314
11
    return;
315
727
316
727
  std::unique_ptr<ToolOutputFile> DwoOut;
317
727
  SmallString<1024> DwoFile(Conf.SplitDwarfOutput);
318
727
  if (!Conf.DwoDir.empty()) {
319
1
    std::error_code EC;
320
1
    if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
321
0
      report_fatal_error("Failed to create directory " + Conf.DwoDir + ": " +
322
0
                         EC.message());
323
1
324
1
    DwoFile = Conf.DwoDir;
325
1
    sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
326
1
    TM->Options.MCOptions.SplitDwarfFile = DwoFile.str().str();
327
1
  } else
328
726
    TM->Options.MCOptions.SplitDwarfFile = Conf.SplitDwarfFile;
329
727
330
727
  if (!DwoFile.empty()) {
331
2
    std::error_code EC;
332
2
    DwoOut = llvm::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::F_None);
333
2
    if (EC)
334
0
      report_fatal_error("Failed to open " + DwoFile + ": " + EC.message());
335
727
  }
336
727
337
727
  auto Stream = AddStream(Task);
338
727
  legacy::PassManager CodeGenPasses;
339
727
  if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
340
727
                              DwoOut ? 
&DwoOut->os()2
:
nullptr725
,
341
727
                              Conf.CGFileType))
342
0
    report_fatal_error("Failed to setup codegen");
343
727
  CodeGenPasses.run(Mod);
344
727
345
727
  if (DwoOut)
346
2
    DwoOut->keep();
347
727
}
348
349
void splitCodeGen(Config &C, TargetMachine *TM, AddStreamFn AddStream,
350
                  unsigned ParallelCodeGenParallelismLevel,
351
4
                  std::unique_ptr<Module> Mod) {
352
4
  ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
353
4
  unsigned ThreadCount = 0;
354
4
  const Target *T = &TM->getTarget();
355
4
356
4
  SplitModule(
357
4
      std::move(Mod), ParallelCodeGenParallelismLevel,
358
8
      [&](std::unique_ptr<Module> MPart) {
359
8
        // We want to clone the module in a new context to multi-thread the
360
8
        // codegen. We do it by serializing partition modules to bitcode
361
8
        // (while still on the main thread, in order to avoid data races) and
362
8
        // spinning up new threads which deserialize the partitions into
363
8
        // separate contexts.
364
8
        // FIXME: Provide a more direct way to do this in LLVM.
365
8
        SmallString<0> BC;
366
8
        raw_svector_ostream BCOS(BC);
367
8
        WriteBitcodeToFile(*MPart, BCOS);
368
8
369
8
        // Enqueue the task
370
8
        CodegenThreadPool.async(
371
8
            [&](const SmallString<0> &BC, unsigned ThreadId) {
372
8
              LTOLLVMContext Ctx(C);
373
8
              Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
374
8
                  MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
375
8
                  Ctx);
376
8
              if (!MOrErr)
377
0
                report_fatal_error("Failed to read bitcode");
378
8
              std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
379
8
380
8
              std::unique_ptr<TargetMachine> TM =
381
8
                  createTargetMachine(C, T, *MPartInCtx);
382
8
383
8
              codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
384
8
            },
385
8
            // Pass BC using std::move to ensure that it get moved rather than
386
8
            // copied into the thread's context.
387
8
            std::move(BC), ThreadCount++);
388
8
      },
389
4
      false);
390
4
391
4
  // Because the inner lambda (which runs in a worker thread) captures our local
392
4
  // variables, we need to wait for the worker threads to terminate before we
393
4
  // can leave the function scope.
394
4
  CodegenThreadPool.wait();
395
4
}
396
397
728
Expected<const Target *> initAndLookupTarget(Config &C, Module &Mod) {
398
728
  if (!C.OverrideTriple.empty())
399
2
    Mod.setTargetTriple(C.OverrideTriple);
400
726
  else if (Mod.getTargetTriple().empty())
401
0
    Mod.setTargetTriple(C.DefaultTriple);
402
728
403
728
  std::string Msg;
404
728
  const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
405
728
  if (!T)
406
0
    return make_error<StringError>(Msg, inconvertibleErrorCode());
407
728
  return T;
408
728
}
409
410
}
411
412
static Error
413
734
finalizeOptimizationRemarks(std::unique_ptr<ToolOutputFile> DiagOutputFile) {
414
734
  // Make sure we flush the diagnostic remarks file in case the linker doesn't
415
734
  // call the global destructors before exiting.
416
734
  if (!DiagOutputFile)
417
726
    return Error::success();
418
8
  DiagOutputFile->keep();
419
8
  DiagOutputFile->os().flush();
420
8
  return Error::success();
421
8
}
422
423
Error lto::backend(Config &C, AddStreamFn AddStream,
424
                   unsigned ParallelCodeGenParallelismLevel,
425
                   std::unique_ptr<Module> Mod,
426
449
                   ModuleSummaryIndex &CombinedIndex) {
427
449
  Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
428
449
  if (!TOrErr)
429
0
    return TOrErr.takeError();
430
449
431
449
  std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
432
449
433
449
  // Setup optimization remarks.
434
449
  auto DiagFileOrErr = lto::setupOptimizationRemarks(
435
449
      Mod->getContext(), C.RemarksFilename, C.RemarksPasses, C.RemarksFormat,
436
449
      C.RemarksWithHotness);
437
449
  if (!DiagFileOrErr)
438
0
    return DiagFileOrErr.takeError();
439
449
  auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
440
449
441
449
  if (!C.CodeGenOnly) {
442
449
    if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
443
449
             /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr))
444
0
      return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
445
449
  }
446
449
447
449
  if (ParallelCodeGenParallelismLevel == 1) {
448
441
    codegen(C, TM.get(), AddStream, 0, *Mod);
449
441
  } else {
450
8
    splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
451
8
                 std::move(Mod));
452
8
  }
453
449
  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
454
449
}
455
456
static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
457
289
                            const ModuleSummaryIndex &Index) {
458
289
  std::vector<GlobalValue*> DeadGVs;
459
289
  for (auto &GV : Mod.global_values())
460
716
    if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
461
431
      if (!Index.isGlobalValueLive(GVS)) {
462
53
        DeadGVs.push_back(&GV);
463
53
        convertToDeclaration(GV);
464
53
      }
465
289
466
289
  // Now that all dead bodies have been dropped, delete the actual objects
467
289
  // themselves when possible.
468
289
  for (GlobalValue *GV : DeadGVs) {
469
53
    GV->removeDeadConstantUsers();
470
53
    // Might reference something defined in native object (i.e. dropped a
471
53
    // non-prevailing IR def, but we need to keep the declaration).
472
53
    if (GV->use_empty())
473
48
      GV->eraseFromParent();
474
53
  }
475
289
}
476
477
Error lto::thinBackend(Config &Conf, unsigned Task, AddStreamFn AddStream,
478
                       Module &Mod, const ModuleSummaryIndex &CombinedIndex,
479
                       const FunctionImporter::ImportMapTy &ImportList,
480
                       const GVSummaryMapTy &DefinedGlobals,
481
283
                       MapVector<StringRef, BitcodeModule> &ModuleMap) {
482
283
  Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
483
283
  if (!TOrErr)
484
0
    return TOrErr.takeError();
485
283
486
283
  std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
487
283
488
283
  // Setup optimization remarks.
489
283
  auto DiagFileOrErr = lto::setupOptimizationRemarks(
490
283
      Mod.getContext(), Conf.RemarksFilename, Conf.RemarksPasses,
491
283
      Conf.RemarksFormat, Conf.RemarksWithHotness, Task);
492
283
  if (!DiagFileOrErr)
493
0
    return DiagFileOrErr.takeError();
494
283
  auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
495
283
496
283
  if (Conf.CodeGenOnly) {
497
0
    codegen(Conf, TM.get(), AddStream, Task, Mod);
498
0
    return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
499
0
  }
500
283
501
283
  if (Conf.PreOptModuleHook && 
!Conf.PreOptModuleHook(Task, Mod)137
)
502
0
    return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
503
283
504
283
  renameModuleForThinLTO(Mod, CombinedIndex);
505
283
506
283
  dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
507
283
508
283
  thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
509
283
510
283
  if (Conf.PostPromoteModuleHook && 
!Conf.PostPromoteModuleHook(Task, Mod)140
)
511
0
    return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
512
283
513
283
  if (!DefinedGlobals.empty())
514
265
    thinLTOInternalizeModule(Mod, DefinedGlobals);
515
283
516
283
  if (Conf.PostInternalizeModuleHook &&
517
283
      
!Conf.PostInternalizeModuleHook(Task, Mod)140
)
518
1
    return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
519
282
520
282
  auto ModuleLoader = [&](StringRef Identifier) {
521
87
    assert(Mod.getContext().isODRUniquingDebugTypes() &&
522
87
           "ODR Type uniquing should be enabled on the context");
523
87
    auto I = ModuleMap.find(Identifier);
524
87
    assert(I != ModuleMap.end());
525
87
    return I->second.getLazyModule(Mod.getContext(),
526
87
                                   /*ShouldLazyLoadMetadata=*/true,
527
87
                                   /*IsImporting*/ true);
528
87
  };
529
282
530
282
  FunctionImporter Importer(CombinedIndex, ModuleLoader);
531
282
  if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
532
0
    return Err;
533
282
534
282
  if (Conf.PostImportModuleHook && 
!Conf.PostImportModuleHook(Task, Mod)140
)
535
0
    return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
536
282
537
282
  if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
538
282
           /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
539
0
    return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
540
282
541
282
  codegen(Conf, TM.get(), AddStream, Task, Mod);
542
282
  return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
543
282
}