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