Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CodeGenAction.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CodeGenAction.cpp - LLVM Code Generation Frontend Action ---------===//
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
#include "clang/CodeGen/CodeGenAction.h"
10
#include "CodeGenModule.h"
11
#include "CoverageMappingGen.h"
12
#include "MacroPPCallbacks.h"
13
#include "clang/AST/ASTConsumer.h"
14
#include "clang/AST/ASTContext.h"
15
#include "clang/AST/DeclCXX.h"
16
#include "clang/AST/DeclGroup.h"
17
#include "clang/Basic/DiagnosticFrontend.h"
18
#include "clang/Basic/FileManager.h"
19
#include "clang/Basic/LangStandard.h"
20
#include "clang/Basic/SourceManager.h"
21
#include "clang/Basic/TargetInfo.h"
22
#include "clang/CodeGen/BackendUtil.h"
23
#include "clang/CodeGen/ModuleBuilder.h"
24
#include "clang/Driver/DriverDiagnostic.h"
25
#include "clang/Frontend/CompilerInstance.h"
26
#include "clang/Frontend/FrontendDiagnostic.h"
27
#include "clang/Lex/Preprocessor.h"
28
#include "llvm/ADT/Hashing.h"
29
#include "llvm/Bitcode/BitcodeReader.h"
30
#include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
31
#include "llvm/Demangle/Demangle.h"
32
#include "llvm/IR/DebugInfo.h"
33
#include "llvm/IR/DiagnosticInfo.h"
34
#include "llvm/IR/DiagnosticPrinter.h"
35
#include "llvm/IR/GlobalValue.h"
36
#include "llvm/IR/LLVMContext.h"
37
#include "llvm/IR/LLVMRemarkStreamer.h"
38
#include "llvm/IR/Module.h"
39
#include "llvm/IRReader/IRReader.h"
40
#include "llvm/LTO/LTOBackend.h"
41
#include "llvm/Linker/Linker.h"
42
#include "llvm/Pass.h"
43
#include "llvm/Support/MemoryBuffer.h"
44
#include "llvm/Support/SourceMgr.h"
45
#include "llvm/Support/TimeProfiler.h"
46
#include "llvm/Support/Timer.h"
47
#include "llvm/Support/ToolOutputFile.h"
48
#include "llvm/Support/YAMLTraits.h"
49
#include "llvm/Transforms/IPO/Internalize.h"
50
51
#include <memory>
52
using namespace clang;
53
using namespace llvm;
54
55
#define DEBUG_TYPE "codegenaction"
56
57
namespace clang {
58
  class BackendConsumer;
59
  class ClangDiagnosticHandler final : public DiagnosticHandler {
60
  public:
61
    ClangDiagnosticHandler(const CodeGenOptions &CGOpts, BackendConsumer *BCon)
62
19.3k
        : CodeGenOpts(CGOpts), BackendCon(BCon) {}
63
64
    bool handleDiagnostics(const DiagnosticInfo &DI) override;
65
66
5.08M
    bool isAnalysisRemarkEnabled(StringRef PassName) const override {
67
5.08M
      return CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(PassName);
68
5.08M
    }
69
425k
    bool isMissedOptRemarkEnabled(StringRef PassName) const override {
70
425k
      return CodeGenOpts.OptimizationRemarkMissed.patternMatches(PassName);
71
425k
    }
72
376k
    bool isPassedOptRemarkEnabled(StringRef PassName) const override {
73
376k
      return CodeGenOpts.OptimizationRemark.patternMatches(PassName);
74
376k
    }
75
76
132k
    bool isAnyRemarkEnabled() const override {
77
132k
      return CodeGenOpts.OptimizationRemarkAnalysis.hasValidPattern() ||
78
132k
             
CodeGenOpts.OptimizationRemarkMissed.hasValidPattern()132k
||
79
132k
             
CodeGenOpts.OptimizationRemark.hasValidPattern()132k
;
80
132k
    }
81
82
  private:
83
    const CodeGenOptions &CodeGenOpts;
84
    BackendConsumer *BackendCon;
85
  };
86
87
  static void reportOptRecordError(Error E, DiagnosticsEngine &Diags,
88
2
                                   const CodeGenOptions CodeGenOpts) {
89
2
    handleAllErrors(
90
2
        std::move(E),
91
2
      [&](const LLVMRemarkSetupFileError &E) {
92
0
          Diags.Report(diag::err_cannot_open_file)
93
0
              << CodeGenOpts.OptRecordFile << E.message();
94
0
        },
95
2
      [&](const LLVMRemarkSetupPatternError &E) {
96
1
          Diags.Report(diag::err_drv_optimization_remark_pattern)
97
1
              << E.message() << CodeGenOpts.OptRecordPasses;
98
1
        },
99
2
      [&](const LLVMRemarkSetupFormatError &E) {
100
1
          Diags.Report(diag::err_drv_optimization_remark_format)
101
1
              << CodeGenOpts.OptRecordFormat;
102
1
        });
103
2
    }
104
105
  class BackendConsumer : public ASTConsumer {
106
    using LinkModule = CodeGenAction::LinkModule;
107
108
    virtual void anchor();
109
    DiagnosticsEngine &Diags;
110
    BackendAction Action;
111
    const HeaderSearchOptions &HeaderSearchOpts;
112
    const CodeGenOptions &CodeGenOpts;
113
    const TargetOptions &TargetOpts;
114
    const LangOptions &LangOpts;
115
    std::unique_ptr<raw_pwrite_stream> AsmOutStream;
116
    ASTContext *Context;
117
118
    Timer LLVMIRGeneration;
119
    unsigned LLVMIRGenerationRefCount;
120
121
    /// True if we've finished generating IR. This prevents us from generating
122
    /// additional LLVM IR after emitting output in HandleTranslationUnit. This
123
    /// can happen when Clang plugins trigger additional AST deserialization.
124
    bool IRGenFinished = false;
125
126
    bool TimerIsEnabled = false;
127
128
    std::unique_ptr<CodeGenerator> Gen;
129
130
    SmallVector<LinkModule, 4> LinkModules;
131
132
    // A map from mangled names to their function's source location, used for
133
    // backend diagnostics as the Clang AST may be unavailable. We actually use
134
    // the mangled name's hash as the key because mangled names can be very
135
    // long and take up lots of space. Using a hash can cause name collision,
136
    // but that is rare and the consequences are pointing to a wrong source
137
    // location which is not severe. This is a vector instead of an actual map
138
    // because we optimize for time building this map rather than time
139
    // retrieving an entry, as backend diagnostics are uncommon.
140
    std::vector<std::pair<llvm::hash_code, FullSourceLoc>>
141
        ManglingFullSourceLocs;
142
143
    // This is here so that the diagnostic printer knows the module a diagnostic
144
    // refers to.
145
    llvm::Module *CurLinkModule = nullptr;
146
147
  public:
148
    BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags,
149
                    const HeaderSearchOptions &HeaderSearchOpts,
150
                    const PreprocessorOptions &PPOpts,
151
                    const CodeGenOptions &CodeGenOpts,
152
                    const TargetOptions &TargetOpts,
153
                    const LangOptions &LangOpts, const std::string &InFile,
154
                    SmallVector<LinkModule, 4> LinkModules,
155
                    std::unique_ptr<raw_pwrite_stream> OS, LLVMContext &C,
156
                    CoverageSourceInfo *CoverageInfo = nullptr)
157
        : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
158
          CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
159
          AsmOutStream(std::move(OS)), Context(nullptr),
160
          LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
161
          LLVMIRGenerationRefCount(0),
162
          Gen(CreateLLVMCodeGen(Diags, InFile, HeaderSearchOpts, PPOpts,
163
                                CodeGenOpts, C, CoverageInfo)),
164
19.4k
          LinkModules(std::move(LinkModules)) {
165
19.4k
      TimerIsEnabled = CodeGenOpts.TimePasses;
166
19.4k
      llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
167
19.4k
      llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
168
19.4k
    }
169
170
    // This constructor is used in installing an empty BackendConsumer
171
    // to use the clang diagnostic handler for IR input files. It avoids
172
    // initializing the OS field.
173
    BackendConsumer(BackendAction Action, DiagnosticsEngine &Diags,
174
                    const HeaderSearchOptions &HeaderSearchOpts,
175
                    const PreprocessorOptions &PPOpts,
176
                    const CodeGenOptions &CodeGenOpts,
177
                    const TargetOptions &TargetOpts,
178
                    const LangOptions &LangOpts, llvm::Module *Module,
179
                    SmallVector<LinkModule, 4> LinkModules, LLVMContext &C,
180
                    CoverageSourceInfo *CoverageInfo = nullptr)
181
        : Diags(Diags), Action(Action), HeaderSearchOpts(HeaderSearchOpts),
182
          CodeGenOpts(CodeGenOpts), TargetOpts(TargetOpts), LangOpts(LangOpts),
183
          Context(nullptr),
184
          LLVMIRGeneration("irgen", "LLVM IR Generation Time"),
185
          LLVMIRGenerationRefCount(0),
186
          Gen(CreateLLVMCodeGen(Diags, "", HeaderSearchOpts, PPOpts,
187
                                CodeGenOpts, C, CoverageInfo)),
188
112
          LinkModules(std::move(LinkModules)), CurLinkModule(Module) {
189
112
      TimerIsEnabled = CodeGenOpts.TimePasses;
190
112
      llvm::TimePassesIsEnabled = CodeGenOpts.TimePasses;
191
112
      llvm::TimePassesPerRun = CodeGenOpts.TimePassesPerRun;
192
112
    }
193
96.2k
    llvm::Module *getModule() const { return Gen->GetModule(); }
194
19.3k
    std::unique_ptr<llvm::Module> takeModule() {
195
19.3k
      return std::unique_ptr<llvm::Module>(Gen->ReleaseModule());
196
19.3k
    }
197
198
38
    CodeGenerator *getCodeGenerator() { return Gen.get(); }
199
200
565k
    void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) override {
201
565k
      Gen->HandleCXXStaticMemberVarInstantiation(VD);
202
565k
    }
