Coverage Report

Created: 2019-07-24 05:18

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