1 //===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the LLVMTargetMachine class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Analysis/Passes.h"
14 #include "llvm/CodeGen/AsmPrinter.h"
15 #include "llvm/CodeGen/BasicTTIImpl.h"
16 #include "llvm/CodeGen/MachineModuleInfo.h"
17 #include "llvm/CodeGen/Passes.h"
18 #include "llvm/CodeGen/TargetPassConfig.h"
19 #include "llvm/IR/LegacyPassManager.h"
20 #include "llvm/MC/MCAsmBackend.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCCodeEmitter.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCInstrInfo.h"
25 #include "llvm/MC/MCObjectWriter.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/FormattedStream.h"
31 #include "llvm/Support/TargetRegistry.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetOptions.h"
35 using namespace llvm;
36 
37 static cl::opt<bool> EnableTrapUnreachable("trap-unreachable",
38   cl::Hidden, cl::ZeroOrMore, cl::init(false),
39   cl::desc("Enable generating trap for unreachable"));
40 
41 void LLVMTargetMachine::initAsmInfo() {
42   MRI.reset(TheTarget.createMCRegInfo(getTargetTriple().str()));
43   assert(MRI && "Unable to create reg info");
44   MII.reset(TheTarget.createMCInstrInfo());
45   assert(MII && "Unable to create instruction info");
46   // FIXME: Having an MCSubtargetInfo on the target machine is a hack due
47   // to some backends having subtarget feature dependent module level
48   // code generation. This is similar to the hack in the AsmPrinter for
49   // module level assembly etc.
50   STI.reset(TheTarget.createMCSubtargetInfo(
51       getTargetTriple().str(), getTargetCPU(), getTargetFeatureString()));
52   assert(STI && "Unable to create subtarget info");
53 
54   MCAsmInfo *TmpAsmInfo = TheTarget.createMCAsmInfo(
55       *MRI, getTargetTriple().str(), Options.MCOptions);
56   // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
57   // and if the old one gets included then MCAsmInfo will be NULL and
58   // we'll crash later.
59   // Provide the user with a useful error message about what's wrong.
60   assert(TmpAsmInfo && "MCAsmInfo not initialized. "
61          "Make sure you include the correct TargetSelect.h"
62          "and that InitializeAllTargetMCs() is being invoked!");
63 
64   if (Options.DisableIntegratedAS)
65     TmpAsmInfo->setUseIntegratedAssembler(false);
66 
67   TmpAsmInfo->setPreserveAsmComments(Options.MCOptions.PreserveAsmComments);
68 
69   TmpAsmInfo->setCompressDebugSections(Options.CompressDebugSections);
70 
71   TmpAsmInfo->setRelaxELFRelocations(Options.RelaxELFRelocations);
72 
73   if (Options.ExceptionModel != ExceptionHandling::None)
74     TmpAsmInfo->setExceptionsType(Options.ExceptionModel);
75 
76   AsmInfo.reset(TmpAsmInfo);
77 }
78 
79 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
80                                      StringRef DataLayoutString,
81                                      const Triple &TT, StringRef CPU,
82                                      StringRef FS, const TargetOptions &Options,
83                                      Reloc::Model RM, CodeModel::Model CM,
84                                      CodeGenOpt::Level OL)
85     : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) {
86   this->RM = RM;
87   this->CMModel = CM;
88   this->OptLevel = OL;
89 
90   if (EnableTrapUnreachable)
91     this->Options.TrapUnreachable = true;
92 }
93 
94 TargetTransformInfo
95 LLVMTargetMachine::getTargetTransformInfo(const Function &F) {
96   return TargetTransformInfo(BasicTTIImpl(this, F));
97 }
98 
99 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
100 static TargetPassConfig *
101 addPassesToGenerateCode(LLVMTargetMachine &TM, PassManagerBase &PM,
102                         bool DisableVerify,
103                         MachineModuleInfoWrapperPass &MMIWP) {
104   // Targets may override createPassConfig to provide a target-specific
105   // subclass.
106   TargetPassConfig *PassConfig = TM.createPassConfig(PM);
107   // Set PassConfig options provided by TargetMachine.
108   PassConfig->setDisableVerify(DisableVerify);
109   PM.add(PassConfig);
110   PM.add(&MMIWP);
111 
112   if (PassConfig->addISelPasses())
113     return nullptr;
114   PassConfig->addMachinePasses();
115   PassConfig->setInitialized();
116   return PassConfig;
117 }
118 
119 bool LLVMTargetMachine::addAsmPrinter(PassManagerBase &PM,
120                                       raw_pwrite_stream &Out,
121                                       raw_pwrite_stream *DwoOut,
122                                       CodeGenFileType FileType,
123                                       MCContext &Context) {
124   Expected<std::unique_ptr<MCStreamer>> MCStreamerOrErr =
125       createMCStreamer(Out, DwoOut, FileType, Context);
126   if (auto Err = MCStreamerOrErr.takeError())
127     return true;
128 
129   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
130   FunctionPass *Printer =
131       getTarget().createAsmPrinter(*this, std::move(*MCStreamerOrErr));
132   if (!Printer)
133     return true;
134 
135   PM.add(Printer);
136   return false;
137 }
138 
139 Expected<std::unique_ptr<MCStreamer>> LLVMTargetMachine::createMCStreamer(
140     raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType,
141     MCContext &Context) {
142   if (Options.MCOptions.MCSaveTempLabels)
143     Context.setAllowTemporaryLabels(false);
144 
145   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
146   const MCAsmInfo &MAI = *getMCAsmInfo();
147   const MCRegisterInfo &MRI = *getMCRegisterInfo();
148   const MCInstrInfo &MII = *getMCInstrInfo();
149 
150   std::unique_ptr<MCStreamer> AsmStreamer;
151 
152   switch (FileType) {
153   case CGFT_AssemblyFile: {
154     MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter(
155         getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI);
156 
157     // Create a code emitter if asked to show the encoding.
158     std::unique_ptr<MCCodeEmitter> MCE;
159     if (Options.MCOptions.ShowMCEncoding)
160       MCE.reset(getTarget().createMCCodeEmitter(MII, MRI, Context));
161 
162     std::unique_ptr<MCAsmBackend> MAB(
163         getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions));
164     auto FOut = std::make_unique<formatted_raw_ostream>(Out);
165     MCStreamer *S = getTarget().createAsmStreamer(
166         Context, std::move(FOut), Options.MCOptions.AsmVerbose,
167         Options.MCOptions.MCUseDwarfDirectory, InstPrinter, std::move(MCE),
168         std::move(MAB), Options.MCOptions.ShowMCInst);
169     AsmStreamer.reset(S);
170     break;
171   }
172   case CGFT_ObjectFile: {
173     // Create the code emitter for the target if it exists.  If not, .o file
174     // emission fails.
175     MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, Context);
176     if (!MCE)
177       return make_error<StringError>("createMCCodeEmitter failed",
178                                      inconvertibleErrorCode());
179     MCAsmBackend *MAB =
180         getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions);
181     if (!MAB)
182       return make_error<StringError>("createMCAsmBackend failed",
183                                      inconvertibleErrorCode());
184 
185     Triple T(getTargetTriple().str());
186     AsmStreamer.reset(getTarget().createMCObjectStreamer(
187         T, Context, std::unique_ptr<MCAsmBackend>(MAB),
188         DwoOut ? MAB->createDwoObjectWriter(Out, *DwoOut)
189                : MAB->createObjectWriter(Out),
190         std::unique_ptr<MCCodeEmitter>(MCE), STI, Options.MCOptions.MCRelaxAll,
191         Options.MCOptions.MCIncrementalLinkerCompatible,
192         /*DWARFMustBeAtTheEnd*/ true));
193     break;
194   }
195   case CGFT_Null:
196     // The Null output is intended for use for performance analysis and testing,
197     // not real users.
198     AsmStreamer.reset(getTarget().createNullStreamer(Context));
199     break;
200   }
201 
202   return std::move(AsmStreamer);
203 }
204 
205 bool LLVMTargetMachine::addPassesToEmitFile(
206     PassManagerBase &PM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut,
207     CodeGenFileType FileType, bool DisableVerify,
208     MachineModuleInfoWrapperPass *MMIWP) {
209   // Add common CodeGen passes.
210   if (!MMIWP)
211     MMIWP = new MachineModuleInfoWrapperPass(this);
212   TargetPassConfig *PassConfig =
213       addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP);
214   if (!PassConfig)
215     return true;
216 
217   if (TargetPassConfig::willCompleteCodeGenPipeline()) {
218     if (addAsmPrinter(PM, Out, DwoOut, FileType, MMIWP->getMMI().getContext()))
219       return true;
220   } else {
221     // MIR printing is redundant with -filetype=null.
222     if (FileType != CGFT_Null)
223       PM.add(createPrintMIRPass(Out));
224   }
225 
226   PM.add(createFreeMachineFunctionPass());
227   return false;
228 }
229 
230 /// addPassesToEmitMC - Add passes to the specified pass manager to get
231 /// machine code emitted with the MCJIT. This method returns true if machine
232 /// code is not supported. It fills the MCContext Ctx pointer which can be
233 /// used to build custom MCStreamer.
234 ///
235 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
236                                           raw_pwrite_stream &Out,
237                                           bool DisableVerify) {
238   // Add common CodeGen passes.
239   MachineModuleInfoWrapperPass *MMIWP = new MachineModuleInfoWrapperPass(this);
240   TargetPassConfig *PassConfig =
241       addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP);
242   if (!PassConfig)
243     return true;
244   assert(TargetPassConfig::willCompleteCodeGenPipeline() &&
245          "Cannot emit MC with limited codegen pipeline");
246 
247   Ctx = &MMIWP->getMMI().getContext();
248   if (Options.MCOptions.MCSaveTempLabels)
249     Ctx->setAllowTemporaryLabels(false);
250 
251   // Create the code emitter for the target if it exists.  If not, .o file
252   // emission fails.
253   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
254   const MCRegisterInfo &MRI = *getMCRegisterInfo();
255   MCCodeEmitter *MCE =
256       getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx);
257   MCAsmBackend *MAB =
258       getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions);
259   if (!MCE || !MAB)
260     return true;
261 
262   const Triple &T = getTargetTriple();
263   std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
264       T, *Ctx, std::unique_ptr<MCAsmBackend>(MAB), MAB->createObjectWriter(Out),
265       std::unique_ptr<MCCodeEmitter>(MCE), STI, Options.MCOptions.MCRelaxAll,
266       Options.MCOptions.MCIncrementalLinkerCompatible,
267       /*DWARFMustBeAtTheEnd*/ true));
268 
269   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
270   FunctionPass *Printer =
271       getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
272   if (!Printer)
273     return true;
274 
275   PM.add(Printer);
276   PM.add(createFreeMachineFunctionPass());
277 
278   return false; // success!
279 }
280