203
204
19.3k
    void Initialize(ASTContext &Ctx) override {
205
19.3k
      assert(!Context && "initialized multiple times");
206
207
0
      Context = &Ctx;
208
209
19.3k
      if (TimerIsEnabled)
210
14
        LLVMIRGeneration.startTimer();
211
212
19.3k
      Gen->Initialize(Ctx);
213
214
19.3k
      if (TimerIsEnabled)
215
14
        LLVMIRGeneration.stopTimer();
216
19.3k
    }
217
218
16.4M
    bool HandleTopLevelDecl(DeclGroupRef D) override {
219
16.4M
      PrettyStackTraceDecl CrashInfo(*D.begin(), SourceLocation(),
220
16.4M
                                     Context->getSourceManager(),
221
16.4M
                                     "LLVM IR generation of declaration");
222
223
      // Recurse.
224
16.4M
      if (TimerIsEnabled) {
225
86
        LLVMIRGenerationRefCount += 1;
226
86
        if (LLVMIRGenerationRefCount == 1)
227
86
          LLVMIRGeneration.startTimer();
228
86
      }
229
230
16.4M
      Gen->HandleTopLevelDecl(D);
231
232
16.4M
      if (TimerIsEnabled) {
233
86
        LLVMIRGenerationRefCount -= 1;
234
86
        if (LLVMIRGenerationRefCount == 0)
235
86
          LLVMIRGeneration.stopTimer();
236
86
      }
237
238
16.4M
      return true;
239
16.4M
    }
240
241
457k
    void HandleInlineFunctionDefinition(FunctionDecl *D) override {
242
457k
      PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
243
457k
                                     Context->getSourceManager(),
244
457k
                                     "LLVM IR generation of inline function");
245
457k
      if (TimerIsEnabled)
246
0
        LLVMIRGeneration.startTimer();
247
248
457k
      Gen->HandleInlineFunctionDefinition(D);
249
250
457k
      if (TimerIsEnabled)
251
0
        LLVMIRGeneration.stopTimer();
252
457k
    }
253
254
74.7k
    void HandleInterestingDecl(DeclGroupRef D) override {
255
      // Ignore interesting decls from the AST reader after IRGen is finished.
256
74.7k
      if (!IRGenFinished)
257
74.7k
        HandleTopLevelDecl(D);
258
74.7k
    }
259
260
    // Links each entry in LinkModules into our module.  Returns true on error.
261
19.2k
    bool LinkInModules() {
262
19.2k
      for (auto &LM : LinkModules) {
263
8
        if (LM.PropagateAttrs)
264
3
          for (Function &F : *LM.Module) {
265
            // Skip intrinsics. Keep consistent with how intrinsics are created
266
            // in LLVM IR.
267
3
            if (F.isIntrinsic())
268
0
              continue;
269
3
            Gen->CGM().addDefaultFunctionDefinitionAttributes(F);
270
3
          }
271
272
8
        CurLinkModule = LM.Module.get();
273
274
8
        bool Err;
275
8
        if (LM.Internalize) {
276
3
          Err = Linker::linkModules(
277
3
              *getModule(), std::move(LM.Module), LM.LinkFlags,
278
3
              [](llvm::Module &M, const llvm::StringSet<> &GVS) {
279
6
                internalizeModule(M, [&GVS](const llvm::GlobalValue &GV) {
280
6
                  return !GV.hasName() || (GVS.count(GV.getName()) == 0);
281
6
                });
282
3
              });
283
5
        } else {
284
5
          Err = Linker::linkModules(*getModule(), std::move(LM.Module),
285
5
                                    LM.LinkFlags);
286
5
        }
287
288
8
        if (Err)
289
1
          return true;
290
8
      }
291
19.2k
      return false; // success
292
19.2k
    }
