Coverage Report

Created: 2021-09-21 08:58

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