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 
initAsmInfo()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.BinutilsVersion.first > 0)
65     TmpAsmInfo->setBinutilsVersion(Options.BinutilsVersion);
66 
67   if (Options.DisableIntegratedAS)
68     TmpAsmInfo->setUseIntegratedAssembler(false);
69 
70   TmpAsmInfo->setPreserveAsmComments(Options.MCOptions.PreserveAsmComments);
71 
72   TmpAsmInfo->setCompressDebugSections(Options.CompressDebugSections);
73 
74   TmpAsmInfo->setRelaxELFRelocations(Options.RelaxELFRelocations);
75 
76   if (Options.ExceptionModel != ExceptionHandling::None)
77     TmpAsmInfo->setExceptionsType(Options.ExceptionModel);
78 
79   AsmInfo.reset(TmpAsmInfo);
80 }
81 
LLVMTargetMachine(const Target & T,StringRef DataLayoutString,const Triple & TT,StringRef CPU,StringRef FS,const TargetOptions & Options,Reloc::Model RM,CodeModel::Model CM,CodeGenOpt::Level OL)82 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
83                                      StringRef DataLayoutString,
84                                      const Triple &TT, StringRef CPU,
85                                      StringRef FS, const TargetOptions &Options,
86                                      Reloc::Model RM, CodeModel::Model CM,
87                                      CodeGenOpt::Level OL)
88     : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) {
89   this->RM = RM;
90   this->CMModel = CM;
91   this->OptLevel = OL;
92 
93   if (EnableTrapUnreachable)
94     this->Options.TrapUnreachable = true;
95 }
96 
97 TargetTransformInfo
getTargetTransformInfo(const Function & F)98 LLVMTargetMachine::getTargetTransformInfo(const Function &F) {
99   return TargetTransformInfo(BasicTTIImpl(this, F));
100 }
101 
102 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
103 static TargetPassConfig *
addPassesToGenerateCode(LLVMTargetMachine & TM,PassManagerBase & PM,bool DisableVerify,MachineModuleInfoWrapperPass & MMIWP)104 addPassesToGenerateCode(LLVMTargetMachine &TM, PassManagerBase &PM,
105                         bool DisableVerify,
106                         MachineModuleInfoWrapperPass &MMIWP) {
107   // Targets may override createPassConfig to provide a target-specific
108   // subclass.
109   TargetPassConfig *PassConfig = TM.createPassConfig(PM);
110   // Set PassConfig options provided by TargetMachine.
111   PassConfig->setDisableVerify(DisableVerify);
112   PM.add(PassConfig);
113   PM.add(&MMIWP);
114 
115   if (PassConfig->addISelPasses())
116     return nullptr;
117   PassConfig->addMachinePasses();
118   PassConfig->setInitialized();
119   return PassConfig;
120 }
121 
addAsmPrinter(PassManagerBase & PM,raw_pwrite_stream & Out,raw_pwrite_stream * DwoOut,CodeGenFileType FileType,MCContext & Context)122 bool LLVMTargetMachine::addAsmPrinter(PassManagerBase &PM,
123                                       raw_pwrite_stream &Out,
124                                       raw_pwrite_stream *DwoOut,
125                                       CodeGenFileType FileType,
126                                       MCContext &Context) {
127   Expected<std::unique_ptr<MCStreamer>> MCStreamerOrErr =
128       createMCStreamer(Out, DwoOut, FileType, Context);
129   if (auto Err = MCStreamerOrErr.takeError())
130     return true;
131 
132   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
133   FunctionPass *Printer =
134       getTarget().createAsmPrinter(*this, std::move(*MCStreamerOrErr));
135   if (!Printer)
136     return true;
137 
138   PM.add(Printer);
139   return false;
140 }
141 
createMCStreamer(raw_pwrite_stream & Out,raw_pwrite_stream * DwoOut,CodeGenFileType FileType,MCContext & Context)142 Expected<std::unique_ptr<MCStreamer>> LLVMTargetMachine::createMCStreamer(
143     raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut, CodeGenFileType FileType,
144     MCContext &Context) {
145   if (Options.MCOptions.MCSaveTempLabels)
146     Context.setAllowTemporaryLabels(false);
147 
148   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
149   const MCAsmInfo &MAI = *getMCAsmInfo();
150   const MCRegisterInfo &MRI = *getMCRegisterInfo();
151   const MCInstrInfo &MII = *getMCInstrInfo();
152 
153   std::unique_ptr<MCStreamer> AsmStreamer;
154 
155   switch (FileType) {
156   case CGFT_AssemblyFile: {
157     MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter(
158         getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI);
159 
160     // Create a code emitter if asked to show the encoding.
161     std::unique_ptr<MCCodeEmitter> MCE;
162     if (Options.MCOptions.ShowMCEncoding)
163       MCE.reset(getTarget().createMCCodeEmitter(MII, MRI, Context));
164 
165     std::unique_ptr<MCAsmBackend> MAB(
166         getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions));
167     auto FOut = std::make_unique<formatted_raw_ostream>(Out);
168     MCStreamer *S = getTarget().createAsmStreamer(
169         Context, std::move(FOut), Options.MCOptions.AsmVerbose,
170         Options.MCOptions.MCUseDwarfDirectory, InstPrinter, std::move(MCE),
171         std::move(MAB), Options.MCOptions.ShowMCInst);
172     AsmStreamer.reset(S);
173     break;
174   }
175   case CGFT_ObjectFile: {
176     // Create the code emitter for the target if it exists.  If not, .o file
177     // emission fails.
178     MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, Context);
179     if (!MCE)
180       return make_error<StringError>("createMCCodeEmitter failed",
181                                      inconvertibleErrorCode());
182     MCAsmBackend *MAB =
183         getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions);
184     if (!MAB)
185       return make_error<StringError>("createMCAsmBackend failed",
186                                      inconvertibleErrorCode());
187 
188     Triple T(getTargetTriple().str());
189     AsmStreamer.reset(getTarget().createMCObjectStreamer(
190         T, Context, std::unique_ptr<MCAsmBackend>(MAB),
191         DwoOut ? MAB->createDwoObjectWriter(Out, *DwoOut)
192                : MAB->createObjectWriter(Out),
193         std::unique_ptr<MCCodeEmitter>(MCE), STI, Options.MCOptions.MCRelaxAll,
194         Options.MCOptions.MCIncrementalLinkerCompatible,
195         /*DWARFMustBeAtTheEnd*/ true));
196     break;
197   }
198   case CGFT_Null:
199     // The Null output is intended for use for performance analysis and testing,
200     // not real users.
201     AsmStreamer.reset(getTarget().createNullStreamer(Context));
202     break;
203   }
204 
205   return std::move(AsmStreamer);
206 }
207 
addPassesToEmitFile(PassManagerBase & PM,raw_pwrite_stream & Out,raw_pwrite_stream * DwoOut,CodeGenFileType FileType,bool DisableVerify,MachineModuleInfoWrapperPass * MMIWP)208 bool LLVMTargetMachine::addPassesToEmitFile(
209     PassManagerBase &PM, raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut,
210     CodeGenFileType FileType, bool DisableVerify,
211     MachineModuleInfoWrapperPass *MMIWP) {
212   // Add common CodeGen passes.
213   if (!MMIWP)
214     MMIWP = new MachineModuleInfoWrapperPass(this);
215   TargetPassConfig *PassConfig =
216       addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP);
217   if (!PassConfig)
218     return true;
219 
220   if (TargetPassConfig::willCompleteCodeGenPipeline()) {
221     if (addAsmPrinter(PM, Out, DwoOut, FileType, MMIWP->getMMI().getContext()))
222       return true;
223   } else {
224     // MIR printing is redundant with -filetype=null.
225     if (FileType != CGFT_Null)
226       PM.add(createPrintMIRPass(Out));
227   }
228 
229   PM.add(createFreeMachineFunctionPass());
230   return false;
231 }
232 
233 /// addPassesToEmitMC - Add passes to the specified pass manager to get
234 /// machine code emitted with the MCJIT. This method returns true if machine
235 /// code is not supported. It fills the MCContext Ctx pointer which can be
236 /// used to build custom MCStreamer.
237 ///
addPassesToEmitMC(PassManagerBase & PM,MCContext * & Ctx,raw_pwrite_stream & Out,bool DisableVerify)238 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
239                                           raw_pwrite_stream &Out,
240                                           bool DisableVerify) {
241   // Add common CodeGen passes.
242   MachineModuleInfoWrapperPass *MMIWP = new MachineModuleInfoWrapperPass(this);
243   TargetPassConfig *PassConfig =
244       addPassesToGenerateCode(*this, PM, DisableVerify, *MMIWP);
245   if (!PassConfig)
246     return true;
247   assert(TargetPassConfig::willCompleteCodeGenPipeline() &&
248          "Cannot emit MC with limited codegen pipeline");
249 
250   Ctx = &MMIWP->getMMI().getContext();
251   if (Options.MCOptions.MCSaveTempLabels)
252     Ctx->setAllowTemporaryLabels(false);
253 
254   // Create the code emitter for the target if it exists.  If not, .o file
255   // emission fails.
256   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
257   const MCRegisterInfo &MRI = *getMCRegisterInfo();
258   MCCodeEmitter *MCE =
259       getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx);
260   MCAsmBackend *MAB =
261       getTarget().createMCAsmBackend(STI, MRI, Options.MCOptions);
262   if (!MCE || !MAB)
263     return true;
264 
265   const Triple &T = getTargetTriple();
266   std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
267       T, *Ctx, std::unique_ptr<MCAsmBackend>(MAB), MAB->createObjectWriter(Out),
268       std::unique_ptr<MCCodeEmitter>(MCE), STI, Options.MCOptions.MCRelaxAll,
269       Options.MCOptions.MCIncrementalLinkerCompatible,
270       /*DWARFMustBeAtTheEnd*/ true));
271 
272   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
273   FunctionPass *Printer =
274       getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
275   if (!Printer)
276     return true;
277 
278   PM.add(Printer);
279   PM.add(createFreeMachineFunctionPass());
280 
281   return false; // success!
282 }
283