293
294
19.4k
    void HandleTranslationUnit(ASTContext &C) override {
295
19.4k
      {
296
19.4k
        llvm::TimeTraceScope TimeScope("Frontend");
297
19.4k
        PrettyStackTraceString CrashInfo("Per-file LLVM IR generation");
298
19.4k
        if (TimerIsEnabled) {
299
14
          LLVMIRGenerationRefCount += 1;
300
14
          if (LLVMIRGenerationRefCount == 1)
301
14
            LLVMIRGeneration.startTimer();
302
14
        }
303
304
19.4k
        Gen->HandleTranslationUnit(C);
305
306
19.4k
        if (TimerIsEnabled) {
307
14
          LLVMIRGenerationRefCount -= 1;
308
14
          if (LLVMIRGenerationRefCount == 0)
309
14
            LLVMIRGeneration.stopTimer();
310
14
        }
311
312
19.4k
        IRGenFinished = true;
313
19.4k
      }
314
315
      // Silently ignore if we weren't initialized for some reason.
316
19.4k
      if (!getModule())
317
204
        return;
318
319
19.2k
      LLVMContext &Ctx = getModule()->getContext();
320
19.2k
      std::unique_ptr<DiagnosticHandler> OldDiagnosticHandler =
321
19.2k
          Ctx.getDiagnosticHandler();
322
19.2k
      Ctx.setDiagnosticHandler(std::make_unique<ClangDiagnosticHandler>(
323
19.2k
        CodeGenOpts, this));
324
325
19.2k
      Expected<std::unique_ptr<llvm::ToolOutputFile>> OptRecordFileOrErr =
326
19.2k
          setupLLVMOptimizationRemarks(
327
19.2k
              Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
328
19.2k
              CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
329
19.2k
              CodeGenOpts.DiagnosticsHotnessThreshold);
330
331
19.2k
      if (Error E = OptRecordFileOrErr.takeError()) {
332
2
        reportOptRecordError(std::move(E), Diags, CodeGenOpts);
333
2
        return;
334
2
      }
335
336
19.2k
      std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
337
19.2k
          std::move(*OptRecordFileOrErr);
338
339
19.2k
      if (OptRecordFile &&
340
19.2k
          
CodeGenOpts.getProfileUse() != CodeGenOptions::ProfileNone7
)
341
1
        Ctx.setDiagnosticsHotnessRequested(true);
342
343
      // Link each LinkModule into our module.
344
19.2k
      if (LinkInModules())
345
1
        return;
346
347
381k
      
for (auto &F : getModule()->functions())19.2k
{
348
381k
        if (const Decl *FD = Gen->GetDeclForMangledName(F.getName())) {
349
271k
          auto Loc = FD->getASTContext().getFullLoc(FD->getLocation());
350
          // TODO: use a fast content hash when available.
351
271k
          auto NameHash = llvm::hash_value(F.getName());
352
271k
          ManglingFullSourceLocs.push_back(std::make_pair(NameHash, Loc));
353
271k
        }
354
381k
      }
355
356
19.2k
      if (CodeGenOpts.ClearASTBeforeBackend) {
357
4.13k
        LLVM_DEBUG(llvm::dbgs() << "Clearing AST...\n");
358
        // Access to the AST is no longer available after this.
359
        // Other things that the ASTContext manages are still available, e.g.
360
        // the SourceManager. It'd be nice if we could separate out all the
361
        // things in ASTContext used after this point and null out the
362
        // ASTContext, but too many various parts of the ASTContext are still
363
        // used in various parts.
364
4.13k
        C.cleanup();
365
4.13k
        C.getAllocator().Reset();
366
4.13k
      }
367
368
19.2k
      EmbedBitcode(getModule(), CodeGenOpts, llvm::MemoryBufferRef());
369
370
19.2k
      EmitBackendOutput(Diags, HeaderSearchOpts, CodeGenOpts, TargetOpts,
371
19.2k
                        LangOpts, C.getTargetInfo().getDataLayoutString(),
372
19.2k
                        getModule(), Action, std::move(AsmOutStream));
373
374
19.2k
      Ctx.setDiagnosticHandler(std::move(OldDiagnosticHandler));
375
376
19.2k
      if (OptRecordFile)
377
7
        OptRecordFile->keep();
378
19.2k
    }
379
380
2.01M
    void HandleTagDeclDefinition(TagDecl *D) override {
381
2.01M
      PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
382
2.01M
                                     Context->getSourceManager(),
383
2.01M
                                     "LLVM IR generation of declaration");
384
2.01M
      Gen->HandleTagDeclDefinition(D);
385
2.01M
    }
386
387
962k
    void HandleTagDeclRequiredDefinition(const TagDecl *D) override {
388
962k
      Gen->HandleTagDeclRequiredDefinition(D);
389
962k
    }
390
391
4.11k
    void CompleteTentativeDefinition(VarDecl *D) override {
392
4.11k
      Gen->CompleteTentativeDefinition(D);
393
4.11k
    }
394
395
7
    void CompleteExternalDeclaration(VarDecl *D) override {
396
7
      Gen->CompleteExternalDeclaration(D);
397
7
    }
398
399
494
    void AssignInheritanceModel(CXXRecordDecl *RD) override {
400
494
      Gen->AssignInheritanceModel(RD);
401
494
    }
402
403
794
    void HandleVTable(CXXRecordDecl *RD) override {
404
794
      Gen->HandleVTable(RD);
405
794
    }
406
407
    /// Get the best possible source location to represent a diagnostic that
408
    /// may have associated debug info.
409
    const FullSourceLoc
410
    getBestLocationFromDebugLoc(const llvm::DiagnosticInfoWithLocationBase &D,
411
                                bool &BadDebugInfo, StringRef &Filename,
412
                                unsigned &Line, unsigned &Column) const;
413
414
    Optional<FullSourceLoc> getFunctionSourceLocation(const Function &F) const;
415
416
    void DiagnosticHandlerImpl(const llvm::DiagnosticInfo &DI);
417
    /// Specialized handler for InlineAsm diagnostic.
418
    /// \return True if the diagnostic has been successfully reported, false
419
    /// otherwise.
420
    bool InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D);
421
    /// Specialized handler for diagnostics reported using SMDiagnostic.
422
    void SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &D);
423
    /// Specialized handler for StackSize diagnostic.
424
    /// \return True if the diagnostic has been successfully reported, false
425
    /// otherwise.
426
    bool StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D);
427
    /// Specialized handler for unsupported backend feature diagnostic.
428
    void UnsupportedDiagHandler(const llvm::DiagnosticInfoUnsupported &D);
429
    /// Specialized handlers for optimization remarks.
430
    /// Note that these handlers only accept remarks and they always handle
431
    /// them.
432
    void EmitOptimizationMessage(const llvm::DiagnosticInfoOptimizationBase &D,
433
                                 unsigned DiagID);
434
    void
435
    OptimizationRemarkHandler(const llvm::DiagnosticInfoOptimizationBase &D);
436
    void OptimizationRemarkHandler(
437
        const llvm::OptimizationRemarkAnalysisFPCommute &D);
438
    void OptimizationRemarkHandler(
439
        const llvm::OptimizationRemarkAnalysisAliasing &D);
440
    void OptimizationFailureHandler(
441
        const llvm::DiagnosticInfoOptimizationFailure &D);
442
    void DontCallDiagHandler(const DiagnosticInfoDontCall &D);
443
  };
444
445
0
  void BackendConsumer::anchor() {}
446
}
447
448
149k
bool ClangDiagnosticHandler::handleDiagnostics(const DiagnosticInfo &DI) {
449
149k
  BackendCon->DiagnosticHandlerImpl(DI);
450
149k
  return true;
451
149k
}
452
453
/// ConvertBackendLocation - Convert a location in a temporary llvm::SourceMgr
454
/// buffer to be a valid FullSourceLoc.
455
static FullSourceLoc ConvertBackendLocation(const llvm::SMDiagnostic &D,
456
9
                                            SourceManager &CSM) {
457
  // Get both the clang and llvm source managers.  The location is relative to
458
  // a memory buffer that the LLVM Source Manager is handling, we need to add
459
  // a copy to the Clang source manager.
460
9
  const llvm::SourceMgr &LSM = *D.getSourceMgr();
461
462
  // We need to copy the underlying LLVM memory buffer because llvm::SourceMgr
463
  // already owns its one and clang::SourceManager wants to own its one.
464
9
  const MemoryBuffer *LBuf =
465
9
  LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(D.getLoc()));
466
467
  // Create the copy and transfer ownership to clang::SourceManager.
468
  // TODO: Avoid copying files into memory.
469
9
  std::unique_ptr<llvm::MemoryBuffer> CBuf =
470
9
      llvm::MemoryBuffer::getMemBufferCopy(LBuf->getBuffer(),
471
9
                                           LBuf->getBufferIdentifier());
472
  // FIXME: Keep a file ID map instead of creating new IDs for each location.
473
9
  FileID FID = CSM.createFileID(std::move(CBuf));
474
475
  // Translate the offset into the file.
476
9
  unsigned Offset = D.getLoc().getPointer() - LBuf->getBufferStart();
477
9
  SourceLocation NewLoc =
478
9
  CSM.getLocForStartOfFile(FID).getLocWithOffset(Offset);
479
9
  return FullSourceLoc(NewLoc, CSM);
480
9
}
481
482
#define ComputeDiagID(Severity, GroupName, DiagID)                             \
483
32
  do {                                                                         \
484
32
    switch (Severity) {                                                        \
485
23
    case llvm::DS_Error:                                                       \
486
23
      DiagID = diag::err_fe_##GroupName;                                       \
487
23
      break;                                                                   \
488
8
    case llvm::DS_Warning:                                                     \
489
8
      DiagID = diag::warn_fe_##GroupName;                                      \
490
8
      break;                                                                   \
491
0
    case llvm::DS_Remark:                                                      \
492
0
      llvm_unreachable("'remark' severity not expected");                      \
493
0
      break;                                                                   \
494
1
    case llvm::DS_Note:                                                        \
495
1
      DiagID = diag::note_fe_##GroupName;                                      \
496
1
      break;                                                                   \
497
32
    }                                                                          \
498
32
  } while (false)
499
500
#define ComputeDiagRemarkID(Severity, GroupName, DiagID)                       \
501
3
  do {                                                                         \
502
3
    switch (Severity) {                                                        \
503
3
    case llvm::DS_Error:                                                       \
504
3
      DiagID = diag::err_fe_##GroupName;                                       \
505
3
      break;                                                                   \
506
0
    case llvm::DS_Warning:                                                     \
507
0
      DiagID = diag::warn_fe_##GroupName;                                      \
508
0
      break;                                                                   \
509
0
    case llvm::DS_Remark:                                                      \
510
0
      DiagID = diag::remark_fe_##GroupName;                                    \
511
0
      break;                                                                   \
512
0
    case llvm::DS_Note:                                                        \
513
0
      DiagID = diag::note_fe_##GroupName;                                      \
514
0
      break;                                                                   \
515
3
    }                                                                          \
516
3
  } while (false)
517
518
10
void BackendConsumer::SrcMgrDiagHandler(const llvm::DiagnosticInfoSrcMgr &DI) {
519
10
  const llvm::SMDiagnostic &D = DI.getSMDiag();
520
521
10
  unsigned DiagID;
522
10
  if (DI.isInlineAsmDiag())
523
10
    ComputeDiagID(DI.getSeverity(), inline_asm, DiagID);
524
0
  else
525
0
    ComputeDiagID(DI.getSeverity(), source_mgr, DiagID);
526
527
  // This is for the empty BackendConsumer that uses the clang diagnostic
528
  // handler for IR input files.
529
10
  if (!Context) {
530
1
    D.print(nullptr, llvm::errs());
531
1
    Diags.Report(DiagID).AddString("cannot compile inline asm");
532
1
    return;
533
1
  }
534
535
  // There are a couple of different kinds of errors we could get here.
536
  // First, we re-format the SMDiagnostic in terms of a clang diagnostic.
537
538
  // Strip "error: " off the start of the message string.
539
9
  StringRef Message = D.getMessage();
540
9
  (void)Message.consume_front("error: ");
541
542
  // If the SMDiagnostic has an inline asm source location, translate it.
543
9
  FullSourceLoc Loc;
544
9
  if (D.getLoc() != SMLoc())
545
9
    Loc = ConvertBackendLocation(D, Context->getSourceManager());
546
547
  // If this problem has clang-level source location information, report the
548
  // issue in the source with a note showing the instantiated
549
  // code.
550
9
  if (DI.isInlineAsmDiag()) {
551
9
    SourceLocation LocCookie =
552
9
        SourceLocation::getFromRawEncoding(DI.getLocCookie());
553
9
    if (LocCookie.isValid()) {
554
8
      Diags.Report(LocCookie, DiagID).AddString(Message);
555
556
8
      if (D.getLoc().isValid()) {
557
8
        DiagnosticBuilder B = Diags.Report(Loc, diag::note_fe_inline_asm_here);
558
        // Convert the SMDiagnostic ranges into SourceRange and attach them
559
        // to the diagnostic.
560
8
        for (const std::pair<unsigned, unsigned> &Range : D.getRanges()) {
561
1
          unsigned Column = D.getColumnNo();
562
1
          B << SourceRange(Loc.getLocWithOffset(Range.first - Column),
563
1
                           Loc.getLocWithOffset(Range.second - Column));
564
1
        }
565
8
      }
566
8
      return;
567
8
    }
568
9
  }
569
570
  // Otherwise, report the backend issue as occurring in the generated .s file.
571
  // If Loc is invalid, we still need to report the issue, it just gets no
572
  // location info.
573
1
  Diags.Report(Loc, DiagID).AddString(Message);
574
1
}
575
576
bool
577
19
BackendConsumer::InlineAsmDiagHandler(const llvm::DiagnosticInfoInlineAsm &D) {
578
19
  unsigned DiagID;
579
19
  ComputeDiagID(D.getSeverity(), inline_asm, DiagID);
580
19
  std::string Message = D.getMsgStr().str();
581
582
  // If this problem has clang-level source location information, report the
583
  // issue as being a problem in the source with a note showing the instantiated
584
  // code.
585
19
  SourceLocation LocCookie =
586
19
      SourceLocation::getFromRawEncoding(D.getLocCookie());
587
19
  if (LocCookie.isValid())
588
19
    Diags.Report(LocCookie, DiagID).AddString(Message);
589
0
  else {
590
    // Otherwise, report the backend diagnostic as occurring in the generated
591
    // .s file.
592
    // If Loc is invalid, we still need to report the diagnostic, it just gets
593
    // no location info.
594
0
    FullSourceLoc Loc;
595
0
    Diags.Report(Loc, DiagID).AddString(Message);
596
0
  }
597
  // We handled all the possible severities.
598
19
  return true;
599
19
}
600
601
bool
602
14
BackendConsumer::StackSizeDiagHandler(const llvm::DiagnosticInfoStackSize &D) {
603
14
  if (D.getSeverity() != llvm::DS_Warning)
604
    // For now, the only support we have for StackSize diagnostic is warning.
605
    // We do not know how to format other severities.
606
0
    return false;
607
608
14
  auto Loc = getFunctionSourceLocation(D.getFunction());
609
14
  if (!Loc)
610
1
    return false;
611
612
  // FIXME: Shouldn't need to truncate to uint32_t
613
13
  Diags.Report(*Loc, diag::warn_fe_frame_larger_than)
614
13
      << static_cast<uint32_t>(D.getStackSize())
615
13
      << static_cast<uint32_t>(D.getStackLimit())
616
13
      << llvm::demangle(D.getFunction().getName().str());
617
13
  return true;
618
14
}
619
620
const FullSourceLoc BackendConsumer::getBestLocationFromDebugLoc(
621
    const llvm::DiagnosticInfoWithLocationBase &D, bool &BadDebugInfo,
622
123
    StringRef &Filename, unsigned &Line, unsigned &Column) const {
623
123
  SourceManager &SourceMgr = Context->getSourceManager();
624
123
  FileManager &FileMgr = SourceMgr.getFileManager();
625
123
  SourceLocation DILoc;
626
627
123
  if (D.isLocationAvailable()) {
628
100
    D.getLocation(Filename, Line, Column);
629
100
    if (Line > 0) {
630
100
      auto FE = FileMgr.getFile(Filename);
631
100
      if (!FE)
632
100
        FE = FileMgr.getFile(D.getAbsolutePath());
633
100
      if (FE) {
634
        // If -gcolumn-info was not used, Column will be 0. This upsets the
635
        // source manager, so pass 1 if Column is not set.
636
99
        DILoc = SourceMgr.translateFileLineCol(*FE, Line, Column ? 
Column73
:
126
);
637
99
      }
638
100
    }
639
100
    BadDebugInfo = DILoc.isInvalid();
640
100
  }
641
642
  // If a location isn't available, try to approximate it using the associated
643
  // function definition. We use the definition's right brace to differentiate
644
  // from diagnostics that genuinely relate to the function itself.
645
123
  FullSourceLoc Loc(DILoc, SourceMgr);
646
123
  if (Loc.isInvalid()) {
647
24
    if (auto MaybeLoc = getFunctionSourceLocation(D.getFunction()))
648
24
      Loc = *MaybeLoc;
649
24
  }
650
651
123
  if (DILoc.isInvalid() && 
D.isLocationAvailable()24
)
652
    // If we were not able to translate the file:line:col information
653
    // back to a SourceLocation, at least emit a note stating that
654
    // we could not translate this location. This can happen in the
655
    // case of #line directives.
656
1
    Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
657
1
        << Filename << Line << Column;
658
659
123
  return Loc;
660
123
}
661
662
Optional<FullSourceLoc>
663
38
BackendConsumer::getFunctionSourceLocation(const Function &F) const {
664
38
  auto Hash = llvm::hash_value(F.getName());
665
108
  for (const auto &Pair : ManglingFullSourceLocs) {
666
108
    if (Pair.first == Hash)
667
37
      return Pair.second;
668
108
  }
669
1
  return Optional<FullSourceLoc>();
670
38
}
671
672
void BackendConsumer::UnsupportedDiagHandler(
673
5
    const llvm::DiagnosticInfoUnsupported &D) {
674
  // We only support warnings or errors.
675
5
  assert(D.getSeverity() == llvm::DS_Error ||
676
5
         D.getSeverity() == llvm::DS_Warning);
677
678
0
  StringRef Filename;
679
5
  unsigned Line, Column;
680
5
  bool BadDebugInfo = false;
681
5
  FullSourceLoc Loc;
682
5
  std::string Msg;
683
5
  raw_string_ostream MsgStream(Msg);
684
685
  // Context will be nullptr for IR input files, we will construct the diag
686
  // message from llvm::DiagnosticInfoUnsupported.
687
5
  if (Context != nullptr) {
688
5
    Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
689
5
    MsgStream << D.getMessage();
690
5
  } else {
691
0
    DiagnosticPrinterRawOStream DP(MsgStream);
692
0
    D.print(DP);
693
0
  }
694
695
5
  auto DiagType = D.getSeverity() == llvm::DS_Error
696
5
                      ? diag::err_fe_backend_unsupported
697
5
                      : 
diag::warn_fe_backend_unsupported0
;
698
5
  Diags.Report(Loc, DiagType) << MsgStream.str();
699
700
5
  if (BadDebugInfo)
701
    // If we were not able to translate the file:line:col information
702
    // back to a SourceLocation, at least emit a note stating that
703
    // we could not translate this location. This can happen in the
704
    // case of #line directives.
705
0
    Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
706
0
        << Filename << Line << Column;
707
5
}
708
709
void BackendConsumer::EmitOptimizationMessage(
710
125
    const llvm::DiagnosticInfoOptimizationBase &D, unsigned DiagID) {
711
  // We only support warnings and remarks.
712
125
  assert(D.getSeverity() == llvm::DS_Remark ||
713
125
         D.getSeverity() == llvm::DS_Warning);
714
715
0
  StringRef Filename;
716
125
  unsigned Line, Column;
717
125
  bool BadDebugInfo = false;
718
125
  FullSourceLoc Loc;
719
125
  std::string Msg;
720
125
  raw_string_ostream MsgStream(Msg);
721
722
  // Context will be nullptr for IR input files, we will construct the remark
723
  // message from llvm::DiagnosticInfoOptimizationBase.
724
125
  if (Context != nullptr) {
725
118
    Loc = getBestLocationFromDebugLoc(D, BadDebugInfo, Filename, Line, Column);
726
118
    MsgStream << D.getMsg();
727
118
  } else {
728
7
    DiagnosticPrinterRawOStream DP(MsgStream);
729
7
    D.print(DP);
730
7
  }
731
732
125
  if (D.getHotness())
733
20
    MsgStream << " (hotness: " << *D.getHotness() << ")";
734
735
125
  Diags.Report(Loc, DiagID)
736
125
      << AddFlagValue(D.getPassName())
737
125
      << MsgStream.str();
738
739
125
  if (BadDebugInfo)
740
    // If we were not able to translate the file:line:col information
741
    // back to a SourceLocation, at least emit a note stating that
742
    // we could not translate this location. This can happen in the
743
    // case of #line directives.
744
1
    Diags.Report(Loc, diag::note_fe_backend_invalid_loc)
745
1
        << Filename << Line << Column;
746
125
}
747
748
void BackendConsumer::OptimizationRemarkHandler(
749
149k
    const llvm::DiagnosticInfoOptimizationBase &D) {
750
  // Without hotness information, don't show noisy remarks.
751
149k
  if (D.isVerbose() && 
!D.getHotness()488
)
752
486
    return;
753
754
149k
  if (D.isPassed()) {
755
    // Optimization remarks are active only if the -Rpass flag has a regular
756
    // expression that matches the name of the pass name in \p D.
757
207
    if (CodeGenOpts.OptimizationRemark.patternMatches(D.getPassName()))
758
64
      EmitOptimizationMessage(D, diag::remark_fe_backend_optimization_remark);
759
148k
  } else if (D.isMissed()) {
760
    // Missed optimization remarks are active only if the -Rpass-missed
761
    // flag has a regular expression that matches the name of the pass
762
    // name in \p D.
763
49.5k
    if (CodeGenOpts.OptimizationRemarkMissed.patternMatches(D.getPassName()))
764
17
      EmitOptimizationMessage(
765
17
          D, diag::remark_fe_backend_optimization_remark_missed);
766
99.2k
  } else {
767
99.2k
    assert(D.isAnalysis() && "Unknown remark type");
768
769
0
    bool ShouldAlwaysPrint = false;
770
99.2k
    if (auto *ORA = dyn_cast<llvm::OptimizationRemarkAnalysis>(&D))
771
55
      ShouldAlwaysPrint = ORA->shouldAlwaysPrint();
772
773
99.2k
    if (ShouldAlwaysPrint ||
774
99.2k
        
CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName())99.2k
)
775
38
      EmitOptimizationMessage(
776
38
          D, diag::remark_fe_backend_optimization_remark_analysis);
777
99.2k
  }
778
149k
}
779
780
void BackendConsumer::OptimizationRemarkHandler(
781
1
    const llvm::OptimizationRemarkAnalysisFPCommute &D) {
782
  // Optimization analysis remarks are active if the pass name is set to
783
  // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
784
  // regular expression that matches the name of the pass name in \p D.
785
786
1
  if (D.shouldAlwaysPrint() ||
787
1
      CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
788
1
    EmitOptimizationMessage(
789
1
        D, diag::remark_fe_backend_optimization_remark_analysis_fpcommute);
790
1
}
791
792
void BackendConsumer::OptimizationRemarkHandler(
793
1
    const llvm::OptimizationRemarkAnalysisAliasing &D) {
794
  // Optimization analysis remarks are active if the pass name is set to
795
  // llvm::DiagnosticInfo::AlwasyPrint or if the -Rpass-analysis flag has a
796
  // regular expression that matches the name of the pass name in \p D.
797
798
1
  if (D.shouldAlwaysPrint() ||
799
1
      CodeGenOpts.OptimizationRemarkAnalysis.patternMatches(D.getPassName()))
800
1
    EmitOptimizationMessage(
801
1
        D, diag::remark_fe_backend_optimization_remark_analysis_aliasing);
802
1
}
803
804
void BackendConsumer::OptimizationFailureHandler(
805
4
    const llvm::DiagnosticInfoOptimizationFailure &D) {
806
4
  EmitOptimizationMessage(D, diag::warn_fe_backend_optimization_failure);
807
4
}
808
809
38
void BackendConsumer::DontCallDiagHandler(const DiagnosticInfoDontCall &D) {
810
38
  SourceLocation LocCookie =
811
38
      SourceLocation::getFromRawEncoding(D.getLocCookie());
812
813
  // FIXME: we can't yet diagnose indirect calls. When/if we can, we
814
  // should instead assert that LocCookie.isValid().
815
38
  if (!LocCookie.isValid())
816
1
    return;
817
818
37
  Diags.Report(LocCookie, D.getSeverity() == DiagnosticSeverity::DS_Error
819
37
                              ? 
diag::err_fe_backend_error_attr25
820
37
                              : 
diag::warn_fe_backend_warning_attr12
)
821
37
      << llvm::demangle(D.getFunctionName().str()) << D.getNote();
822
37
}
823
824
/// This function is invoked when the backend needs
825
/// to report something to the user.
826
149k
void BackendConsumer::DiagnosticHandlerImpl(const DiagnosticInfo &DI) {
827
149k
  unsigned DiagID = diag::err_fe_inline_asm;
828
149k
  llvm::DiagnosticSeverity Severity = DI.getSeverity();
829
  // Get the diagnostic ID based.
830
149k
  switch (DI.getKind()) {
831
19
  case llvm::DK_InlineAsm:
832
19
    if (InlineAsmDiagHandler(cast<DiagnosticInfoInlineAsm>(DI)))
833
19
      return;
834
0
    ComputeDiagID(Severity, inline_asm, DiagID);
835
0
    break;
836
10
  case llvm::DK_SrcMgr:
837
10
    SrcMgrDiagHandler(cast<DiagnosticInfoSrcMgr>(DI));
838
10
    return;
839
14
  case llvm::DK_StackSize:
840
14
    if (StackSizeDiagHandler(cast<DiagnosticInfoStackSize>(DI)))
841
13
      return;
842
1
    ComputeDiagID(Severity, backend_frame_larger_than, DiagID);
843
1
    break;
844
2
  case DK_Linker:
845
2
    ComputeDiagID(Severity, linking_module, DiagID);
846
2
    break;
847
207
  case llvm::DK_OptimizationRemark:
848
    // Optimization remarks are always handled completely by this
849
    // handler. There is no generic way of emitting them.
850
207
    OptimizationRemarkHandler(cast<OptimizationRemark>(DI));
851
207
    return;
852
50.0k
  case llvm::DK_OptimizationRemarkMissed:
853
    // Optimization remarks are always handled completely by this
854
    // handler. There is no generic way of emitting them.
855
50.0k
    OptimizationRemarkHandler(cast<OptimizationRemarkMissed>(DI));
856
50.0k
    return;
857
55
  case llvm::DK_OptimizationRemarkAnalysis:
858
    // Optimization remarks are always handled completely by this
859
    // handler. There is no generic way of emitting them.
860
55
    OptimizationRemarkHandler(cast<OptimizationRemarkAnalysis>(DI));
861
55
    return;
862
1
  case llvm::DK_OptimizationRemarkAnalysisFPCommute:
863
    // Optimization remarks are always handled completely by this
864
    // handler. There is no generic way of emitting them.
865
1
    OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisFPCommute>(DI));
866
1
    return;
867
1
  case llvm::DK_OptimizationRemarkAnalysisAliasing:
868
    // Optimization remarks are always handled completely by this
869
    // handler. There is no generic way of emitting them.
870
1
    OptimizationRemarkHandler(cast<OptimizationRemarkAnalysisAliasing>(DI));
871
1
    return;
872
0
  case llvm::DK_MachineOptimizationRemark:
873
    // Optimization remarks are always handled completely by this
874
    // handler. There is no generic way of emitting them.
875
0
    OptimizationRemarkHandler(cast<MachineOptimizationRemark>(DI));
876
0
    return;
877
24
  case llvm::DK_MachineOptimizationRemarkMissed:
878
    // Optimization remarks are always handled completely by this
879
    // handler. There is no generic way of emitting them.
880
24
    OptimizationRemarkHandler(cast<MachineOptimizationRemarkMissed>(DI));
881
24
    return;
882
99.1k
  case llvm::DK_MachineOptimizationRemarkAnalysis:
883
    // Optimization remarks are always handled completely by this
884
    // handler. There is no generic way of emitting them.
885
99.1k
    OptimizationRemarkHandler(cast<MachineOptimizationRemarkAnalysis>(DI));
886
99.1k
    return;
887
4
  case llvm::DK_OptimizationFailure:
888
    // Optimization failures are always handled completely by this
889
    // handler.
890
4
    OptimizationFailureHandler(cast<DiagnosticInfoOptimizationFailure>(DI));
891
4
    return;
892
5
  case llvm::DK_Unsupported:
893
5
    UnsupportedDiagHandler(cast<DiagnosticInfoUnsupported>(DI));
894
5
    return;
895
38
  case llvm::DK_DontCall:
896
38
    DontCallDiagHandler(cast<DiagnosticInfoDontCall>(DI));
897
38
    return;
898
3
  default:
899
    // Plugin IDs are not bound to any value as they are set dynamically.
900
3
    ComputeDiagRemarkID(Severity, backend_plugin, DiagID);
901
3
    break;
902
149k
  }
903
6
  std::string MsgStorage;
904
6
  {
905
6
    raw_string_ostream Stream(MsgStorage);
906
6
    DiagnosticPrinterRawOStream DP(Stream);
907
6
    DI.print(DP);
908
6
  }
909
910
6
  if (DI.getKind() == DK_Linker) {
911
2
    assert(CurLinkModule && "CurLinkModule must be set for linker diagnostics");
912
0
    Diags.Report(DiagID) << CurLinkModule->getModuleIdentifier() << MsgStorage;
913
2
    return;
914
2
  }
915
916
  // Report the backend message using the usual diagnostic mechanism.
917
4
  FullSourceLoc Loc;
918
4
  Diags.Report(Loc, DiagID).AddString(MsgStorage);
919
4
}
920
#undef ComputeDiagID
921
922
CodeGenAction::CodeGenAction(unsigned _Act, LLVMContext *_VMContext)
923
    : Act(_Act), VMContext(_VMContext ? _VMContext : new LLVMContext),
924
19.5k
      OwnsVMContext(!_VMContext) {}
925
926
15.2k
CodeGenAction::~CodeGenAction() {
927
15.2k
  TheModule.reset();
928
15.2k
  if (OwnsVMContext)
929
15.2k
    delete VMContext;
930
15.2k
}
931
932
146
bool CodeGenAction::hasIRSupport() const { return true; }
933
934
19.5k
void CodeGenAction::EndSourceFileAction() {
935
  // If the consumer creation failed, do nothing.
936
19.5k
  if (!getCompilerInstance().hasASTConsumer())
937
113
    return;
938
939
  // Steal the module from the consumer.
940
19.3k
  TheModule = BEConsumer->takeModule();
941
19.3k
}
942
943
0
std::unique_ptr<llvm::Module> CodeGenAction::takeModule() {
944
0
  return std::move(TheModule);
945
0
}
946
947
0
llvm::LLVMContext *CodeGenAction::takeLLVMContext() {
948
0
  OwnsVMContext = false;
949
0
  return VMContext;
950
0
}
951
952
33
CodeGenerator *CodeGenAction::getCodeGenerator() const {
953
33
  return BEConsumer->getCodeGenerator();
954
33
}
955
956
static std::unique_ptr<raw_pwrite_stream>
957
19.5k
GetOutputStream(CompilerInstance &CI, StringRef InFile, BackendAction Action) {
958
19.5k
  switch (Action) {
959
523
  case Backend_EmitAssembly:
960
523
    return CI.createDefaultOutputFile(false, InFile, "s");
961
14.6k
  case Backend_EmitLL:
962
14.6k
    return CI.createDefaultOutputFile(false, InFile, "ll");
963
553
  case Backend_EmitBC:
964
553
    return CI.createDefaultOutputFile(true, InFile, "bc");
965
257
  case Backend_EmitNothing:
966
257
    return nullptr;
967
8
  case Backend_EmitMCNull:
968
8
    return CI.createNullOutputFile();
969
3.54k
  case Backend_EmitObj:
970
3.54k
    return CI.createDefaultOutputFile(true, InFile, "o");
971
19.5k
  }
972
973
0
  llvm_unreachable("Invalid action!");
974
0
}
975
976
std::unique_ptr<ASTConsumer>
977
19.4k
CodeGenAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
978
19.4k
  BackendAction BA = static_cast<BackendAction>(Act);
979
19.4k
  std::unique_ptr<raw_pwrite_stream> OS = CI.takeOutputStream();
980
19.4k
  if (!OS)
981
19.4k
    OS = GetOutputStream(CI, InFile, BA);
982
983
19.4k
  if (BA != Backend_EmitNothing && 
!OS19.1k
)
984
2
    return nullptr;
985
986
  // Load bitcode modules to link with, if we need to.
987
19.4k
  if (LinkModules.empty())
988
19.4k
    for (const CodeGenOptions::BitcodeFileToLink &F :
989
19.4k
         CI.getCodeGenOpts().LinkBitcodeFiles) {
990
9
      auto BCBuf = CI.getFileManager().getBufferForFile(F.Filename);
991
9
      if (!BCBuf) {
992
1
        CI.getDiagnostics().Report(diag::err_cannot_open_file)
993
1
            << F.Filename << BCBuf.getError().message();
994
1
        LinkModules.clear();
995
1
        return nullptr;
996
1
      }
997
998
8
      Expected<std::unique_ptr<llvm::Module>> ModuleOrErr =
999
8
          getOwningLazyBitcodeModule(std::move(*BCBuf), *VMContext);
1000
8
      if (!ModuleOrErr) {
1001
0
        handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
1002
0
          CI.getDiagnostics().Report(diag::err_cannot_open_file)
1003
0
              << F.Filename << EIB.message();
1004
0
        });
1005
0
        LinkModules.clear();
1006
0
        return nullptr;
1007
0
      }
1008
8
      LinkModules.push_back({std::move(ModuleOrErr.get()), F.PropagateAttrs,
1009
8
                             F.Internalize, F.LinkFlags});
1010
8
    }
1011
1012
19.4k
  CoverageSourceInfo *CoverageInfo = nullptr;
1013
  // Add the preprocessor callback only when the coverage mapping is generated.
1014
19.4k
  if (CI.getCodeGenOpts().CoverageMapping)
1015
80
    CoverageInfo = CodeGen::CoverageMappingModuleGen::setUpCoverageCallbacks(
1016
80
        CI.getPreprocessor());
1017
1018
19.4k
  std::unique_ptr<BackendConsumer> Result(new BackendConsumer(
1019
19.4k
      BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
1020
19.4k
      CI.getPreprocessorOpts(), CI.getCodeGenOpts(), CI.getTargetOpts(),
1021
19.4k
      CI.getLangOpts(), std::string(InFile), std::move(LinkModules),
1022
19.4k
      std::move(OS), *VMContext, CoverageInfo));
1023
19.4k
  BEConsumer = Result.get();
1024
1025
  // Enable generating macro debug info only when debug info is not disabled and
1026
  // also macro debug info is enabled.
1027
19.4k
  if (CI.getCodeGenOpts().getDebugInfo() != codegenoptions::NoDebugInfo &&
1028
19.4k
      
CI.getCodeGenOpts().MacroDebugInfo4.11k
) {
1029
5
    std::unique_ptr<PPCallbacks> Callbacks =
1030
5
        std::make_unique<MacroPPCallbacks>(BEConsumer->getCodeGenerator(),
1031
5
                                            CI.getPreprocessor());
1032
5
    CI.getPreprocessor().addPPCallbacks(std::move(Callbacks));
1033
5
  }
1034
1035
19.4k
  return std::move(Result);
1036
19.4k
}
1037
1038
std::unique_ptr<llvm::Module>
1039
113
CodeGenAction::loadModule(MemoryBufferRef MBRef) {
1040
113
  CompilerInstance &CI = getCompilerInstance();
1041
113
  SourceManager &SM = CI.getSourceManager();
1042
1043
  // For ThinLTO backend invocations, ensure that the context
1044
  // merges types based on ODR identifiers. We also need to read
1045
  // the correct module out of a multi-module bitcode file.
1046
113
  if (!CI.getCodeGenOpts().ThinLTOIndexFile.empty()) {
1047
59
    VMContext->enableDebugTypeODRUniquing();
1048
1049
59
    auto DiagErrors = [&](Error E) -> std::unique_ptr<llvm::Module> {
1050
0
      unsigned DiagID =
1051
0
          CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
1052
0
      handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1053
0
        CI.getDiagnostics().Report(DiagID) << EIB.message();
1054
0
      });
1055
0
      return {};
1056
0
    };
1057
1058
59
    Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
1059
59
    if (!BMsOrErr)
1060
0
      return DiagErrors(BMsOrErr.takeError());
1061
59
    BitcodeModule *Bm = llvm::lto::findThinLTOModule(*BMsOrErr);
1062
    // We have nothing to do if the file contains no ThinLTO module. This is
1063
    // possible if ThinLTO compilation was not able to split module. Content of
1064
    // the file was already processed by indexing and will be passed to the
1065
    // linker using merged object file.
1066
59
    if (!Bm) {
1067
1
      auto M = std::make_unique<llvm::Module>("empty", *VMContext);
1068
1
      M->setTargetTriple(CI.getTargetOpts().Triple);
1069
1
      return M;
1070
1
    }
1071
58
    Expected<std::unique_ptr<llvm::Module>> MOrErr =
1072
58
        Bm->parseModule(*VMContext);
1073
58
    if (!MOrErr)
1074
0
      return DiagErrors(MOrErr.takeError());
1075
58
    return std::move(*MOrErr);
1076
58
  }
1077
1078
54
  llvm::SMDiagnostic Err;
1079
54
  if (std::unique_ptr<llvm::Module> M = parseIR(MBRef, Err, *VMContext))
1080
53
    return M;
1081
1082
  // Translate from the diagnostic info to the SourceManager location if
1083
  // available.
1084
  // TODO: Unify this with ConvertBackendLocation()
1085
1
  SourceLocation Loc;
1086
1
  if (Err.getLineNo() > 0) {
1087
1
    assert(Err.getColumnNo() >= 0);
1088
0
    Loc = SM.translateFileLineCol(SM.getFileEntryForID(SM.getMainFileID()),
1089
1
                                  Err.getLineNo(), Err.getColumnNo() + 1);
1090
1
  }
1091
1092
  // Strip off a leading diagnostic code if there is one.
1093
0
  StringRef Msg = Err.getMessage();
1094
1
  if (Msg.startswith("error: "))
1095
0
    Msg = Msg.substr(7);
1096
1097
1
  unsigned DiagID =
1098
1
      CI.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error, "%0");
1099
1100
1
  CI.getDiagnostics().Report(Loc, DiagID) << Msg;
1101
1
  return {};
1102
54
}
1103
1104
19.5k
void CodeGenAction::ExecuteAction() {
1105
19.5k
  if (getCurrentFileKind().getLanguage() != Language::LLVM_IR) {
1106
19.3k
    this->ASTFrontendAction::ExecuteAction();
1107
19.3k
    return;
1108
19.3k
  }
1109
1110
  // If this is an IR file, we have to treat it specially.
1111
113
  BackendAction BA = static_cast<BackendAction>(Act);
1112
113
  CompilerInstance &CI = getCompilerInstance();
1113
113
  auto &CodeGenOpts = CI.getCodeGenOpts();
1114
113
  auto &Diagnostics = CI.getDiagnostics();
1115
113
  std::unique_ptr<raw_pwrite_stream> OS =
1116
113
      GetOutputStream(CI, getCurrentFile(), BA);
1117
113
  if (BA != Backend_EmitNothing && !OS)
1118
0
    return;
1119
1120
113
  SourceManager &SM = CI.getSourceManager();
1121
113
  FileID FID = SM.getMainFileID();
1122
113
  Optional<MemoryBufferRef> MainFile = SM.getBufferOrNone(FID);
1123
113
  if (!MainFile)
1124
0
    return;
1125
1126
113
  TheModule = loadModule(*MainFile);
1127
113
  if (!TheModule)
1128
1
    return;
1129
1130
112
  const TargetOptions &TargetOpts = CI.getTargetOpts();
1131
112
  if (TheModule->getTargetTriple() != TargetOpts.Triple) {
1132
37
    Diagnostics.Report(SourceLocation(), diag::warn_fe_override_module)
1133
37
        << TargetOpts.Triple;
1134
37
    TheModule->setTargetTriple(TargetOpts.Triple);
1135
37
  }
1136
1137
112
  EmbedBitcode(TheModule.get(), CodeGenOpts, *MainFile);
1138
1139
112
  LLVMContext &Ctx = TheModule->getContext();
1140
1141
  // Restore any diagnostic handler previously set before returning from this
1142
  // function.
1143
112
  struct RAII {
1144
112
    LLVMContext &Ctx;
1145
112
    std::unique_ptr<DiagnosticHandler> PrevHandler = Ctx.getDiagnosticHandler();
1146
112
    ~RAII() { Ctx.setDiagnosticHandler(std::move(PrevHandler)); }
1147
112
  } _{Ctx};
1148
1149
  // Set clang diagnostic handler. To do this we need to create a fake
1150
  // BackendConsumer.
1151
112
  BackendConsumer Result(BA, CI.getDiagnostics(), CI.getHeaderSearchOpts(),
1152
112
                         CI.getPreprocessorOpts(), CI.getCodeGenOpts(),
1153
112
                         CI.getTargetOpts(), CI.getLangOpts(), TheModule.get(),
1154
112
                         std::move(LinkModules), *VMContext, nullptr);
1155
  // PR44896: Force DiscardValueNames as false. DiscardValueNames cannot be
1156
  // true here because the valued names are needed for reading textual IR.
1157
112
  Ctx.setDiscardValueNames(false);
1158
112
  Ctx.setDiagnosticHandler(
1159
112
      std::make_unique<ClangDiagnosticHandler>(CodeGenOpts, &Result));
1160
1161
112
  Expected<std::unique_ptr<llvm::ToolOutputFile>> OptRecordFileOrErr =
1162
112
      setupLLVMOptimizationRemarks(
1163
112
          Ctx, CodeGenOpts.OptRecordFile, CodeGenOpts.OptRecordPasses,
1164
112
          CodeGenOpts.OptRecordFormat, CodeGenOpts.DiagnosticsWithHotness,
1165
112
          CodeGenOpts.DiagnosticsHotnessThreshold);
1166
1167
112
  if (Error E = OptRecordFileOrErr.takeError()) {
1168
0
    reportOptRecordError(std::move(E), Diagnostics, CodeGenOpts);
1169
0
    return;
1170
0
  }
1171
112
  std::unique_ptr<llvm::ToolOutputFile> OptRecordFile =
1172
112
      std::move(*OptRecordFileOrErr);
1173
1174
112
  EmitBackendOutput(Diagnostics, CI.getHeaderSearchOpts(), CodeGenOpts,
1175
112
                    TargetOpts, CI.getLangOpts(),
1176
112
                    CI.getTarget().getDataLayoutString(), TheModule.get(), BA,
1177
112
                    std::move(OS));
1178
112
  if (OptRecordFile)
1179
2
    OptRecordFile->keep();
1180
112
}
1181
1182
//
1183
1184
0
void EmitAssemblyAction::anchor() { }
1185
EmitAssemblyAction::EmitAssemblyAction(llvm::LLVMContext *_VMContext)
1186
532
  : CodeGenAction(Backend_EmitAssembly, _VMContext) {}
1187
1188
0
void EmitBCAction::anchor() { }
1189
EmitBCAction::EmitBCAction(llvm::LLVMContext *_VMContext)
1190
556
  : CodeGenAction(Backend_EmitBC, _VMContext) {}
1191
1192
0
void EmitLLVMAction::anchor() { }
1193
EmitLLVMAction::EmitLLVMAction(llvm::LLVMContext *_VMContext)
1194
14.6k
  : CodeGenAction(Backend_EmitLL, _VMContext) {}
1195
1196
0
void EmitLLVMOnlyAction::anchor() { }
1197
EmitLLVMOnlyAction::EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext)
1198
257
  : CodeGenAction(Backend_EmitNothing, _VMContext) {}
1199
1200
0
void EmitCodeGenOnlyAction::anchor() { }
1201
EmitCodeGenOnlyAction::EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext)
1202
7
  : CodeGenAction(Backend_EmitMCNull, _VMContext) {}
1203
1204
0
void EmitObjAction::anchor() { }
1205
EmitObjAction::EmitObjAction(llvm::LLVMContext *_VMContext)
1206
3.54k
  : CodeGenAction(Backend_EmitObj, _VMContext) {}